AIStoreHub Package Vault: mathema
Package Slug: mathema
Archetype: mcp_server
Upstream Repository: https://github.com/tetrionlabs/mathema
Workspace Files & Specifications (67 files)
- aistorehub.json (647 bytes)
{ "name": "mathema", "slug": "mathema", "version": "1.0.0", "type": "mcp_server", "description": "Claim-Driven Development: turn software intent into verifiable evidence.", "owner": "community", "repository": "catalog", "github_repo_url": "https://github.com/tetrionlabs/mathema", "tags": [ "design-by-contract", "claim-driven-development", "property-based-testing", "software-verification", "mcp-server", "ai-assisted-development", "code-review", "test-driven-development", "system-0-engine", "mcp-servers", "spec-driven-development" ], "imported_at": "2026-11-24T20:32:34.186Z" } - CHANGELOG.md (58861 bytes)
# Changelog Notable changes to mathema are recorded here from its first public release onward. ## 0.6.6.2 ### Highlights - A function read as a pattern validator is decided on the solver route for more claim forms: `assuming f is defined, f(s) == s` for a validator that refuses every text outside its language; a match on `s or ''` over a language of texts; a `let`-bound variable with another name than the parameter; literal text added around the variable, decided over all text when the texts called on leave the variable's language; an exception class of the function's own package with a builtin exception as its only base and nothing of its own; and a message reading a module-level text constant. - `mathema.regular` has the calls of a term algebra: `validate`, `contains` and `matcher` (on a definition, with a bound and a budget, reporting the work spent, or on a bare node), `atoms`, `shortest_member` and `find_member`. - A language's persisted form states its regular-language term under the key `term`. A form that carries only `definition` is still read, for this release; a form that states both is read by `term`. - A code point range written as a tuple in a regular-language definition is read as the list it stands for, with the same canonical text and hash. A definition that states both `language` and the bounds `at_least` and `at_most` is refused. - A record whose verdict rests on a language's stated definition, compared with the language's `contains()`, goes stale when that `contains()` changes, or a text constant a validator's message reads. ### Upgrading from 0.6.6.1 - The `language` extra takes mathema-language 0.2 to 0.4. - An assumption a proof rests on, compared with a language's `contains()` on the values tried, has the status `assumed` where it read `checked`; a stored `checked` is still read, as a comparison that agreed on every value. In a proof outline an entry may say what the comparison fell short of: `(assumed, 3 of 14 values skipped)`, `(assumed, no value compared)`. - A claim whose every variable is a text has no `[float]` companion row. - Every record is checked again once. The claims fingerprint a record stores for freshness now carries mathema's rules number (`mathema._rules.RULES`, 1 in this release: canonical statement text). A record written before it reads as written under earlier rules and is re-adjudicated by the next `mathema verify`, then fresh. The claim identity (`claims_fingerprint`) does not carry the rules number; it moves only for a claim whose stored text this release writes differently (a negated relation, a string literal an earlier release quoted ambiguously). - The stored statement text of a string literal is written from its value, and a negated relation keeps its parentheses. A domain set's string member is still read as the text between its quotes (`{"\t"}` is a backslash and a t); when that differs from the same text read as an expression literal, `mathema verify` says so in a note. A record an earlier release wrote in the old spelling of an unedited claim is re-recorded with a note, never a supersession. - `lineage.statement_text` is no longer written. - A claim whose stored text 0.6.6.1 wrote and cannot read back (`= not (a < x and x < b)`) is checked again as written and re-recorded with a note, where 0.6.6.1 failed the whole function with "rebuild the record". An edit made to that claim since its record was written is adopted without `--as superseded`. ### Fixes - The check of a language's definition compares the strings the claim itself writes. Agreement on the values tried is no proof: the definition, the reading of a validator and `<L> holds only texts` each stand as `assumed`, with an `axiom` id and a `corroboration` record of the values drawn, compared and skipped, the seed and the outcome. A proven line names a definition it assumes when a value was skipped or none was compared. - A language whose `contains()` admits a value that is not a text proves no claim on the solver route; a proof lists `<L> holds only texts` among its assumptions. - A falsified claim's witness, shrunk inside a language, stays inside the claim's premise. - The derivative matcher answers a bounded repeat followed by anything on long texts, and gives up on a term too deep to read with `MatchBudget`. - Stored text an earlier release wrote for two different claims (`f(s, '}"', 's')` and `f(s, '}"", "s')`) is reported as ambiguous, naming both readings and `mathema accept ... --as superseded` for an edit; the claim is checked as written, never kept at its old verdict. - A key that raises after its record is written, while it is checked or while its dependencies are settled, gets the record it had before the run back, whatever stopped it (an exception, running out of memory, an interrupt or the wall-clock alarm), and a read of the store later in the same run sees what is on disk. - A claim whose stored text mathema cannot write fails its function's row and shows its kept row as `unchecked`; the function is checked again on every run until the text can be written. - A risk accepted on a claim that a later check proves or finds holding stays in the record as history, is no longer counted as accepted risk, and the sweep says so. - After an earlier key's release move, a moved key still names its rename remedy. - A note names each character it shows (`a tab (U+0009)`), a claim whose stored text moved in more than one way gets every note that applies, and docsync's diagnostics follow `--root`. ### Known limits - In a few narrow cases a result is reported at a higher level than its evidence supports, or a verdict is wrong; each is described with a small example in the issue tracker (#120 to #132). The statement checked is true in most of them and the effect on ordinary claims is small. They were found by checking mathema's verdicts against executed results and by mutation runs over KOINE. - A claim someone wrote still runs its function on values drawn from the claim's domain. A function that writes, deletes or sends should not carry claims that are probed. ## 0.6.6.1 ### Upgrading from 0.6.6 - Implementation counts only the lines reached by the probes of claims included for a function (in a claims file, its docstring or a decorator, or a suggestion accepted as evidence). A function with no such claim is not run while it is scored, so code with neither tests nor claims reads lower than in 0.6.6. - `check()` and `mathema verify` run the built-in checks (the structural battery, the shape and type probes, and the rows for a value that is not there) only for a function with a written claim or a mathema type marker. A function with neither is not called with values mathema generates. `MATHEMA_BUILTIN_CHECKS=on` runs them for every function, `off` for none. - The `language` extra takes mathema-language 0.2 or 0.3. ### Fixes - `.mathema/.gitignore` ignores `/cache/`, and `mathema init` adds the lines an existing one lacks. Warnings kept in the scoring cache name files relative to the repository root. ### Known limits - A claim someone wrote still runs its function on values drawn from the claim's domain. Until 0.6.7, a function that writes, deletes or sends should not carry claims that are probed. ## 0.6.6 ### Highlights - KOINE has `operator::truth::ambiguous(x)`, a truth value not yet decided. The interpreter and the renderers stop on it with "the truth of x is ambiguous". - Risk acceptances can carry a lifetime. With `accepted_risk_lifetime_days: N` under `acceptance:` in `.mathema/meta/policy.yaml`, every risk acceptance written from then on (`mathema accept --as risk`, and a risk sign-off with `--transition`) records `expires`, N days after it was written. From that date the acceptance no longer counts: an unknown claim fails again in both modes, and a skipped claim fails in strict mode and passes `--lenient` with a warning, its line naming the date and the command that accepts it again. With no key nothing expires; acceptances written before the key was set carry no expiry, and evidence acceptances never expire. Accepting a risk again keeps the acceptance it replaces in the claim's `acceptance_history` as a `superseded` event (`at`, `by`, `note`, `level`, `expires`). A lifetime that is not a positive whole number, or a `transitions:` entry outside the kinds, modes and actions, stops `mathema verify` and `mathema accept` with exit 2 as an unreadable policy, naming the entry and its value. - A claim's `pseudo_infinity=(lo, hi)` pair is two finite numbers, `lo` below zero standing for -oo and `hi` above zero for +oo. A pair such as `(nan, nan)`, `(1e6, -1e6)`, `(5, 5)`, `(-1e6, -1)`, `(0, 1e6)` or one with an infinite side is refused with that reason when the claim is made, in the same words and place as a single magnitude `let |inf| be` would refuse, so it never reaches a probe as a nan or backwards range. - Suggested claims call a function the way its signature accepts. A derivative-sign suggestion passes a keyword-only parameter by keyword (`d(f(a, k=k), a) >= 0`), and the derivative-sign families read that spelling as their own statement. - The suggestions that swap, scale or transform arguments (`commutative`, `associative`, `scale_equivariant`, `even`, `odd`, `idempotent` and the sequence transforms) move only the parameters passed by position and hold every keyword-only parameter at its default: `def f(a, b, *, s=1.0)` gets `f(a, b) == f(b, a)`. A function whose operands are keyword-only, or with a keyword-only parameter that has no default, gets none of them, and `is_numerically_stable` is not suggested for a function with a keyword-only parameter. - A claims-file `runtime_types:` entry naming a type whose library is not installed (`{xs: pandas.Series}` without pandas) still states a sequence: the claim's mathematics is decided reading the domain per element, and every row that would run the code on that type (its `[float, pandas.Series]` computation line, its empty-input line, a probe standing in for an undecided derive) is `skipped`, naming the library. No row is run on lists standing in for the declared type, and the computation line keeps the name it has where the library is installed. ### Upgrading from 0.6.5 - A function with accepted risk names it in its row (`1 accepted-risk claim(s)`) in every mode. - Accepted risk passes `mathema verify` in strict mode as well as under `--lenient` (0.6.5 refused it in strict mode), named in the row as accepted risk: an `unknown` or `skipped` claim accepted with `accept --as risk`, a claim stored as `skipped:unknown_but_accepted`, and a fall carrying a risk sign-off. Strict still fails a `skipped` claim nobody accepted, a `falsified` claim is never accepted as risk, and every risk acceptance is still held to the project's acceptance policy at every verify. A pipeline that relied on strict refusing accepted risk sees those rows pass. - A plain domain on a parameter (a finite set, or an interval with no `^n`) binds the value itself. It is read as the domain of each element only for a parameter whose annotation or runtime type states a sequence (`list`, `tuple`, `Sequence[float]`, `np.ndarray`, `pd.Series`, a `Vec` marker, a claims-file `runtime_types:` entry). A body that iterates or indexes an unannotated parameter leaves its binding the domain of the value: `for value in {1, 2.5, 1e300}, f(value) == (-value, value)` on `pseudo_infinity_range(value)` draws the three numbers. For a parameter that takes a sequence, annotate it as one (`xs: list`). - The bundled `numpy.quantile` definition row is stated over `[-1e150, 1e150]^n`, as its range row already was: beyond that magnitude numpy's linear interpolation can overflow to inf where the exact quantile is finite. ### Fixes - A function wrapped by a decorator written as a class is adjudicated as the wrapped function when the instance's `__call__` passes its arguments on and returns the result unchanged; a class whose `__call__` does anything else with the wrapped function has every claim `skipped` with that reason. - A raise guard is certified only where the raising branch can run, given the exponents a claim fixes to integers and the range a loop index takes. - A disproof certified by interval arithmetic is reported as falsified only when a run of the function on the witness's exact values reproduces it; otherwise the claim is unknown, a passing sample does not make it holds, and the certificate stays in the note. - A claim word (`sum`, `prod`, `dot`) over complex numbers keeps the exact value of a real or imaginary part beyond float range, as it does for real values, and the claim is judged against it. - Waiting test runs are served in the order they arrived (`scripts/test_slots.py`). ## 0.6.5 ### Highlights - `invalidated` names a function: one that changed since its record, by its form, its body's provenance, a parameter default, its own claims, the pseudo-infinity a claim runs to, a library version, a definition row, a premise, or anything along its dependency chain. The record names the triggers that fired in `mathema.invalidated_by` and the roots of a moved chain in `mathema.chain_moved`, and reverify is the action on that function. - A claim keeps the verdict its latest run found, and a move from the verdict before it is a transition kept beside it in `mathema.transitions`: `regressed`, `weakened`, `strengthened` or `fixed`, with its cause (`this function changed`, `a callee changed` or `nothing changed`), the date and the commit. A move after a code change also keeps the triggers that fired and the moved chain's roots, and the line for a fall to `unknown` or `skipped` names them. A transition stays open until a person acknowledges it or the claim is back at the level it fell from. - The gate acts on each open transition by its kind and the mode: `regressed` fails in both modes; `weakened` from `proven` to `holds` fails strict and warns under `--lenient`; a supported claim fallen to `unknown` or `skipped` fails in both modes until a person accepts the risk at the level it fell from; `strengthened` and `fixed` pass. A regression or a fall to `unknown` with nothing changed says that two runs disagree. `.mathema/meta/policy.yaml` sets the action per kind under `transitions:`, and an entry applies to every move of its kind. - `mathema accept KEY CLAIM --transition` acknowledges the open transitions on the named claims, recording `acknowledged: {at, by, note}`. On a claim fallen to `unknown` or `skipped` it is a risk acceptance, `acknowledged: {at, by, note, as: risk, level}`, held to the project's acceptance policy (required verification, methods, keys) when written and at every verify. The claim is then accepted risk at the level it fell from, as `--as risk` makes it, and the sign-off stays on the record until the claim is back at that level. - Classes carry a form hash, a dependency's chain reaches through the functions and classes it reads transitively, and a class built on an install - CLA.md (7447 bytes)
# Tetrion Ltd Contributor Licence Agreement Version 1.0 Thank you for your interest in contributing to software and specifications published by Tetrion Ltd, a company registered in England and Wales ("Tetrion", "we", "us"). This agreement records the terms on which you contribute. It protects you, Tetrion, and everyone who uses the Projects. It does not change your rights to use your own Contributions for any other purpose. Please read it carefully. By submitting a Contribution to a Project, you accept these terms. ## 1. Definitions "Project" means any repository, package, specification or other work that Tetrion publishes and to which this agreement is attached, including the software known as mathema and the specification known as Claim-Driven Development, and any successor to either. "Contribution" means any original work of authorship, including any modification or addition to an existing work, that you intentionally submit to Tetrion for inclusion in a Project, in any form, including source code, documentation, specification text, test cases, data and designs. "Submit" means intentionally providing a Contribution to Tetrion or its representatives for inclusion in or incorporation into a Project, including through a pull request, patch or other submission mechanism. Ordinary discussions, suggestions, issue reports, questions and other communications about a Project are not Contributions unless the material is expressly submitted for inclusion in or incorporation into the Project. A communication conspicuously marked in writing as "Not a Contribution" is not a Contribution. "You" means the individual or legal entity accepting this agreement. Where you are an entity, "you" includes every entity that controls, is controlled by, or is under common control with that entity. ## 2. Copyright licence You grant to Tetrion, and to recipients of works Tetrion distributes, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable copyright licence to reproduce, prepare derivative works of, publicly display, publicly perform, distribute, sublicense through multiple tiers, and otherwise use your Contributions and such derivative works, in whole or in part, in any form and by any means now known or later developed. ## 3. Relicensing Without limiting section 2, you agree that Tetrion may distribute your Contributions, and any Project containing them, under any licence terms Tetrion chooses, whether open source, source available, proprietary or commercial, and may change those terms from time to time, including by: (a) including your Contributions in products or services that Tetrion offers under commercial or proprietary terms; (b) offering your Contributions under a licence that is different from, more restrictive than, or less restrictive than the licence under which you received the Project; and (c) continuing to distribute your Contributions under source available or proprietary terms after any version of a Project has converted to an open source licence under a change-date or similar mechanism. Tetrion will not remove your authorship attribution from any Contribution that carries one. ## 4. Patent licence You grant to Tetrion, and to recipients of works Tetrion distributes, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable (except as stated in this section) patent licence to make, have made, use, offer to sell, sell, import and otherwise transfer the Project, where that licence applies only to those patent claims licensable by you that are necessarily infringed by your Contribution alone or by the combination of your Contribution with the Project to which it was submitted. If any person institutes patent litigation against you or any other person alleging that your Contribution, or the Project to which you contributed, constitutes direct or contributory patent infringement, then any patent licence granted to that person under this agreement for that Contribution or Project terminates as of the date the litigation is filed. ## 5. Moral rights To the fullest extent permitted by law, you waive, and agree not to assert against Tetrion or its licensees, any moral rights you may have in your Contributions, including rights of attribution and integrity under the Copyright, Designs and Patents Act 1988 or any equivalent law elsewhere. Tetrion's undertaking in section 3 to preserve authorship attribution is contractual and is not affected by this waiver. ## 6. Your representations You represent that: (a) each Contribution is your original work, or you have identified any part that is not, as described in section 7; (b) you are legally entitled to grant the licences in this agreement. If your employer or any other person has rights in intellectual property you create, including your Contributions, you represent that you have received permission to make the Contribution on behalf of that person, that the person has waived such rights for your Contributions, or that the person has itself accepted this agreement; (c) where you accept this agreement on behalf of an entity, you have authority to bind that entity, and Schedule A is complete; and (d) your Contribution does not, to your knowledge, infringe the intellectual property rights of any third party. You agree to notify Tetrion promptly of any facts or circumstances of which you become aware that would make any representation inaccurate. ## 7. Third-party material If any part of a Contribution is not your original work, or is subject to any licence, patent, trademark or other restriction of which you are aware, you must identify that part and its source and restrictions in the submission, in a form such as: "Submitted on behalf of a third party: [name], licensed under [licence]". Tetrion may decline any Contribution on that basis. ## 8. No obligation and no warranty Tetrion is under no obligation to include any Contribution in any Project, and may remove a Contribution at any time. Except for the representations in section 6, you provide your Contributions "as is", without warranty of any kind, express or implied, including any warranty of merchantability, fitness for a particular purpose, title or non-infringement, and you have no obligation to provide support. ## 9. Your own rights Nothing in this agreement transfers ownership of your Contributions to Tetrion, or prevents you from using, licensing or distributing your own Contributions for any purpose, including in other projects and under other licences. ## 10. General This agreement is governed by the law of England and Wales, and the courts of England and Wales have exclusive jurisdiction over any dispute arising from it. If any provision is held unenforceable, the remainder continues in effect and the provision is read as narrowly as needed to be enforceable. This agreement is the entire agreement between you and Tetrion concerning your Contributions and supersedes any prior agreement on that subject. Tetrion may publish updated versions of this agreement; an updated version applies only to Contributions submitted after you accept it. ## Schedule A: entity contributors Entity name: Registered address and company number: Authorised signatory name and title: Initial list of contributors authorised to submit on the entity's behalf (may be updated by written notice to Tetrion): - claims/assumptions.claims.yaml (1572 bytes)
mathema.domain_relations.agreed_on_counts: claims: - name: agreement_is_some_compared_none_against_none_skipped statement: 'for compared in {0, 1, 2, 3}, disagreed in {0, 1, 2}, skipped in {0, 1, 2}, f(compared, disagreed, skipped) == (compared > 0 and disagreed == 0 and skipped == 0)' - name: nothing_compared_is_no_agreement statement: 'for disagreed in {0, 1, 2}, skipped in {0, 1, 2}, f(0, disagreed, skipped) == False' - name: a_skipped_value_is_no_agreement statement: 'for compared in {0, 1, 2, 3}, skipped in {1, 2}, f(compared, 0, skipped) == False' claims.smt_support.record_agreed: claims: - name: the_record_agrees_exactly_when_its_counts_do statement: 'let stated = claims.smt_support.agreement_stated, for compared in {0, 1, 2, 3}, disagreed in {0, 1, 2}, skipped in {0, 1, 2}, f(compared, disagreed, skipped) == stated(compared, disagreed, skipped)' claims.smt_support.outline_entry_is_bare: claims: - name: the_outline_is_bare_exactly_when_every_value_agreed statement: 'let stated = claims.smt_support.agreement_stated, for compared in {0, 1, 2, 3}, disagreed in {0, 1, 2}, skipped in {0, 1, 2}, f(compared, disagreed, skipped) == stated(compared, disagreed, skipped)' claims.smt_support.shortfall_is_empty: claims: - name: nothing_fell_short_exactly_when_every_value_agreed statement: 'let stated = claims.smt_support.agreement_stated, for compared in {0, 1, 2, 3}, disagreed in {0, 1, 2}, skipped in {0, 1, 2}, f(compared, disagreed, skipped) == stated(compared, disagreed, skipped)' - claims/smt_relations.claims.yaml (596 bytes)
claims.smt_support.interval_verdict: claims: - name: the_verdict_is_the_truth_of_the_relation statement: 'let truth = claims.smt_support.interval_truth, for relation in {0, 1, 2, 3, 4}, a in {0, 1, 2, 3}, b in {0, 1, 2, 3}, c in {0, 1, 2, 3}, d in {0, 1, 2, 3}, f(relation, a, b, c, d) == truth(relation, a, b, c, d)' claims.smt_support.interval_text_is_stable: claims: - name: the_canonical_text_reads_back_as_itself statement: 'for relation in {0, 1, 2, 3, 4}, a in {0, 1, 2, 3}, b in {0, 1, 2, 3}, c in {0, 1, 2, 3}, d in {0, 1, 2, 3}, f(relation, a, b, c, d) == True' - claims/smt_support.py (10325 bytes)
# SPDX-License-Identifier: BUSL-1.1 # Copyright 2026 Tetrion Ltd """Functions the claims about `mathema.regular`, `mathema._validators` and `mathema.domain_relations` are stated over: each takes numbers or text a claim can quantify, builds the documents, functions or domain texts the module under claim reads, and returns a value a claim can compare. `regular.py` and `_validators.py` import nothing from the rest of the package, so they are loaded here from their files, under names of their own: the claims over them can then be checked by any installed mathema, a released one included, against the files in this tree.""" from __future__ import annotations import importlib.util import re import sys from fractions import Fraction from pathlib import Path _PACKAGE = Path(__file__).resolve().parent.parent / "mathema" def _load(name: str): """The module in the file `mathema/<name>.py` of this tree, loaded once under the name `candidate_<name>`.""" key = f"candidate_{name.lstrip('_')}" if key not in sys.modules: spec = importlib.util.spec_from_file_location(key, _PACKAGE / f"{name}.py") module = importlib.util.module_from_spec(spec) sys.modules[key] = module spec.loader.exec_module(module) return sys.modules[key] ALL = [[0, 0x10FFFF]] def _document(node: dict, source: "dict | None" = None) -> dict: document = {"kind": "regular_language", "version": 1, "alphabet": ALL, "exact": True, "language": node} if source is not None: document["source"] = source return document def _span(lo: int, width: int) -> dict: return {"op": "chars", "ranges": [[int(lo), int(lo) + width]]} # ---- mathema.regular -------------------------------------------------- def literal_hash(text: str, note: str) -> str: """The hash of the definition holding exactly `text`, compiled from a source described by `note`.""" return _load("regular").term_hash( _document({"op": "literal", "codes": [ord(c) for c in text]}, {"dialect": "by hand", "pattern": note})) def canonical_twice_is_canonical(a: int, b: int, shape: int) -> bool: """Whether the canonical form of a nested node built from the code points `a` and `b` is its own canonical form. `shape` picks the nesting.""" regular = _load("regular") lo, hi = sorted((int(a), int(b))) chars = {"op": "chars", "ranges": [[hi, hi], [lo, hi]]} letter = {"op": "literal", "codes": [lo]} nodes = [ {"op": "concat", "args": [letter, {"op": "concat", "args": [chars, {"op": "epsilon"}]}]}, {"op": "union", "args": [chars, {"op": "union", "args": [letter, chars]}]}, {"op": "inter", "args": [{"op": "repeat", "arg": chars, "min": 0, "max": None}, {"op": "complement", "arg": letter}]}, {"op": "concat", "args": [letter, {"op": "empty"}]}, ] once = regular.canonical(nodes[int(shape) % len(nodes)]) return regular.canonical(once) == once def separating_status(a: int, b: int) -> str: """`member` or `none`: whether some one-character string lies in the code points `a` to `a + 3` and outside `b` to `b + 10`.""" found = _load("regular").find_member(ALL, inside=[_span(a, 3)], outside=[_span(b, 10)]) return found.status def span_inside(a: int, b: int) -> str: """`none` when every whole number from `a` to `a + 3` lies in `b` to `b + 10`, else `member`, by arithmetic on the endpoints.""" return "none" if int(b) <= int(a) and int(a) + 3 <= int(b) + 10 else "member" def member_found_separates(a: int, b: int) -> bool: """Whether the string the solver returns for the question of `separating_status`, when it returns one, is one character in `a` to `a + 3` and outside `b` to `b + 10`.""" found = _load("regular").find_member(ALL, inside=[_span(a, 3)], outside=[_span(b, 10)]) if found.status != "member": return found.status == "none" code = ord(found.member) if len(found.member) == 1 else -1 return int(a) <= code <= int(a) + 3 and not int(b) <= code <= int(b) + 10 # ---- mathema._validators ---------------------------------------------- _SLUG = re.compile(r"[a-z0-9][a-z0-9-]*$") _SLUG_FIXED = re.compile(r"[a-z0-9][a-z0-9-]*\Z") class _Lookalike: def fullmatch(self, text): return text == "ok" _FAKE = _Lookalike() def _refuses_dollar(text): if not _SLUG.match(text): raise ValueError(text) return text def _refuses_fixed(text): if _SLUG_FIXED.fullmatch(text) is None: raise ValueError(text) return text def _predicate_search(text): return bool(_SLUG.search(text)) def _predicate_negated(text): return _SLUG_FIXED.fullmatch(text) is None def _inline(text): return re.fullmatch(r"[a-z]+", text, re.IGNORECASE) is not None def _by_lookalike(text): return bool(_FAKE.fullmatch(text)) def _shadowed(re): # noqa: A002 return bool(re.fullmatch("a", re)) def _strips(text): return bool(_SLUG.fullmatch(text.strip())) def _lowers(text): if not _SLUG.match(text): raise ValueError(text) return text.lower() VALIDATORS = (_refuses_dollar, _refuses_fixed, _predicate_search, _predicate_negated, _inline) NOT_VALIDATORS = (_by_lookalike, _shadowed, _strips, _lowers) TEXTS = ("", "a", "a-b", "ab\n", "-a", "A", "a b", "9", "a\n\n", "Zz") def reading_agrees_with_the_function(which: int, text_index: int) -> bool: """Whether the validator read from the function `VALIDATORS[which]` accepts `TEXTS[text_index]` exactly when the function itself does: a refusing validator returns it, a predicate returns True (False for a negated one).""" fn, text = VALIDATORS[int(which)], TEXTS[int(text_index)] read = _load("_validators").read_validator(fn) if isinstance(read, str): return False matched = read.accepts(text) is not None try: returned = fn(text) except ValueError: return read.raises is ValueError and not matched if read.raises is not None: return matched and returned == text return returned is (matched != read.negated) def function_accepts(which: int, text_index: int) -> bool: """Whether the function `VALIDATORS[which]` accepts `TEXTS[text_index]`: returns it, or returns True.""" try: returned = VALIDATORS[int(which)](TEXTS[int(text_index)]) except ValueError: return False return returned is not False def is_declined(which: int) -> bool: """Whether `NOT_VALIDATORS[which]` is declined, with a reason.""" return isinstance(_load("_validators").read_validator(NOT_VALIDATORS[int(which)]), str) # ---- mathema.domain_relations ----------------------------------------- RELATIONS = ("subset", "not subset", "=", "!=", "disjoint") def interval_statement(relation: int, a: int, b: int, c: int, d: int) -> str: """`[a, b] <relation> [c, d]`, the equalities with the type clause that marks a bracket pair a domain.""" word = RELATIONS[int(relation)] clause = " : real" if word in ("=", "!=") else "" return f"[{int(a)}, {int(b)}]{clause} {word} [{int(c)}, {int(d)}]{clause}" def interval_verdict(relation: int, a: int, b: int, c: int, d: int) -> str: """The verdict `mathema.domain_relations` gives the statement.""" from mathema import domain_relations stated = domain_relations.parse(interval_statement(relation, a, b, c, d)) return domain_relations.decide(stated).verdict def interval_truth(relation: int, a: int, b: int, c: int, d: int) -> str: """`proven` or `falsified` for the same statement, by testing every quarter step from -1 to 8 against the endpoints: between whole endpoints that settles every relation of two closed intervals.""" points = [Fraction(n, 4) for n in range(-4, 33)] left = {p for p in points if a <= p <= b} right = {p for p in points if c <= p <= d} holds = {"subset": left <= right, "not subset": not left <= right, "=": left == right, "!=": left != right, "disjoint": not left & right}[RELATIONS[int(relation)]] return "proven" if holds else "falsified" def interval_text_is_stable(relation: int, a: int, b: int, c: int, d: int) -> bool: """Whether the canonical text of the statement reads back as the same canonical text.""" from mathema import domain_relations once = domain_relations.parse(interval_statement(relation, a, b, c, d)).text() return domain_relations.parse(once).text() == once def agreement_stated(compared: int, disagreed: int, skipped: int) -> bool: """A comparison agreed on every value when at least one value was compared, none disagreed and none was skipped.""" return int(compared) > 0 and int(disagreed) == 0 and int(skipped) == 0 def record_agreed(compared: int, disagreed: int, skipped: int) -> bool: """What `domain_relations.agreed_on_every_value` says of an assumption whose corroboration record has these counts.""" from mathema import domain_relations compared, disagreed, skipped = int(compared), int(disagreed), int(skipped) return domain_relations.agreed_on_every_value({"statement": "A", "status": "assumed", "corroboration": { "values drawn": compared + skipped, "values compared": compared, "values skipped": skipped, "disagreed": disagreed}}) def outline_entry_is_bare(compared: int, disagreed: int, skipped: int) -> bool: """Whether the proof outline states an assumption whose corroboration record has these counts as `A (assumed)` and nothing more.""" from mathema import domain_relations compared, disagreed, skipped = int(compared), int(disagreed), int(skipped) entry = domain_relations.assumption_entry_text({"statement": "A", "status": "assumed", "corroboration": { "values drawn": compared + skipped, "values compared": compared, "values skipped": skipped, "disagreed": disagreed}}) return entry == "A (assumed)" def shortfall_is_empty(compared: int, disagreed: int, skipped: int) -> bool: """Whether `domain_relations.corroboration_shortfall` has nothing to say of these counts.""" from mathema import domain_relations return domain_relations.corroboration_shortfall( int(compared), int(disagreed), int(skipped)) == "" - claims/smt.claims.yaml (1415 bytes)
claims.smt_support.literal_hash: claims: - name: the_hash_never_reads_the_source statement: 'for text in L[ascii], note in L[ascii], f(text, note) == f(text, "")' - name: two_texts_are_two_hashes statement: 'let other be {"", "a", "b", "ab", "ba"}, for text in {"", "a", "b", "ab", "ba"}, assuming text != other, f(text, "") != f(other, "")' claims.smt_support.canonical_twice_is_canonical: claims: - name: canonical_is_idempotent statement: 'for a in [32, 126] subset Z, b in [32, 126] subset Z, shape in {0, 1, 2, 3}, f(a, b, shape) == True' claims.smt_support.separating_status: claims: - name: no_member_exactly_when_the_span_is_inside statement: 'let inside = claims.smt_support.span_inside, for a in [48, 68] subset Z, b in [48, 68] subset Z, f(a, b) == inside(a, b)' claims.smt_support.member_found_separates: claims: - name: a_member_found_is_inside_and_outside statement: 'for a in [48, 68] subset Z, b in [48, 68] subset Z, f(a, b) == True' claims.smt_support.reading_agrees_with_the_function: claims: - name: the_reading_accepts_what_the_function_accepts statement: 'for which in {0, 1, 2, 3, 4}, text_index in {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, f(which, text_index) == True' claims.smt_support.is_declined: claims: - name: a_function_that_is_no_validator_is_declined statement: 'for which in {0, 1, 2, 3}, f(which) == True' - CODE_OF_CONDUCT.md (3384 bytes)
# Code of Conduct ## Our pledge We as members, contributors, and maintainers pledge to make participation in this project a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. ## Our standards Examples of behaviour that contributes to a positive environment: - Demonstrating empathy and kindness toward other people - Being respectful of differing opinions, viewpoints, and experiences - Giving and gracefully accepting constructive feedback - Accepting responsibility and apologising to those affected by our mistakes, and learning from the experience - Focusing on what is best for the community, not just for ourselves Examples of unacceptable behaviour: - The use of sexualised language or imagery, and sexual attention or advances of any kind - Trolling, insulting or derogatory comments, and personal or political attacks - Public or private harassment - Publishing others' private information, such as a physical or email address, without their explicit permission - Other conduct which could reasonably be considered inappropriate in a professional setting ## Enforcement responsibilities Project maintainers are responsible for clarifying and enforcing these standards and will take appropriate and fair corrective action in response to any behaviour they deem inappropriate, threatening, offensive, or harmful. Maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. ## Scope This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the project in public spaces. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behaviour may be reported to the maintainers at **[email protected]**. All complaints will be reviewed and investigated promptly and fairly. All maintainers are obligated to respect the privacy and security of the reporter of any incident. ## Enforcement guidelines Maintainers will follow these guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: 1. **Correction.** A private, written warning, providing clarity around the nature of the violation and an explanation of why the behaviour was inappropriate. A public apology may be requested. 2. **Warning.** A warning with consequences for continued behaviour, including a period of no interaction with the people involved. 3. **Temporary ban.** A temporary ban from any sort of interaction or public communication with the community. 4. **Permanent ban.** A permanent ban from any sort of public interaction within the community. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org/), version 2.1, available at <https://www.contributor-covenant.org/version/2/1/code_of_conduct.html>.
- CONTRIBUTING.md (3267 bytes)
# Contributing ## Before your first contribution You'll need to agree to the [Contributor License Agreement](CLA.md) before a contribution from you can be merged. There is no separate signing step to do in advance: by submitting a Contribution, you accept the terms of CLA.md. For your first pull request, please confirm in a comment that you have read and agree to the terms of CLA.md. This confirmation is recorded with the pull request. ## Process 1. Open an issue first for anything beyond a small, obvious fix, so the approach can be discussed before you put time into an implementation. 2. Fork the repository and work on a branch. In a virtual environment, `pip install -e '.[test]'` installs mathema plus everything needed to run the test suite. 3. Make sure `python -m pytest`, `ruff check .`, and `mypy mathema` all pass locally before opening a pull request. Use `python -m pytest`, not bare `pytest`: `tests/` has no `__init__.py` and some test modules import from a sibling as `from tests.test_x import y`, which only resolves when the repository root is on `sys.path`, and the `-m` form puts it there. For a faster loop, `python -m pytest -n 4` runs the suite in parallel. The `dev` extra (build, twine, pre-commit, ruff, mypy) needs Python 3.11 or later; mathema itself supports and is tested on 3.10. One thing worth knowing before you trust a red result: proof attempts are capped on the wall clock, so anything that slows the machine (heavy load, a second test run, coverage tracing) can turn a `proven` into a `holds` and fail an assertion about the verdict rather than about the code. Re-run a failing verdict assertion on its own before believing it, and check `Probe.meta["mathema.timeout"]`, which records when a cap fired. 4. Every new claim family, probe, or derive-route capability needs test coverage exercising both the case where it applies and the case where it correctly declines to. 5. Open the pull request against `main`, describing what changed and why. Reference the issue it addresses, if any. ## What's most useful to contribute - **New claim families**: a built-in algebraic law (like the existing commutativity/idempotence/monotonicity checks) that applies broadly enough to be worth probing for automatically, not just something specific to one function. - **Reduced counterexamples**: when a probe falsifies a claim, a smaller or simpler counterexample than the one first found is a real improvement to the record, not a cosmetic one. - **Specification clarifications**: mathema implements [claim-driven-development](https://github.com/aaronbyrnephd/claim-driven-development), a separate, independently maintained spec. If you find a place where mathema's own output doesn't match what the spec actually says (or where the spec itself is ambiguous), an issue describing the mismatch precisely, quoting both sides, is genuinely useful, whether the fix belongs in mathema or upstream in the spec. ## Reporting a bug See [SECURITY.md](SECURITY.md) for a security vulnerability. For anything else, `mathema describe --issue` generates a structured failure report you can attach to a new GitHub issue; see its `--help` output for usage.
- docs/agent-setup.md (5448 bytes)
# Set up mathema for a coding agent This guide registers mathema's MCP server with the agent tool you use, vendors the skills that teach the agent the claim loop, and puts in place the two controls that stay with you: a PIN and a policy. It assumes you have read [Working with coding agents](agents.md), which says what an agent can and cannot do here. The commands on this page write to your tool's configuration, fetch from the network or read a PIN from your terminal, so they are shown rather than run by the test suite behind the other pages. Each was run by hand while this page was written; the server blocks were checked by starting `mathema mcp serve --root <project>` from a project environment and listing its tools over stdio. ## 1. Install the extra <!-- checked by hand --> ```bash pip install "mathema[mcp]" ``` The extra brings the MCP SDK. Without it, `mathema mcp serve` prints the install hint and exits 2. ## 2. Register the server The server runs on stdio: your tool starts `mathema mcp serve` as a subprocess and talks to it over its standard input and output. Two things matter in the configuration. Run it from the project's own environment, because the tools import your code to check it, so the `mathema` that serves must be the one installed beside your project's dependencies. And give both paths in full, since the tool's working directory is not your project's. **Claude Code** reads `.mcp.json` at the project root; commit it so the team shares one configuration. <!-- checked by hand --> ```json { "mcpServers": { "mathema": { "type": "stdio", "command": "/path/to/project/.venv/bin/mathema", "args": ["mcp", "serve", "--root", "/path/to/project"] } } } ``` **Cursor** reads `.cursor/mcp.json` in the project, or `~/.cursor/mcp.json` for every project. **Claude Desktop** reads `~/Library/Application Support/Claude/claude_desktop_config.json` on macOS and `%APPDATA%\Claude\claude_desktop_config.json` on Windows. Both take the same block without the `type` field: <!-- checked by hand --> ```json { "mcpServers": { "mathema": { "command": "/path/to/project/.venv/bin/mathema", "args": ["mcp", "serve", "--root", "/path/to/project"] } } } ``` In a project managed with uv, `"command": "uv"` with `"args": ["run", "--directory", "/path/to/project", "mathema", "mcp", "serve", "--root", "/path/to/project"]` does the same through uv. Once the tool restarts, its server list shows `mathema` with fifteen tools, three resources and three prompts. [The MCP interface](modes/mcp.md) lists each one. None of them accepts a verdict from the agent, and there is no accept tool: the deciding stays in the terminal, with you. ## 3. Vendor the skills <!-- checked by hand --> ```bash mathema init --agents claude ``` `init --agents` copies the [mathema-agents](https://github.com/tetrionlabs/mathema-agents) skills, the agent-facing procedures for writing and checking claims, into the place your tool reads them, plus the one adapter file that tool wants. Name the tool (`claude`, `codex`, `gemini`, `cursor`, `copilot`, `windsurf`, `cline`) or let bare `--agents` detect the one your project already uses. This is the one command in mathema that reaches the network, through your own `git`, and only when you run it. A file already present is left as it is, so a re-run is safe. [`mathema init`](modes/init.md#the-agent-skills-agents) has the table of where each tool's files land. ## 4. Set a PIN the agent does not know <!-- checked by hand --> ```bash mathema pin set ``` The PIN is read from the controlling terminal only, never from a pipe or a subprocess, which is how an agent runs commands. `--yes` skips the y/N prompt on `mathema accept` and never the PIN. It is stored salted and hashed in `~/.config/mathema/auth.yaml` by default (`XDG_CONFIG_HOME` moves it), outside the project, and every acceptance made with it carries the credential's key id in the record. `mathema pin status` prints the method and that key id; you need it for the next step. ## 5. Commit a policy An agent with a shell could remove `auth.yaml` and set a PIN of its own. That changes the key id, so the defence is a committed policy naming the key ids you accept, in `.mathema/meta/policy.yaml`: <!-- checked by hand --> ```yaml acceptance: require_verification: true keys: [a3f2c1] ``` With the policy committed, `mathema verify` fails on any acceptance that was not made with one of those keys, at write time and again on every sweep, so a signature the agent made for itself fails CI rather than slipping through. Protect `.mathema/meta/` and `.mathema/verified/` with your forge's code-owner review, so the policy itself changes only with a person's approval. [`mathema pin`](modes/pin.md#project-policy) has the full policy file. ## 6. What happens from here The agent proposes claims and checks them with `adjudicate_target`, reads every verdict and counterexample, sees what is waiting on a person in `pending_decisions`, and may lock a function it has finished with `lock_target`. What it cannot do is decide what a verdict means: accepting evidence as sufficient, owning a risk, recording that a falsification was a wrong claim, or unlocking a function all go through `mathema accept` and `mathema unlock` at your terminal, behind the PIN. The table on [Working with coding agents](agents.md#what-an-agent-can-and-cannot-do) has the full division. - docs/agents.md (4935 bytes)
# Working with coding agents mathema does not need an agent, and nothing in the core depends on one. This section is for people who pair with a coding agent (Claude Code, Cursor and the like) and want the agent to use mathema without being able to decide on its own what counts as correct. The division of labour is simple to state: agents propose, mathema adjudicates, people accept. An agent can write claims, run checks and read every verdict and counterexample, which is most of the loop, but no verdict ever comes from the agent, and no decision about what a verdict means for the project is the agent's to make. That is what lets you hand an agent the keyboard without handing it the definition of correct. ## What an agent can and cannot do | An agent can | Only a person can | |---|---| | propose claims and check them against the real function | accept evidence as sufficient, or own a residual risk | | read verdicts, counterexamples and the human-decision queue | record that a falsification was a wrong claim rather than a bug | | lock a function it has finished | unlock a locked function | | edit claims in docstrings and claims files, and adopt suggested claims (`mathema claims KEY --adopt NAME`) | accept an edited claim over the one already verified | The last row is the one people ask about. When a claim that already has a verified record is edited, weakened or narrowed, the verified version keeps being checked and the sweep reports the claim as re-authored, until a person accepts the change with `mathema accept KEY CLAIM --as superseded`. A claim deleted from every authoring surface is restored from its verified record for the same reason. An agent can propose a weaker claim; it cannot make the record forget the stronger one. ## Set a PIN the agent does not know Every acceptance and every unlock asks for a y/N confirmation, and an agent with a shell can answer that. What it cannot answer is a PIN it does not know. Set one yourself, in your own terminal: ```bash mathema pin set ``` The PIN is read from the controlling terminal only, never from a pipe or a subprocess, which is how an agent runs commands, and `--yes` skips the y/N prompt but never the PIN. It is stored salted and hashed in `~/.config/mathema/auth.yaml`, outside the project, and every acceptance made with it carries its key id in the record. Without a PIN, `mathema accept --yes` works for anyone with a shell, an agent included. The name on an acceptance (`--by`, which defaults to your git `user.name`) is free text for the same reason, so when it matters who decided, read the record's `verified_by` key id rather than the name. An agent with unrestricted shell access could still delete that file and set a PIN of its own. That changes the key id, so the defence is to commit a policy naming the key ids you accept: ```yaml # .mathema/meta/policy.yaml acceptance: require_verification: true keys: [a3f2c1] ``` With the policy committed, `mathema verify` fails on any acceptance that was not made with one of those keys, so a signature the agent made for itself fails CI rather than slipping through. Protect `.mathema/meta/` (and `.mathema/verified/`) with your forge's code-owner review so the policy itself changes only with a person's approval. [mathema pin](modes/pin.md) has the details, including rotation. None of this is a wall against an agent determined to subvert it, and it is not meant to be one: it is a tripwire. The normal loop cannot cross it, and every way around it leaves a trace in the record or the diff. ## Claims an agent writes A claim can bind a function with `let` (`let g = json.dumps`). That is the same as importing the library and calling the function in your own code: the function runs. mathema refuses a binding that reaches the system (`os`, `sys`, `subprocess`, `builtins`, `shutil`, `socket`, `importlib` and others), and a binding into third-party code whose effects mathema cannot establish runs with a warning on the claim's line and in the record. Review a `let` in an agent's claim as you would an import in its code. [Security and execution](security.md) has the details. ## Giving an agent the tools Two pieces, both optional: - **The MCP server.** `mathema mcp serve` exposes the checking tools (adjudicate a function, parse a claim, read the decision queue, lock) over MCP, and deliberately none of the deciding ones. Register it as a stdio server in your agent's MCP settings, run from the project's own environment. [The MCP interface](modes/mcp.md) lists every tool. - **Agent skills.** `mathema init --agents` vendors skills and per-tool instructions from the public [mathema-agents](https://github.com/tetrionlabs/mathema-agents) repository, which teach an agent to run the claim loop properly rather than guess at it. It is the one command in mathema that fetches anything, and only when you run it. See [mathema init](modes/init.md).
- docs/api.md (2465 bytes)
# API reference Generated directly from docstrings, so it never drifts from what the code actually does. ## `mathema` ::: mathema options: members: - check - analyze - track_claims - Record - resolve - resolve_function - gate - verify_project ## `mathema.reason_codes` ::: mathema.reason_codes options: members: - ReasonCode - Category - ClaimReasonCode - LoopReason - BranchReason - blocked_code - describe_code - claim_reason_code ## `mathema.conjecture` ::: mathema.conjecture options: members: - claim - check_conjectures - Conjecture ## `mathema.symbolic` ::: mathema.symbolic options: members: - lift - lift_conditioned - try_prove - try_prove_raises - Lifted - ProofResult ## `mathema.inventory` ::: mathema.inventory options: members: - is_pure_enough - purity_reason - claim_floor - derivability_report - structural_complexity - scope_dependencies - mutated_globals - typing_info - wrapped_target - docstring_quality - docs_checklist - is_test_covered - read_test_coverage - suggest_coverage_command ## `mathema.types` ::: mathema.types options: members: - Probability - Positive - Nonnegative - Shape ## `mathema.runtime_types` ::: mathema.runtime_types options: members: - RuntimeTypeAdapter - Detection - AbstractVec - AbstractMat - AbstractTable - RuntimeType - adapters - detect_parameters - realise - observe ## `mathema.identity` ::: mathema.identity options: members: - form_hash ## `mathema.compiled` ::: mathema.compiled options: members: - CompiledForm - compile_form - numeric_check ## `mathema.forms` ::: mathema.forms options: members: - closed_forms - substituted_forms - executable_forms - Form - SubstitutedForm - Substitution - register_substitution ## `mathema.targets` ::: mathema.targets options: members: - resolve - resolve_function - Target - TargetError - docs/authoring.md (44312 bytes)
# Authoring claims Four surfaces, one precedence order (lowest to highest, a same-named claim from a higher surface overrides a lower one), and one grammar they all share. ## The claim grammar Claims are written over the generic function name `f` and the function's own parameter names, in a typeable superset of ordinary math: ``` f(-x) == -f(x) # odd f(x)^2 >= 0 # ^ is power; == / <= / >= are the relations f(x) ≤ f(y) # Unicode ≤ ≥ − · × π accepted, normalized for x in [0, 1], f(x) <= 1 # domain quantifier raises(f(x), ValueError) # partiality: asserts the call raises f(x) == g(x) # relate two implementations (funcs={"g": other_fn}) ``` Shorthand: `|x|`/`||x||`/`⌊x⌋`/`⌈x⌉` for `abs`/`norm`/`floor`/`ceil`, the norm's order a subscript on the closing bars (`||x||_1`, `||x||_inf`), each wrapping any expression, so `|x + y - f(x, y)|` is the absolute value of the whole difference; `!=`/`≈` as their own relations. Every claim renders to LaTeX exactly (`mathema.grammar.to_latex`), going *through* sympy so it's mathematically faithful, not typographically literal. A domain quantifier's range only ever adds a *sign assumption* (`positive`/`nonnegative`) for the derive route's proof, never a substitution, `for x in [0, 5], ...` proves things true for *every* `x` in that range, it doesn't pick one. The one exception is a **degenerate, single-point range** (`for c in [0, 0], ...`, lower bound equal to upper bound): that genuinely does pin `c` to the literal `0` before the claim is decided, since there's only one value left to assume anything about. To check a claim at any *other* specific value, pass it as a literal argument to `f(...)` directly (`f(a, b, 0)`) rather than declaring a domain for it, ordinary symbolic substitution, unrelated to the domain mechanism. Three more forms, **derive route only**, that turn ordinary claims into calculus, PDE, and (mechanically) SDE claims: ``` d(f(t, x), t) == d(f(t, x), x, x) # partial derivatives; this is the heat equation lim(f(x)/x, x, 0) == 1 # limits (point: a constant, or oo / -oo) integrate(f(x, mu, sigma), x, -oo, oo) == 1 # definite/indefinite integrals Sum(f(i), i, 0, n) == n*(n+1)/2 # indexed sums/products ``` Shorter spellings for a single-parameter derivative, when there's no variable to name at all: `d(<expr>)` (the argument's own single free name is inferred) and prime notation, `f'(x)`/`f''(x)`/... (one apostrophe per differentiation): ``` d(f(x)) == 2*x # f has one parameter, x, same as d(f(x), x) f'(x) == 2*x # same claim again f''(x) == 2 # d(f(x), x, x) ``` The traditional `df/dx` fraction spelling is also accepted, but only *inside* a `d(...)`/`∂(...)` call (`d` and `∂` are interchangeable throughout this sugar), where the intent (differentiate) is unambiguous even though the variable isn't; `d(f(x)/dx)` is the same claim once more. A bare, unscoped `df/dx` anywhere else in a law is never read this way: at the text level it's ordinary division by a variable that happens to be named `dx`, with no calling context to disambiguate it. The variable guessed from a fraction's denominator is checked against the function's own real parameters once they're known. A genuine collision (`gibbs_free_energy(dh, t, ds)`, a real parameter literally named `dh`) is `skipped:misspecified` rather than silently guessed wrong, with a note naming the unambiguous `d(expr, h)` form to use instead. A `∂`-marked denominator name is never ambiguous this way (`∂` can't appear in a real Python identifier at all), so `∂(f(dh,t,ds)/∂h) == -ds` never needs that check. A mixed or higher-order denominator concatenates one marker per variable, each with its own optional exponent (superscript digits or `^<n>`, matching how `\frac{\partial^3 f}{\partial x^2 \partial y}` is conventionally written): ``` d(f(x,y)/dx^2dy) == 0 # d(f(x,y), x, x, y), order 2 in x, order 1 in y ∂(f(x,y)/∂x²∂y) == 0 # the same claim, curly and superscript ``` The call's own opening symbol may carry a restated total order (`d^3(...)`/`d³(...)`), purely decorative unless it disagrees with what the denominator's own exponents sum to, in which case the whole call is left unexpanded as a likely typo: ``` d^3(f(x,y)/dx^2dy) == 0 # 2 + 1 == 3, consistent ``` An evaluation marker, `@{v=val, ...}` (or the word `at` instead of `@`, either with optional whitespace around it), states a claim at a specific point rather than across a whole domain: `d(<expr>, <vars...>)@{v=val, ...}` differentiates first, then substitutes each named variable (an extremum/critical-point claim; "the derivative is exactly zero here", not just "nonnegative everywhere"). Composes with every other `d(...)` spelling above: ``` d(f(v0, theta, g), theta)@{theta=pi/4} == 0 # range is maximized at 45° d(f(v0, theta, g)/dtheta) at {theta=pi/4} == 0 # same claim again d(f(x)/dx^2)@{x=1} == 6 # differentiates twice, then substitutes f'(x) at {x=1} == 3 # prime notation, one free variable ``` Prime notation takes its variable from the call's single free name, so it only reads on a one-variable call. `f'(v0, theta, g)` has three, and `claim()` refuses it with an `InvalidConjecture` that names the explicit spelling, `d(f(v0, theta, g), <var>)`. `integrate(<expr>, <var>)|_{a}^{b}` (matching LaTeX's own `\big|_a^b` convention) is pure sugar for the already-existing bounded 4-argument form. A bound needs braces only when it contains its own space or comma, a plain token, however long, doesn't: ``` integrate(f(x, mu, sigma), x)|_{-oo}^{oo} == 1 # same as the 4-arg form above integrate(f(x), x)|_0^oo == oo # a bound needs no braces on its own ``` `∫` and the word `integral` are synonyms for `integrate`, and a bracket-free form drops the parens entirely, chaining one bound-bar per differential (each variable may itself be omitted when the expression has exactly one free name): ``` integral f(x)|_0^1 == 1/2 # var omitted, no parens integral f(x,y) dx|_0^1 dy|_0^2 == 1 # sympy's own multi-bound integrate() ``` A bracket-free form of `lim` drops the parens: `lim f(x), x -> a`, or `lim f(x) as x -> a` ("as" reads the way this is conventionally spoken, and is a pure synonym for the comma). Unlike `d`/`integrate`, `lim`'s variable is always named explicitly; `lim f(x) -> a` reads ambiguously without it, so that shorter spelling isn't accepted. `raises(...)` only ever proves an *explicit* `raise` reachable through a domain-conditioned branch, never an exception implicit in an arithmetic operation (`1/(1+r)` genuinely raising `ZeroDivisionError` at `r = -1`, with no `if` guard anywhere). It also needs the domain declared on the **guard's own parameter**, not just a literal call argument that happens to trigger it, branch pruning evaluates the guard condition against the function's own declared parameter domains, before any `f(...)` call-site substitution even happens: <!-- example: raises-guard run --> ```python def f(a, b, c): if a == 0: raise ValueError("a must be nonzero") return b / a + c ``` <!-- example: raises-guard verdicts fn=f --> ``` raises(f(a, b, 0), ValueError) # falsified, a's own domain isn't declared, so a sampled a != 0 returns for a in [0, 0], raises(f(a, b, c), ValueError) # proven ``` ## Set-notation domains: exclusion, union, type refinement, missing values A quantifier binding leans on ordinary set notation, and accepts several spellings of each operator, all canonicalize to the same domain internally, so pick whichever reads best: ``` for x in [0, 1], ... # membership: in / ∈ / \in / \elem for x ∈ (-oo, 0]: ... # same operator, different spelling ``` **Exclusion** (`\` set-minus, or the `exclude={...}` keyword form) removes specific points; a pole, say, from an otherwise ordinary interval: ``` for r in [-1, 1] \ {1}, ... # excludes the single point r=1 for r in [-1, 1], exclude={1}, ... # same thing, keyword form ``` **Union** (`|` or `∪`) combines two or more pieces into one domain, for a genuinely piecewise range: ``` for x in [-10, -1) | (1, 10], ... # two disjoint intervals for x in [-10, -1) | (1, 10] \ {5}, ... # a union, with a point excluded from it ``` **Type refinement** (`⊂`, or the text spellings `\sub`/`\subset`) narrows a domain to integers or naturals; omitted, a real (`R`) domain is assumed, matching how an unrestricted parameter already needs no domain entry at all: ``` for n in [0, 10] ⊂ Z, ... # a bounded integer domain for n in Z, ... # bare, unbounded, still a stated type ``` ### Missing values A value can be not there in two ways: **absent** (`None`, the object itself) and **missing** (a hole in a slot: `nan`, a `None` element, `pd.NA`). A domain says which it admits (`: float|missing`, `\ {absent}`), and a binding without a type clause takes that from the annotation. What a function does with each is its policy, stated as a claim (`missing(f, x) propagates`). [Missing values](missing-values.md) is the full account. The statement shows what the domain admits: <!-- example: missing-default run --> ```python import math import mathema def root(x: float) -> float: return math.sqrt(x) row = mathema.check(root, claims=["for x in [0, 1], f(x) >= 0"]).probes[0] print(row.statement) print(row.meta["mathema.missing"]["admitted"]) ``` <!-- example: missing-default output --> ```text for x in [0.0, 1.0] : float|missing, f(x) >= 0 {'x': {'absent': False, 'missing': ['nan']}} ``` The canonical text lists what the domain admits in the order `absent`, `missing`, then member words, fused onto the type in ASCII and written as a union in unicode. It shows an exclusion only when the exclusion removes something the annotation would admit and no type clause says so already. Every spelling from an earlier release (`[0.0, 1.0]:float|missing`, `∪ {∅}`, `\ {∅}`) still reads and comes back in this form: <!-- example: missing-spelling run inline --> ```python from mathema import claim from mathema.spec import render_claim_text render_claim_text(claim("for x in [0, 1] ⊂ ℝ ∪ {None, ∅}, f(x) >= 0"), unicode=False) # 'for x in [0.0, 1.0] : float|absent|missing, f(x) >= 0' render_claim_text(claim("for x in [0, 1] : float|None, f(x) >= 0"), unicode=True) # '∀ x ∈ [0.0, 1.0] ⊂ ℝ ∪ {absent}, f(x) ≥ 0' render_claim_text(claim("for xs in [0, 1]^n : float|missing, f(xs) >= 0"), unicode=False) # 'for xs in ([0.0, 1.0] | {missing})^n : float, f(xs) >= 0' ``` `enforce_domain()` checks a sequence argument element by element against its declared domain, including this missing-value policy; an out-of-bounds or unexpectedly-missing element is rejected the same way a scalar argument outside its own domain already is. `enforce_dimensions()` (see [shape markers](#shape-markers-and-their-shorthand)) rejects a wrong shape the same way. Both decorators declare what they make true: one `excluded_outside_domain(p)` claim per guarded parameter, proven by construction. The author can state the same claim with the `excluding` keyword. ### Language domains A function over text has a domain too: not an interval of numbers but a language, a set of strings. `L[<name>]` quantifies over one: ``` for s in L[unicode], f(f(s)) == f(s) for s in L[unicode], len(f(s)) <= len(s) for s in L[digit] \ {""}, f(s + "0") == 10 * f(s) ``` The names come from the `mathema-language` package (`pip install "mathema[language]"`), which follows Python's own reading of each alphabet: `ascii` (`str.isascii`), `latin-1` (what the codec encodes), `unicode` (every `str`, lone surrogates included), `printable`, `digit`, `alpha`, `alnum`, `identifier` (`str.isidentifier`), `json` (what `json.loads` accepts) and more; [Language domains](language.md) lists them and shows how to register your own. An alphabet language is a Kleene star: it contains the empty string, and `L[ascii] \ {""}` is the way to exclude it. Union with a finite set of members, and what the domain admits, read exactly as they do for a numeric domain: `L[alnum] ∪ {"n/a"}`. A length bound goes inside the brackets, `L[ascii, len <= 80]`, `L[unicode, len > 20]` or `L[unicode, len in [1, 80]]`, lengths counted in code points as Python's `len` counts them; without one, a very long input is a hazard the probe visits on its own. A name mathema cannot resolve is refused with the vocabulary and the package that provides one; nothing is ever read as a wider language than the one written. Think of the function as a map between languages, and the claims write themselves. A normaliser is idempotent (`collapse` above) and a contraction (`len(f(s)) <= len(s)`); an escaper never shortens (`len(f(s)) >= len(s)`); a parser and its renderer are a section and a retraction, stated with a `let`-bound inverse: ``` let u = html.unescape, for s in L[unicode], u(f(s)) == s let dump = json.dumps, for s in L[json], f(dump(f(s))) == f(s) ``` A `let` binding imports the function it names and calls it, the same as importing it in your own code. For third-party code whose effects mathema cannot establish, the claim's line carries a warning saying so, and a binding that reaches the system (`os`, `subprocess` and the like) is refused; see [Security and execution](security.md). A parser of decimal digits is a homomorphism from concatenation to arithmetic, which is what `f(s + "0") == 10 * f(s)` says. Where a function raises inside the language it was declared over, the claim is falsified with that member as the witness, the same rule a numeric domain follows; a parser that rejects some of the language is declared over the language it accepts, or its raising region is stated as its own `raises(...)` claim. The probe samples members: the language's own hazards first (the empty string, whitespace, NUL and the other control code points, the alphabet's boundary, a long member, a lone surrogate, a byte-order mark), then random members, and it never draws a value outside the language. Every record states what a language resolved to (`meta["mathema.language"]`: the name, its source, its level and kind, and its persisted form), and the statement carries what the domain admits, as usual. The derive route has no reading of a string, so it declines with the reason rather than proving real-only facts about a symbol standing in for one; a finite language (an enumeration a package registers) is the exception, swept point by point and proven or falsified with the member. `is_language_defined(text)` over a language holds each member to an answer (a return or an exit status) and each non-member to a refusal; over a plain string it fuzzes the parameter, reads exits and deliberate or guarded raises as the f - docs/case-studies.md (10474 bytes)
# Case studies: real formulae, real verdicts Two worked examples on formulae you can look up, taken from openly licensed references. Every claim on this page is in the claim lexicon and is executed by the test suite, so what follows is what mathema actually returns, including where it declines. The point of both is the same: the interesting result is rarely one claim. It is what a small set of claims says together, and what the disagreements between them tell you. ## Put-call parity and the Greeks An option's price is not a simple formula. The Black-Scholes call involves a logarithm, a square root, an exponential and the normal CDF, which is itself an error function. Put-call parity says that however complicated each leg is, the difference between a call and a put on the same strike collapses to something elementary: C - P = S - K*exp(-r*T) No volatility term survives. That is a strong statement about a function whose body mentions volatility five times, and it is exactly the kind of claim worth checking against the implementation rather than against a textbook. <!-- example: parity verdicts fn=mathema.lexicon:put_call_parity_gap expect=proven --> ``` for s in [50,150], k in [50,150], r in [0.0,0.1], t in [0.1,2], sigma in [0.05,0.8], f(s,k,r,t,sigma) == s - k*exp(-r*t) ``` On `put_call_parity_gap` that is **proven**, not sampled. The two legs, with all their error functions, cancel symbolically. ### The Greeks are partial derivatives, so state them as partial derivatives Delta is the sensitivity of the price to the spot, which is to say it is the partial derivative of the price in `s`. The grammar says that directly: <!-- example: delta-lower verdicts fn=mathema.lexicon:black_scholes_call expect=proven --> ``` for s in [50,150], k in [50,150], r in [0.0,0.1], t in [0.1,2], sigma in [0.05,0.8], ∂(f(s,k,r,t,sigma), s) >= 0 ``` <!-- example: delta-upper verdicts fn=mathema.lexicon:black_scholes_call expect=proven --> ``` for s in [50,150], k in [50,150], r in [0.0,0.1], t in [0.1,2], sigma in [0.05,0.8], ∂(f(s,k,r,t,sigma), s) <= 1 ``` Both are **proven** against `black_scholes_call`. Together they establish the textbook fact that a call's delta lies in `[0, 1]`, and they establish it from the code you are shipping rather than from the paper the code was meant to implement. Nothing was differentiated by hand: the claim names the partial derivative and the derive route takes it. Both spellings work, so `d(f(...), s)` and `∂(f(...), s)` are the same claim. Use whichever your readers will check. ## The sigmoid: calculus as a specification The logistic function is one line of code and a great deal of mathematics: ```python def logistic_standard(x: float) -> float: return 1.0 / (1.0 + math.exp(-x)) ``` Its defining properties are calculus facts, and each is a claim. **Its derivative is expressible in the function itself.** This is the identity backpropagation is built on: <!-- example: sigmoid-derivative verdicts fn=mathema.lexicon:logistic_standard expect=proven --> ``` for x in [-700, 700], d(f(x), x) == f(x)*(1 - f(x)) ``` **It is symmetric about the origin:** <!-- example: sigmoid-symmetry verdicts fn=mathema.lexicon:logistic_standard expect=proven --> ``` for x in [-700, 700], f(-x) == 1 - f(x) ``` **It saturates, which limits state:** <!-- example: sigmoid-limit-upper verdicts fn=mathema.lexicon:logistic_standard expect=proven --> ``` lim(f(x), x -> oo) == 1 ``` <!-- example: sigmoid-limit-lower verdicts fn=mathema.lexicon:logistic_standard expect=proven --> ``` lim(f(x), x -> -oo) == 0 ``` **Its derivative is a probability density,** which an integral over the whole line states exactly: <!-- example: sigmoid-density verdicts fn=mathema.lexicon:logistic_standard expect=proven --> ``` ∫(d(f(x), x), x, -oo, oo) == 1 ``` All five are **proven**. The derivative identity, the limits and the integral are settled symbolically, which is the difference between knowing a property and having sampled it. The two identities carry a range for the sake of the computation rather than the mathematics: stated over the whole line both are proven all the same, and the difference shows one row down, on the symmetry identity's `[float]` companion, which runs this code at the corners of the domain and is falsified where `math.exp(-x)` overflows, below about `x = -709.78` (the derivative identity, a calculus form, spawns no companion): <!-- example: sigmoid-whole-line run --> ```python import mathema from mathema.lexicon import logistic_standard rec = mathema.check(logistic_standard, claims=["f(-x) == 1 - f(x)"]) for p in rec.probes: print(f"{p.name:22} {p.verdict:9} {p.counterexample or p.condition or ''}") ``` <!-- example: sigmoid-whole-line output --> ```text f_x_eq_1_f_x proven ∀ x ∈ ℝ f_x_eq_1_f_x[float] falsified x = -1.7976931348623157e+308 missing[x] holds ``` The proof is over ℝ, with infinity as infinity, and the companion says what the computation does out at the corner it was run to. The range in the claims above is one way to make both rows hold; `let |inf| be 700` on the whole-line claim is the other, since the companion then runs the unbounded directions out to `700`, where this code still returns, and the proof is the same proof over ℝ either way. ### Where it gets interesting: a true claim that falsifies The sigmoid is bounded strictly between zero and one. Every textbook says so, and it is true of the mathematics. State it unquantified and mathema disagrees: | claim | verdict | witness | |---|---|---| | `f(x) > 0` | falsified | `x = -1e6` raised `OverflowError` | | `f(x) < 1` | falsified | `x = 1e6` returned exactly `1.0` | | `for x in [0, 1e6], f(x) < 1` | falsified | `x = 1e6` returned exactly `1.0` | None of these is a mathematical error, and none of them is a proof either, which is where they part from the identities above: the strict bounds are the one thing on this page the derive route cannot close (sympy does not settle the strict positivity of `exp(x)/(exp(x) + 1)` over the whole line, and the record lists what it tried), so each falls through to the probe route, where a claim is decided by running the code and the computation answers for itself. At `x = -1e6`, `math.exp(1e6)` overflows before any division happens, and a raise is no value, so the lower bound is falsified with that witness. The upper bound fails a different way: at `x = 1e6`, `exp(-x)` underflows to zero and the result saturates to exactly `1.0`, so the strict inequality fails in float64 while remaining true in the reals, and it does so from about `x = 36.7` onward, which is the region the bounds below stay clear of. This is the distinction the record is built to preserve: the mathematics is sound and the computation is not total over the inputs the claim quantified, and the record says which of the two it established. Where the derive route closes the mathematics, as it does for the identities, the proof stands over ℝ and the computation's verdict sits on the `[float]` row beneath it; where it cannot, the claim carries the computation's verdict, with the route that decided it named in the record. The remedy is claims-side in both cases, an operational infinity where the code merely stops short of infinity, or a domain, which is usually what you meant anyway: <!-- example: sigmoid-above-zero verdicts fn=mathema.lexicon:logistic_standard expect=proven --> ``` for x in [-30, 30], f(x) > 0 ``` <!-- example: sigmoid-below-one verdicts fn=mathema.lexicon:logistic_standard expect=proven --> ``` for x in [-30, 30], f(x) < 1 ``` Both **proven**, and both `[float]` companions hold, since nothing in `[-30, 30]` overflows or saturates. A bounded domain is not a weaker claim, it is an honest one, and the record now states the range over which the bound was established rather than implying the whole line. ### Gradient descent, and a claim that composes Fixed-step gradient descent on the quadratic bowl `0.5*q*t^2` multiplies the iterate by `r = 1 - alpha*q` each step, so it converges exactly when `|r| < 1`. That condition is a claim about the step size: <!-- example: descent verdicts fn=mathema.lexicon:gd_convergence_factor expect=proven --> ``` for alpha in [0.01,1.9], q in [0.5,1.0], |f(alpha,q)| < 1 ``` **Proven** on `gd_convergence_factor`. The claim is more useful than the sentence it encodes, because it is attached to the code: change the step-size policy and the claim is re-adjudicated. ## Composing: lemmas over case studies Each claim above stands alone, which is the weakest way to use them. A claim can rest on another through an `assuming` premise, and then the evidence composes: ```python from mathema.claims import check_conjectures, claim from mathema.lexicon import logistic_standard check_conjectures(logistic_standard, [ claim("for x in [-30, 30], f(x) > 0", name="positive", route="derive"), claim("assuming positive is proven, for x in [-30, 30], f(x)*(1 - f(x)) >= 0", name="derivative_nonneg"), ]) ``` `derivative_nonneg` is not re-deriving positivity; it is resting on it, and the record says so. If `positive` were only sampled, a premise that demands `is proven` would have nothing to rest on and `derivative_nonneg` would come back `unknown`; written `assuming positive holds`, the conclusion would be capped at `holds` and `meta["mathema.capped_by"]` would name it. That is the property that makes a chain trustworthy: evidence never gets stronger as it propagates. See [Lemmas](lemmas.md) for the full behaviour. ## Finding a spelling Every claim here is a lexicon entry, and the lexicon is browsable, so you do not have to remember the grammar: ```python from mathema import lexicon lexicon.show("sigmoid_derivative") # one entry, both renderings lexicon.get("parity_identity") # just the claim text ``` The entries are grouped by what they demonstrate (calculus, assuming, domains, case studies), which makes the lexicon a reasonable first stop when you know what you want to say but not how to spell it. ## Sources The formulae are standard and the implementations here are mathema's own. The references are openly licensed: - Put-call parity, Black-Scholes model, Greeks (finance), and Logistic function: Wikipedia, CC BY-SA 4.0. - Fixed-step gradient descent on a quadratic: Scientific Python Lectures, CC BY 4.0, "Mathematical optimization: finding minima of functions". - docs/cdd.md (13230 bytes)
# The method: claim-driven development mathema is the tool; claim-driven development is the method it implements. This page sets out that method and the vocabulary every part of mathema shares, and is the one to come back to when a term shows up somewhere else in these docs. This page restates **claim-driven development v0.2**, the specification mathema implements. The specification itself lives in a separate repository, [claim-driven-development](https://github.com/aaronbyrnephd/claim-driven-development), and is published under [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/). mathema targets exactly one spec version at a time, readable at runtime as `mathema.SPEC_VERSION`, and every verified record stamps the version it was written against in its `lineage.CDD_spec_version` field. ## The problem it addresses A test tells you a function behaved correctly on the specific inputs the test author thought to write down. A type hint tells you the *shapes* of the inputs and outputs line up. Neither tells you *why* the function is trusted, in a form that survives the function being rewritten, or that a reviewer (human or model) can check against the real code in seconds rather than by re-reading the implementation. Claim-driven development is a small, deliberately spec-first answer to that gap: a **claim** is a specific, checkable statement about what a function does (`f(-x) == -f(x)`, `min(x) <= f(x) <= max(x)`, `f` raises on a shape mismatch), adjudicated against the *real* function, not assumed from its signature. The claim, its verdict, and the evidence behind that verdict are the durable artifact, not a disposable test file that only proves something the day it was written. The full specification, including the exact vocabulary and the YAML record schema, lives in a sibling repository: [claim-driven-development](https://github.com/aaronbyrnephd/claim-driven-development) on GitHub. mathema is one implementation of it, in Python. The name mathema is Greek: μάθημα, that which is learned. A function is trusted exactly to the extent of its verified claims. ## What Claim-Driven Development is State what a function should do, then keep a machine-checkable record of whether the real implementation satisfies it. The claim says what should be true, the implementation says how it is achieved, and the evidence says why it should be believed. A claim is a statement like `f(-x) == -f(x)` (an odd function) or `for x in [0, 1], f(x) <= 1` (bounded on a declared domain), written over the generic function name `f` and the function's own parameter names. ## The two evidence routes - **`probe`**: call the real function on seeded, synthesized inputs and check the claim numerically. Verdict: `holds (n=...)` or `falsified` with a counterexample. Evidence, not proof. - **`derive`**: lift the function's body to a symbolic expression and decide the claim algebraically. Verdict: `proven`, or `falsified` with a witness the real function reproduced, and never a false `proven`. A symbolic disproof with no point to execute (a derivative or limit claim, say) stays `unknown`. When the body will not lift, or the proof cannot close, the claim falls through to the probe route with the reason the derive attempt stopped kept in the record; a matrix identity is sampled over matrices of its declared shape, and stays `unknown` only where it cannot be sampled. A claim declared `route: derive` takes only a falsification from that sampling: draws that find no counterexample leave it `unknown`, never `holds`. Only available for a real subset of functions; see [The derive route](derive-route.md). ## Verdict vocabulary The reference page for verdicts is [Verdicts and exit codes](verdicts.md); the method's own account of them follows. | Verdict | Route | Means | |---|---|---| | `proven` | derive | Established by algebra over the whole declared domain, in exact real arithmetic. That is all it says: the computation in float64 is its own claim, the `<name>[float]` companion every proof spawns (see [the evidence ladder](evidence-ladder.md#a-proof-is-the-mathematics-float-is-the-computation)). A point inside the domain where the mathematics is undefined, or where the function's own source raises, still falsifies the claim itself; a failure of the computation there, an overflow say, falsifies the `[float]` companion instead; see [the sigmoid case study](case-studies.md#the-sigmoid-calculus-as-a-specification). | | `holds (n=...)` | probe | Held on every one of `n` seeded trials. Evidence, not proof. | | `falsified` | either | A counterexample exists and is kept, permanently. | | `unknown` | either | Adjudication ran but couldn't decide (an undecided proof, inconclusive sampling). | | `skipped` | either | Couldn't be adjudicated at all (unliftable body, foreign grammar, an unresolvable key). | | `regressed`, `weakened` | either | Not verdicts but transitions: a supported claim that no longer is keeps the verdict it fell to, and the record keeps the move beside it until a person acknowledges it (see [verdicts](verdicts.md#transitions-and-what-invalidated-names)). | | `documented` | none | Of intent, not a claim: stated intent a person has accepted with `mathema accept --intent`. | | `declared` | none | Of a claim: authored and stored, awaiting adjudication. Of intent: stated, not yet accepted by a person (the lowest rung of [the evidence ladder](evidence-ladder.md)). | A verdict may carry a colon subroute refining its base family, e.g. `skipped:misspecified` when the claim itself is malformed rather than the function unadjudicable. Everything before the colon is the base family; the fold into supported/refuted/blocked/undecided uses only the base, so a subroute never changes what a verdict counts as, it only says more precisely why. The `route` field follows the same convention (`derive:extensive`, `probe:semi_analytical`, `derive:brute_force`, `derive:brute_force:within_float64` name the mechanism that actually decided). Verdicts are pedantic and exact: nothing is called proven that isn't, and a raise is not a value, so a value claim whose calls raise anywhere inside its declared domain is falsified, the `[float]` companion where the mathematics is proven and the raise is the number representation's (an overflow past what a double holds), the claim itself otherwise; the remedy is always claims-side, narrowing the domain, declaring an operational infinity, or stating the raising region as its own `raises(...)` claim, never a softer adjudication. The counterexample behind a `falsified` verdict is knowledge, kept permanently in the record, and a falsified claim fails `mathema verify`'s exit code in every mode, because a gate that waves through a known-broken claim isn't a gate. A human decides what the falsification *means*: fix the code (the recorded counterexample replays until the claim proves), or, when the code was right and the claim was wrong, record the discovery with [`mathema accept --as discovery`](modes/accept.md), stating the corrected claim (or adopting a verified mechanical inverse), each adjudicated before it is written. An `unknown` claim also fails until it is resolved or a human owns the gap with `accept --as risk`. An accepted risk passes in both modes, named in the row. Only a `skipped` claim nobody accepted is mode-dependent (strict refuses it, lenient reports it). See [mathema verify](modes/verify.md). ## Identity hashes Every record binds to the function's `form` hash (a rename/reformat- invariant AST fingerprint) and `sig` hash (parameter shape), so a claim can't silently outlive the code it describes. If the function's `form` changes, the claim is re-adjudicated, not assumed still true. ## The spec record `mathema.write_spec(fn, ...)` writes a standalone YAML record (`.mathema/verified/<key>.yaml`) conforming to the `claim-driven-development` repo's `record-schema.md`: intent, identity, claims with verdicts, references, and the reasoning chain that connects them. The record is deliberately independent of the Python implementation; it carries the identity hashes, so it can outlive the code and be re-verified against a regeneration. ## Four ways to author a claim, one precedence order Lowest to highest precedence, a same-named claim from a higher surface overrides a lower one. See [Authoring claims](authoring.md) for the full reference. 1. **Inferred from types**, a `typing.Annotated` marker on the signature, automatic, no claim actually typed. 2. **Docstring** `Claims:` block. 3. **Decorator**: `@mathema.claims_decorator(...)`. 4. **A claims file** on disk (`*.claims.yaml`, `claims/*.yaml`, anywhere in the tree). All four funnel into the same declared shape, nothing downstream cares which surface a claim came from. ## Which specification version `mathema.SPEC_VERSION` is the one authority for which version a given release targets, and that exact string is written into every record's `lineage.CDD_spec_version`. A record therefore says which vocabulary it was adjudicated under, so a store written today stays readable when the specification moves on. Read it rather than assuming: ```python import mathema mathema.SPEC_VERSION ``` The specification is versioned separately from mathema: a mathema release names the one spec version it targets, and a spec revision lands in mathema as a deliberate, documented upgrade rather than silently. ## What mathema does with a claim - **Structural analysis** (pure `ast`, no dependencies): loop shape, purity and effects, parameter kinds, per-parameter domain guards. - **Probing**: runs the real function on seeded random inputs and checks built-in algebraic laws (commutativity, idempotence, boundedness, parity, monotonicity, equivariances) plus any claim you state yourself. `holds (n=...)` is evidence, not proof. `n` is a trial budget decided once per call from the function's own structure, never a flat constant, and `falsified` comes with the counterexample, permanently. - **Symbolic proof (the derive route)**: lifts a function's body to a symbolic expression and decides a claim algebraically, over several mathematics engines (principally sympy) and mathema's own solving. `proven` is strictly stronger than `holds`: not "n samples agreed," but "the relation holds for every input in the domain", an equality or an inequality alike. See [The derive route](derive-route.md) for exactly what is liftable. - **The conjecture pipeline**: state a claim as one string (`"f(-x) == -f(x)"`) or a `Conjecture`. Laws are validated against a strict AST whitelist before they run. A proposal from an untrusted source (a human in review, or a model) can call the function under test, mathema's helpers and the functions it binds with `let`; a binding that reaches the system is refused, and one into third-party code runs as an import and a call in your own code would, with a warning. The function itself runs as it would in its own tests, see [Security and execution](security.md). The proposer never adjudicates its own claims. - **Identity hashes**: `form` (rename/format-invariant AST structure) and `sig` (parameter shape). Every claim binds to them, so a record cannot silently outlive the code it describes. - **The spec store**: `mathema.write_spec(fn, ...)` writes a standalone YAML record to `.mathema/verified/`, and `mathema verify` re-checks every record whose function or dependencies changed. ## Exit codes Every verb uses the same four, so a CI step can tell a failing gate apart from a broken invocation without parsing output (the reference page is [Verdicts and exit codes](verdicts.md#exit-codes)): | Code | Meaning | |---|---| | 0 | ran, and nothing gated: claims adjudicated as stated, or the verb only reports | | 1 | ran, and the gate failed: a claim is falsified or unknown, a transition is open and the mode fails it, a claim nobody accepted as risk is skipped in strict mode, or a conflict is unresolved | | 2 | could not run: a target that does not resolve, an unreadable or malformed file, a bad argument, a missing optional extra | | 130 | interrupted (Ctrl-C or EOF) | The distinction that matters in CI is 1 against 2. A 1 is a real finding about your code and the record will say which claim; a 2 means mathema never got far enough to have an opinion, so treating the two alike hides a broken invocation as a failing test. `--lenient` moves accepted risks out of the gate and so can turn a 1 into a 0, but it never turns a 2 into either (see [what fails the run](modes/verify.md#what-fails-the-run)). ## The specification documents The full vocabulary and schema this package is checked against: - [claim-driven-development](https://github.com/aaronbyrnephd/claim-driven-development): the repository itself, starting with its own README. Each published version has its own directory, holding the three documents mathema is checked against: - `cdd.md`, the core vocabulary (claim, verdict, evidence route). - `claim-anatomy.md`, what a claim is made of. - `record-schema.md`, the exact shape of the YAML record shown in step 4 of [A first look](first-look.md). - docs/claims-transfer.md (24557 bytes)
# Claims transfer Evidence is earned about one implementation. This page is about the three ways it travels: **in**, from curated knowledge about libraries your code calls; **across**, between implementations shown equivalent, in another language included; and **out**, publishing your own verified claims as a compendium others consume. ## In: the compendium A compendium is an ordinary claims file whose keys are a library's functions rather than your own, with two file-level fields beside the optional `grammar`: `compendium`, naming the library, and `versions`, the range of its installed versions the claims apply to (`"*"`, `">=X"` or `">=X,<Y"`, and the standard library always counts as `"*"`): ```yaml compendium: numpy versions: ">=1.24,<3" numpy.sqrt: claims: - name: is_defined statement: "x >= 0" note: "Principal square root; a negative input returns nan with a RuntimeWarning, never raises." numpy.clip: claims: - name: clip_lower statement: "assuming a_min <= a_max, for a in [-1e6, 1e6], a_min <= f(a, a_min, a_max)" ``` A third, optional file-level field, `aliases`, lists other names the library goes by. The installed version is looked up under the library name and then under each alias, so a file about an import name whose distribution is called something else still applies: ```yaml compendium: yaml aliases: [PyYAML] versions: ">=6" ``` An alias is also a key prefix: a key written under one (`np.cbrt` in a file with `compendium: numpy` and `aliases: [np]`) is the library's key (`numpy.cbrt`), and two keys naming the same function that way are refused. A row can also carry its own `versions:` range, overriding the file's for that row alone. A row whose range excludes the installed version is never used as a fact, and is still adjudicated when the project calls the function, so [`mathema compendium update`](modes/compendium.md#update-rows-for-the-calls-the-project-makes) can widen its range once it holds on the installed version. The parameter names are the library's own (`inspect.signature`, so numpy's `clip` takes `a`, `a_min` and `a_max`), and every row is a claim like any other, with a `note:` on the row where the library's behaviour needs saying in prose. A library function's intent is its own, read from its docstring like any function's, so a compendium file states none. mathema bundles such files for `math`, `statistics`, `numpy` (numpy's covered functions split into scalars, reductions, bounds, definitions, linear algebra, elementwise functions and statistics), `pandas` and `polars.Series` (their [definition rows](#definition-rows)), and a project states its own anywhere its claims files already live, `claims/numpy.claims.yaml` for instance, where a key shadows the bundled entry for that function. A file applies only when the library is importable at a version inside its range; otherwise it contributes nothing, which is better than contributing stale facts. A file whose `compendium:` names your project's own package is ignored: those are your own claims, stated in your ordinary claims files, and `mathema verify` prints a note naming the file. The bundled compendium applies to every `check`, from the command line or the Python API alike, without being asked: it is part of what mathema knows, the way `math.sqrt` raising below zero is. Your project's own compendium files apply wherever mathema reads the project (`mathema check`, `mathema verify`, `write_spec`). A row about a library function passes the parameters it does not bind at the library's own defaults, rather than sampling them: `for a in R^n, min(a) <= f(a) <= max(a)` on `numpy.mean` samples `a` and leaves `axis`, `dtype`, `out`, `keepdims` and `where` as numpy defines them. The record says so: each row carries the values it passed in `mathema.defaults`, keyed by the function they were passed to, since one claim can call several library functions (`{numpy.mean: {axis: None, keepdims: <no value>, ...}}`, and a `let g = numpy.sqrt` binding the claim calls adds `numpy.sqrt`'s own), and its note lists them as `held at their defaults: axis=None, ...`. A different value is a pin, `let axis be 0` (see [the grammar](grammar.md)), shown as `0 (pinned)`. `mathema verify` compares those values with the installed library on every sweep, so a release inside the declared `versions` range that changes a default of any function the row calls marks the row stale and it is adjudicated again, and a pin naming a parameter the library no longer has makes the row misspecified. Your own functions are not affected: their defaulted parameters are sampled like any other. ### Row kinds, by stratum A compendium row belongs to one of the two strata [the guarantees](guarantees.md#mathematics-and-computation) separate, and the stratum decides what mathema does with it. **Mathematics.** An `is_defined` row with a stated region reads as "has a value on exactly this region", so `numpy.sqrt`'s `x >= 0` says that outside it the call has no value, whether the library raises there (`math.sqrt`) or returns nan (`numpy.sqrt`); the bare `is_defined(f)` says the function is total. Such a row is a fact about the function as a mathematical object: it enters the derive route as a guard, so a caller's claim over a region that reaches the no-value region is falsified with an executed witness, exactly as it would be over an explicit raise. A `raises(f(x), Exc)` row with an ordinary type (`ValueError`) is mathematics too, added only where the exception type itself matters. A region stated with an ordering (`x >= 0`, `-1 <= x <= 1`) is a statement over real inputs, since the complex numbers have no order: at a call whose argument is complex (a parameter the claim binds in `C`, a `complex` annotation, or an expression the derive route knows is complex) it does not apply. Where a library computes a function over the complex plane, its row for complex input is a bare `is_defined(f)` over `C`, less the points where it has no value there, and those points are a guard at complex arguments only: ```yaml numpy.log: claims: - name: is_defined statement: "x > 0" - name: is_defined_over_complex statement: "for x in C \\ {0}, is_defined(f)" ``` numpy's square root, inverse sine, inverse cosine and inverse hyperbolic cosine are defined on the whole plane; its logarithms have no value at 0, `log1p` at -1 and `arctanh` at 1 and -1. **Computation.** A computation-safety family in restriction form states the region where one implementation is safe in that respect: `is_overflow_safe: x <= 709.782712893384` on `numpy.exp` says numpy's exponential on float64 stays inside float range exactly there (an infinity past it). A `raises` row whose type is a machine failure (`OverflowError`, `MemoryError`, `RecursionError`, `FloatingPointError`) is computation as well. These rows never enter a proof: `exp(x) >= 0` on a numpy caller is proven over the reals whatever the threshold, and the overflow shows on the computation side (the `[float]` companion, the probe route). They feed the hazard points, `is_library_safe`'s diagnosis, the reach of the key's own `is_defined` row and the companion's sketch. `numpy.exp` carries one row of each kind: ```yaml numpy.exp: claims: - name: is_defined statement: "is_defined(f)" - name: is_overflow_safe statement: "x <= 709.782712893384" note: "Exponential; overflows to inf above roughly x = 709.78, with a RuntimeWarning." ``` Consumption paths: - Definedness and overflow-safe regions become sampling hazards: their boundary values join the probe candidates for every caller, whether it spells the call `numpy.sqrt(x)` or `np.sqrt(x)`. - `is_library_safe(numpy)` asserts a function never silently emits a non-finite value (nan/inf) through an unguarded call into a covered library function; the probe samples the hazard boundaries and the empty-sequence case, and falsifies on a nan/inf output. When the covered call states a computation region, the counterexample names it: `the covered call numpy.exp is overflow-safe only for x <= 709.782712893384, and x = 1000 lies outside it`. - A `[float]` companion falsified by a call into a covered function names the same region in its sketch. - A library key's own bare `is_defined` row is adjudicated inside its `is_overflow_safe` region (the function is total; where it overflows is the other row's fact), and inside the number representation's range otherwise. The same rule holds for every function checked by execution, your own included: an `is_overflow_safe` claim in its claims file keeps the `is_defined` sampling inside that region, and without one an overflow at the reach is a finding about the computation in the note, pointing at `is_overflow_safe`, never a point where f has no value. An infinity or a nan nothing tells from an overflow (no overflow error, no numpy flag, and a body the exact reading cannot follow) decides nothing: `is_defined` is then `unknown`, the note naming the point. - Claims may be named as premises: `assuming clip_lower holds`, or qualified, `assuming numpy.clip.clip_lower holds`. A compendium row is testimony, and it never enters the evidence chain silently. `mathema verify` adjudicates the rows of every library function your project calls or rests a premise on by executing them against the library you have installed, records the local verdict with the row's provenance (`compendium:numpy-2.5`), and a premise then resolves at that verdict; a project that never calls numpy verifies none of its rows. That default is lazy: only the library functions the project uses are adjudicated. To adjudicate a whole file up front, name it: ```bash mathema verify claims/numpy.claims.yaml mathema verify mathema/compendium/numpy/scalars.claims.yaml ``` The second names a bundled file by the path records give it. Every entry in the named file is adjudicated and recorded, whether or not your code calls it; a file whose library is not importable, or is installed outside the file's `versions`, says so on one line (see [`mathema verify`](modes/verify.md#library-claims-lazy-by-default-a-file-up-front)). Library rows gate the run exactly like your own claims: a row verify cannot settle here fails it, with a line naming both ways to settle it, and the resting claim stays `unknown` with the same two paths in its note. One is a fresh local verdict; the other is: ```bash mathema accept numpy.clip clip_lower --as trusted ``` takes the row at the level it claims (the row's `meta: {mathema.compendium_claimed: proven}`, `holds` when it states none), and every conclusion resting on it caps there, with the provenance (`compendium:numpy-2.5/clip_lower`) named in the record. Accepting is a statement of trust. A later verify replaces it only with a local verdict that contradicts it (`falsified`) or is at least as strong (a `proven` replaces a trusted `proven` or `holds`, a `holds` a trusted `holds`). A weaker local verdict that agrees leaves the trust standing at its level, and the row says what was seen: `trusted as: proven, strongest evidence seen: holds`. ### Definition rows A **definition row** is a row named `definition` that states what a library function computes, in the grammar's own words, over inputs with nothing missing (a named space such as `R^n` states that on its own): ```yaml compendium: pandas versions: ">=2,<4" pandas.Series.std: claims: - name: definition statement: "for a in R^n, assuming dim(a) >= 2, f(a) == std(a, ddof=1)" - name: definition@ddof=0 statement: "let ddof be 0, for a in R^n, f(a) == std(a, ddof=0)" ``` A method's key names its class (`pandas.Series.std`, `numpy.ndarray.T`), and its receiver is the row's first parameter `a`, sampled as that class; the method's other parameters keep their names and defaults. A row for a call that pins a parameter away from its default is named `definition@<parameter>=<value>` and pins it with `let`, so `np.std(x, ddof=1)` reads through `numpy.std`'s `definition@ddof=1`. Each row is an ordinary claim: `mathema verify` executes it against the installed library, so a wrong row (`std(a, ddof=0)` for pandas) is falsified like any other claim. The bundled pandas rows cover, for `pandas.Series`: `mean`, `std`, `var`, `sum`, `prod`, `cumsum`, `cumprod` and `count`; the running extrema `cummax` and `cummin`; `min`, `max` and `abs`; `median` and `quantile` (at `q` 0.5, 0.25 and 0.75); the arithmetic methods `add`, `sub`, `mul`, `div`, `truediv` and `pow`, with a number or a Series of the same length; `size`; and `shift`, `diff` and `pct_change`, which leave their first positions missing and so are stated over the positions that carry a value (`f(a)[1:] == a[:-1]`). For `pandas.DataFrame` they cover `sum` and `mean` per column; a column read (`df.w`, `df["w"]`) is grammar, and a Series method called on a column reads through the Series rows. A bundled compendium ships its rows, not verified records: mathema's own test suite verifies every row against the installed library, and a project's run takes each row at the evidence that run gives it. How the library treats a missing value is a separate matter from what it computes, and the rows leave it out. As installed today: numpy propagates a missing element (nan) to the result; pandas skips nan, None and `pd.NA` in its reductions and keeps a missing position missing in `cumsum` and `cumprod`; polars skips a null but carries a NaN through as a float (a Series holding NaN has mean NaN, and `count` counts it). #### numpy's rows numpy's definition rows live in `mathema/compendium/numpy/`, one file per area, each row stated over inputs with nothing missing: | file | functions | |---|---| | `definitions.claims.yaml`, `reductions.claims.yaml`, `definitions_2_4.claims.yaml` | `mean`, `std`, `var`, `sum`, `prod`, `cumsum`, `cumprod`, `trace`, `transpose`, `dot`, `linalg.inv`, `linalg.det`, and the ndarray's `mean`, `std`, `sum` and `T` | | `linalg.claims.yaml` | `linalg.norm` (`sqrt(sum(x ** 2))` for a vector, `ord=1` and `ord=2`, and the Frobenius norm of a matrix), `linalg.solve`, `linalg.pinv`, `linalg.eigvalsh` (symmetric), `linalg.matrix_rank`, `linalg.cond`, `outer`, `kron`, `diag`, `identity`, `eye` | | `linalg_2_4.claims.yaml` (numpy 2.4 on) | `matmul` | | `elementwise.claims.yaml` (numpy 2.4 on) | `absolute`, `fabs`, `square`, `negative`, `maximum` (`(x1 + x2 + abs(x1 - x2)) / 2`) and `minimum` (the same with `-`), `sign` | | `statistics.claims.yaml` | `max`, `min`, `amax`, `amin`, `diff`, `nansum`, `nanprod`, `nanmean`, `nanstd`, `nanvar`, `nanmax`, `nanmin`, the ndarray's `min`, `max`, `prod`, `cumsum`, `cumprod` and `var`; `median`, `percentile` and `quantile` state the range their value lies in | A function whose calls all read through rows is decided as mathematics: `np.linalg.norm(x) >= 0` and `np.linalg.norm(c * x) == c * np.linalg.norm(x)` are proven for every length, as are `np.ma - docs/conditional-claims.md (12123 bytes)
# Conditional claims and lemmas A claim is unconditional by default: `for x in [0, 1], f(x) >= 0` quantifies over its whole declared region. An `assuming` clause makes the claim conditional, and mathema gives the premise real semantics on both routes: the region narrows, the evidence chain records what the conclusion rests on, and a premise that cannot be established caps or blocks the conclusion rather than being quietly ignored. The clause leads the claim, before any quantifier: ``` assuming x > 0, for x in [-10, 10], f(x) > 0 ``` ## Relation premises The simplest premise is a relation over the claim's own variables, or several joined with `and`: ``` assuming b^2 - 4*a*c >= 0.01, f(a, b, c) <= f(a, -b, c) assuming k != 0 and j > 0, for x in [1, 5], f(x, k, j) * k * j == x ``` A relation premise narrows the region actually adjudicated. On the derive route the constraint reaches the prover as an assumption; on the probe route sampling stays inside the assumed region. The rendered record states the narrowed region explicitly, so a conditional claim and its unconditional twin can never read alike, and never share an identity. A premise relating two parameters (`a <= b`) is handled by the assumed-gap machinery rather than by interval narrowing, because that region is not a box. ## `is_defined` as a claim: restriction or totality Besides the premise below, `is_defined` is a claim in its own right, and it carries two readings, told apart by whether the claim states a region: ```yaml - name: is_defined # RESTRICTION: f returns on exactly this region statement: "x >= 0" ``` ``` is_defined(f) # TOTALITY: f returns everywhere, it never raises f is defined # the same claim, postfix spelling ``` One predicate, because the English reads correctly either way: "f is defined on `x >= 0`" states a restriction, "f is defined" states that there is none. A restriction claim proves when the stated region matches the region mathema computes from the body's raise guards, and falsifies when it differs (naming the fresh region) or when the function is in fact total. The bare form proves when the body has no raise region at all, and falsifies when it has one, naming the region `f` actually returns on. mathema suggests the restriction form for a partial function and never for a total one. When there is no body to compute a region from (a builtin, a numpy ufunc), or the comparison does not decide (a library function whose region reads `det(a)` or `dim(a)`), the claim is adjudicated by execution: every sampled point inside the region must return a value and every point outside it must not, where a raise, a nan and an infinity for a finite input are all no value. Where the computation leaves float range is not a definedness fact but a computation one, stated by an `is_overflow_safe` row (see [claims transfer](claims-transfer.md#row-kinds-by-stratum)), and a library function's bare `is_defined` is adjudicated inside that region. A region over `det(a)` draws square matrices, singular ones on its boundary; one over `dim(a)` draws sequences, the empty one below it. An indexed row (`is_defined[2]`, one conjunct of a region with several) only asks for no value outside it, since inside it the other conjuncts decide. The verdict is `holds` at best, and the note says how many points were executed on each side. ## The definedness premise ``` assuming is_defined(f), abs(f(x, y)) <= 1 assuming f is defined, abs(f(x, y)) <= 1 ``` Both spellings mean the same thing: the claim quantifies over exactly the region where every call to `f` returns. mathema computes that region from the function's own raise guards and from registered partiality lemmas (below), then states it in the record behind an arrow: ``` assuming f is defined --> b != 0, b*f(a, b) = a ``` The region after `-->` is the resolved fact the claim was adjudicated under. On a later run the pin is validated, never trusted: while the code still agrees, the pin is kept byte-for-byte, so the record is stable; when the code has moved out from under it, the region is recomputed and the note says so, naming both. A function with no raise region at all keeps the premise arrow-free (`assuming f is defined`), because there is nothing to state. ## Dimension premises A premise may relate the shapes of a function's arguments, not just their values. `dim(x, axis)` is the canonical spelling for a dimension; `len(x)`, `rows(A)` and `cols(A)` are sugar for `dim(x, 0)`, `dim(A, 0)` and `dim(A, 1)`. ``` assuming len(x) == len(y), f(x, y) == f(y, x) assuming dim(x, 0) >= 3, f(x) >= x[2] ``` On the probe route a dimension premise is drawn to hold **by construction**: an equality between two dimensions shares one drawn size across them, and a bound against a constant constrains the draw, so a claim about a function that legitimately requires equal lengths no longer falsifies on synthesised mismatches. The four spellings share one identity, so a record is stable however the premise was written. ### Matrices, and named dimensions The mechanism is axis-general. A parameter carrying a `Shape` marker (`types.Shape("m", "n")`) has as many axes as the marker names, and `dim(A, 1)` reads the second one: ```python def matvec(a: Annotated[list, Shape("m", "n")], x: Annotated[list, Shape("n")]) -> Annotated[list, Shape("m")]: ... ``` ``` assuming n >= 2, dim(f(a, x), 0) == dim(a, 0) ``` Two things follow from the marker. First, a marked matrix parameter is synthesised as a nested list of the right shape, so ordinary claims run against matrix functions (an unmarked nested-list parameter stays a plain one-dimensional sequence, mathema never invents a second axis it was not told about). Second, a marker dimension name is a first-class symbol in a premise or law: a premise may bound it (`assuming n >= 2, ...`), a law may relate it (`dim(a, 1) == n`), and a name shared between two parameters (`Shape("m", "n")` and `Shape("n")` both naming `n`) is drawn once, so the arguments are conformable every trial. `len`, `rows` and `cols` remain sugar for `dim` on axes 0, 0 and 1. A parameter's domain can also state the SPACE directly, rather than its element domain: `for v in R^n` is a real vector of length `n`, `for xs in [0, 1]^n` a vector with elements in `[0, 1]`, and `for A in R^(m,n)` an `m`-by-`n` matrix (rows, then columns, the order of a numpy shape). The element domain is the base and the dimensions the exponent; in unicode the exponent renders as a superscript (`ℝⁿ`, `ℝᵐˣⁿ`, `ℝ²ˣ³`), the missing-value clause trailing the whole space. A dimension whose name the superscripts cannot carry (one containing an `x`, which would read as the `ˣ` separator, or a letter with no superscript form such as `q`) renders as the plain exponent instead (`ℝ^(x,n)`). The matrix space is also accepted as `R^{m,n}`, `R^(m×n)`, `R^{m×n}`, `R^(m*n)`, `ℝᵐˣⁿ` and, for a fixed size, `ℝ³ˣ³` or `ℝ^{3×3}`; every one of these is the same claim and is written back as `R^(m,n)`. A dimension NAME is the constraint: `R^n` on two parameters draws them to one length every trial, so a claim about a function that requires equal-length inputs holds without a separate premise. `len`/`rows`/`cols` remain the axis-0/0/1 sugar for reading a dimension back. To enforce a dimension premise at RUNTIME, the shape analogue of `@enforce_domain` is `@enforce_dimensions`: <!-- example: enforce-dimensions run inline --> ```python from mathema import claims_decorator, enforce_dimensions @enforce_dimensions() @claims_decorator("assuming len(x) == len(y), f(x, y) == f(y, x)") def dot(x, y): return sum(a * b for a, b in zip(x, y)) dot([1, 2], [3]) # ValueError: dot: dim(x, 0)=2 violates the declared premise dim(x, 0) == dim(y, 0)=1 ``` `@enforce_domain` guards a parameter's VALUE domain. `@enforce_dimensions` guards SHAPES: the rank and the fixed sizes a marker or a binding states, a dimension name shared across parameters, the relations a premise states between them, and the result against the return marker (see [shape markers](authoring.md#shape-markers-and-their-shorthand)). Neither makes a claim true by fiat: each makes the function reject inputs the claim was never about, so a premise and its runtime guard are one precondition stated once. Beyond shape, a matrix parameter can declare its STRUCTURE (symmetric, positive definite, and so on) and state linear-algebra identities over it. See [Matrix structure and linear algebra](matrix-structure.md). ## Prerequisite claims A claim may rest on a sibling claim from the same batch or file: ``` assuming positive holds, for x in [0, 10], f(2*x) >= f(x) assuming real_roots is proven, f(a, b, c) <= f(a, -b, c) ``` The referenced claim must reach the named verdict first. mathema orders the batch by dependency (a forward reference works), reports a cycle as a skip naming both claims, and enforces the evidence ladder: a prerequisite that only `holds` empirically caps the resting claim at `holds` too, with `meta["mathema.capped_by"]` naming the premise. A proof cannot stand on sampling. A bare sibling name (`assuming real_roots, ...`) borrows that claim's relation as a region constraint instead of consulting its verdict. ## Partiality lemmas The definedness machinery reads raise guards from the function's own body, and, for functions it calls, from registered lemmas: ```python import sympy import mathema.partiality def stable_kernel(u, tol): ... # raises for u <= tol mathema.partiality.register_raises_when( stable_kernel, lambda u, tol: sympy.Le(u, tol), "ValueError") ``` A claim about any function that calls `stable_kernel` then treats `u <= tol` exactly like an explicit raise guard: a value claim quantifying over that region is falsified with a witness, and a definedness premise excludes it. The `math` module's own partiality (`sqrt`, `log`, `asin`, ...) ships registered out of the box. ## The compendium The registration generalises to claims files about libraries: a file that declares `compendium: numpy` (and a `versions:` range) holds claims whose keys are the library's functions, and mathema bundles such files for `math` and `numpy`. A project states its own in any claims file (`claims/numpy.claims.yaml`), shadowing the bundled entry per function. An `is_defined` row there states the region where the function returns a value, so a caller's claim is read against it the way it is read against an explicit raise guard, and a compendium claim may be named as a premise, by bare name or by its qualified spelling (`assuming numpy.clip.clip_lower holds`). The bundled files apply to every `check`, the Python API included, with nothing to install; a project's own compendium files apply wherever mathema reads the project. Outside an `is_defined` region the call has no value: a raise, a nan, and an infinity returned for a finite input all count the same, and each falsifies a value claim that reaches it. A compendium verdict never enters the evidence chain silently: `mathema verify` adjudicates the library rows your project calls or rests on by executing them against the installed library, and the premise resolves at the verdict recorded there. Those rows gate the run like the project's own claims. A row verify cannot settle fails it and leaves the resting claim `unknown`, both naming `mathema accept <key> <claim> --as trusted`, which takes the row at the level it claims (the conclusion caps there, provenance named). A file whose `versions` range does not match the installed library contributes nothing. The wider story, including transfer between implementations, is [Claims transfer](claims-transfer.md). ## What the record carries The premise is part of the claim's canonical text, so it survives every store round trip and participates in the claim's identity: a conditional claim is never superseded by its unconditional twin. The resolved definedness region is recorded for the reader but stripped from the identity, because it is recomputed evidence, not something the author asserted. - docs/derive-route.md (45878 bytes)
# The derive route: what's liftable The `derive` route lifts a function's body to a symbolic expression and decides a claim algebraically. `proven` is strictly stronger evidence than `holds (n=...)`, not "n samples agreed," but "the relation holds for every input in the declared domain", in exact real arithmetic. It's also only available for the functions it can actually lift, which is a real subset. This page is the complete, current reference for what that subset is. A `proven` is the mathematics, and only the mathematics. Whether the computation in float64 carries it is a second claim, `<name>[float]`, which every proof spawns and which runs the real code at the domain's corners and at sampled points; `route="derive:math_only"` reports the mathematics line only, with the computation and its policies outside its remit. [The evidence ladder](evidence-ladder.md#a-proof-is-the-mathematics-float-is-the-computation) shows the two side by side. Lifting is honest, not clever: it never guesses at a closed form. Anything not covered below is `underivable` on the derive route (the record's note names the likely reason), never a false `proven`, and the claim falls through to the probe route (which, for a claim pinned to `route: derive`, can only falsify it). Probe-route claims remain viable regardless of any of this, see [CDD in one page](cdd.md). ## What's liftable | Shape | Liftable? | |---|---| | A loop-free, branch-free, non-recursive, all-scalar body | ✅ base case | | A single accumulator folded over one sequence parameter (or none at all; `for i in range(n):`, a bare fixed-iteration-count fold), updated by an expression affine in the element and the accumulator | ✅; closes to a sum over the sequence, see below | | A purely additive accumulator (`acc = acc + <anything>`, however nonlinear) over zero or more sequences, nested loops, `enumerate()`, or multiple sequential passes | ✅, no telescoping needed, see "General sum accumulation" below | | A self-recursive linear recurrence (fibonacci, doubling, factorial) over one scalar parameter | ✅ via its `rsolve` closed form, gated to integer domains, see "Recurrences" below | | Any other recursion (multiple parameters, mutual recursion, memoized wrappers) | ❌ | | A read-only method on a dataclass or simple class: `self.field` reads expand to field symbols, `self.helper(...)` sibling calls inline, `for self.field in [lo, hi]` quantifies the field | ✅, stateful (a write to `self`, or `self` escaping) stays out | | `sum(<generator>)`, `sum(xs)`, `sum(map(g, xs))`, `sum(filter(p, xs))`; filters become exact conditional summands | ✅, desugared to the accumulator loop above | | A comprehension VALUE (`return [v*2 for v in xs]`, dict/set comps) | ❌ vector-valued | | A body-local `g = lambda t: ...` called in the same body, or a lambda bound via `funcs=` | ✅ applied by substitution | | A branch, condition over a signature parameter | ✅ if a claim's declared domain settles which side runs | | A branch, condition over a local variable, or an equivalent expression written directly in the `if` | ✅ if it traces back to unmodified parameters and the declared domain settles it: exactly by corner evaluation when it's *affine* (`denom = x + y`, or `if x + y == 0:` inline), by an interval hull otherwise (`denom = x * y`) | | A branch whose condition the declared domain does not settle (`denom = x * y` with `x` ranging across zero) | ❌ undecided on the derive route | | A ternary (`x if cond else y`) | ✅ if the condition is a comparison or a boolean combination of them | | A ternary with a bare boolean-name condition (`x if flag else y`) | ✅ if the declared domain pins the name to exactly `True` or `False`, see below | | `return a, b` (a tuple) | ✅, compare elementwise or index a single element | | A parameter that's a flat `@dataclass`, or a dict read by literal string keys | ✅, expands into one symbol per field/key | | `min`/`max`/`np.minimum`/`np.maximum`/`np.clip` | ✅ against a declared domain | | A call to a plain function this one calls (`_scale(x)`, not a method or module-qualified call) | ✅ up to 3 levels deep by default, including a callee with its own branch if the caller's domain settles it, see below | | A claim relating two (or more) functions, `f(x) == g(x)`, `d(f(x, g(x,I,px,py), a), x) == 0` | ✅ each bound function lifts to its own closed form and substitutes like `f`, see "Multi-function claims" below | | A non-scalar parameter | ❌ for `lift()` itself, with two independent exceptions: a whole body that's exactly `return np.dot(a, b)` (see "Dot products"), or a loop that sums over it; any loop, nested or sequential, whose accumulator is purely additive (see "General sum accumulation") | | A parameter typed as a matrix/vector | ❌ for lifting the body in general; a matrix claim declares its domain as `R^(m,n)` and is adjudicated by probing and the linear-algebra identities in [Matrix structure](matrix-structure.md) | | A straight-line body over a numpy, pandas or polars vector or matrix whose library calls (`returns.std(ddof=1)`, `np.mean(x)`, `A.T`, `np.linalg.inv(A)`) all have definition rows | ✅ read through the rows, then lowered to sums over a symbolic length or decided in the matrix algebra, see "Vectors through definition rows" below | | A *local* array built from `np.linspace`/`np.arange`, transformed elementwise, returned bare or as one element of a tuple | ✅; index it in claim text via `f(...)[i]`, see "Local symbolic arrays" below | ## Callees A call to a name that isn't a known math function but does resolve to a real, plain Python function this one calls is inlined rather than refused outright: the callee is itself lifted (recursively, a callee can call its own callees), and its parameters are substituted with this call site's argument expressions. <!-- example: callee run --> ```python def _scale(x: float) -> float: return 2.0 * x def _offset(y: float, c: float) -> float: return y + c def uses_helper(x: float) -> float: return _offset(_scale(x), 1.0) ``` <!-- example: callee verdicts fn=uses_helper route=derive --> ``` f(x) == 2*x + 1 # proven ``` Capped at 3 levels deep by default (`symbolic.lift()`'s own `max_callee_depth` parameter, the same concept, and the same default, as `docstring.docstring_sync()`'s own callee resolution, applied here to proof instead of docstring/code sync). A cycle through calls (`A` calls `B` calls `A`, not a bare self-call) is refused outright rather than chasing the depth budget down to exhaustion. Declines rather than guessing whenever the callee itself isn't cleanly liftable (references a module-level global, has a loop, takes a composite `@dataclass`/dict parameter), the call uses keyword arguments, or it's a method or module-qualified call (`obj.method(x)`, `mod.helper(x)`), only a bare `name(...)` call to a plain function is ever attempted. ### A callee with its own branch A callee's branch isn't an automatic refusal either, when the caller's own declared domain settles it: <!-- example: callee-branch run --> ```python def guarded(y: float) -> float: if y > 0: return y return -y def caller(x: float) -> float: return guarded(x) + 1.0 ``` <!-- example: callee-branch verdicts fn=caller route=derive --> ``` for x in [1, 5], f(x) == x + 1 # proven for x in [-5, -1], f(x) == -x + 1 # proven ``` Only a **bare-parameter-passthrough** call-site argument contributes a domain for the callee; `guarded(x)`, where `x` is exactly the caller's own domain-bounded parameter. A computed argument (`guarded(x + 1.0)`) is skipped rather than approximated; there's no attempt to work out the image of a domain under an arbitrary expression, only the exact case where the value literally is the caller's own parameter. This threads through further calls too, a branch-free function calling a callee that itself calls a branchy one still resolves, as long as the whole chain is bare-parameter-passthrough and within `max_callee_depth`. ## Branches, in more detail A branch is refused unconditionally by the base lifter. A claim can still resolve one two ways: - **Domain-conditioned**: the branch condition compares an unmodified signature parameter against a literal, and the claim's own declared domain settles which side always runs. ```python def strength_to_distance(r: float, scale: str = "info") -> float: if scale == "info": return math.sqrt(1.0 - r ** 2) return 1.0 - r ``` ``` for r in [0, 1], scale in {"info"}, f(r, scale) == sqrt(1.0 - r^2) # proven ``` - **Affine-local**: the condition is over a *local* variable, not a bare parameter, traced back to unmodified parameters via a straight-line chain of simple assignments. ```python def divides(x: float, y: float) -> float: denom = x + y if denom == 0.0: return 0.0 return x / denom ``` ``` for x in [1, 1], y in [-1, -1], f(x, y) == 0.0 # proven ``` A **non-affine** local (`denom = x * y`) resolves too, but not by corners: corner evaluation over a domain box is only exact for affine expressions, so a non-affine condition is decided by the interval hull of its expression over the box instead. The hull contains the true range, so what it settles is settled soundly; a box it cannot settle (one where `x * y` can be zero and can be nonzero) leaves the branch undecided. ```python def ratio(x: float, y: float) -> float: denom = x * y if denom == 0.0: return 0.0 return x / denom ``` ``` for x in [1, 2], y in [1, 3], f(x, y) == 1/y # proven ``` The condition doesn't have to be bound to a name first, an expression written directly in the `if` resolves exactly the same way a named affine local does, via the identical mechanism: ```python def voltage_divider(vin: float, r1: float, r2: float) -> float: if r1 + r2 <= 0: raise ValueError("invalid resistances") return vin * r2 / (r1 + r2) ``` ``` for r1 in [-1, -1], r2 in [0, 0], raises(f(vin, r1, r2), ValueError) # proven ``` - **Boolean and identity guards, and the finite-set split**: a parameter annotated `bool` states its entire domain the same way a `Literal[...]`/`Enum` annotation does, the real `{False, True}` objects, never the numerically-equal `0`/`1` (code comparing with `is True` genuinely distinguishes them, and probe sampling draws the stated values too). Every spelling of a boolean guard resolves: bare truthiness (`if flag:`), equality (`== True`, `== 1`, `!= 0`), identity (`is True`, `is not True`, decided exactly, per element, over a discrete domain; an interval domain leaves identity undecided by design), negation (`not flag`), and either ordering inside `and`/`or` compounds. And when the declared (or stated) domain spans both branches, a small finite domain (up to 8 values) splits into its individual values and the claim proves on each piece separately, so this proves with nothing declared in the claim at all: ```python def gate(flag: bool, x: float) -> float: if flag is True: return x + 1.0 return x - 1.0 ``` ``` for x in [1, 5], f(flag, x) >= x - 1 # proven (split into {False}, {True}) ``` An *authored* int domain keeps honest identity semantics: under `for flag in {1}`, the guard `flag is True` decides `False` (`1 is not True` in Python), so a then-branch claim falsifies rather than being waved through as equality. See `mathema audit`'s blocked detail (in [mathema audit](modes/audit.md)) for a precise diagnosis of exactly why a specific branch is or isn't resolvable in your own code; the same diagnosis a *live claim's* own failure sketch now names too, rather than one generic message for every reason branch pruning could fail: "this condition shape isn't recognized at all" reads differently from "the shape is fine, but the domain doesn't cover the parameters it needs", and `raises(...)` specifically says so directly when there's no explicit `raise` anywhere in the function to find in the first place; see [Authoring claims](authoring.md)'s own note on `raises(...)`. ## Ternaries A ternary (`x if cond else y`) whose condition is a comparison or a boolean combination of comparisons always lifts, to a domain-agnostic `sympy.Piecewise`, no domain needed at lift time, since `try_prove()`'s own sign-decidability chain resolves it later, the same way a `min`/ `max` clamp does. A **bare boolean-name condition** (`x if flag else y`) is different: on its own, an ordinary real-valued sympy symbol isn't a sympy Boolean, so there's nothing to build a `Piecewise` *from* without already knowing `flag`'s truth value. This resolves the same way a domain-conditioned branch does, if the declared domain pins `flag` to exactly `True` or exactly `False`, the matching side is evaluated directly, no `Piecewise` involved at all: <!-- example: pick run --> ```python def pick(flag: bool, x: float, y: float) -> float: return x if flag else y ``` <!-- example: pick verdicts fn=pick route=derive --> ``` for flag in {True}, x in [0, 1], y in [0, 1], f(flag, x, y) == x # proven for flag in {False}, x in [0, 1], y in [0, 1], f(flag, x, y) == y # proven ``` A domain that admits *both* `True` and `False` stays exactly as unresolved as before, genuinely ambiguous, not guessed at. And a `flag` that's *reassigned* anywhere in the function body before the ternary is never trusted against its original declared domain either, even if the domain would otherwise pin it, the same never-reassigned-anywhere check `lift_conditioned()` already applies before trusting a domain against an `if` *statement*. ## Tuple returns <!-- example: tuple run --> ```python from math import cos, sin def to_cartesian(r: float, theta: float) -> tuple: return r * cos(theta), r * sin(theta) ``` <!-- example: tuple verdicts fn=to_cartesian route=derive --> ``` f(r, theta) == (r * cos(theta), r * sin(theta)) # proven, elementwise f(r, theta)[0] == r * cos(theta) # proven, single element ``` ## Bundled parameters A parameter that bundles many scalars, a flat `@dataclass`, or a dict accessed only via literal string keys, expands into one symbol per field/key instead of being refused outright: <!-- example: bundled run --> ```python from dataclasses import dataclass @dataclass class Config: a: float b: float def sum_fields(cfg: Config) -> float: return cfg.a + cfg.b ``` <!-- example: bundled verdicts fn=sum_fields route=derive --> ``` f(cfg) == cfg.a + cfg.b # proven ``` A claim can address a field the same way regardless of whether the function itself used attribute or subscript syntax (`cfg.a` or `cfg["a"]`). There's no way to substitute "a different Config instance" in this grammar, an `f(...)` call's argument for a bundled parameter's slot must be a bare reference to the same parameter name. ## Clamps <!-- example: clamp run --> ``` - docs/evidence-ladder.md (12733 bytes)
# The evidence ladder Evidence isn't binary, and the most useful thing a verification tool can do is tell you honestly how strong each piece of it is. mathema ranks every supported claim by how it was established, from a proof that covers every input in the declared domain down to a sentence someone wrote in a docstring, and it never lets a weaker result be reported as a stronger one. <div class="mx-figure"> <svg class="mx-diagram" viewBox="0 0 640 330" role="img" aria-labelledby="ladder-title ladder-desc" xmlns="http://www.w3.org/2000/svg"> <title id="ladder-title">The evidence ladder</title> <desc id="ladder-desc">Six rungs, strongest at the top: derive and examine, derive extensive, informed probing, probing, documented, declared.</desc> <g class="mx-d-rail"><line x1="40" y1="20" x2="40" y2="310"/><line x1="600" y1="20" x2="600" y2="310"/></g> <g class="mx-d-rung mx-d-strong"><rect x="60" y="20" width="520" height="40" rx="3"/><text x="80" y="45" class="mx-d-label">derive · examine</text><text x="560" y="45" class="mx-d-verdict" text-anchor="end">proven</text></g> <g class="mx-d-rung mx-d-strong"><rect x="60" y="70" width="520" height="40" rx="3"/><text x="80" y="95" class="mx-d-label">derive:extensive</text><text x="560" y="95" class="mx-d-verdict" text-anchor="end">proven</text></g> <g class="mx-d-rung"><rect x="60" y="120" width="520" height="40" rx="3"/><text x="80" y="145" class="mx-d-label">informed probing (four techniques)</text><text x="560" y="145" class="mx-d-verdict" text-anchor="end">holds (n=…)</text></g> <g class="mx-d-rung"><rect x="60" y="170" width="520" height="40" rx="3"/><text x="80" y="195" class="mx-d-label">probe · probe:lifted_numeric</text><text x="560" y="195" class="mx-d-verdict" text-anchor="end">holds (n=…)</text></g> <g class="mx-d-rung mx-d-weak"><rect x="60" y="220" width="520" height="40" rx="3"/><text x="80" y="245" class="mx-d-label">documented</text><text x="560" y="245" class="mx-d-verdict" text-anchor="end">stated deliberately</text></g> <g class="mx-d-rung mx-d-weak"><rect x="60" y="270" width="520" height="40" rx="3"/><text x="80" y="295" class="mx-d-label">declared</text><text x="560" y="295" class="mx-d-verdict" text-anchor="end">inferred from a summary</text></g> </svg> </div> ## The rungs, strongest first | Rung | Verdict | What established it | |---|---|---| | `derive`, `derive:brute_force`, `derive:math_only` | `proven` | A proof. The body was lifted to a symbolic expression and the claim settled over the whole declared domain (`derive`); every point of a finite domain was checked (`brute_force`); or the mathematics was proven and the record reports that line alone, with the computation and what it does with a missing input outside its remit (`math_only`). | | `examine` | `proven` | A proof from the function's structure, with nothing lifted: a guard that rejects before the body runs, or a body that writes nothing outside itself. | | `derive:extensive` | `proven` | The same, reached only by the deeper search you opt into with `extensive=True`. | | `derive:brute_force:within_float64` | `proven` | Every point of a finite domain was run and the claim held at each to within float64's precision: at a point with no exact value the float64 result misses the relation by at most 8 unit roundoffs of the value compared against, plus the function's relative condition number times the magnitude of the value it returned there, where both can be read, and a larger miss is not this rung: not counted, so `unknown`, or a `holds` on `derive:brute_force` under a declared tolerance; the record states the largest delta. A point lands here when it has no exact value, including when a decision the body takes on a float (a comparison, a branch, a rounding, a dict key) goes one way in the exact reading and the other in the function's own float run; where every decision goes the same way, the point stays exact. Nothing was left untried, which puts it above sampling; a difference smaller than the stated delta would not show, which puts it below an exact proof. | | `probe:semi_analytical`, `probe:algorithmic`, `probe:minimal_example`, `probe:counterfactual` | `holds (n=...)` | The real function survived `n` trials whose inputs were chosen by analysis, such as the points where a denominator vanishes, by a technique specific to the claim, by fuzzing that shrinks what it finds, or by refilling a missing value to see what the function would have done. | | `probe`, `probe:lifted_numeric` | `holds (n=...)` | The real function survived `n` seeded random trials; or, where the claim takes a derivative, integral, sum or limit that running the code cannot give, mathema's own symbolic reconstruction of the function survived `n` trials (`probe:lifted_numeric`, and the note says so). | | `axiom` | `trusted` | A definition row in a compendium, trusted rather than adjudicated: it counts as much as a plain `holds`, never more. | | `documented` | none | Stated intent that a person has accepted with `mathema accept --intent`. | | `declared` | none | Stated intent (a docstring summary, an `Intent:` block, an `intent:` field) that no person has accepted yet, the weakest rung there is. | `derive` and `examine` share the top rung, a proof either way; the informed probing routes share a rung too: they draw on different information, and none is stronger than another. A language's own derive strategy reports `derive:` followed by its mechanism's name and ranks with `derive:extensive`; one that names no mechanism (`derive:language`) ranks with `derive`. The ladder is defined in the engine as `mathema.conjecture.EVIDENCE_LADDER`, and a route mathema does not recognise, such as one from a verification technique you have plugged in yourself, ranks below everything it does. <a id="a-proof-is-the-mathematics-float-is-the-code"></a> ## A proof is the mathematics; `[float]` is the computation A `proven` from the derive route means the claim holds in exact real arithmetic over the declared domain, with infinity as infinity, and nothing more. It does not say the computation in float64 gets the same answer. That is a separate claim, and mathema makes it for you: every claim the derive route proves spawns a companion named `<name>[float]`, in the numerical stability family, adjudicated on the probe route against the real code. A printed record shows it as the `computation` line under the claim, beside the `mathematics` line that carries the proof; the record file keeps it as its own row, `<name>[float]`. The companion runs the relation at every corner of the declared domain and at sampled interior points. A raise, a `NaN`, or an `inf` or a loss of precision where the relation fails on the executed values falsifies it, with that point as the witness. An unbounded direction runs to the claim's `|inf|` when one is declared, and otherwise out to float64's maximum (`sys.float_info.max`, about `1.8e308`), sampled log-uniformly so moderate magnitudes are visited too. <!-- example: companion run --> ```python import mathema from mathema.conjecture import claim def one(x: float) -> float: """One, computed the long way round.""" return (x + 1.0) - x for law, route in [("for x in [0, 1e6], f(x) == 1", "derive"), ("f(x) == 1", "derive"), ("f(x) == 1", "derive:math_only")]: rec = mathema.check(one, claims=[claim(law, name="one", route=route)]) for p in rec.probes: print(f"{route:16} {p.name:10} {p.verdict:9} " f"{p.counterexample or ''}".rstrip()) ``` <!-- example: companion output --> ```text derive one proven derive one[float] holds derive missing[x] holds derive one proven derive one[float] falsified x = -1.7976931348623157e+308 derive missing[x] holds derive:math_only one proven ``` `(x + 1) - x` is `1` for every real `x`, so all three proofs stand. The third row of the first block is the policy row mathema writes for a float's nan (what f does with a value that is not there); it holds because f gives nan back. In float64 the `+ 1` is lost once `|x|` passes `2^53`, so the companion of the unbounded claim is falsified, and its row names the stratum: mathematics sound, its computation numerically unstable (`implementation:numerical-instability`). Two claims, two verdicts, and the companion gates `mathema verify` like any other claim. Which remedies apply depends on what the condition number at the witness says. Here it says the loss is the code's: `(x + 1) - x` is a well-conditioned way to write `1`, and the precision goes in the arithmetic rather than in the inputs, so the companion is not accepted on its own. The ways out are to fix the code, to accept the whole claim as a discovery (the proven row and its companion retire together under one acceptance, the witness kept, and the claim no longer counts as proven), to narrow the claim's domain knowingly (edit it, then accept it `--as superseded`), or to state the claim with `route="derive:math_only"` (`[derive:math_only]` in a docstring), which reports the mathematics line only, leaves the computation and its policies (what f does with a missing input) outside its remit, and records the opt-out on the proof's row, which is why the last block above has a single row. Where the loss is inherent in the inputs instead (no float64 computation could do better at the witness), the companion may be accepted alone as a discovery with `mathema accept`. Whenever the companion fails along an unbounded direction, as the one above does at `-1.8e308`, the note also offers `let |inf| be B`, whatever the conditioning says and whether the witness was a lost digit, an overflow, a `NaN` or a raise. The binding bounds only the computation and never the proof, which stays over the full domain. mathema runs the claim under the binding before offering it and offers it only where the computation line then holds: B is the condition number's own bound where it gives one and it holds, and otherwise the largest power of ten below the witness's magnitude at which the run holds, found by bisection on the exponent in at most ten runs, which are filed apart from the claim's own evidence. For `(x + 1) - x` over the reals that is `let |inf| be 1e+15`, since `x + 1.0` is exact below `2^53`; where no power of ten holds, nothing is offered. The companion is written to the verified record beside its parent, with `meta.mathema.companion_of` naming it. It is never part of the declared layer: it is respawned from its parent on every adjudication, so it does not enter the claims fingerprint and is not repopulated as a claim of its own. A limit or an integral is a statement about the mathematics and spawns no companion. ## What sits off the ladder The ladder ranks how a claim came to be *supported*. Four other outcomes are reported alongside it, and none of them is a weak form of support: | Verdict | Means | |---|---| | `falsified` | A counterexample was found by running the function, and it is kept permanently. A falsification is equally definitive whichever route found it. | | `unknown` | An adjudication ran and decided nothing either way, for instance a proof attempt that could not close. | | `skipped` | The claim could not be adjudicated at all, for a reason the record names. | | a transition | Not a verdict: a claim that was once `proven` or `holds` and no longer is keeps the verdict it fell to, and the record keeps the move (`regressed` or `weakened`, with its cause) beside it until a person acknowledges it. | A `falsified` verdict is knowledge rather than failure: it tells you exactly where the function and the claim part ways, and the [accept workflow](modes/accept.md) lets a person decide whether that is a bug in the code or a discovery about the specification. ## Why the rungs are kept apart A result that holds on a thousand random inputs and a result that holds for every input are different kinds of knowledge, and a report that blurs them is telling you what you want to hear. So every verdict carries its route, a `holds` always carries its trial count, a derive attempt that cannot close hands the claim to the probe route with the reason it stopped kept in the record (a sampled `holds` never passes itself off as a proof), and a symbolic disproof that nothing can reproduce against the real function, even compared exactly, comes back `unknown` and flagged instead of `falsified`, since it more likely points at a fault in the engine than in your code. [Claim-driven development](cdd.md) has the full verdict vocabulary, and [the derive route](derive-route.md) covers which functions can reach the top rung. - docs/existing-codebase.md (12066 bytes)
--- hide: - toc --- # Add claims to an existing codebase This guide takes a package with functions, tests and no claims to a passing `mathema verify`, without rewriting anything. It assumes the [quick start](quickstart.md), so you have written one claim and seen a record. The running example is the fees module of a billing service, three functions and a small test file: <!-- example: codebase file=billing/__init__.py --> ```python """Fees and settlements for a billing service.""" ``` <!-- example: codebase file=billing/fees.py --> ```python def late_fee(days: int, base: float) -> float: """The fee for a payment that is `days` late: one percent of base a day.""" return base * 0.01 * days def discounted(price: float, rate: float) -> float: """The price after applying a discount rate.""" return price * (1 - rate) def settle(exposure: float) -> float: """The settlement amount for a signed exposure.""" return abs(exposure) ``` <!-- example: codebase file=test_fees.py --> ```python from billing.fees import discounted, settle def test_discounted(): assert discounted(100.0, 0.25) == 75.0 def test_settle(): assert settle(-3.0) == 3.0 ``` ## 1. See where you stand `mathema audit` gives every function under a package one line: where it lives, whether it has claims, whether the derive route could prove things about it, what state outside its parameters it touches, whether a test report covers it, and how well its docstring states its intent. <!-- example: codebase run requires=coverage --> ```bash mathema audit billing --root . ``` <!-- example: codebase output --> ```text || || derive route || typing || globals || || docs || key | span || claims || derives | cx | reason | code || typed | finite_domain || vars | mutates | funcs || tested || quality || docsync billing.fees .discounted | 6:8p || {11 | 0 | -} || yes | 1 | - | - || yes | - || - | - | - || no-report || 4/5 || 26% .late_fee | 1:3p || {7 | 0 | -} || yes | 1 | - | - || yes | - || - | - | - || no-report || 4/5 || 26% .settle | 11:13p || {9 | 0 | -} || yes | 1 | - | - || yes | - || - | - | - || no-report || 3/4 || 26% 0/3 claimed, 3/3 derivable, 3/3 derive reads with nothing supplied, 3/3 fully typed, 11/14 docstring quality criteria met, no coverage.json/.coverage report found, mean docsync 26%. `derives` is what the derive route can do here, given the domain the signature, docstring and claims declare. The reason/code cells describe what derive reads with nothing supplied, so a branch:needs-domain row reads blocked there and derives all the same, once a claim declares the domain that prunes the branch. Neither is a ceiling: a probe claim can still be written and checked for every function here. ``` `0/3 claimed`, and all three could be proven. The `claims` cell reads `{floor | actual | expected}`: the least a function of this shape gives you to state (eleven for `discounted`, one per relevant built-in claim and target), what it states (nothing yet), and what a function of this shape typically carries (`-`: not known without a corpus). `tested` says `no-report`: there is no coverage report yet for the tests to count. ## 2. Scaffold the store `mathema init` writes the git files a tracked store wants and, for each function with no claims, an empty placeholder in a claims file: <!-- example: codebase run --> ```bash mathema init billing --root . cat claims/billing.fees.claims.yaml ``` <!-- example: codebase output --> ```text mathema init: scaffolded git files: .gitattributes .mathema/.gitignore mathema init: wrote stub entries to: claims/billing.fees.claims.yaml # mathema init: bare declared stubs for billing.fees (fill in claims; an empty list means nothing declared yet) billing.fees.discounted: claims: [] billing.fees.late_fee: claims: [] billing.fees.settle: claims: [] ``` A stub is a task, not a claim. `init` is additive: run it again as the package grows and it appends keys it has not seen, never touching a claim you wrote. ## 3. Start from a suggestion For one function, `mathema claims --suggest` renders the standard claims mathema would check, each with the route it would take, in three sections: claims that stand alone, questions with candidate answers (which way f moves or bends in each parameter), and claims likely to be unknowable (none here): <!-- example: codebase run --> ```bash mathema claims billing.fees.discounted --suggest --root . ``` <!-- example: codebase output match=subset --> ```text billing.fees.discounted: 18 suggested claim(s) (adopt with: mathema claims KEY --adopt NAME) individual claims: - commutative: f(price, rate) == f(rate, price) [route best] - associative: f(f(price, rate), c) == f(price, f(rate, c)) [route best] - is_deterministic: f(price, rate) == f(price, rate) [route best] - is_state_safe: f(price, rate) == f(price, rate) [route best] - is_numerically_stable: g(f, price, rate) == 1 [route best] - is_representation_safe[price]: is_representation_safe(price) [route examine] - is_representation_safe[rate]: is_representation_safe(rate) [route examine] questions with candidate answers (adopt every answer that holds): monotonicity[price]: - monotonic_increasing[price]: d(f(price, rate), price) >= 0 [route best] - monotonic_decreasing[price]: d(f(price, rate), price) <= 0 [route best] shape[price]: - affine[price]: d(f(price, rate), price, price) == 0 [route best] - convex[price]: d(f(price, rate), price, price) >= 0 [route best] - concave[price]: d(f(price, rate), price, price) <= 0 [route best] monotonicity[rate]: - monotonic_increasing[rate]: d(f(price, rate), rate) >= 0 [route best] - monotonic_decreasing[rate]: d(f(price, rate), rate) <= 0 [route best] ``` A suggestion is not verified and never gates until someone adopts it. A higher rate means a lower price, so adopt the one that says so: <!-- example: codebase run --> ```bash mathema claims billing.fees.discounted --adopt "monotonic_decreasing[rate]" --root . cat claims/adopted.claims.yaml ``` <!-- example: codebase output --> ```text adopted monotonic_decreasing[rate] into ./claims/adopted.claims.yaml: d(f(price, rate), rate) <= 0 billing.fees.discounted: claims: - name: monotonic_decreasing[rate] statement: d(f(price, rate), rate) <= 0 route: best grammar: mathema ``` ## 4. Try it before the sweep writes anything `mathema check` adjudicates a function's claims and writes no record, so it is the place to find out whether a claim is right before `verify` keeps it: <!-- example: codebase run --> ```bash mathema check billing.fees.discounted --root . ``` <!-- example: codebase output --> ```text FAIL billing.fees.discounted: source, no side effects; claims 3/3 checked (0 proven, 2 holds, 1 falsified) <- 1 falsified claim(s) ``` Falsified. The witness says why: <!-- example: codebase run --> ```python import mathema from billing.fees import discounted (p,) = mathema.claims.check_conjectures(discounted, [ mathema.claim("d(f(price, rate), rate) <= 0", name="monotonic_decreasing[rate]")]) print(p.verdict, p.counterexample) ``` <!-- example: codebase output --> ```text falsified rate = -2.7255878198803085 -> -32.66347642639832, rate = 4.922577492583454 -> 34.39055087522713 at price = -8.767334983247743 (not decreasing) ``` The derivative of `price * (1 - rate)` in `rate` is `-price`, which is positive when the price is negative, and the claim said nothing about prices. Both values were computed at the same price, the one the witness prints after `at`. (`d(f(price, rate), rate)` is the derivative in `rate`; [the claim grammar](grammar.md#calculus) lists the calculus forms.) The suggestion was right about the function and silent about its domain, which is the usual state of a suggestion. Say what the function is for, a price that is never negative and a rate between none and all of it: <!-- example: codebase file=claims/adopted.claims.yaml --> ```yaml billing.fees.discounted: claims: - name: monotonic_decreasing[rate] statement: "for price in [0, 1e6], rate in [0, 1], d(f(price, rate), rate) <= 0" route: best grammar: mathema ``` ## 5. Put a claim beside the code A claim can also live in the function's docstring, where the next reader of the code sees it. `settle` returns a magnitude: <!-- example: codebase file=billing/fees.py --> ```python def late_fee(days: int, base: float) -> float: """The fee for a payment that is `days` late: one percent of base a day.""" return base * 0.01 * days def discounted(price: float, rate: float) -> float: """The price after applying a discount rate.""" return price * (1 - rate) def settle(exposure: float) -> float: """The settlement amount for a signed exposure. Claims: nonneg: f(exposure) >= 0 """ return abs(exposure) ``` The two places are equal: a docstring claim and a claims-file claim are adjudicated the same way, and [Authoring claims](authoring.md) says which wins when both name the same claim. ## 6. The first sweep <!-- example: codebase run --> ```bash mathema verify --root . mathema audit billing --root . --filter unclaimed --cols key,claims ``` <!-- example: codebase output --> ```text ok billing.fees.discounted: no baseline record; 2 proven (1 claim, 1 built-in), 2 holds, 0 falsified ok billing.fees.late_fee: no baseline record; 1 proven, 0 holds, 0 falsified ok billing.fees.settle: no baseline record; 2 proven (1 claim, 1 built-in), 2 holds, 0 falsified 0 unchanged since the last run (not run again), 3 checked, 0 problem(s) grammars detected: mathema; verified by this run: mathema 4 intents to accept (1 package, 3 functions): mathema accept --intent {"prefix":"billing.fees.","cols":["key","claims"],"rows":[["late_fee",0]]} ``` Both claims proved on the derive route, and every record also carries `dependencies_current`, the claim `verify` adds that what the function depends on has not moved; that is the second `proven` on the two claimed functions and the only one on `late_fee`. The `2 holds` on `settle` are the proof's computation line, the same claim run through the real code in floating point, and its policy line for a `nan` input; the `2 holds` on `discounted` are its policy lines for a `nan` price and a `nan` rate. `--filter unclaimed` is the list of what is left, as data, cut to two columns with `--cols`: one function. The records under `.mathema/verified/` are the evidence, and they are meant to be committed with the code. ## 7. Let the tests you have count The tests already exercise `discounted` and `settle`. Run them under coverage once, and `mathema coverage` counts their lines beside the lines mathema's own probes and proofs reached: <!-- example: codebase run --> ```bash python -m coverage run -m pytest -q test_fees.py python -m coverage json -q mathema coverage billing --root . ``` <!-- example: codebase output match=subset --> ```text 2 passed in 0.05s 100% billing.fees.discounted [test+probe+derive] 100% billing.fees.late_fee [probe] 100% billing.fees.settle [test+probe+derive] implementation coverage: 100% ``` `late_fee` has no claim of its own, so it reads `probe` alone: `coverage` runs mathema's standard claims about a function while tracing it, and the lines they ran count, but a proof counts the body as modelled only for a claim included for the function and recorded by the sweep, as `discounted`'s and `settle`'s are. [`mathema coverage`](modes/coverage.md) explains the three sources and what happens to a test report when the code moves on. From here, [Gate a pipeline with mathema verify](gate-a-pipeline.md) puts the sweep in CI, and [From a pytest test to a claim](from-a-pytest-test.md) turns the tests you already have into claims. - docs/extending.md (29848 bytes)
# Extending mathema mathema discovers extensions through entry points. A package that registers one can add a claim family, replace how something is shown, or contribute MCP tools, without mathema knowing anything about it beyond the name it registered under. This page is for people writing such a package. It is not the API reference: [that page](api.md) covers what you use to write and check claims. The surface here is narrower in audience and wider in what it exposes. ## The entry-point groups | Group | What it registers | Discovered by | |---|---|---| | `mathema.claim_families` | a claim-adjudication strategy: can this claim be proven, and by which routes | `mathema.families` | | `mathema.capabilities` | a presentation hook: how should something already computed be shown | `mathema._providers` | | `mathema.mcp_tools` | extra tools for the MCP server | `mathema.interfaces.mcp.server` | | `mathema.target_resolvers` | a resolver for tagged target keys (`<tag>:...`) | `mathema._target_resolvers` | | `mathema.runtime_types` | a runtime type adapter: how a vector, matrix or table is realised as the object a function receives (see [runtime types](runtime-types.md#adding-a-runtime-type)) | `mathema.runtime_types` | | `mathema.languages` | a named language a claim quantifies over with `L[<name>]` | `mathema.languages` | | `mathema.language_adaptors` | an adaptor turning an imported object (a schema class, a type) into a language, or `None` for an object it does not handle | `mathema.languages` | | `mathema.language_refinements` | a refinement key inside `L[...]` (`len`, `depth`), the entry point's name being the key | `mathema.languages` | | `mathema.lexicon` | worked claims (rows, sections, tags, example functions) that join mathema's lexicon | `mathema.lexicon` | | `mathema.compendium` | directories of compendium files: claims about a library's functions, read beside the ones mathema bundles | `mathema.compendium` | A claim family answers "can this be proven." A capability answers "how should this be shown." They are separate mechanisms with separate groups on purpose, and nothing is discoverable through both. Discovery is fail-soft everywhere. A provider that raises on import is skipped with a warning, and mathema falls back to its own behaviour. Your extension being broken or absent never crashes someone's run. ## Runtime type adapters An adapter registered under `mathema.runtime_types` follows the `mathema.runtime_types.RuntimeTypeAdapter` protocol, described with its `name`, `kinds`, `requires`, `detect`, `realise` and `observe` in [runtime types](runtime-types.md#adding-a-runtime-type). Besides `ALIASES`, it may state `USES`, a `BodyUses` naming the uses of a parameter its type supports and a list does not: ```python from mathema.runtime_types import BodyUses class TorchTensorAdapter: name = "torch.Tensor" kinds = frozenset({"vec", "mat"}) requires = ("torch",) ALIASES = {"th": "torch"} USES = BodyUses( attributes=frozenset({"T", "shape", "device"}), methods=frozenset({"mean", "sum", "numel", "detach"}), matmul=True, described="a torch tensor") ... ``` `attributes` are names read off the parameter (`x.shape`), `methods` names called on it (`x.mean()`), `keyed` methods called with a column name as the first argument (`df.groupby("k")`), and `matmul` says the type can be an operand of `@`. `described` is how the record names the type: `the body uses it as a torch tensor`. An unannotated parameter is drawn as the adapter's type when every use the body makes of it (apart from what every Python object has, such as `.__class__`) is one the adapter declares, the function's module imports the adapter's library, and no other imported library's adapter supports the same uses. An attribute or method the adapter does not declare rules it out, and the hint names that use; with two matching libraries the parameter is drawn as a list and the hint names both. Declare only names your type has and a list lacks: a name a list also has (`index`, `copy`, `sort`) would draw a list-using function as your type. An adapter without `USES` is never chosen this way. An adapter whose `kinds` include `table` realises mathema's typed table: a Spark, Arrow or database frame in a package needs nothing in core beyond the adapter. `realise` receives an `AbstractTable`, named columns of one length in order (`column_names()`, `row_count()`), each an `AbstractVec` whose `values` hold the column's cells, `missing` the positions holding a hole, and `element_type(column)` its type, one of `float`, `int`, `bool` and `str` (`column_types()` gives them all). It builds the frame with each column in the library's type for that element type, and a hole as the library holds one (a hole the library cannot hold as drawn, NaN in a string column, say, as its null). `observe` turns a returned frame back into an `AbstractTable`, stating each column's `element` from the library's type, so a column of holes only keeps its type; a one-dimensional result indexed by column names (what a reduction of a table returns) is an `AbstractVec` with those names as its `labels`, which a claim reads by name: ```python from mathema.runtime_types import (AbstractTable, AbstractVec, NotMine, element_type) _TYPES = {"float": "double", "int": "bigint", "bool": "boolean", "str": "string"} class SparkFrameAdapter: name = "pyspark.sql.DataFrame" kinds = frozenset({"table"}) requires = ("pyspark",) def detect(self, annotation): ... def realise(self, table, options): schema = ", ".join(f"{name} {_TYPES[element_type(col)]}" for name, col in table.columns.items()) rows = [tuple(None if k in col.missing else col.values[k] for col in table.columns.values()) for k in range(table.row_count())] return self.spark.createDataFrame(rows, schema) def observe(self, obj): if type(obj).__name__ != "DataFrame": return NotMine ... return AbstractTable({name: AbstractVec(values, missing, element=element) for name, (values, missing, element) in columns.items()}) ``` Code inside mathema reads a table through `mathema.runtime_types` (`column_names`, `column_types`, `column`, `row_count`, `as_table`), which goes through `observe`, so a registered adapter's frames read exactly as pandas and polars ones do. ## Target resolvers A fourth group, `mathema.target_resolvers`, turns a tagged target key (`<tag>:src/ema#ema`) into ordinary callables. The entry point's name is the tag it serves; the loaded object is a callable `resolver(target, root)` returning a `Target` (from the `targets` seam) whose values are Python callables standing in for the foreign functions, or `None` for a target it does not handle, in which case resolution falls through to the normal import path. The seam is consulted by `mathema check`'s target resolution and by `verify`'s store-key sweep, and it is fail-soft: a resolver that fails to load warns and is skipped, and an unregistered tag fails (exit 2) with a message naming the tag and the entry-point group an adaptor package registers under. What the returned callables must satisfy is the runtime contract in `mathema.interfaces.runtime`: raise real exceptions for the failure kinds, return non-finite floats for non-finite markers, and return plain values otherwise. Calls arrive positionally. ## Registered safety predicates A claim family registered under a name shaped like `is_<slug>_safe` contributes that name to the safety-predicate vocabulary: the grammar recognizes the claim form (`is_cyber_safe(x)`, or the postfix `x is cyber safe`), and the claim adjudicates through the family's own derive and probe halves, exactly as mathema's built-in members do. The registered name IS the predicate, the same name-is-the-contract rule target resolvers use, so a family owning several predicates registers one entry point per predicate (they may load the same object). `mathema.claim_families.SafetyFamily` is the assembly kit: pass the base name, the derive half, and optionally the probe half, and the family verdict contract (a falsification must carry its witness) is enforced for you. The static tables (`routes.SAFETY_PREDICATES` and kin) keep meaning core's own vocabulary; live membership is read through `routes.safety_predicates()` / `routes.examine_predicates()`. ## Registered languages and adaptors `L[<name>]` in a claim resolves through the registry in `mathema.languages`: an in-process `register_language(name, obj)` first, then the `mathema.languages` entry point of that name, then a dotted path to a `Language` object, and last the `mathema.language_adaptors` adaptors, each called as `adapt(obj)` on the imported object and answering a `Language` or `None`. The adaptors are asked in an explicit order: an adaptor may carry `__mathema_adaptor_priority__`, an int (0 when absent), and a higher one is asked first, ties going to the entry-point name. An adaptor that recognises a library's own model classes sets a higher priority than a structural one, so a SQLAlchemy class that is also a dataclass goes to the SQLAlchemy adaptor rather than the dataclass one; `language_adaptors()` returns the registry in that order, for a package that builds on the adaptors itself. A language is any object satisfying the `Language` protocol; `language_problems(obj)` lists what one is missing, and a registered or loaded object that fails it is skipped with a warning, never served. Core ships no language: the alphabets, predicate languages, hazard families and schema adaptors are the `mathema-language` package's, and an unknown name is refused with the vocabulary and the group to register under. An output-contract predicate registered under a name shaped `output_<slug>` or `is_<slug>_output` joins the grammar the way `is_<slug>_safe` does. A language may also declare how a function over it refuses a value outside it and what counts as answering a member, as two optional attributes: `refusal`, a `Refusal`, and `defined_answer`, a `DefinedAnswer`. `excluded_outside_domain` then holds an outside draw to the declared refusal instead of any raise, and `is_language_defined` holds a member to the declared answer instead of any return or exit status, and a non-member to the declared refusal instead of any raise. Each names the exception classes that count (optionally narrowed by a `when` test on the exception) and a `returns` test on a returned value, and its `text` is how a witness names it. `Refusal.exit(2)` and `DefinedAnswer.exit(0, 1)` are a command-line program's: `SystemExit` with exit code 2, and a return or `SystemExit` with exit code 0 or 1. ```python from mathema.interfaces.extension import DefinedAnswer, Refusal class ArgvLanguage: ... refusal = Refusal.exit(2) defined_answer = DefinedAnswer.exit(0, 1) ``` Either may be absent or `None`, which keeps the claims' default reading, and `language_problems` reports one of the wrong type. ## What a family probe returns A family's empirical half is the callable it registers under `"probe:algorithmic"`, called as `probe(fn, facts, claim, domain, rng, trials)`, and it answers `None` to decline or a tuple: | Form | Meaning | |---|---| | `(verdict, checked, cx)` | the verdict, how many trials ran, and the witness (a falsification must carry one) | | `(verdict, checked, cx, established)` | the same, with `established` naming why the coverage was exhaustive, which is the only way a probe may say `proven` | | either form, then a mapping | the mapping is merged into the record's `meta` | The trailing mapping is how a probe states what it resolved while it ran, the target language it held the output to, say, so that a `holds` record is not silent about what held. Use namespaced keys (`"my_package.target"`), since the record is shared with everything else that writes to it. The mapping reaches the record whichever report stands: when the probe's verdict stands it is the probe's meta, and when the probe skipped and derive's `unknown` stands instead, it is merged in beneath derive's own keys, which win on a clash. It is copied, never shared. One key merges rather than replaces: under `"mathema.language"` core already writes a description of every `L[...]` binding, one entry per parameter, and a family's entries sit beside those, so `{"mathema.language": {"return": [...]}}` from `output_in_language` lands next to the parameter's own entry. The mapping is an addition to the return shape, so a probe written against the three- or four-element forms keeps working unchanged and the extension API version stays where it is. ## Registered refinements `L[json, depth <= 6]` hands the refinement `depth <= 6` to whatever is registered under the key `depth`: `register_refinement(key, refine)` in the process, or a `mathema.language_refinements` entry point named by the key. `refine(language, interval)` returns the refined language, and `RefinedLanguage(language, key, interval, measure=..., plain=..., build=..., schema=..., hazard_kind=...)` builds one from a measure: it keeps the members whose measure lies in the interval, samples by rejection and then from `build`, visits the members at each bound first (`plain`, else `build`), draws one past a bound as the outside member, and merges `schema` into the persisted form. mathema registers no key; `refinement_keys()` lists what is served, and a key nothing serves raises `UnknownRefinement` naming them. ## Registered lexicons A package's worked claims join mathema's lexicon through the `mathema.lexicon` group. The entry point's name is the lexicon's name, and the object it loads (a module is the usual choice) provides `LEXICON`, a mapping of row keys to claim text, and optionally `SECTIONS`, `TAGS` and `EXAMPLE_FUNCTIONS`, in the shapes `mathema.lexicon` uses for its own. Installed, the rows are included in `entries()`, `search()`, `find()`, `get()` and `show()`, a section reads `<name>/<section>`, `find()` marks each row with the lexicon it came from, and `origin(key)` says the same. A row reusing a key another lexicon already has is skipped with a warning, mathema's own rows winning. mathema's `LEXICON` and its golden snapshot stay mathema's alone, so nothing about them depends on what is installed. A package lexicon is held to the checks mathema's own is, by the same code: `lexicon_problems(lexicon_source(name, module), golden=path, expected=verdicts)` returns every check with a problem (it parses and renders in both forms, matches its own golden snapshot, is a fixed point of render and parse in both modes, has a stable canonical form that reaches the same verdict, survives the declared store and the verified record, states its missing-value polic - docs/findings.md (12956 bytes)
# See what mathema finds Four short functions, each of the kind that passes review, and what mathema reports about each one. Every output on this page is from a real run. ## A midpoint that only works on integers <!-- example: finds file=mid.py --> ```python def midpoint(a: float, b: float) -> float: """The point halfway between a and b.""" return (a + b) // 2 ``` A test with `assert midpoint(2, 8) == 5` passes. The claim that matters is that a midpoint lies between its inputs, so mathema checks it over the integers and over the reals: <!-- example: finds run --> ```python import mathema from mid import midpoint print(mathema.check(midpoint, claims=[ mathema.claim("for a in [0, 100] subset Z, b in [0, 100] subset Z, " "min(a, b) <= f(a, b) <= max(a, b)", name="between_integers"), mathema.claim("for a in [0, 100], b in [0, 100], " "min(a, b) <= f(a, b) <= max(a, b)", name="between_reals"), ])) ``` <!-- example: finds output --> ```text mathema.Record(midpoint) · source, no side effects · form py:1825c3784c39 proven between_integers: for a in [0, 100] : int, b in [0, 100] : int, min(a, b) <= f(a, b) <= max(a, b) for a in [0, 100] : int, b in [0, 100] : int between_reals for a in [0.0, 100.0] : float|missing, b in [0.0, 100.0] : float|missing, min(a, b) <= f(a, b) <= max(a, b) falsified: min(a, b) <= f(a, b) fails at a = 99.9999, b = 100 falsified computation for a in [0.0, 100.0] : float, b in [0.0, 100.0] : float, min(a, b) <= f(a, b) <= max(a, b) counterexample link 1: min(a, b) <= f(a, b): a = 99.9999, b = 100: 99.9999 vs 99.0 holds policy f(a=nan) no missing policy stated; assumed propagates holds policy f(b=nan) no missing policy stated; assumed propagates ``` Proven for every pair of integers in range, and falsified over the reals, where floor division puts the midpoint of 99.9999 and 100 at 99. Under the falsified claim, the `mathematics` line carries the counterexample, and the two `policy` lines say what `midpoint` does with a `nan` in either argument: nothing in the claim says, so mathema assumes the `nan` propagates to the result, and it does. The same claim, two domains, two different and equally definite answers, which is why a claim always carries the domain it was checked over. ## A pole nobody sampled <!-- example: finds run --> ```python def discount_factor(x: float) -> float: """A discount factor that divides by one minus the rate.""" return 1 / (1 - x) ``` With no claims at all, mathema runs the laws every function gets and the safety checks that apply to this one: <!-- example: finds run --> ```python print(mathema.check(discount_factor)) ``` <!-- example: finds output match=subset --> ```text mathema.Record(discount_factor) · source, no side effects · form py:bc2becbbf4fb falsified monotonic_increasing[x]: d(f(x), x) >= 0 counterexample x = 1 falsified even: f(-x) = f(x) counterexample x = -1 proven is_deterministic: f(x) = f(x) missing for x (float) means nan proven is_defined: 1 - x != 0 falsified is_pole_safe[x]: is_pole_safe(x) counterexample x = 1 is admitted by the declared domain but sits at or beside a pole: the call raised ZeroDivisionError falsified is_representation_safe[x]: is_representation_safe(x) counterexample x = 1 (the int spelling) is admitted by the declared domain but the call raised ZeroDivisionError [implementation:representation] ``` (trimmed from fourteen entries). Random sampling over the reals lands on exactly `x == 1` with probability zero, so a property-based test can run this function a thousand times and see nothing wrong. mathema solves the lifted expression for where the denominator vanishes and then makes sure that point is tried, which is what the route on each result records: <!-- example: finds run --> ```python for p in mathema.check(discount_factor).probes: print(f"{p.name:<26} {p.verdict:<10} {p.route}") ``` <!-- example: finds output --> ```text monotonic_increasing[x] falsified derive monotonic_decreasing[x] falsified derive affine[x] falsified derive convex[x] falsified derive concave[x] falsified derive even falsified derive odd falsified derive idempotent falsified derive is_deterministic proven examine is_state_safe proven examine is_numerically_stable holds probe:algorithmic is_defined proven derive is_pole_safe[x] falsified probe:algorithmic is_representation_safe[x] falsified probe:algorithmic ``` Every falsification here carries a witness that was executed against the function. The derive rows are witnessed by the call at the pole itself (`even` fails at `x = -1` because `f(1)` raises), which says the claim has no value there, not whether its mathematics holds, so they carry no tag. `[implementation:representation]` means the mathematics was fine and the computation fell over, here because the integer `1` is admitted by the domain and raises. `is_defined` is the same pole seen from the other side: a claim named `is_defined` states the region on which `f` returns, and it is proven because `f` returns on exactly `1 - x != 0` and raises everywhere else. ## A claim that needed its domain Put-call parity for a Black-Scholes pricer is a true identity, and mathema [proves it](case-studies.md) over a realistic region of prices, rates, maturities and volatilities. Stated with no domain at all: <!-- example: parity file=options.py --> ```python import math def put_call_parity_gap(s: float, k: float, r: float, t: float, sigma: float) -> float: """A European call minus a European put on the same strike.""" root_t = math.sqrt(t) d1 = (math.log(s / k) + (r + 0.5 * sigma * sigma) * t) / (sigma * root_t) d2 = d1 - sigma * root_t phi = lambda z: 0.5 * (1.0 + math.erf(z / math.sqrt(2.0))) call = s * phi(d1) - k * math.exp(-r * t) * phi(d2) put = k * math.exp(-r * t) * phi(-d2) - s * phi(-d1) return call - put ``` <!-- example: parity run --> ```bash mathema check options.py --claim "f(s,k,r,t,sigma) == s - k*exp(-r*t)" ``` <!-- example: parity output --> ```text FAIL options.put_call_parity_gap: source, no side effects; claims 6/6 checked (0 proven, 5 holds, 1 falsified) <- 1 falsified claim(s) ``` The counterexample is `s = 1, k = 1, r = 1, t = -1, sigma = 1`, a negative maturity at which `math.sqrt(t)` raises. A claim with no domain covers every real input, and mathema will not assume the range you had in mind; the domain is part of the claim, and stating it is what turns this `falsified` into `proven`. ## An order that matters <!-- example: finds run --> ```python def ema(x: list[float], alpha: float) -> float: """Exponentially weighted moving average.""" y = x[0] for v in x[1:]: y = alpha * v + (1 - alpha) * y return y ``` <!-- example: finds run --> ```python print(mathema.check(ema)) ``` Among the results, all found with no claims written: <!-- example: finds output match=subset --> ```text bounded_lower min(x) <= f(x, alpha) falsified at x = [3.39795039513268, 3.3979503951326806, 3.39795039513268, 3.3979503951326806, 3.39795039513268, 3.3979503951326806, 3.39795039513268], alpha = -1.9849565326553186e+115 falsified computation min(x) <= f(x, alpha) 63 entries across 14 draws, sizes (1, 1) to (7, 1); counterexample x = [3.39795039513268, 3.3979503951326806, 3.39795039513268, 3.3979503951326806, 3.39795039513268, 3.3979503951326806, 3.39795039513268], alpha = -1.9849565326553186e+115: f returned -inf, and an infinity for a finite input is no value; and x = [1.7976931348623157e+308, -1.7976931348623157e+308, 1.7976931348623157e+308, -1.7976931348623157e+308, 1.7976931348623157e+308, -1.7976931348623157e+308], alpha = -1.8642753322018042e+135: f returned nan falsified policy f(x=[]) f(x, alpha) raises IndexError at x = [], alpha = 5.159088058806049 with no emptiness guard in the body: the empty input is stumbled into, not handled possible fixes: (i) if the IndexError is the intended refusal, state: raises(ema([], alpha), IndexError) (ii) guard the empty input at entry permutation_invariant let g = mathema.f.reverse_seq, f(x, alpha) = f(g(x), alpha) falsified at x = [8.6338492787308, 4.71865260026944, -2.6880969810273942, -9.949931458213397, 0.18213495115984912, 5.228217794578978, 8.329741555874289, -5.381751396732593], alpha = 2.9581766625133312 falsified computation let g = mathema.f.reverse_seq, f(x, alpha) = f(g(x), alpha) counterexample x = [8.6338492787308, 4.71865260026944, -2.6880969810273942, -9.949931458213397, 0.18213495115984912, 5.228217794578978, 8.329741555874289, -5.381751396732593], alpha = 2.9581766625133312: -378.93676851822386 vs 1734.7013930509886 falsified policy f(x=[]) f(x, alpha) raises IndexError at x = [], alpha = 5.159088058806049 with no emptiness guard in the body: the empty input is stumbled into, not handled possible fixes: (i) if the IndexError is the intended refusal, state: raises(ema([], alpha), IndexError) (ii) guard the empty input at entry scale_equivariant let g = mathema.f.scale_seq, let c be [-5.0, 5.0], c*f(x, alpha) = f(g(x, c), alpha) falsified at x = [-1.7976931348623157e+308, -1.7976931348623157e+308, -1.7976931348623157e+308], alpha = -1.7976931348623157e+308, c = -5 proven mathematics let g = mathema.f.scale_seq, let c be [-5.0, 5.0], c*f(x, alpha) = f(g(x, c), alpha) falsified computation let g = mathema.f.scale_seq, let c be [-5.0, 5.0], c*f(x, alpha) = f(g(x, c), alpha) counterexample x = [-1.7976931348623157e+308, -1.7976931348623157e+308, -1.7976931348623157e+308], alpha = -1.7976931348623157e+308, c = -5 [mathematics sound, implementation:numerical-instability] falsified policy f(x=[]) f(x, alpha) raises IndexError at x = [], alpha = 5.159088058806049 with no emptiness guard in the body: the empty input is stumbled into, not handled possible fixes: (i) if the IndexError is the intended refusal, state: raises(ema([], alpha), IndexError) (ii) guard the empty input at entry translation_equivariant let g = mathema.f.shift_seq, let c be [-5.0, 5.0], c + f(x, alpha) = f(g(x, c), alpha) falsified at x = [0.0, 0.0, 0.0], alpha = -1.7976931348623157e+308, c = -5 proven mathematics let g = mathema.f.shift_seq, let c be [-5.0, 5.0], c + f(x, alpha) = f(g(x, c), alpha) falsified computation let g = mathema.f.shift_seq, let c be [-5.0, 5.0], c + f(x, alpha) = f(g(x, c), alpha) counterexample x = [0.0, 0.0, 0.0], alpha = -1.7976931348623157e+308, c = -5 [mathematics sound, implementation:numerical-instability] falsified policy f(x=[]) f(x, alpha) raises IndexError at x = [], alpha = 5.159088058806049 with no emptiness guard in the body: the empty input is stumbled into, not handled possible fixes: (i) if the IndexError is the intended refusal, state: raises(ema([], alpha), IndexError) ``` Scaling or shifting every input scales or shifts the average the same way: the `mathematics` line of each equivariance is proven for sequences of any length. The bound fails because nothing restricts `alpha` to `[0, 1]`, and outside that range this is not a weighted average at all, which is a finding about the missing domain rather than the loop. Reversing the input changes the answer, as it should for an average that weights recent values more heavily: mathema does not know that is intended, so it reports the counterexample and leaves the judgement to a person. Every claim over `x` also fails at the empty list, on its `policy` line, because `ema` reads `x[0]` first. The `computation` line under each equivariance runs the proven law through the real code in floating point, where nothing bounds the inputs, so it reaches elements and an `alpha` at float64's extremes, about `1.8e+308` in size. There the loop's arithmetic overflows and subtracts one infinity from another, so both sides of the law come out NaN, and a NaN is no value: it agrees with nothing, not even the other side's NaN. The mathematics is sound and the float code does not follow it out there; a domain for `alpha`, or a `let |inf| be ...` binding, is the fix. [A first look](first-look.md) takes `ema` through domains, both evidence routes and the stored record. - docs/first-look.md (21076 bytes)
# A first look *One function, walked through built-in claims, a domain, both evidence routes and the stored record.* <!-- example: ema run --> ```python import mathema def ema(x: list[float], alpha: float) -> float: """Exponentially weighted moving average.""" y = x[0] for v in x[1:]: y = alpha * v + (1 - alpha) * y return y ``` `ema` has a real loop in it. That matters later (see [The derive route](derive-route.md)), but not yet: the simplest way to use mathema needs nothing special about the function at all. ## Step 1: the built-in claims, before you write one <!-- example: ema run --> ```python print(mathema.check(ema, domain={"x": (-1e6, 1e6), "alpha": (-10, 10)})) ``` The `domain=` states a plausible range for the data and the smoothing factor. Without one, every claim ranges over all of the reals, out to the largest double, and the computation in float64 overflows long before it gets there (see [operational infinity](grammar.md#operational-infinity-let-inf-be)). With no `claims=` argument, mathema still runs the computational claims every function gets (`is_deterministic`, `is_state_safe`, `is_numerically_stable`, `is_representation_safe`, `is_dimension_safe`), plus whichever mathematical claims apply to `ema`'s actual shape. Here that means one sequence parameter feeding a numeric result, so the bounds, `permutation_invariant`, `scale_equivariant` and `translation_equivariant` all run too, alongside shape claims over the scalar parameter. This is an excerpt of the real result; the full record has a block like these for every claim: <!-- example: ema output match=subset --> ```text mathema.Record(ema) · source, no side effects · form py:72e6a357d7bb monotonic_increasing[alpha] d(f(x, alpha), alpha) >= 0 falsified at alpha = 8.459992498903986 -> -4.930559650170467e+304, alpha = 8.70201321389522 -> -5.772547268351122e+304 at x = [1e+300, -1e+300, -2.7255878198803085, 1.4703849054783387, 4.922577492583454, -8.999703650149867] (not increasing) falsified computation d(f(x, alpha), alpha) >= 0 counterexample alpha = 8.459992498903986 -> -4.930559650170467e+304, alpha = 8.70201321389522 -> -5.772547268351122e+304 at x = [1e+300, -1e+300, -2.7255878198803085, 1.4703849054783387, 4.922577492583454, -8.999703650149867] (not increasing) falsified policy f(x=[]) f(x, alpha) raises IndexError at x = [], alpha = 5.159088058806049 with no emptiness guard in the body: the empty input is stumbled into, not handled possible fixes: (i) if the IndexError is the intended refusal, state: raises(ema([], alpha), IndexError) (ii) guard the empty input at entry proven is_deterministic: f(x, alpha) = f(x, alpha) proven is_state_safe: f(x, alpha) = f(x, alpha) unknown is_numerically_stable: let g = mathema.f.accurate, g(f, x, alpha) = 1 derive could not decide it; the probe could not decide it either (accuracy against the exact value is read for scalar parameters only) holds is_representation_safe[alpha]: is_representation_safe(alpha) (20 draws) bounded_lower min(x) <= f(x, alpha) falsified at x = [222791.29884554766, -852156.6094995309, -647122.5636467072, -772598.9379420548, 854595.3224724911, 999998], alpha = 4.542301584683122 falsified computation min(x) <= f(x, alpha) counterexample x = [222791.29884554766, -852156.6094995309, -647122.5636467072, -772598.9379420548, 854595.3224724911, 999998], alpha = 4.542301584683122: -852156.6094995309 vs -656298366.2095869 falsified policy f(x=[]) f(x, alpha) raises IndexError at x = [], alpha = 5.159088058806049 with no emptiness guard in the body: the empty input is stumbled into, not handled possible fixes: (i) if the IndexError is the intended refusal, state: raises(ema([], alpha), IndexError) (ii) guard the empty input at entry permutation_invariant let g = mathema.f.reverse_seq, f(x, alpha) = f(g(x), alpha) falsified at x = [850043.9278135903, 905210.656449008, 782687.5954072354], alpha = 6.752137638609439 falsified computation let g = mathema.f.reverse_seq, f(x, alpha) = f(g(x), alpha) counterexample x = [850043.9278135903, 905210.656449008, 782687.5954072354], alpha = 6.752137638609439: -1747388.2882860936 vs -3521213.9192287754 falsified policy f(x=[]) f(x, alpha) raises IndexError at x = [], alpha = 5.159088058806049 with no emptiness guard in the body: the empty input is stumbled into, not handled possible fixes: (i) if the IndexError is the intended refusal, state: raises(ema([], alpha), IndexError) (ii) guard the empty input at entry scale_equivariant let g = mathema.f.scale_seq, let c be [-5.0, 5.0], c*f(x, alpha) = f(g(x, c), alpha) falsified at x = [], alpha = 5.159088058806049 proven mathematics let g = mathema.f.scale_seq, let c be [-5.0, 5.0], c*f(x, alpha) = f(g(x, c), alpha) holds computation let g = mathema.f.scale_seq, let c be [-5.0, 5.0], c*f(x, alpha) = f(g(x, c), alpha) 288 entries across 68 draws, sizes (1, 1) to (8, 1); differs by 0.00131 at x = [1000000.0, 1000000.0, 1000000.0, 1000000.0, -1000000.0, 1000000.0, 1000000.0, 1000000.0], alpha = -9.99998, c = -1.4095238757810247, within the default tolerance (3.75e+03) falsified policy f(x=[]) f(x, alpha) raises IndexError at x = [], alpha = 5.159088058806049 with no emptiness guard in the body: the empty input is stumbled into, not handled possible fixes: (i) if the IndexError is the intended refusal, state: raises(ema([], alpha), IndexError) (ii) guard the empty input at entry ``` Each claim prints as a headline (its name, its statement and its verdict, with the witness when it is falsified) and the lines the verdict rests on, indented under it. A `mathematics` line is the claim over the real numbers. A `computation` line runs the same claim through the real code in float64. A `policy` line covers an input that is not an ordinary number, here the empty list. The headline is falsified when any line under it is. Every counterexample names the inputs that produced it, so a failure is a thing you can paste into a REPL rather than a claim to take on faith. Three of these are genuinely informative rather than noise. - Every claim over `x` is falsified at `x = []`. `ema` reads `x[0]` before anything else, so an empty list raises `IndexError`, and the policy line says the body stumbles into it rather than handling it. - The bounds fail because nothing here constrains `alpha` to `[0, 1]`, and outside that range `ema` is not a weighted average at all, which the witness shows at `alpha = 4.54`. - `permutation_invariant` fails because `ema` is order-sensitive by design, which is what "exponentially weighted" means. mathema does not know that is intentional, so it reports the counterexample and lets a reader judge it. The equivariances show the layout at its clearest: the mathematics line is proven for every input, the computation line holds at every float64 input it ran, and the headline is still falsified, by the empty list alone. Note `is_deterministic` and `is_state_safe` came back `proven` with no trial count. mathema never runs a function to answer them: it reads `ema`'s source and found nothing it reads beyond its arguments and nothing it writes outside the call. The `192 draws` on `is_dimension_safe` is not a flat constant either, it is a trial budget decided once per call from `ema`'s own structure and the domain it is checked over (128 by default, +32 for the loop, +32 for a domain as wide as `x`'s). A computation line runs on its own, smaller set of points: the corners of the domain and sampled points inside it. See [mathema check](modes/check.md#the-trial-budget) for how that is decided, and `--trials-downscale` for turning it down in a fast dev loop. Every verdict reports the exact `n` it used, plus a `meta["mathema.confidence"]` score capped below the derive route's own, since sampling is never proof. A family fact such as `is_deterministic` is already a statement about the code, so it has no lines under it. Drop the `domain=` and the equivariances' computation lines no longer hold: the corners then sit at float64's maximum, about `1.8e+308`, where `alpha * v` overflows to infinity and the next step of the loop gives `nan`, so each computation line is falsified with that point as its witness, tagged `[mathematics sound, implementation:numerical-instability]`, while the mathematics stands. A claim over all of the reals means all of them. ## Step 2: declare a domain <!-- example: ema run --> ```python print(mathema.check(ema, domain={"x": (-1e6, 1e6), "alpha": (0, 1)})) ``` Narrowing `alpha` to where `ema` is actually meant to be used changes the picture, not just the wording (an excerpt, from the bounds on): <!-- example: ema output match=subset --> ```text bounded_lower min(x) <= f(x, alpha) falsified at x = [], alpha = 0.7579544029403025 proven mathematics min(x) <= f(x, alpha) holds computation min(x) <= f(x, alpha) 230 entries across 50 draws, sizes (1, 1) to (8, 1) falsified policy f(x=[]) f(x, alpha) raises IndexError at x = [], alpha = 0.7579544029403025 with no emptiness guard in the body: the empty input is stumbled into, not handled possible fixes: (i) if the IndexError is the intended refusal, state: raises(ema([], alpha), IndexError) (ii) guard the empty input at entry bounded_upper f(x, alpha) <= max(x) falsified at x = [], alpha = 0.7579544029403025 proven mathematics f(x, alpha) <= max(x) holds computation f(x, alpha) <= max(x) 230 entries across 50 draws, sizes (1, 1) to (8, 1) falsified policy f(x=[]) f(x, alpha) raises IndexError at x = [], alpha = 0.7579544029403025 with no emptiness guard in the body: the empty input is stumbled into, not handled possible fixes: (i) if the IndexError is the intended refusal, state: raises(ema([], alpha), IndexError) (ii) guard the empty input at entry permutation_invariant let g = mathema.f.reverse_seq, f(x, alpha) = f(g(x), alpha) falsified at x = [924900.393424673, 1e+06, 1e+06, -839686.100553984], alpha = 0.5 falsified computation let g = mathema.f.reverse_seq, f(x, alpha) = f(g(x), alpha) counterexample x = [924900.393424673, 1e+06, 1e+06, -839686.100553984], alpha = 0.5: 70769.4989010921 vs 732489.4341430885 falsified policy f(x=[]) f(x, alpha) raises IndexError at x = [], alpha = 0.7579544029403025 with no emptiness guard in the body: the empty input is stumbled into, not handled possible fixes: (i) if the IndexError is the intended refusal, state: raises(ema([], alpha), IndexError) (ii) guard the empty input at entry scale_equivariant let g = mathema.f.scale_seq, let c be [-5.0, 5.0], c*f(x, alpha) = f(g(x, c), alpha) falsified at x = [], alpha = 0.7579544029403025 proven mathematics let g = mathema.f.scale_seq, let c be [-5.0, 5.0], c*f(x, alpha) = f(g(x, c), alpha) holds computation let g = mathema.f.scale_seq, let c be [-5.0, 5.0], c*f(x, alpha) = f(g(x, c), alpha) 288 entries across 68 draws, sizes (1, 1) to (8, 1); differs by 2.09e-09 at x = [1000000.0, 1000000.0, -1000000.0, 1000000.0], alpha = 1e-06, c = 4.229996249451993, within the default tolerance (0.423) falsified policy f(x=[]) f(x, alpha) raises IndexError at x = [], alpha = 0.7579544029403025 with no emptiness guard in the body: the empty input is stumbled into, not handled possible fixes: (i) if the IndexError is the intended refusal, state: raises(ema([], alpha), IndexError) (ii) guard the empty input at entry ``` Both bounds' mathematics lines flip to `proven`. Inside `[0, 1]` each step of the loop is a convex combination of the new element and the running value, so `ema` really is bounded by `min(x)` and `max(x)`, and the same code that failed a moment ago now passes, because the claim finally says where it applies; their computation lines hold as well. The headlines stay falsified at `x = []`: narrowing `alpha` says nothing about the empty list. `permutation_invariant` stays falsified, as it should: narrowing the domain does not make an order-sensitive function order-insensitive. A declared domain is documentation, not enforcement. Whether the code itself *rejects* an out-of-domain argument is a separate question, and a separate claim you opt into: <!-- example: ema run --> ```python print(mathema.check(ema, claims=["excluding"], domain={"alpha": (0, 1)})) ``` <!-- example: ema output --> ```text mathema.Record(ema) · source, no side effects · form py:72e6a357d7bb falsified excluded_outside_domain[alpha]: excluded_outside_domain(alpha) counterexample alpha = -0.5 is outside the declared domain but was accepted (returned 1.0125000000000001e+301); the exclusion is asserted, not enforced ``` `ema` has no guard at all, so this is falsified, and the message says exactly what that means: the exclusion is asserted, not enforced. If you want the guard rather than the finding, the [`enforce_domain` decorator](authoring.md) writes one from the domains already declared on the function's claims. ## Step 3: state a claim of your own, on both evidence routes Every claim is adjudicated on one of two routes. **probe** calls the real function on seeded random inputs and reports `holds (n=...)`, evidence, not proof. **derive** lifts the function's body to a symbolic expression and decides the claim algebraically, reporting `proven` when it can. The same claim, checked on both, with a premise that says it is about lists of at least one element (step 1 showed what `ema` does with an empty one), so it gets no empty-list line: <!-- example: ema run --> ```python collapses = [ mathema.claim("assuming len(x) >= 1, f(x, 1.0) == x[-1]", name="collapses_probed", route="probe"), mathema.claim("assuming len(x) >= 1, f(x, 1.0) == x[-1]", name="collapses_derived", route="derive"), ] print(mathema.check(ema, claims=collapses)) ``` <!-- example: ema output --> ```text mathema.Record(ema) · source, no side effects · form py:72e6a357d7bb collapses_probed assuming len(x) >= 1, f(x, 1.0) = x[-1] holds holds computation assuming len(x) >= 1, f(x, 1.0) = x[-1] 628 entries across 132 draws, sizes (1, 1) to (8, 1) holds policy f(x=[ - docs/from-a-pytest-test.md (8614 bytes)
# From a pytest test to a claim An example-based test fixes what a function does at the inputs its author chose. A claim states the same thing over a range of inputs and leaves the choice of inputs to mathema, which looks for the ones that break it. This guide takes one real test, writes its intent as a claim, and shows what each of the two catches. It assumes the [quick start](quickstart.md). ## The test numpy's `ptp` returns the range of an array, its largest value minus its smallest. This is its own test, from [`numpy/lib/tests/test_function_base.py`](https://github.com/numpy/numpy/blob/v2.5.3/numpy/lib/tests/test_function_base.py#L731-L744) in numpy 2.5.3 (BSD-3-Clause, copyright NumPy Developers): ```python class TestPtp: def test_basic(self): a = np.array([3, 4, 5, 10, -3, -5, 6.0]) assert_equal(np.ptp(a, axis=0), 15.0) b = np.array([[3, 6.0, 9.0], [4, 10.0, 5.0], [8, 3.0, 2.0]]) assert_equal(np.ptp(b, axis=0), [5.0, 7.0, 7.0]) assert_equal(np.ptp(b, axis=-1), [6.0, 6.0, 6.0]) assert_equal(np.ptp(b, axis=0, keepdims=True), [[5.0, 7.0, 7.0]]) assert_equal(np.ptp(b, axis=(0, 1), keepdims=True), [[8.0]]) ``` The test does two things well. It pins exact values at concrete arrays, and the first array has negative entries, so its `15.0` is `10 - (-5)` and not `10`. And its second half exercises `axis` and `keepdims` over a two-dimensional array, which the claims below, written over vectors, do not touch. Read as a sentence, the first assertion says: the range of a vector is its largest value minus its smallest. ## A first attempt, and what it found Suppose the sentence came out slightly wrong: the range is at most the largest value. `ptp` is a library's function, so the claim goes in a compendium file, a claims file whose keys are numpy's functions and whose header names the library and the versions it applies to. `for a in [-100, 100]^n` is a vector of any length with entries in that range, and `f` is the function the key names. <!-- example: ptp file=claims/numpy.claims.yaml --> ```yaml compendium: numpy versions: ">=2,<3" numpy.ptp: claims: - name: at_most_the_largest statement: "for a in [-100, 100]^n, f(a) <= max(a)" ``` Naming the file adjudicates every row in it against the numpy that is installed: <!-- example: ptp run requires=numpy --> ```bash mathema verify claims/numpy.claims.yaml --root . ``` <!-- example: ptp output wrap=80 --> ```text note numpy.ptp: at_most_the_largest initially falsified: the installed library does not do what the row states: (i) to record the falsification as a discovery, run: mathema accept numpy.ptp at_most_the_largest --as discovery (ii) correct the row in claims/numpy.claims.yaml, then run: mathema accept numpy.ptp at_most_the_largest --as superseded FAIL numpy.ptp: library claims from claims/numpy.claims.yaml; no baseline record; 1 proven, 1 holds, 1 falsified <- 1 falsified claim(s) note definition: numpy.ptp gives no value at a = [1.7976931348623157e+308, -1.7976931348623157e+308], a magnitude corner where the exact value is finite: a finding about its computation; the row stands 0 unchanged since the last run (not run again), 1 checked, 1 problem(s) grammars detected: mathema; verified by this run: mathema ``` Falsified, and the record keeps the input that did it: <!-- example: ptp run --> ```bash grep -m1 counterexample .mathema/verified/numpy.ptp.yaml ``` <!-- example: ptp output --> ```text counterexample: "a = [-100, -100], axis = None, out = None, keepdims = <no value>: 0.0 vs -100.0" ``` Two values, both negative: the range of `[-100, -100]` is 0, and the largest value is -100. Whenever every value is negative the range sits above the largest value. The test's own first array says the same in another way, since its range of 15 is above its largest value of 10; the claim found a case without anyone choosing the array. The other parameters were passed at numpy's defaults, as the witness says. ## Record the discovery The code is right and the claim was wrong. That is a discovery about the function, and `mathema accept --as discovery` records it as one: the falsified claim moves to the record's discoveries section with its witness, and the corrected claim, adjudicated before anything is written, takes its place in the file. `--yes` answers the confirmation prompt, which is fine when a person types the command: <!-- example: ptp run --> ```bash mathema accept numpy.ptp at_most_the_largest --as discovery --corrected "for a in [-100, 100]^n, f(a) == max(a) - min(a)" --by "Ada Lovelace" --yes ``` <!-- example: ptp output match=subset wrap=80 --> ```text accept numpy.ptp :: at_most_the_largest as a discovery, by Ada Lovelace falsified at a = [-100, -100], axis = None, out = None, keepdims = <no value>: 0.0 vs -100.0 the claim moves to discoveries with that witness, out of claims/numpy.claims.yaml the corrected claim takes its place: at_most_the_largest_corrected [probe]: for a in [-100, 100]^n, f(a) == max(a) - min(a), checked now: holds over 131 trials written. ``` `holds over 160 trials`, on the probe route: the corrected claim is the test's sentence, run at 160 vectors mathema chose. The record's sampling line says how: `a~[-100.0, 100.0]^n, seed=20260718, n=160`, vectors of two to eight entries drawn inside the range. `axis`, `out` and `keepdims` are not on it, since nothing drew them: the note says they were held at numpy's defaults. It is evidence, not proof. The corrected claim carries `route: probe`, which `accept` wrote, so the derive route was not tried for it; the first attempt's record shows what it met: `derive: underivable (a is a vector or matrix, which the scalar derive route does not read, and the matrix algebra did not close the claim)`. ## Claims the test never stated The file is yours to add to. Two more things true of a range, that no assertion in `test_basic` states: <!-- example: ptp file=claims/numpy.claims.yaml --> ```yaml compendium: numpy versions: ">=2,<3" numpy.ptp: claims: - name: at_most_the_largest_corrected statement: "for a in [-100, 100]^n, f(a) == max(a) - min(a)" route: probe - name: never_negative statement: "for a in [-100, 100]^n, f(a) >= 0" - name: unchanged_by_a_shift statement: "for a in [-100, 100]^n, let s = mathema.f.shift_seq, let c be [-5, 5], f(s(a, c)) == f(a)" ``` <!-- example: ptp run --> ```bash mathema verify claims/numpy.claims.yaml --root . ``` <!-- example: ptp output --> ```text ok numpy.ptp: library claims from claims/numpy.claims.yaml; claims changed; 1 proven, 4 holds, 0 falsified note definition: numpy.ptp gives no value at a = [1.7976931348623157e+308, -1.7976931348623157e+308], a magnitude corner where the exact value is finite: a finding about its computation; the row stands 0 unchanged since the last run (not run again), 1 checked, 0 problem(s) grammars detected: mathema; verified by this run: mathema ``` `let s = mathema.f.shift_seq, let c be [-5, 5]` names adding the same constant to every entry; the range does not move. The `1 proven` is `dependencies_current`, the claim `verify` adds to every record that what the function depends on has not changed. ## What each one still does The test still does what the claims do not: it fixes the exact values, and it covers the two-dimensional cases and the `keepdims` argument. The claims do what the test cannot: they say the sentence once, over every vector in a range, and each sweep runs it again at inputs a person did not pick. Keep both. When one of your own tests reads as a sentence about every input, that sentence is a claim. ## For a function of your own A claim about your own function does not need a compendium file. Put it in the function's docstring under `Claims:`, as the [quick start](quickstart.md#move-it-into-the-code) does, or in an ordinary claims file, as [the CDD loop](tutorial.md) does; [Authoring claims](authoring.md) lists the four places and which one wins. [Add claims to an existing codebase](existing-codebase.md) starts from a package with none. The compendium file stays the right place for a claim about a library you call; [See what mathema knows about a library you call](library-claims.md) shows what mathema already states about numpy and how your own rows join in. [The claim grammar](grammar.md) has one example per form used here: the `[a, b]^n` space, `let c be [-5, 5]` and `let s = mathema.f.shift_seq`. - docs/gate-a-pipeline.md (11018 bytes)
# Gate a pipeline with mathema verify This guide wires `mathema verify` into a pipeline so that a pull request fails on a falsified or undecided claim and passes on a clean store. It assumes you have written a claim before ([quick start](quickstart.md)) and know what a record is ([the CDD loop](tutorial.md)). The running example is the fees module of a billing service from [Add claims to an existing codebase](existing-codebase.md), as a later commit left it: the late fee now grows with the log of the delay, which brings in `math.log`, and the discount has a bug in it. <!-- example: gate file=fees.py --> ```python import math def late_fee(days: int, base: float) -> float: """The fee for a payment that is `days` late.""" return base * math.log(1 + days) def discounted(price: float, rate: float) -> float: """The price after applying a discount rate.""" return price * (1 + rate) ``` <!-- example: gate file=claims/fees.claims.yaml --> ```yaml fees.late_fee: claims: - name: grows_with_delay statement: "for days in [0, 365] subset Z, base in [1, 100], f(days + 1, base) >= f(days, base)" fees.discounted: claims: - name: never_raises_price statement: "for price in [0, 1e6], rate in [0, 1], f(price, rate) <= price" ``` ## 1. Write the workflow `mathema init --ci` writes the GitHub Actions workflow (`--ci gitlab` writes a GitLab fragment and the `include:` line to add). It is written only where absent, and it is yours to edit from then on. <!-- example: gate run --> ```bash mathema init --ci cat .github/workflows/mathema-verify.yml ``` <!-- example: gate output --> ```text mathema init: scaffolded git files: .gitattributes .mathema/.gitignore mathema init: scaffolded the CI gate: .github/workflows/mathema-verify.yml # mathema verify is the CI gate over the committed .mathema/ store: it # checks again whatever changed and gates the result. verify is # strict by default, which fails a falsified claim, an open unknown # one, and also a claim that could not be checked at all (an unreachable # surface, an unsupported shape). Most stores have some of the last # kind at first, so expect the first run to be red and to tell you # exactly which claims it means. Accepted risk passes in both modes. # Add --lenient to report those unverifiable claims without failing, and keep # strict for falsified and unknown, once you have decided each one is # understood. Exit codes: 0 clean, 1 gate failure, 2 broken invocation # or store, so a failing gate is distinguishable from a broken job # without parsing any output. name: mathema on: push: branches: [main] pull_request: jobs: verify: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-python@v5 with: python-version: "3.12" # your project must import for its claims to adjudicate; adjust # this line to however your project installs - run: pip install -e . mathema - run: mathema verify --root . # optional: the claim-level delta since the base, for a PR comment # - run: mathema review --format json --output review.json ``` The one line you will change is the install step: your project has to import for its claims to adjudicate, so it is installed the way your project installs. ## 2. Commit the store `init` also wrote `.gitattributes`, which marks the records `linguist-generated` so their diff collapses by default, and `.mathema/.gitignore`, which tracks `verified/`, `meta/` and `badges/` and ignores regenerated state. Commit `.mathema/` with the code. The workflow's `mathema verify --root .` reads that store: a record is the durable statement of what was checked, and the next run needs it as its baseline. ## 3. Read the first red run Run the gate locally before the pipeline does. The last line prints the exit code the job would see: <!-- example: gate run --> ```bash mathema verify --root .; echo "exit code $?" ``` <!-- example: gate output wrap=80 --> ```text note fees.discounted: never_raises_price initially falsified. A declared claim is kept until a human decides it: (i) fix the code (ii) to record it as a discovery, run: mathema accept fees.discounted <claim> --as discovery (iii) to replace it with a corrected claim, edit it, then run: mathema accept fees.discounted <claim> --as superseded (iv) to try a spelling first (it writes nothing), run: mathema check fees.discounted --claim "..." FAIL math.log: library claims from mathema/compendium/math.claims.yaml; no baseline record; 1 proven, 0 holds, 0 falsified, 1 unknown <- log_monotone unknown: derive could not decide it compendium:math declares 'log_monotone' for math.log; mathema verify recorded it unknown against the installed library: (i) to take it on its word, run: mathema accept math.log log_monotone --as trusted (ii) to decide it, restate the row, then run: mathema check math.log --claim "..." FAIL fees.discounted: no baseline record; 1 proven, 2 holds, 1 falsified <- 1 falsified claim(s) ok fees.late_fee: no baseline record; 1 proven, 2 holds, 0 falsified 0 unchanged since the last run (not run again), 3 checked, 2 problem(s) grammars detected: mathema; verified by this run: mathema 2 intents to accept (2 functions): mathema accept --intent exit code 1 ``` Three keys were adjudicated, and two of them fail the gate. - `fees.discounted` is falsified: the bug. The `note` above it says what a declared claim does when it is initially falsified: it is kept, with its counterexample, until a person decides whether the code or the claim was wrong. - `math.log` is a function nobody on the team wrote. `late_fee` calls it, so the sweep adjudicated the claims mathema ships about it, and one of them, `log_monotone`, a derivative claim, is recorded `unknown`: `math.log` is a C function with no Python body for the derive route to lift, and the probe route does not evaluate `d(f(x), x)` by calling the function (`probe: skipped (unrecognized call 'd' ...)` in the record). An unknown claim fails the gate in every mode. - `fees.late_fee` passes. The `1 proven` in every row is `dependencies_current`, the claim `verify` adds to each record that what the function depends on has not moved. ## 4. Decide about the row nobody wrote An `unknown` on a library row is a decision for the team, not a flag to set, and `--lenient` does not pass it. Two acceptances are available, and the failure line named the first: - `--as trusted` takes the compendium's word for the row at the level it claims. It is testimony, recorded as such, and a later sweep that can settle the row locally replaces it with a local verdict. - `--as risk` records that the team owns the gap, with a note, and keeps the row visible in every report; verify passes it in both modes. For a row mathema ships about a library you did not write, trusting it is the usual decision. `--yes` answers the confirmation prompt, which is acceptable when a person is typing the command and never in agent tooling: <!-- example: gate run --> ```bash mathema accept math.log log_monotone --as trusted --by "Grace Hopper" --yes mathema verify --root .; echo "exit code $?" ``` <!-- example: gate output wrap=80 --> ```text accept math.log :: log_monotone as trusted, by Grace Hopper verdict unknown the claim is trusted at its claimed level, holds, on the word of compendium:math; a local verdict replaces it when verify checks this key again written. FAIL fees.discounted: fresh; 1 falsified claim(s) 3 unchanged since the last run (not run again), 0 checked, 1 problem(s) grammars detected: mathema; verified by this run: mathema 2 intents to accept (2 functions): mathema accept --intent exit code 1 ``` Nothing was re-adjudicated: every form hash is unchanged, so the sweep reads the stored verdicts, and the stored falsification still fails. ## 5. Fix the code, not the gate There is no accepting a falsified claim as risk. The discount adds the rate instead of subtracting it; fix it, and the changed form hash makes the sweep re-adjudicate that one function: <!-- example: gate file=fees.py --> ```python import math def late_fee(days: int, base: float) -> float: """The fee for a payment that is `days` late.""" return base * math.log(1 + days) def discounted(price: float, rate: float) -> float: """The price after applying a discount rate.""" return price * (1 - rate) ``` <!-- example: gate run --> ```bash mathema verify --root .; echo "exit code $?" ``` <!-- example: gate output --> ```text ok fees.discounted: form changed; 2 proven (1 claim, 1 built-in), 3 holds, 0 falsified 2 unchanged since the last run (not run again), 1 checked, 0 problem(s) grammars detected: mathema; verified by this run: mathema 2 intents to accept (2 functions): mathema accept --intent exit code 0 ``` The claim is now proven, the lines under it hold (the floating-point computation, and what `discounted` does with a `nan` price or rate), and the gate is green. Had the claim been the wrong one rather than the code, `mathema accept ... --as discovery` records the corrected claim instead; [the CDD loop](tutorial.md) walks that fork. ## 6. Strict or lenient `verify` is strict by default: falsified and unknown claims fail, and so does a regression no one has acknowledged, a claim that could not be checked at all (`skipped`), and gaps a person has accepted as risk. `--lenient` reports the last two by name and proceeds; it never passes a falsified or an unaccepted unknown claim. The full table is on [`mathema verify`](modes/verify.md#what-fails-the-run). Keep the default. Decide each red claim, `accept --as risk` for a gap the team owns and `--as trusted` for a library row, and add `--lenient` only once every skipped or accepted-risk claim has been decided, so that a new one still stops the pipeline. ## 7. Tell a failing gate from a broken job Every verb exits 0 when nothing gated, 1 when the gate failed, 2 when mathema could not run, and 130 when interrupted. A 2 is not a finding about your code: <!-- example: gate run --> ```bash mathema verify fees.nosuch --root .; echo "exit code $?" ``` <!-- example: gate output --> ```text mathema: no such key under .: fees.nosuch (nothing to verify) exit code 2 ``` Keep the two apart in the job: a step that treats any non-zero exit as a failing claim hides a broken install or a mistyped key as a bug. The codes are listed on [Verdicts and exit codes](verdicts.md#exit-codes). ## 8. The claim-level delta on the pull request The workflow's last, commented line is optional: `mathema review --format json --output review.json` compares the records at the base ref with the working tree and reports which verdicts flipped and which claims were added, removed or newly falsified, as data a job can post as a comment. [`mathema review`](modes/review.md) has the worked example. - docs/governance.md (6256 bytes)
# Governance and audit A verification record is only worth keeping if a reviewer can tell who decided what, on what evidence, and whether anything has changed since without anyone saying so. mathema is built around that question, in the manner of a ledger rather than a report: every verdict is bound to the code that earned it, every human decision is recorded with its author and its reason, nothing is deleted when a belief turns out to be wrong, and the gate in CI fails on anything that has drifted. This page puts the pieces together for the person who has to sign off on them, whether an engineering lead, a model validator or an auditor. ## Who can do what | Action | Who | Where it is recorded | |---|---|---| | State or propose a claim | anyone, including a coding agent | the declared layer, with where it was authored (`authored.surface`) and who proposed it | | Adjudicate a claim | only mathema | the verified record: verdict, route, evidence, and the form hash of the code | | Accept evidence as sufficient, own a gap as risk, or record a falsification as a discovery | only a person, at a terminal, with [`mathema accept`](modes/accept.md) | the claim's `accepted` block and the record's acceptance history | | Lock a function against change | a person or an agent | the lock file and the record's lock history | | Unlock a function | only a person, behind a prompt and optionally a PIN, with no `--yes` | the lock history | No tool exposed to agents over MCP accepts a verdict from its caller or performs an acceptance, and a weaker restatement of a claim never erases the stronger one it replaces, see [Working with coding agents](agents.md). ## What a decision records An acceptance writes what was accepted (`evidence`, `risk`, `discovery`, and the housekeeping kinds), the date, who decided, their note, and the form hash of the code the decision was about, so an acceptance never silently carries over to code that has since changed. An evidence acceptance also keeps the trial count and confidence it was granted on. Each decision is appended to the record's acceptance history rather than overwriting the last one. Who decided is, by default, your git `user.name`, which is a name rather than a proof of identity. To make it an attestation, set a [PIN](modes/pin.md): the decision is then stamped `verified_by` with the method and a key id. The code is read from the controlling terminal only, which an agent driving a shell normally does not have, and the secret lives outside the repository. A committed [project policy](modes/pin.md#project-policy) can require that stamp, restrict it to stronger methods, and name the key ids allowed to sign, and `mathema verify` then fails any acceptance that does not carry it, including one written into the YAML by hand. ## Nothing is deleted A claim that was believed and turns out wrong is not removed. It moves to the record's `discoveries`, `historical` or `superseded` section with the commit of its last supported run, and a claim that stops holding on changed code keeps the verdict it fell to, with the move recorded beside it, until it holds again or a person records why it no longer should. A year later the record still says someone believed the opposite, and why they stopped. See [the CDD loop](tutorial.md) for the whole sequence on a real function. ## The integrity checksum Every verified record carries a checksum over the parts of the record a decision rests on: - for every live claim and every row of the `discoveries`, `historical` and `superseded` sections: its name, statement, domain, route, tolerance and verdict, what supersedes it, and a summary of its acceptance (the kind, the attesting key, and whether it has gone stale); - the function's form hash and claims fingerprint, the accepted intent, and the locked form. Notes, proof sketches, trial counts and sampling details are outside it, since they explain a verdict rather than constitute it. The checksum detects a record that was changed outside mathema: a hand-edit, a botched merge, a rebase that interleaved two histories. `mathema verify` reports such a record by name and says what most likely happened; under a policy with `require_verification` the mismatch fails the run. After a legitimate merge, `mathema accept --as reconciled` restamps the record and records that it did. The checksum is unkeyed, so anyone who can run mathema can restamp a record. It is a tripwire for changes that did not go through mathema, not a signature. What makes a deliberate change visible is the combination around it: records are committed YAML, reviewed like code, [`mathema review`](modes/review.md) renders a pull request's changes as flipped verdicts, added and removed claims and new acceptances rather than as YAML noise, and a CODEOWNERS rule on `.mathema/verified/` puts a named approver in front of every change to it. ## The gate `mathema verify` in CI re-adjudicates everything whose code has changed and fails the run on a falsified or unknown claim, on a regression no one has acknowledged, on a changed body behind a lock, on a lock removed outside `mathema unlock`, and on an acceptance the policy rejects. In its default strict mode it also fails on skipped claims nobody accepted, so relaxing the gate is itself a visible flag rather than a quiet default. A risk a person has accepted passes in both modes, named in the row, and its acceptance is held to the policy like any other. The full table is in [`mathema verify`](modes/verify.md#what-fails-the-run). A pipeline that holds this together: ```yaml - run: mathema verify # the gate - run: mathema review origin/main --format json > review.json # the PR comment ``` ## Reproducing a verdict A record states the mathema version, the CDD spec version, the date and the commit it was adjudicated at, and sampling is seeded, with the seed kept in the record's sampling plan. Re-running `mathema verify --all` at that commit, with that version, reproduces the same draws and the same verdicts, with one stated exception: a proof close to its time cap can finish on one machine and not on a slower one, and the record says so whenever a cap was hit. See [Guarantees and limits](guarantees.md).
- docs/grammar-words.md (10344 bytes)
# The grammar's words A claim about vectors and matrices is written with the grammar's own words: `sum`, `mean`, `std`, `dot`, `norm`, `det`, `cumsum`, `quantile` and the rest. Each word has one meaning, and this page states it. Both routes read a word the same way: the probe evaluates it exactly at every draw, and the derive route lowers it to sums over a vector of any length, or to matrix algebra, when it proves a claim. The words matter beyond the claims you write. A [definition row](claims-transfer.md#definition-rows) maps a library's function onto a word (`numpy.std` with `ddof=1` onto `std(a, ddof=1)`), and a trusted row is taken at face value, so a proof that reads `np.std(x, ddof=1)` through that row rests on what `std` means here. ## Reading the table `x` and `y` are vectors of length `n`, `A` and `B` matrices, `b` a vector, and `x[i]` the element at position `i`, counted from 0. A *value slot* is a position that holds a value; a *hole* is a missing position (`None`, `nan`, `pd.NA`, see [missing values](missing-values.md)). "Has a value" states where the word has one beyond its arguments having the shapes its call names. Every vector in a claim's domain has at least one element (`R^n` means `n >= 1`), so "always" means for every such vector. Where a word has no value, a claim that uses it has none there either: `std(x, ddof=1)` at a vector of one element, or `inv(A)` at a singular `A`. A proof needs a premise that excludes those inputs, stated after `assuming`: `dim(x) >= 2`, or `det(A) != 0`. A keyword is written as in numpy, with the default shown. The derive route reads the keywords the table names and leaves a claim with any other (`axis=` among them) to the probe. ## The words | Word | Computes | Has a value | Keywords | A hole | Derive reads it | |---|---|---|---|---|---| | `len(x)` | the number of slots of `x` | always | none | counts every slot, holes included | over vectors of any length | | `dim(x, axis=0)` | the size of axis `axis` of `x`: a vector's length, a matrix's rows; `dim(A, 1)` its columns | always | `axis=0` | counts every slot, holes included | over vectors of any length | | `count(x, axis=None)` | the number of value slots of `x` | always | `axis=None` | counts the value slots; 0 when every slot is a hole | over vectors of any length | | `sum(x, axis=None)` | `x[0] + x[1] + ... + x[n-1]` | always | `axis=None` | reads the value slots; 0 when every slot is a hole | over vectors of any length | | `prod(x, axis=None)` | `x[0] * x[1] * ... * x[n-1]` | always | `axis=None` | reads the value slots; 1 when every slot is a hole | over vectors of any length | | `mean(x, axis=None)` | `sum(x) / n` | always | `axis=None` | reads the value slots; a hole when every slot is one | over vectors of any length | | `var(x, ddof=0, axis=None)` | `sum((x[i] - mean(x))^2) / (n - ddof)`, the population variance at `ddof=0` and the sample variance at `ddof=1` | `n >= ddof + 1` | `ddof=0`, `axis=None` (derive reads `ddof`) | reads the value slots; a hole when every slot is one | over vectors of any length | | `std(x, ddof=0, axis=None)` | `sqrt(var(x, ddof))` | `n >= ddof + 1` | `ddof=0`, `axis=None` (derive reads `ddof`) | reads the value slots; a hole when every slot is one | over vectors of any length | | `min(x, axis=None)` | the least element of `x`; `min(a, b, ...)` the least of several numbers | always | `axis=None` | reads the value slots; a hole when every slot is one | over vectors of any length | | `max(x, axis=None)` | the greatest element of `x`; `max(a, b, ...)` the greatest of several numbers | always | `axis=None` | reads the value slots; a hole when every slot is one | over vectors of any length | | `median(x, axis=None)` | the middle element of `x` sorted, or the mean of the middle two when `n` is even | always | `axis=None` | reads the value slots; a hole when every slot is one | no, sampled only | | `quantile(x, q)` | with `s` the sorted `x` and `h = (n - 1) * q`: `s[floor(h)] + (h - floor(h)) * (s[floor(h) + 1] - s[floor(h)])`, linear interpolation; a list of levels gives one quantile each | `0 <= q <= 1` | none | reads the value slots; a hole when every slot is one | no, sampled only | | `cumsum(x, axis=None)` | entry `i` is `sum(x[0..i])` | always | `axis=None` | a hole stays at its position; entry `i` reads the value slots among `0..i` | over vectors of any length | | `cumprod(x, axis=None)` | entry `i` is `prod(x[0..i])` | always | `axis=None` | a hole stays at its position; entry `i` reads the value slots among `0..i` | over vectors of any length | | `cummax(x, axis=None)` | entry `i` is `max(x[0..i])` | always | `axis=None` | a hole stays at its position; entry `i` reads the value slots among `0..i` | over vectors of any length | | `cummin(x, axis=None)` | entry `i` is `min(x[0..i])` | always | `axis=None` | a hole stays at its position; entry `i` reads the value slots among `0..i` | over vectors of any length | | `abs(x)` | `abs(x[i])` at every position; the absolute value of a number | always | none | a hole stays a hole | over vectors of any length | | `dot(x, y)` | `sum(x[i] * y[i])` for two vectors of one length; the matrix product when either argument is a matrix | the inner dimensions agree | none | reads the positions where both vectors hold a value; 0 when there is none | over vectors of any length, in matrix algebra | | `norm(x, ord=None)` | `sqrt(sum(x[i]^2))`, the Euclidean norm of a vector and the Frobenius norm of a matrix; `ord=1` is `sum(abs(x[i]))` (a matrix's largest column sum), `ord=inf` `max(abs(x[i]))` (a matrix's largest row sum), `ord=2` on a matrix the largest singular value | always | `ord=None` (derive reads `ord`) | reads the value slots at every order; 0 when every slot is a hole; a matrix's `ord=2` norm with a hole entry is a hole | over vectors of any length, in matrix algebra | | `outer(x, y)` | the matrix with entry `(i, j)` equal to `x[i] * y[j]` | always | none | not read over holes: a hole entry is nan | in matrix algebra | | `kron(A, B)` | the Kronecker product: block `(i, j)` is `A[i, j] * B` | always | none | not read over holes: a hole entry is nan | in matrix algebra | | `det(A)` | the determinant of `A` | `A` square | none | not read over holes: a hole entry is nan | in matrix algebra | | `trace(A)` | `A[0, 0] + A[1, 1] + ... + A[n-1, n-1]` | `A` square | none | not read over holes: a hole entry is nan | in matrix algebra | | `transpose(A)` | `A` with rows and columns exchanged, also written `A.T`; a vector is its own transpose | always | none | not read over holes: a hole entry is nan | in matrix algebra | | `inv(A)` | the matrix `B` with `A @ B == I(n)` | `det(A) != 0` | none | not read over holes: a hole entry is nan | in matrix algebra | | `solve(A, b)` | the `x` with `A @ x == b`, which is `inv(A) @ b` | `det(A) != 0` | none | not read over holes: a hole entry is nan | in matrix algebra | | `I(n)` | the `n` by `n` identity matrix | `n` a whole number, `n >= 0` | none | not read over holes: a hole entry is nan | in matrix algebra | | `matrix_power(A, k)` | `A @ A @ ... @ A`, `k` factors; `I(n)` at `k = 0`; `matrix_power(inv(A), -k)` for a negative `k` | `A` square, `k` whole; `det(A) != 0` for `k < 0` | none | not read over holes: a hole entry is nan | in matrix algebra | | `diag(x)` | the square matrix with `x` on its diagonal and 0 elsewhere; of a matrix, the vector of its diagonal entries | always | none | not read over holes: a hole entry is nan | no, sampled only | | `rank(A)` | the number of linearly independent rows of `A` | always | none | not read over holes: a hole entry is nan | in matrix algebra | | `eigvals(A)` | the eigenvalues of `A`, each as often as its algebraic multiplicity, sorted by real then imaginary part | `A` square | none | not read over holes: a hole entry is nan | no, sampled only | | `eigvalsh(A)` | the eigenvalues of a symmetric `A`, real and ascending | `A` square and symmetric | none | not read over holes: a hole entry is nan | no, sampled only | | `cond(A)` | the largest singular value of `A` over its smallest | `A` of full rank | none | not read over holes: a hole entry is nan | no, sampled only | | `pinv(A)` | the Moore-Penrose pseudoinverse of `A` | always | none | not read over holes: a hole entry is nan | no, sampled only | ## Exact on the mathematics line The probe computes every word exactly and rounds the result once to the nearest float: `mean(x)` is the exact mean of the elements drawn, `det([[1, 2], [3, 4]])` is exactly `-2`, and `inv` of a singular matrix has no value even where floating-point elimination would return one. The derive route computes over the rationals and reals, so the two routes agree on every word, value for value. ## Words the derive route knows through bounds `min`, `max`, `cummax`, `cummin`, `norm(x, ord=inf)` and `rank` have no closed form as a sum, so the derive route reads each as a number known only through facts: `min(x)` is one of the elements of `x` and at most every one of them, so it is at most `mean(x)`; `cummax(x)[i]` is one of `x[0..i]` and at least `x[i]`. A claim that follows from those facts is proven; one that needs more is left to the probe. ## Words left to the probe `median`, `quantile`, `diag`, `eigvals`, `eigvalsh`, `cond` and `pinv` are evaluated by the probe only; a claim that uses one is never proven, whatever its definition rows say. The exceptions are two identities the derive route reads directly: `sum(eigvals(A))` is `trace(A)` and `prod(eigvals(A))` is `det(A)`, the eigenvalues counted with their algebraic multiplicity. ## Holes The derive route reads vectors with no holes, as definition rows are stated over inputs with nothing missing. What a word does with a hole matters to the probe and to the missing-value lines under a claim: the reductions read the value slots (`count`, `mean`, `std` and `sum` count only those). Over a vector holding only holes, a reduction with an identity gives it (`sum` 0, `prod` 1, `count` 0, `norm` 0, and `dot` 0 where no position holds a value in both vectors), and one without gives a hole (`mean`, `std`, `var`, `min`, `max`, `median`, `quantile`). `len` and `dim` count every slot, and the running words keep a hole at its own position. [Missing values](missing-values.md) describes how a claim states what a function does with one.
- docs/grammar.md (54375 bytes)
# The claim grammar Every example on this page is taken from `mathema.lexicon.LEXICON`, a curated set of claims that is checked by the test suite, so nothing here can drift away from what the parser actually accepts. A claim is one string. At its simplest it is a relation between the function under test, written `f`, and something else: ``` f(x) == x ``` Everything after that is optional detail: where the claim applies, what the symbols mean, and what you are allowed to assume. ## Terse in, explicit out The grammar accepts the shortest reasonable spelling of anything, and several spellings of most things, because a claim you have to look up the syntax for is a claim you will not write. ASCII and Unicode are interchangeable, and equivalent spellings parse to exactly the same claim: | These are the same claim | |---| | `f(x) <= 1` and `f(x) ≤ 1` | | `for x in [0, 1], f(x) >= 0` and `for x ∈ [0, 1], f(x) ≥ 0` | | `for n in [0, 100] subset Z, f(n) >= 0` and `for n in [0, 100] ⊂ ℤ, f(n) >= 0` | | `d(f(x), x) >= 0` and `f'(x) >= 0` | | `integrate(f(x), x, 0, 1) == 1` and `∫(f(x), x, 0, 1) == 1` | | `for x in [0, 1], f(x) >= 0` and `∀ x ∈ [0, 1], f(x) ≥ 0` | | `for n in [0, 100] subset Z, f(n) >= 0` and `∀ n ∈ [0, 100] ⊂ ℤ, f(n) ≥ 0` | | `f(x)^2 >= 0` and `f(x)² ≥ 0` | | `for x in [0, 1], sqrt(f(x)) >= 0` and `∀ x ∈ [0, 1], √(f(x)) ≥ 0` | | `for x in [0, 1], f(x) * 2 == 4*x` and `∀ x ∈ [0, 1], f(x) · 2 == 4*x` | | `for x in [0, oo), f(x) >= 0` and `∀ x ∈ [0, ∞), f(x) ≥ 0` | | `for x in [0, 1], f(x) >= 0` and `\forall x \in [0, 1], f(x) \geq 0` | What you get back is never terse. Whatever mathema resolved your input to is rendered explicitly in the record, the error message and the proof condition, so a shorthand never quietly becomes something you did not mean. Setting `MATHEMA_UNICODE=0` switches output to ASCII; see [symbology and rendering](symbology.md). ## Mathematical notation, and how to read it Every symbol below is accepted by the parser and means exactly what its ASCII spelling means, so a claim can be written the way the mathematics is written without becoming a different claim. Code points are given because several of these have visually identical neighbours that are *not* the same symbol, and a claim pasted out of a PDF is a common way to meet one. | Symbol | Code point | Read it as | ASCII | |---|---|---|---| | `∀` | U+2200 | for all | `for` | | `∈` | U+2208 | in, an element of | `in` | | `⊂` | U+2282 | a subset of | `subset` | | `ℝ` | U+211D | the reals | `R` | | `ℤ` | U+2124 | the integers | `Z` | | `ℕ` | U+2115 | the naturals | `N` | | `ℂ` | U+2102 | the complex numbers | `C` | | `≤` | U+2264 | less than or equal to | `<=` | | `≥` | U+2265 | greater than or equal to | `>=` | | `≠` | U+2260 | not equal to | `!=` | | `≈` | U+2248 | approximately equal to, within a tolerance | `~=` | | `≡` | U+2261 | equivalent to, as a whole function, in its mathematics and its computation | `=:=` | | `⟹` | U+27F9 | implies | `=>` | | `·` | U+00B7 | times | `*` | | `×` | U+00D7 | times | `*` | | `−` | U+2212 | minus | `-` | | `√` | U+221A | the square root of | `sqrt` | | `∞` | U+221E | infinity, also written `oo` or `infinity` | `inf` | | `∂` | U+2202 | the partial derivative of | `d(` | | `∫` | U+222B | the integral of | `integrate(` | | `→` | U+2192 | tends to, inside a limit | `->` | | `⌊ ⌋` | U+230A, U+230B | the floor of | `floor(` | | `⌈ ⌉` | U+2308, U+2309 | the ceiling of | `ceil(` | | <code>| |</code> | U+007C | the absolute value of | `abs(` | | <code>|| ||</code> | U+007C | the norm of; `_1`, `_2` or `_inf` after the closing bars is the order | `norm(` | | `‖ ‖` | U+2016 | the norm of; `₁`, `₂` or `∞` after the closing glyph is the order | <code>|| ||</code> | | `²` | U+00B2 | squared, and likewise `³` and the rest | `^2` | Greek letters are accepted as themselves (`α`, `σ`, `Δ`), and so are the mathematical-italic Greek letters in U+1D6E2 to U+1D7FF, which is what many PDF and LaTeX renders paste instead. Both spell the same parameter. Where a symbol has a plain LaTeX command with no braces, that is accepted typed literally too, so `\forall x \in [0,1], f(x) \geq 0` is the same claim as its Unicode and ASCII forms. A few more spellings are accepted and read as their ascii forms: | Spelling | Reads as | |---|---| | `∀ x ∈ [1, 4], f(x) ≥ √x` | `√` without parentheses, the root of the atom after it | | `∀ x ∈ [1, 2], f(x) ≥ x⁻¹` | a superscript minus, a negative power | | `let g = mathema.lexicon.double, f \equiv g` | `\equiv`, function equivalence | | `\forall x \in [0, 1], f(x) \leqslant 2` | `\leqslant`, the slanted `<=` | | `\forall x \in [0, 1], f(x) \geqslant 0` | `\geqslant`, the slanted `>=` | | `for x in [0, 1], abs(f(x) - x) \leq \varepsilon` | `\varepsilon`, the claim's tolerance like `ε` | | `for \varphi in [0, 1], f(\varphi) \leq 1` | `\varphi`, the letter `φ` | | `for x in [-1, 1], \left| f(x) \right| \leq 2` | `\left`/`\right` sizing, dropped | A radical whose reach would be unclear (`√x^2`) is refused; write `√(x^2)` or `(√x)^2`. ### The look-alikes worth knowing about `⊂` (U+2282) is the subset operator the grammar accepts. **`⊆` (U+2286) is deliberately rejected**, with an error rather than a silent reinterpretation, because a proper subset and a subset-or-equal are different mathematical statements and treating them as spellings of one another would quietly change what you claimed. Two pairs go the other way and *are* merged, since they are typesetting variants of one symbol rather than distinct ones: `⩽`/`⩾` (U+2A7D, U+2A7E) are the ISO-style slanted forms of `≤`/`≥`, and `𝜋` (U+1D70B, mathematical italic) is the same constant as `π` (U+03C0). And keep `≡` and `≈` apart, since they sit next to each other on this page and mean very different things. `≡` claims two implementations are the same function, adjudicated on its own ladder. `≈` claims equality within a tolerance. ### Symbols beyond this set This table is the notation the core grammar knows. For domain-conventional symbols, the notation a particular field expects for its own quantities, see [mathema-symbology](symbology.md), which supplies those names and renders claims in them. ## Relations | Spelling | Meaning | |---|---| | `f(x) == x` | equality | | `f(x) ≤ 1` | inequality, in either ASCII or Unicode | | `f(x) ~= x` | approximate equality, within a tolerance | | `f =:= g` | function equivalence: two implementations of the same mathematics, whose computations agree within the claim's tolerance | | `f equiv g` | the word alias for the same relation | | `for a in [0.1,10], b in [0.1,10], 2/(1/a+1/b) <= f(a,b) <= (a+b)/2` | a chained comparison, both bounds in one claim | | `for s in L[unicode], f(s) in L[unicode]` | membership: every output is a member of a language or a set, `∈` in Unicode | | `for x in [0, 1], f(x) in [0, 1]` | membership in a numeric interval, read as the chain it means | | `for s in L[unicode], "<" not in f(s)` | containment: the value on the left is never found in the value on the right, `∉` in Unicode | ### How close counts as equal `a ~= b` means `abs(a - b) <= ε`, with `ε` the claim's declared tolerance or else 1e-9 (see below), and the record says so: "read as abs(f(x) - x) <= ε, ε = 1e-9 (the default)". On the derive route every relation is decided exactly: `==` asks whether the two sides are the same over the whole domain, in exact real arithmetic, and `~=` whether their difference stays within `ε`, so `x + 1e-12` is not `x` under `==` and is under `~=`. A definition row in a compendium is an exact equation, written with `==`. On the probe route, which runs the real function in floating point, `~=` is the same `abs(a - b) <= ε` in float64, and `==` counts the computed sides as equal when they agree within the computation's allowance, a relative 1e-7 of the result plus an absolute part of at most 1e-9. A draw that passes only within that allowance is decided again in exact arithmetic wherever the body can be read exactly, so `x * (1 + 1e-8)` written in the body is not `x` under `==`, while the same factor read from a module constant, which has no exact reading, leaves such a draw inconclusive and uncounted. A claim sets its own absolute tolerance with the `tolerance` field of a claims file, or `tolerance=` on `mathema.claim()`, and that value replaces the whole allowance: the two sides must agree within it, with no relative tolerance on top. On `==`, `<=`, `>=` and `!=`, as on a function equivalence `f =:= g`, the tolerance governs the computation line alone, since the mathematics line is exact: `x + 1e-6 == x` with a tolerance of 1e-3 is falsified by its exact gap, as is `x + 1e-10 <= x` with a tolerance of 1e-9, and "close enough mathematically" is `~=`, as [Multi-function claims](multi-function-claims.md) describes for `=:=`. A single `a ~= b`, and an `f =:= g`, may also name the tolerance's kind (see [Tolerance kinds](#tolerance-kinds) below), while every other relation takes a bare number. Inside the claim text, `ε` (also `eps`, `epsilon` or `\epsilon`) names that tolerance directly: the declared value when there is one, and the 1e-9 default otherwise, on both routes. It is never a free variable to sample, and a function parameter that happens to be called `eps` or `ε` stays a parameter. With two functions in `gaps.py`, one off by `1e-10` and one by `1e-7`: <!-- example: eps file=gaps.py --> ```python def nearly_identity(x: float) -> float: return x + 1e-10 def small_gap(x: float) -> float: return x + 1e-7 ``` <!-- example: eps run --> ```bash mathema check gaps.py --claim "for x in [0, 1], abs(f(x) - x) <= ε" ``` <!-- example: eps output --> ```text ok gaps.nearly_identity: source, no side effects; claims 3/3 checked (1 proven, 2 holds, 0 falsified) FAIL gaps.small_gap: source, no side effects; claims 2/2 checked (0 proven, 1 holds, 1 falsified) <- 1 falsified claim(s) ``` The first gap is within the default tolerance and proves for every `x` in the range (its second claim is the proof's `[float]` companion, which holds); the second is a hundred times larger than it and is falsified. The other relations use the same allowance where it makes sense: `<=` and `>=` accept a difference within the absolute tolerance, `<` and `>` accept none, since equality must not pass for strictly less, and `!=` with no declared tolerance fails only where the two sides are exactly equal. On the probe route a draw whose computed values meet `==`, `<=` or `>=` only within the allowance (inside its absolute part as well as through its relative part) is decided again in exact arithmetic wherever the body can be read exactly, its literals as the decimals written: false there falsifies, with that draw as the witness, so the allowance never carries a claim that is false at a point the probe ran. Where the body cannot be read exactly (a float it reads from outside, a library's value), such a pass is no evidence either way: it is not counted, and a claim with no other draw ends `unknown` with the note "N draws passed only within the tolerance and could not be evaluated in exact arithmetic, so they are not counted". A declared tolerance makes such a pass count, since the claim asks for that allowance. Every computation line that holds with a gap the tolerance absorbed says so in its note, for `==` as for `<=` and `>=`, on every route (a probe line, a ground claim's one call, the `[float]` line a proof spawns, the computation row of an `f =:= g` claim): the largest gap, the point it was measured at, and the tolerance it fell within (the declared one, or the default allowance's value at that point). A pass with no gap carries no such clause, so a bit-exact pass reads apart from an absorbed one. The derive route has no allowance to spend: when it disproves a `<=`, `>=` or `==` claim, the real code is run at derive's witness and compared exactly, and a violation there, however small, falsifies the claim with that point as the witness. So `f(x) == x` is falsified for `x + 1e-10`, but not for `x + 1e-20` on `[1, 2]`, where rounding makes the executed values exactly equal. For a function that returns `-1e-10`: <!-- example: just-below run --> ```python import mathema def just_below(x: float) -> float: return -1e-10 for route in ["probe", "derive"]: (p,) = mathema.claims.check( just_below, [mathema.claim("for x in [0, 1], f(x) >= 0", route=route)]) print(f"{route:7} {p.verdict:9} {p.counterexample or ''}") print(f" {p.note}") ``` <!-- example: just-below output --> ```text probe falsified x = 0: -1e-10 vs 0, within the float tolerance but false here in exact arithmetic derive falsified x = 0.06163325083761284 reproduced exactly at derive's witness: the executed code misses the relation there by 1e-10, within the allowance (1e-09) the probe route gives the computation, and compared exactly it fails ``` A declared tolerance binds the computation line only: the probe compares the floats within it, and derive's disproof stands on the exact gap however small. Where the executed code rounds the difference away, the body is read exactly at derive's witness: a literal is the decimal written, so `x + 1e-20` is `x + 1/10^20` and the claim is falsified on the mathematics, the record noting that the float computation holds within its allowance. A derive disproof that neither the executed code nor the exact reading reproduces (the gap comes from a float the body reads from outside, a module constant or a library's value) comes back `unknown` with `mathema.corroboration: "uncorroborated"`; when the exact comparison ran at the point where the exact difference is, the record adds `mathema.corroboration_reason: "exact arithmetic only"` and the note says the difference exists in exact arithmetic and floating point does not reproduce it. Any other unreproduced disproof is flagged as a probable engine bug. ### Tolerance kinds A bare number is an absolute allowance, which is the wrong shape for a value that spans many orders of magnitude: an option deep out of the money prices at 1e-7 and the same function prices at 190 in the money, so `1e-9` is half a percent of the small price and a rounding error at the large one. On `a ~= b` (and on `f =:= g`) the tolerance may instead name its kind, in a claims file as `tolerance: {rel: 1e-9, floor: 1e-14}` or on `mathema.claim()` as `tolerance={"rel": 1e-9, "floor": 1e-14}`: | Kind | Allows | |---|---| | `{abs: x}` | `abs(a - b) <= x` | | `{rel: x}` | `abs(a - b) <= x * max(abs(a), abs(b))` | | `{ulp: n}` | `abs(a - b)` within `n` units in the last place of the float64 nearest `max(abs(a), abs(b))`, `n` a whole number | | `floor: x`, beside any of them | adds `x` to the kind's own allowance | The floor adds, so `{rel: 1e-9, floor: 1e-14}` allows `1e-9 * max(abs(a), abs(b)) + 1e-14`, which is the relative-plus-absolute error of the standard rounding-error model, and it app - docs/guarantees.md (18834 bytes)
# Guarantees and limits A verification result is only as useful as the reader's certainty about what it means, so this page states, in one place, what each verdict establishes, what it deliberately does not, and what the record keeps as evidence. Every statement here describes the engine as it runs today. Where a limit exists it is stated precisely rather than hedged, because a verifier that is vague about its own edges is asking to be trusted rather than checked. ## What each verdict guarantees | Verdict | What it establishes | What it does not | What the record keeps | |---|---|---|---| | `proven` | The claim holds for every input in the declared domain, established by algebra in exact real arithmetic. On a finite integer domain, `derive:brute_force` has instead evaluated every point, each decided exactly; where a point has no exact value the sweep is `proven` on `derive:brute_force:within_float64`, every point run in float64, each such point's float64 result within float64's own precision of the relation there, and the largest delta stated; a larger miss is not counted (`unknown`), or `holds` under a declared tolerance. | That floating point reproduces what the reals prove. Where the function is undefined inside the domain as mathematics (a root of a negative, a division by zero), or its own source raises there, no proof is reached and the claim itself is falsified; where the computation fails on an input the mathematics admits (an overflow, a NaN, a precision collapse) the `[float]` companion claim, which runs the real function at the domain's corners and across its interior, is falsified while the proof stands, see [Mathematics and computation](#mathematics-and-computation) below and [the sigmoid case study](case-studies.md#the-sigmoid-calculus-as-a-specification). | The route (`derive`, `derive:extensive`, `derive:brute_force`, `derive:brute_force:within_float64`) and a sketch naming the mechanism behind the proof. A `proven` never rests on an unnamed step. | | `holds (n=...)` | The real function survived exactly `n` executed trials without a counterexample, on seeded inputs biased toward domain edges, corners, poles and special values. | A probability of failure. No statistical bound is computed or implied. The confidence stars beside a `holds` measure sampling density against the function's structure, and top out at four of five, since five is reserved for proof. | `n`, the sampling plan including its seed, and the confidence breakdown. | | `falsified` | The real function, called at an in-domain point, violates the claim. That point is the **witness**, and a `falsified` always has one. A negated claim (`not is_defined(f)`) says the positive claim fails somewhere, which no single point can refute, so its witness is the proof of the positive claim over the whole domain. A missing input is not such a point: what the function does with one is judged by its policy row ([missing values](missing-values.md)), and a policy row the code contradicts is falsified like any claim. A raise at that point, a NaN computed from inputs that are not missing, or an infinity returned for a finite input (an overflow or a pole, where `math` would raise), is no value, so it falsifies every relation, `!=` included. The one agreement is two sides that overflow toward the same infinity (both `inf`, or both `-inf`): that is one extended-real point, so the point reads as two equal values; a NaN agrees with nothing, not even another NaN. Probing runs under one pinned floating-point regime, so the witness does not depend on the caller's `numpy.seterr` settings. | Anything about why. A falsification may mean the code is wrong or the claim is, and the loop exists to tell those apart, see [the CDD loop](tutorial.md). | The counterexample, kept permanently and replayed on every later run, so a bug cannot be fixed by accident and quietly unfixed. | | a transition (`regressed`, `weakened`) | The claim's verdict is weaker than in the previous record: `proven` or `holds` to `falsified` is `regressed`, a smaller fall is `weakened`. The verdict itself is the fresh one. | That it may simply be re-adjudicated away. The move stays on the record until the claim is supported again at the level it fell from, or a person acknowledges it. | The verdict it fell from and to, the kind, the cause (this function changed, a callee changed, or nothing changed), the date and commit, and the last commit where the claim was supported. | | `unknown` | Nothing was decided, and the reason is kept. This includes a symbolic disproof that no executed point reproduces, which is flagged as a probable engine fault rather than reported as a bug in your code. | A pass. `verify` fails on an `unknown` unless a person accepts it as risk. | Why each route stopped (unliftable, undecided, timed out). | | `skipped` | The claim could not be adjudicated as stated: misspecified, or a form the chosen route cannot evaluate. | A pass. `verify` fails on a `skipped` in its default strict mode unless a person accepts it as risk. | The reason, with a [reason code](reason-codes.md). | **Accepted risk** is not a verdict. It is a person's recorded decision to own an `unknown` or `skipped` gap, with their name, the date and their note. It stays visible in every report, and `verify` passes it in both strict and lenient mode. See [`mathema accept`](modes/accept.md). ## Mathematics and computation Every result mathema reports belongs to one of two strata, and the record never lets one stand in for the other. The mathematics is the function as an object over the reals and its declared sets, the same in every language and on every machine, and it is what the derive route reasons about: a `proven` means the claim holds in exact real arithmetic over the declared domain, with infinity as infinity, and nothing about the number representation the code happens to run on enters that reasoning, no largest double, no overflow threshold, no operational infinity. What does enter is the mathematics of definedness, namely the real domain of the primitives (a root of a negative, a logarithm at or below zero, a division by zero), a `raise` the function's own source states, a nan or an infinity its source returns as the value (`math.nan`, `float("inf")`), and a library's `is_defined` row, since a function undefined at a point of its domain is not the function the claim describes. The computation is one implementation executed in one language, one runtime and one number representation, and the number representation follows the domain: float64 for a claim over `R`, complex128 for one over `C` (its companion is `<name>[complex]`). Everything that belongs to the computation, a raise and its type, a NaN, an overflow, a loss of precision, a recursion limit, is established only by running that implementation, belongs to that implementation, and never transfers to another, however the two are related mathematically. An executed value is read by one rule on every path that executes anything, the probe route, the `[float]` companion, the computation-safety families (`is_numerically_stable`, `is_representation_safe`, `is_missing_safe` and the rest) and the computation line of `=:=` alike. A raise, a NaN computed from inputs that are not missing, or an infinity returned for a finite input is no value, and no value fails every relation, `!=` included; two sides that overflow toward the same infinity are one extended-real point and agree, while a NaN agrees with nothing, not even another NaN. The reading does not change with the kind of claim, so a witness means the same thing wherever it appears in the record. A missing input belongs to neither stratum's value claims: the function's behaviour there (raises, drops, propagates, converts, introduces) is its own claim, the policy row. The number representation never overturns a proof. Where the derive route closes a claim, the computation's verdict lives on the `<name>[float]` companion the proof spawns, which runs the real function at the corners of the declared domain and across its interior and is falsified, with a witness, where the computation fails on an input the mathematics admits; the proof stands, the companion gates `verify` like any other claim, and a row that is mathematically proven above a falsified companion reads exactly as it should, the mathematics sound and the computation in float64 failing at the witness (see [the evidence ladder](evidence-ladder.md#a-proof-is-the-mathematics-float-is-the-computation)). Where the derive route cannot close a claim, the probe's verdict is the claim's verdict and its route says so, and an overflow met there falsifies the claim itself, since a claim decided by execution is a claim about the computation until something proves the mathematics. In the other direction a derive disproof becomes `falsified` only with an executed witness, so the mathematics is never allowed to convict code that behaves. An operational infinity is a fact about the computation and only that: it says how far along an unbounded direction the code is exercised, by the probe route and by the companion, and it never bounds a proof, which is over ℝ whatever the binding says. It is declared on the claim, `let |inf| be 1e100` in the grammar or `pseudo_infinity=` in Python, and a claim's own declaration takes precedence over the levels beneath it. Those resolve in the order claim, function, project (`MATHEMA_PSEUDO_INFINITY`) and then the number representation's own maximum, `sys.float_info.max` (about `1.8e308`) for float64. The value that applied is shown only where it bounds an unbounded direction of the claim's effective domain, as a plain binding in front of the computation rows' condition (`let |inf| be 1e+06, for x in R`), never in the claim's statement, with the level it came from recorded in `meta["mathema.pseudo_infinity"]`; a claim whose every direction is already bounded says nothing about infinity at all. See [operational infinity](grammar.md#operational-infinity-let-inf-be) for the grammar and a worked example. The computation-safety families each answer one of three questions about a function: does it run on my domain, is the answer right in float64, and is it repeatable. [The claim grammar](grammar.md#which-question-each-one-answers) lists every family under its question, with what it tells you and the usual fix. A safety predicate reads the claim's `assuming` clause like every other claim (its trials run only at points inside the premise, an equality premise drawn on its surface), and a raise from the function at such a point is no value, so it falsifies the predicate with that point and the exception as the witness. ## Corroboration: why every falsification has a witness The derive route can report that a claim is false by algebra alone. Such a disproof stands only if running the real function reproduces it: the engine tries the symbolic witness, small perturbations of it, and a seeded blind search, and calls the function at each point. If one of them fails the claim, the result is `falsified` with that executed witness, recorded as `mathema.corroboration: "reproduced"`. If none do, the result is `unknown` with `mathema.corroboration: "uncorroborated"`, since an algebraic disproof that the code never exhibits more likely points at a fault in the engine than in the code. A safety predicate's structural disproof follows the same rule. A pole inside the declared domain (`is_pole_safe`, `is_numerically_stable`), or a raising guard on a missing value the domain admits (`is_missing_safe`), is checked by calling the function at the point the structure names. A raise there, or a non-finite result at a pole, is the witness; a call that behaves leaves the disproof uncorroborated. Where the code, run where the difference is, rounds it away, the body is read exactly there (its literals as written, its divisions as ratios, a root as sympy holds it), and a difference that reading confirms is the witness. A pole no float lands on (`sqrt(2)` for `1 / (x*x - 2)`, where the nearest float returns a large finite number) is the witness itself when interval arithmetic certifies that the divisor is zero there, independently of the solver that found it, as `is_defined` certifies the same point. Where no exact reading confirms it (a gap below float resolution that comes from a float outside the body), the record adds `mathema.corroboration_reason: "exact arithmetic only"` and the note says so instead of naming an engine bug. A falsification is therefore equally strong whichever route found it, because it always rests on the same thing, the real function failing at a real input. ## How the routes combine A claim takes the `best` route unless you pin one. The engine first attempts a proof (a fast attempt, then the [extensive strategy ladder](index.md#no-model-in-the-loop)), and a claim the proof cannot decide falls through to probing, with the reason the proof stopped kept in the record. The result names the mechanism that settled it, and a claim's name never implies a route. - A claim pinned to `route: derive` makes the fast proof attempt only, and derive gives its verdict. When the proof cannot settle it (a body derive cannot read, a branch it cannot decide, the wall clock), the probe still samples the claim, as a falsifier only: a counterexample it executes falsifies the claim, on the probe's route with derive's reason in the note, and draws that find none leave the claim `unknown`, never `holds`, with the number of draws in the note. A proof's `[float]` companion and a disproof's executed witness are as on any route. - A claim pinned to `route: probe` never attempts a proof. - Calculus forms (`d`, `lim`, `integrate`, `Sum`, `Prod`) are decided by the derive route. When the proof cannot close, numeric evidence on the lifted expression is reported as such, as mathema's reconstruction of the code rather than the code itself. - A matrix identity the algebra cannot close is sampled over matrices of its declared shape, and stays `unknown` only where it cannot be sampled. ## What composes, and what does not Evidence never gets stronger as it propagates. A claim that rests on another through an `assuming` premise is capped at the evidence of the weakest premise, and the record names the cap (`meta["mathema.capped_by"]`); a premise that demands `is proven` and finds only `holds` leaves the conclusion `unknown`. See [Conditional claims and lemmas](lemmas.md). An equivalence between two implementations lets one's mathematical claims stand for the other at the equivalence's own evidence level and never higher, so a `holds` equivalence can never make a claim about the other implementation `proven`. Safety properties (state, representation, overflow) never transfer, since they belong to an implementation and its language rather than to the mathematics. Recording transferred claims in the other implementation's own record, with the equivale - docs/index.md (24729 bytes)
--- template: home.html title: mathema hide: - navigation - toc --- <span class="brkw eyebrow"><span class="brk l"></span><span class="bin">The problem</span><span class="brk r"></span></span> ## AI made code cheap. Verification didn't. Tests pass. CI is green. The agent says done. But what do you actually know? Traditional metrics tell you how much code you have. Test coverage tells you how much of it you executed. mathema tells you where your knowledge of the code ends. <span class="brkw eyebrow"><span class="brk l"></span><span class="bin">The gap</span><span class="brk r"></span></span> ## Passing tests don't tell you what you know A passing suite says the code did what the tests asked at the inputs the tests chose, which is worth a great deal and is still a narrow slice of what anyone reviewing the code actually wants to know. It says nothing, on its own, about: - how the function behaves at the inputs nobody wrote a test for, which mathema samples and, where the mathematics permits, proves over the whole declared domain; - the properties that follow from the implementation whether or not anyone intended them, such as symmetry, monotonicity or boundedness, which mathema checks with no claims written at all; - the assumptions a result silently relies on, which a claim has to state as a domain or an `assuming` premise before it will check; - where the behaviour becomes undefined, such as a pole, a raise or a non-finite result, which mathema looks for deliberately rather than hoping to stumble on; - whether the docstring still describes the code, which [`mathema docsync`](modes/docsync.md) reports as drift; - whether a change has invalidated something established earlier, including through a function it depends on, which [`mathema verify`](modes/verify.md) catches by re-checking every record whose code or dependencies moved; - and what remains unverified, which mathema reports as plainly as what it has proven. <span class="brkw eyebrow"><span class="brk l"></span><span class="bin">How it works</span><span class="brk r"></span></span> ## Give your code an evidence layer You state what a function is meant to do as a claim, a short mathematical statement such as `f(-x) == -f(x)`. mathema adjudicates that claim against the real function by the strongest route the function's shape allows, and keeps a record of what was established, how, and against exactly which version of the code. <div class="mx-figure"> <svg class="mx-diagram" viewBox="0 0 700 170" role="img" aria-labelledby="pipe-title pipe-desc" xmlns="http://www.w3.org/2000/svg"> <title id="pipe-title">The evidence layer</title> <desc id="pipe-desc">Intent becomes claims; claims are checked against the implementation by tests, probes and proofs; the result is an auditable record.</desc> <defs><marker id="pipe-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0,0 L10,5 L0,10 z" class="mx-d-head"/></marker></defs> <g class="mx-d-rung"><rect x="10" y="55" width="110" height="60" rx="3"/><text x="65" y="90" text-anchor="middle">intent</text></g> <g class="mx-d-rung"><rect x="150" y="55" width="110" height="60" rx="3"/><text x="205" y="90" text-anchor="middle">claims</text></g> <g class="mx-d-rung"><rect x="290" y="10" width="130" height="40" rx="3"/><text x="355" y="35" text-anchor="middle">tests</text></g> <g class="mx-d-rung"><rect x="290" y="65" width="130" height="40" rx="3"/><text x="355" y="90" text-anchor="middle">probes</text></g> <g class="mx-d-rung mx-d-strong"><rect x="290" y="120" width="130" height="40" rx="3"/><text x="355" y="145" text-anchor="middle">proofs</text></g> <g class="mx-d-rung mx-d-strong"><rect x="520" y="55" width="170" height="60" rx="3"/><text x="605" y="84" text-anchor="middle">auditable</text><text x="605" y="102" text-anchor="middle">knowledge</text></g> <g class="mx-d-arrow"> <line x1="120" y1="85" x2="146" y2="85" marker-end="url(#pipe-arrow)"/> <line x1="260" y1="85" x2="286" y2="30" marker-end="url(#pipe-arrow)"/> <line x1="260" y1="85" x2="286" y2="85" marker-end="url(#pipe-arrow)"/> <line x1="260" y1="85" x2="286" y2="140" marker-end="url(#pipe-arrow)"/> <line x1="420" y1="30" x2="516" y2="80" marker-end="url(#pipe-arrow)"/> <line x1="420" y1="85" x2="516" y2="85" marker-end="url(#pipe-arrow)"/> <line x1="420" y1="140" x2="516" y2="90" marker-end="url(#pipe-arrow)"/> </g> </svg> </div> Tests you already have count toward what is known about each line of code, probes run the real function on inputs chosen to find trouble, and proofs settle a claim for every input at once where the function can be read as mathematics. The record that comes out is plain YAML, bound to a hash of the function's structure, so it can be reviewed, diffed and re-checked long after the conversation that produced the code has gone. <span class="brkw eyebrow"><span class="brk l"></span><span class="bin">Strength of evidence</span><span class="brk r"></span></span> ## Evidence isn't binary A claim that held on a thousand random inputs and a claim that holds on every input are different kinds of knowledge, and mathema never lets one pass for the other. Every verdict carries the route that reached it: | Verdict | What it means | |---|---| | `proven` | settled mathematically, for every input in the declared domain | | `holds (n=...)` | survived exactly `n` trials against the real function, with inputs chosen by analysis where possible | | `falsified` | a counterexample, found by running the function and kept permanently | | `unknown` / `skipped` | not settled, with the reason in the record | Nothing is asserted and nothing is quietly upgraded. Evidence remains evidence, proof remains proof, and an unresolved claim remains unresolved. [The evidence ladder](evidence-ladder.md) sets out every rung, and [Guarantees and limits](guarantees.md) states what each verdict does and does not establish. The same rule holds for this site: every output on it was produced by a real run, and the test suite parses every claim these pages show, so a claim cannot quietly fall out of the grammar. <span class="brkw eyebrow"><span class="brk l"></span><span class="bin">A worked finding</span><span class="brk r"></span></span> ## See what mathema finds Here is a midpoint function of the kind that gets written, reviewed and merged every day, and the test someone wrote for it: <!-- example: midpoint file=mid.py --> ```python def midpoint(a: float, b: float) -> float: """The point halfway between a and b.""" return (a + b) // 2 ``` <!-- example: midpoint file=test_mid.py --> ```python from mid import midpoint def test_midpoint(): assert midpoint(2, 8) == 5 assert midpoint(0, 10) == 5 ``` <!-- example: midpoint run --> ```bash python -m pytest -q test_mid.py ``` <!-- example: midpoint output match=subset --> ```text 1 passed in 0.00s ``` The developer's claim is that the midpoint lies between its two inputs, which is the whole point of a midpoint. mathema checks that claim twice, once over the integers the test happened to use and once over the real numbers the type hints promise: <!-- example: midpoint run --> ```python import mathema from mid import midpoint print(mathema.check(midpoint, claims=[ mathema.claim("for a in [0, 100] subset Z, b in [0, 100] subset Z, " "min(a, b) <= f(a, b) <= max(a, b)", name="between_integers"), mathema.claim("for a in [0, 100], b in [0, 100], " "min(a, b) <= f(a, b) <= max(a, b)", name="between_reals"), ])) ``` <!-- example: midpoint output --> ```text mathema.Record(midpoint) · source, no side effects · form py:1825c3784c39 proven between_integers: for a in [0, 100] : int, b in [0, 100] : int, min(a, b) <= f(a, b) <= max(a, b) for a in [0, 100] : int, b in [0, 100] : int between_reals for a in [0.0, 100.0] : float|missing, b in [0.0, 100.0] : float|missing, min(a, b) <= f(a, b) <= max(a, b) falsified: min(a, b) <= f(a, b) fails at a = 99.9999, b = 100 falsified computation for a in [0.0, 100.0] : float, b in [0.0, 100.0] : float, min(a, b) <= f(a, b) <= max(a, b) counterexample link 1: min(a, b) <= f(a, b): a = 99.9999, b = 100: 99.9999 vs 99.0 holds policy f(a=nan) no missing policy stated; assumed propagates holds policy f(b=nan) no missing policy stated; assumed propagates ``` So the test established that the function works at two integer points. mathema established that over the integers it is correct everywhere in range, as a proof rather than a sample, and that over the reals it is wrong: floor division throws away the fraction, so the "midpoint" of 99.9999 and 100 is 99, below both of them. Nothing about this bug is exotic, and nothing in the test suite could have found it, because the suite only ever asked about integers. The fix is one character, and mathema proves it: <!-- example: midpoint file=mid.py --> ```python def midpoint(a: float, b: float) -> float: """The point halfway between a and b.""" return (a + b) / 2 ``` <!-- example: midpoint run --> ```bash mathema check mid.py:midpoint --claim "for a in [0, 100], b in [0, 100], min(a, b) <= f(a, b) <= max(a, b)" ``` <!-- example: midpoint output --> ```text ok mid.midpoint: source, no side effects; claims 4/4 checked (1 proven, 3 holds, 0 falsified) ``` One claim, four lines under it in the full record. The mathematics line is the proof over the real numbers. The computation line runs the same claim through the real code in floating point, at the region's corners and at sampled points inside it, and holds. The two policy lines cover a value that is not there: a float may be `nan`, nothing in the claim says what `midpoint` should do with one, so mathema assumes the `nan` passes through to the result (it propagates) and checks that it does. <span class="brkw eyebrow"><span class="brk l"></span><span class="bin">A whole codebase</span><span class="brk r"></span></span> ## The Monday-morning audit `mathema audit` answers the question anyone asks on their first morning with a codebase, namely where to start, without running a single test. Every function it can find gets a row: where it lives as a ready-made `sed -n` range, how branchy it is, whether it carries any claims, whether the derive route could prove things about it, what state outside its parameters it reads or writes, whether any test report covers it, and how well its docstring states its intent. Here is one module of mathema's own source: <!-- example: audit run requires=mathema_language --> ```bash mathema audit mathema.intent --root . ``` <!-- example: audit output --> ```text || || derive route || typing || globals || || docs || key | span || claims || derives | cx | reason | code || typed | finite_domain || vars | mutates | funcs || tested || quality || docsync mathema.intent ._references | 92:145p || {5 | 0 | -} || no | 15 | 9 branches, 3 loops (1 nested) | loop:multiple-loops || yes | - || _REF_SECTIONS, _URL, _DOI | - | re || no-report || 0/4 || 50% ._sections | 67:73p || {5 | 0 | -} || no | 2 | 1 loop | loop:not-a-fold || yes | - || _SECTION | - | - || no-report || 0/3 || 50% ._summary | 76:80p || {5 | 0 | -} || no | 2 | 1 loop | loop:not-a-fold || yes | - || _SECTION, _GOOGLE_HEADER | - | - || no-report || 0/2 || 44% .parse_doc | 148:162p || {5 | 0 | -} || no | 4 | 2 branches, 1 loop | loop:not-a-fold || yes | - || KEYWORDS | - | DocIntent, _sections, _summary, +1 || no-report || 2/3 || 40% 0/4 claimed, 0/4 derivable, 0/4 derive reads with nothing supplied, 4/4 fully typed, 2/12 docstring quality criteria met, no coverage.json/.coverage report found, 4/4 depend on state outside their own parameters (see the global_vars/unresolved columns), mean docsync 46%. `derives` is what the derive route can do here, given the domain the signature, docstring and claims declare. The reason/code cells describe what derive reads with nothing supplied, so a branch:needs-domain row reads blocked there and derives all the same, once a claim declares the domain that prunes the branch. Neither is a ceiling: a probe claim can still be written and checked for every function here. ``` `sed -n 149,163p mathema/intent.py` prints `parse_doc` and nothing else, which is what makes the table useful to an agent as much as to a person: it can go from "where is the function that parses a docstring" to the exact lines in one step. `mathema audit --index` writes the same map for a whole codebase to `.mathema/index.yaml`, with each module's stated intent, every function's file, line and span, and a pointer to its verified record where one exists. <span class="brkw eyebrow"><span class="brk l"></span><span class="bin">Agents and people</span><span class="brk r"></span></span> ## Let AI write the code. Don't let it define what correct means. A claim outlives the implementation it describes: when an agent rewrites a function, the claims about it are re-checked against the new code, and if one breaks you know which, where and with what counterexample. Where behaviour cannot be established, mathema says where it stopped rather than guessing. What an agent may not do is decide what counts as correct. No tool mathema exposes to an agent accepts a verdict from its caller, and the decisions that turn a verdict into an accepted fact about your codebase, accepting evidence as sufficient, owning a residual risk, or declaring that a falsification revealed a wrong claim rather than a bug, go through [`mathema accept`](modes/accept.md), which is a person at a terminal. Set a [PIN](modes/pin.md) the agent does not know, and every such decision needs it and is stamped in the record as made by someone who knew it, which the agent cannot be. Settled code can be frozen at the level that matters, the individual function. [`mathema lock`](modes/lock.md) pins a function's structure, after which any change to its body fails the sweep, while docstring edits and every other function in the file stay free: <!-- example: lock file=pricing.py --> ```python def discounted(price: float, rate: float) -> float: """The price after applying a discount rate.""" return price * (1 - rate) ``` <!-- example: lock run --> ```bash mathema lock pricing.discounte - docs/install.md (2449 bytes)
# Install mathema needs Python 3.10 or newer and has two required dependencies, sympy for the symbolic route and pyyaml for the record store. Install it into a virtual environment rather than a system Python: ```bash python3 -m venv .venv && source .venv/bin/activate pip install "mathema[all]" ``` or, in a project managed with uv: ```bash uv add "mathema[all]" ``` `[all]` adds numpy for array-shaped claims, z3 for the nonlinear proof rung, the MCP server, the native coverage reader and mathema-language for string and structured-value domains; `pip install mathema` is the minimal core, which already has `mathema check`, `verify`, `audit`, `lock`, the derive route and the record store. pandas and polars are separate extras, installed when your code uses them. ## Optional extras Each extra adds one capability without making it everyone's dependency. | Extra | Adds | |---|---| | `numpy` | array-shaped claims, matrix structure checks and array parameter synthesis | | `pandas` | a parameter annotated `pd.Series` or `pd.DataFrame` is sampled as one, so a claim about a pandas function runs against the object the code expects | | `polars` | the same for a parameter annotated `pl.Series` or `pl.DataFrame` | | `smt` | z3's nonlinear real arithmetic as one rung of the `extensive` proof ladder (a native library of roughly 100 MB) | | `mcp` | `mathema mcp serve`, which exposes mathema's checking tools to a coding agent | | `coverage` | reading a native `.coverage` report, so the tests you already run count toward the implementation score (a `coverage.json` export works without it) | | `symbology` | conventional notation for parameter and function names when claims are rendered | | `language` | the `L[...]` domains over strings and structured values, from the [mathema-language](language.md) package | | `all` | `numpy`, `smt`, `mcp`, `coverage` and `language` together, the recommended install | ```bash pip install mathema # the minimal core pip install "mathema[pandas]" # one extra at a time ``` ## Offline by design mathema makes no network calls. There is no account, no API key and no telemetry, so it runs against a private codebase without source or claims leaving the machine. The one command that fetches anything, `mathema init --agents`, does so only when you run it explicitly. ## Next The [quick start](quickstart.md) takes five minutes and one function from a falsified claim to a proven one.
- docs/language.md (14069 bytes)
# Language domains A claim over a function of text needs a domain the way a claim over a function of numbers does. A language is that domain: the set of strings a name stands for, or of structured values a schema stands for, written `L[<name>]` where a numeric claim writes `R` or `[0, 1]`. ``` for s in L[unicode], f(f(s)) == f(s) for s in L[unicode] \ {""}, len(f(s)) >= 1 for s in L[unicode], len(f(s)) <= len(s) ``` ## Three words An **alphabet** is a set of characters (`ascii`, `latin-1`, `digit`). A **language** is a set of strings, or more generally of values: `L[ascii]` is every string over the ascii alphabet, the way a Kleene star reads, so the empty string is a member and `\ {""}` removes it; `L[json]` is every string `json.loads` accepts; a schema names the language of its documents. **Text** is the carrier, Python's `str`, the way the reals are the carrier of `R`. `L` is rendered in both output alphabets; `𝕃` is accepted on input. Union with a finite set of members, exclusion and the missing-value policy read exactly as they do for a numeric domain, and a finite set of strings is itself the simplest language, the one mathema always had: ``` for scale in {"info", "linear"}, f(r, scale) >= 0 ``` ## What mathema does with a language The probe draws members of the language and never a value outside it: the language's own hazards first (the empty string, whitespace, NUL and the other control code points, an alphabet's boundary, a long member, a lone surrogate, a byte-order mark), every one of them once before any random member is drawn, then random members. The hazards count toward the trial budget the way a wide interval does (see [the trial budget](modes/check.md#the-trial-budget)), and the confidence score is marked down for them the same way. A function that raises on a member falsifies the claim with that member as the witness, the rule a numeric domain follows. The derive route has no reading of a string, so it declines with the reason rather than proving real-only facts about a symbol standing in for one; a finite language is the exception, swept point by point and proven or falsified with the member. `@enforce_domain()` reads a language binding and rejects a non-member at call time. Every record states what a name resolved to, in `meta["mathema.language"]`: the name, its source (an in-process registration, a package's entry point, a dotted object, an adaptor), its level (finite, alphabet, regular, predicate, schema) and its persisted form. A family that resolves something of its own writes it beside the parameters, so `output_in_language` records the language it held the output to under `return`, with where that came from. A claim over a language is stamped `grammar: mathema/language`, the dialect of the claim grammar that reads language vocabulary; a claim over a finite set stays plain `mathema`. In that dialect a length renders as `len(s)`, while the canonical form underneath keeps `dim(s, 0)`, mathema's one spelling of a dimension, so the rendered text parses back to the same claim. ## Refinements A refinement narrows a language inside its brackets, a key and a bound on the whole number it measures: ``` for s in L[ascii, len <= 80], len(f(s)) <= 80 for s in L[unicode, len > 20], len(f(s)) <= len(s) for s in L[unicode, len in [1, 80]], f(s) in L[unicode, len in [1, 80]] ``` mathema reads the shape, `key <= n`, `key < n`, `key >= n`, `key > n` or `key in [lo, hi]`, renders the keys in one order and records each under its own name, and owns no key itself: what a key measures is the refinement registered under it, in the process or under the `mathema.language_refinements` entry-point group, and a key nothing serves is refused when the claim is checked, with the keys that are known. The `mathema-language` package serves `len`, a count of code points (Python's `len`, not bytes, and not the characters a reader sees, since `"é"` can be one code point or two). A refined language is a language of its own: every member the probe draws fits the bound, the members at each bound are the first hazards it visits, as plain as the language allows (`"a" * 80`), and a member one past the bound is its outside draw, so `excluded_outside_domain(s)` checks that the function refuses the 81st character. `L[unicode, len >= 1]` is the same set as `L[unicode] \ {""}`. A parameter annotated `Annotated[str, MaxLen(80)]` (annotated_types, pydantic) infers `L[unicode, len <= 80]` through the package's text adaptor, and the record's note says so. A language domain spells a missing value as a word in both modes: to a reader of formal languages `∅` is the empty language, a different set. A string has no hole of its own, so the missing value of a string parameter is its absence, `L[unicode]|None`, which an `Optional[str]` admits and a `str` does not; `for s in {missing}` over a `str` is refused with the reason. ## Paths into a member A binding can name a path into a member of a language, through fields and indices, at any depth: ``` for o in L[myapp.Order], o.address.zip in L[digit, len <= 5], ... for o in L[myapp.Order], o.lines[0].sku in L[slug], ... for o in L[myapp.Order], o.lines[*].qty in [1, 10], total(o) >= 0 ``` `[*]` means every element. A path binding narrows the members the probe draws: every value the path reaches is in the bound. A path through a missing field or past the end of a list is absent, and a bare bound already means the value is there; `| {absent}` on the bound keeps such a record in. A `None` list element and a `nan` are holes, not absences. The derive route reads a numeric leaf at any depth the body reads (`o.lines[0].qty`, `o["address"]["zip"]`) with the bound the language states for it, and a claim's own path binding, the `[*]` form included, overrides that bound. ## Membership and containment The output side has two spellings of its own. `f(s) in L[slug]` says every output is a member of a language (or a finite set, or a named number set); `∈` and `∉` are the Unicode forms, and a plain numeric interval on the right is read as the chain it means, so `f(x) in [0, 1]` is recorded as `0 <= f(x) <= 1`. `"<" not in f(s)` says the value on the left is never found in the value on the right, Python's own containment, which is how a claim states that an escaper never emits a character. Both are decided by execution: a member is a member or it is not, a missing value is a member of nothing unless the right-hand side names it explicitly, and the derive route declines with the reason. ``` for s in L[slug], f(s) in L[slug] for s in L[unicode], f(s) ∉ L[ascii] for s in L[unicode], "<" not in f(s) for x in [0, 1], f(x) in [0, 1] ``` In order: closure into the language, an output that always leaves ASCII, a token that is never emitted, and the chain `0 <= f(x) <= 1`. ## Installing the languages mathema itself parses, renders and records `L[...]` and resolves no name. The names come from the `mathema-language` package: ```bash pip install "mathema[language]" ``` It provides the alphabets (`ascii`, `latin-1`, `unicode`, `printable`, `digit`, `alpha`, `alnum`), the predicate languages with an exact standard-library test behind each (`identifier`, `json`, `uuid`, `iso_date`, `iso_datetime`, `ipv4`, `ipv6`, `base64`, `hex`, `slug`, `shell_safe`), the hazard sub-alphabets a probe mixes in (control and format characters, combining marks, surrogates, the characters whose NFKC form differs, the astral planes), the built-in claims `is_length_safe` and `is_encoding_safe`, and the schema adaptors that turn a dataclass, a `TypedDict`, a pydantic model or a JSON Schema into the language of its rows (a SQLAlchemy table and a Django model too). Without it, a claim over `L[unicode]` is `unknown`, and its note says it needs mathema-language. The package keeps its own reference, published on this site as [the language reference](/language/reference/): every language and its membership test, the hazards, a page for each row adaptor with what it reads and which validator decides membership, how to write an adaptor of your own, and a catalogue of claims worth writing about a function over text, each one run by the package's tests and held to the verdict printed beside it. This page stays with the grammar and with what a record states. ## Writing your own A language is any object satisfying `mathema.languages.Language`: a `name`, a `kind` (what a member is), a `level` (how far the engine can decide it), and `contains`, `explain`, `sample`, `members`, `hazards`, `outside`, `shrink`, `fields`, `render` and `to_json`. `mathema.languages.StringLanguage` assembles one from a per-character test or a whole-string predicate, and `language_problems(obj)` says what an object is missing. Three ways to make it resolvable: - `register_language("slug", obj)` in the process that checks the claims. - A `mathema.languages` entry point in your package, the name being the language name. - A dotted path, `L[myapp.text.SLUG]`, to a `Language` object, or to anything a `mathema.language_adaptors` adaptor accepts. [Extending mathema](extending.md) documents the two entry-point groups. A language may also supply a derive strategy for claims quantified over it, a `derive` method taking `param`, `lhs`, `relation`, `rhs`, `functions` (the target as `f` and under its own name, with every function the claim binds) and `refinements` (each key in force mapped to the whole-number range it keeps), and returning a `ProofResult` or None. It is found through any refinements wrapped around the language and runs under the wall-clock cap. A proof it returns is the claim's derive verdict, on the route `derive:<mechanism>` named by the result's `mathema.derive_route`; anything else leaves the claim to the probe, and a disproof it claims is read as undecided, since only an executed witness falsifies. mathema-language's recursive row languages prove fold claims this way, on `derive:induction`. ## Refusal and a defined answer Two built-in claims ask how a function treats its language. `excluded_outside_domain(s)` asks that every value outside the domain is refused, and by default any raise refuses. `is_language_defined(s)` reads the language as the declared domain: every member gets an answer, by default a return or an exit status, so any other raise on a member falsifies it, whether or not the function guards it and whatever its type; and every non-member is refused, by default by any raise (an exit included), so a value returned for one falsifies it too. With no language bound (a plain `str` parameter), the function's refusals define its language: an exit, a guarded raise and a deliberate one (a `ValueError`) refuse the string, the record's note lists the strings refused and how, and only an accidental unguarded crash (a `TypeError`, an `IndexError` and the like) falsifies. Whether f is defined on every string is `is_defined`'s question. A command-line program says both things differently: it refuses a bad argument list by exiting with code 2, and it answers with exit code 0 or 1. A language can declare both, and the two claims then read the declaration instead of the default: - `refusal`, a `Refusal`: a raise of the exception classes it names, optionally narrowed by a test on the exception, or a return its `returns` test accepts. `Refusal.exit(2)` is `SystemExit` with exit code 2. - `defined_answer`, a `DefinedAnswer`: a return (every return, or those its `returns` test accepts), or a raise of the exception classes it names. `DefinedAnswer.exit(0, 1)` is a return, or `SystemExit` with exit code 0 or 1. An outside draw then has to be refused the declared way, and a member has to get the declared answer; the witness names the declaration and what the call did instead. The record's `meta["mathema.language"]` entry for the parameter states the declarations under `refusal` and `defined answer`, in the same words, so a `holds` says what it held to. A language that declares neither is read as before, and its entry is unchanged. `StringLanguage` takes both as keywords, a refined language keeps its base's, and a language object of your own sets them as attributes: <!-- example: refusal run --> ```python import sys import mathema from mathema.languages import DefinedAnswer, Refusal, StringLanguage, register_language register_language("count", StringLanguage( "count", char_ok=lambda c: c in "0123456789", pool="0123456789", outside_pool="x-", refusal=Refusal.exit(2), defined_answer=DefinedAnswer.exit(0, 1))) def parity(s: str) -> None: """Exit 0 for an even count, 1 for an odd one.""" if not s.isdigit(): sys.exit(2) sys.exit(int(s) % 2) def parity_by_hand(s: str) -> None: """Exit 0 for a count divisible by three, else the remainder.""" sys.exit(int(s) % 3) for fn in (parity, parity_by_hand): for p in mathema.check_conjectures(fn, [ 'for s in L[count] \\ {""}, excluded_outside_domain(s)', 'for s in L[count] \\ {""}, is_language_defined(s)']): print(fn.__name__, p.name, p.verdict) if p.counterexample: print(" ", p.counterexample) ``` <!-- example: refusal output --> ```text parity excluded_outside_domain[s] holds parity is_language_defined[s] holds parity_by_hand excluded_outside_domain[s] falsified s = 'á' (outside L[count] at [0]: count alphabet) is outside the declared domain and was not refused the way the language declares (SystemExit (exit code 2)): the call raised ValueError parity_by_hand is_language_defined[s] falsified s = '' (outside L[count] \ {""}) raised ValueError, where a non-member is refused (SystemExit (exit code 2)) ``` `parity` refuses anything that is not a count with exit code 2 and answers every count with 0 or 1, so both claims hold. `parity_by_hand` lets `int` raise a `ValueError` on a value outside the language, which is a crash rather than the refusal the language declares, as the empty string the claim removes shows; it also exits 2 on `"77"`, a member, which is not an answer. - docs/lemmas.md (7013 bytes)
# Lemmas: one claim resting on another A lemma in mathema is not a separate kind of object. There is no `lemma` keyword, no lemma field in the record, and nothing to declare. A claim becomes a lemma **by being referenced**: another claim names it in an `assuming` clause, and from then on the two are related by evidence. ``` assuming grows holds, for x in [0,10], f(x) == 2*x ``` That claim rests on a sibling named `grows`. If `grows` is established, this one is adjudicated normally. If it is not, this one does not silently proceed: it reports that what it rests on was never settled. Two spellings, and they ask for different strengths: ``` assuming grows holds, for x in [0,10], f(x) >= 0 ``` ``` assuming base_case is proven, for n in [2, 30] subset Z, f(n) == f(n-1) + f(n-2) ``` `holds` accepts either a proof or empirical agreement. `is proven` accepts only a proof. Nothing else is interpreted as a verdict reference: `X is falsified` and `X is unknown` are not premises, because a claim that failed is not something to build on. ## What a reference actually does Three separate mechanisms fire, and it is worth keeping them apart because they fail differently. **It gates.** If the referenced claim does not reach the strength asked for, the dependent claim comes back `unknown`, with `meta["mathema.premise"]` naming why. The claim itself was never attempted; only what it rests on failed. That is an undecided state, not a refutation, and the note says which prerequisite was missing. **It caps.** A conclusion can never be stronger than what it rests on. A lemma established only empirically caps its dependents at `holds` even when their own proof would otherwise be exact. **It lends.** A discharged lemma's relation is handed to the proof as an assumption, which is what makes this modus ponens rather than bookkeeping. This is the part that turns a chain of claims into a chain of reasoning. ## Chaining Claims are adjudicated in dependency order, not declaration order, so a lemma may be written after the claim that uses it. The results still come back in the order you wrote them. <!-- example: chain run --> ```python from mathema.claims import check_conjectures, claim def scale(x: float) -> float: """Twice x.""" return 2 * x out = {p.name: p for p in check_conjectures(scale, [ claim("for x in [0,10], f(x) >= x", name="grows", route="derive"), claim("assuming grows is proven, for x in [0,10], f(x) >= 0", name="nonneg"), claim("assuming nonneg holds, for x in [0,10], f(x) + 1 > 0", name="offset"), ])} for name, p in out.items(): print(f"{name:<8} {p.verdict}") ``` Each link is proven, and `offset` is proven on the strength of `nonneg`, which is proven on the strength of `grows`: <!-- example: chain output --> ```text grows proven nonneg proven offset proven ``` ## The weakest link bounds the conclusion When a claim rests on several lemmas, the weakest one sets the ceiling. This is the rule that stops a chain from laundering sampled evidence into a proof. <!-- example: weakest run after=chain --> ```python out = {p.name: p for p in check_conjectures(scale, [ claim("for x in [0,10], f(x) >= x", name="grows", route="derive"), claim("for x in [0,10], f(x) >= 0", name="sampled", route="probe"), claim("assuming grows is proven and sampled holds, " "for x in [0,10], f(x) + 1 > 0", name="rests_on_both"), ])} for name, p in out.items(): cap = p.meta.get("mathema.capped_by") print(f"{name:<14} {p.verdict}" + (f" capped_by={cap}" if cap else "")) ``` <!-- example: weakest output --> ```text grows proven sampled holds rests_on_both holds capped_by=sampled ``` `rests_on_both` could have been proven on its own. It is reported as `holds` because one of the things it rests on was only sampled, and `meta["mathema.capped_by"]` names which one. Read that field when a claim you expected to prove came back weaker: it points at the lemma to strengthen, not at the claim you were looking at. ## Lending has a domain guard A lemma lends its content only where it was established. A lemma proven over `x in [0,10]` says nothing about `x = -3`, so if the dependent claim quantifies over a different region the lemma still gates and still caps, but its relation is not handed to the proof. This is deliberately strict: the bounds must agree, not merely overlap. ## When a prerequisite cannot be resolved <!-- example: orphan run after=chain --> ```python (p,) = check_conjectures(scale, [ claim("assuming absent holds, for x in [0,10], f(x) >= 0", name="orphan")]) print(p.name, p.verdict, "|", p.meta["mathema.premise"]) print("note:", p.note) ``` <!-- example: orphan output --> ```text orphan unknown | missing-prerequisite note: prerequisite 'absent' is not a claim in this batch, nothing to rest this claim on ``` The other resolution failures report themselves the same way. A name matching more than one claim is `ambiguous-reference` rather than being quietly bound to the first. A cycle skips every claim in it, each note naming both claims. A premise that mixes a verdict reference with a relation in one clause is refused rather than half-interpreted. A premise can also reach outside the batch, to another function's claim, by qualifying the name: ``` assuming numpy.clip.clip_lower holds, for w in [-50, 50], f(F0,k,m,-w,c) == f(F0,k,m,w,c) ``` Resolution prefers an in-batch sibling, then the verified layer. An external row enters at declared status and satisfies nothing until it has been accepted or genuinely verified, so a library stub cannot quietly discharge your premise. ## Two things that are not lemmas **Partiality lemmas** are a different feature with a confusingly similar name. They are Python-registered facts about where a function raises, used by the derive route to reason about partial functions, and they are not claims. See [Conditional claims](conditional-claims.md). **The outcome clause** looks like implication but is not adjudicated: ``` f(x) > 0 => self.stays_positive ``` Everything after `=>` names a sibling claim that should follow when this one holds. It is captured verbatim and travels in the record, but nothing currently derives the named claim from it. If you want one claim to actually rest on another, use an `assuming` premise, which is what this page describes. ## Limits Resolution is by name, so names must be unique within what is being adjudicated together. A bare sibling name without `holds` or `is proven` is a different construct: it borrows that sibling's relation as a region constraint rather than consulting its verdict, and it requires the sibling to carry a plain relation. Lending recurses as far as the chain goes, but each link is only as good as its own evidence, and the cap propagates the whole way. A long chain resting on one sampled lemma is a sampled result at the end of it, which is the honest outcome rather than a limitation to work around. - docs/library-claims.md (10640 bytes)
# See what mathema knows about a library you call Your function calls numpy. mathema ships claims about numpy's functions, and when it sweeps your code it also adjudicates those claims for the calls your code makes, against the numpy you have installed. This guide shows how to see which of your calls are covered, which are not, and how to state a claim about a call nothing covers. It assumes [the CDD loop](tutorial.md). The running example is a risk module with three functions, each with one claim of its own: <!-- example: library file=risk.py --> ```python import numpy as np def volatility(returns: np.ndarray) -> float: """Annualised volatility of daily returns.""" return float(np.std(returns, ddof=1) * np.sqrt(252)) def value_at_risk(returns: np.ndarray) -> float: """The loss not exceeded on 95 percent of days, as a positive number.""" if len(returns) == 0: raise ValueError("value at risk needs at least one return") return float(-np.percentile(returns, 5)) def moves(returns: np.ndarray) -> np.ndarray: """The change from each day to the next.""" return np.ediff1d(returns) ``` <!-- example: library file=claims/risk.claims.yaml --> ```yaml risk.volatility: claims: - name: nonneg statement: "for returns in [-0.1, 0.1]^n, assuming dim(returns) >= 2, f(returns) >= 0" risk.value_at_risk: claims: - name: within_the_worst_day statement: "for returns in [-0.1, 0.1]^n, f(returns) <= -min(returns)" risk.moves: claims: - name: telescopes statement: "for returns in [-0.1, 0.1]^n, assuming dim(returns) >= 2, sum(f(returns)) ~= returns[-1] - returns[0]" ``` ## 1. Ask what is known <!-- example: library run requires=numpy --> ```bash mathema compendium status --root . ``` <!-- example: library output match=subset --> ```text claims files: mathema/compendium/numpy/bounds.claims.yaml (bundled, >=1.24,<3, in range) mathema/compendium/numpy/definitions.claims.yaml (bundled, >=1.24,<3, in range) mathema/compendium/numpy/linalg.claims.yaml (bundled, >=1.24,<3, in range) mathema/compendium/numpy/reductions.claims.yaml (bundled, >=1.24,<3, in range) mathema/compendium/numpy/scalars.claims.yaml (bundled, >=1.24,<3, in range) mathema/compendium/numpy/statistics.claims.yaml (bundled, >=1.24,<3, in range) numpy.percentile 1 call, 2 rows: 0 verified locally, 0 trusted, 0 falsified, 2 unsettled numpy.sqrt 1 call, 2 rows: 0 verified locally, 0 trusted, 0 falsified, 2 unsettled numpy.std 1 call, 4 rows: 0 verified locally, 0 trusted, 0 falsified, 4 unsettled no claims: numpy.ediff1d ``` One block per library, headed by its installed version and the number of calls, a call counted once per function that makes it. The claims files are the ones mathema ships for numpy: a compendium is a claims file whose keys are a library's functions rather than your own, with the range of library versions it applies to, and each file is marked in range or out of range for the numpy installed. The excerpts on this page leave out the heading, which names your numpy's version, and the three files for numpy 2.4 and later, which are out of range on an older numpy. Then each called function that has rows, with how many are settled: none yet, since nothing has run. `numpy.ediff1d` has no rows at all, so what it does under your inputs is a black box to mathema until someone states a claim about it. ## 2. Sweep `mathema verify` adjudicates the rows for the library functions your code calls, and only those, against the installed library. A project that never calls numpy verifies none of numpy's rows. <!-- example: library run requires=numpy --> ```bash mathema verify --root . ``` <!-- example: library output --> ```text ok numpy.percentile: library claims from mathema/compendium/numpy/statistics.claims.yaml; no baseline record; 1 proven, 2 holds, 0 falsified note definition: numpy.percentile gives no value at a = [1.7976931348623157e+308, -1.7976931348623157e+308], q = 30.72597523513774, a magnitude corner where the exact value is finite: a finding about its computation; the row stands ok numpy.sqrt: library claims from mathema/compendium/numpy/scalars.claims.yaml; no baseline record; 1 proven, 2 holds, 0 falsified ok numpy.std: library claims from mathema/compendium/numpy/reductions.claims.yaml; no baseline record; 1 proven, 4 holds, 0 falsified note definition: numpy.std gives no value at a = [1e+300, -1e+300], a magnitude corner where the exact value is finite: a finding about its computation; the row stands note definition@ddof=1: numpy.std gives no value at a = [1e+300, -1e+300], a magnitude corner where the exact value is finite: a finding about its computation; the row stands ok risk.moves: no baseline record; 1 proven, 2 holds, 0 falsified ok risk.value_at_risk: no baseline record; 1 proven, 3 holds, 0 falsified ok risk.volatility: no baseline record; 1 proven, 2 holds, 0 falsified 0 unchanged since the last run (not run again), 6 checked, 0 problem(s) grammars detected: mathema; verified by this run: mathema 3 intents to accept (3 functions): mathema accept --intent ``` Each library row now has a record of its own under `.mathema/verified/`, named by the file it came from. The `1 proven` on every line is `dependencies_current`, the claim `verify` adds to each record that what the function depends on has not moved. ## 3. Ask again <!-- example: library run requires=numpy --> ```bash mathema compendium status --root . ``` <!-- example: library output match=subset --> ```text numpy.percentile 1 call, 2 rows: 2 verified locally, 0 trusted, 0 falsified, 0 unsettled numpy.sqrt 1 call, 2 rows: 2 verified locally, 0 trusted, 0 falsified, 0 unsettled numpy.std 1 call, 4 rows: 4 verified locally, 0 trusted, 0 falsified, 0 unsettled no claims: numpy.ediff1d ``` Verified locally means proven or holding in this project's store, on this machine's numpy. The gap is unchanged. ## 4. State what you rely on A compendium file of your own closes the gap. It sits with your other claims files, names the library and the versions the row applies to, and its keys are the library's functions with the library's own parameter names (`numpy.ediff1d` takes `ary`): <!-- example: library file=claims/numpy.claims.yaml --> ```yaml compendium: numpy versions: ">=2,<3" numpy.ediff1d: claims: - name: differences statement: "for ary in [-100, 100]^n, assuming dim(ary) >= 2, f(ary) == ary[1:] - ary[:-1]" route: probe ``` `route: probe` says up front that the row is checked by running the function. Left out, mathema tries the derive route first and falls back to probing, and the record keeps why: for `ediff1d`, that branch pruning could not settle whether `to_begin` and `to_end` are both None under the declared domain. Either way the next sweep adjudicates the new row and nothing else, every other record being fresh: <!-- example: library run requires=numpy --> ```bash mathema verify --root . ``` <!-- example: library output match=subset --> ```text ok numpy.ediff1d: library claims from claims/numpy.claims.yaml; no baseline record; 1 proven, 1 holds, 0 falsified 6 unchanged since the last run (not run again), 1 checked, 0 problem(s) ``` <!-- example: library run requires=numpy --> ```bash mathema compendium status --root . ``` <!-- example: library output match=subset --> ```text claims files: mathema/compendium/numpy/bounds.claims.yaml (bundled, >=1.24,<3, in range) mathema/compendium/numpy/definitions.claims.yaml (bundled, >=1.24,<3, in range) mathema/compendium/numpy/linalg.claims.yaml (bundled, >=1.24,<3, in range) mathema/compendium/numpy/reductions.claims.yaml (bundled, >=1.24,<3, in range) mathema/compendium/numpy/scalars.claims.yaml (bundled, >=1.24,<3, in range) mathema/compendium/numpy/statistics.claims.yaml (bundled, >=1.24,<3, in range) claims/numpy.claims.yaml (project, >=2,<3, in range) numpy.ediff1d 1 call, 1 row: 1 verified locally, 0 trusted, 0 falsified, 0 unsettled numpy.percentile 1 call, 2 rows: 2 verified locally, 0 trusted, 0 falsified, 0 unsettled numpy.sqrt 1 call, 2 rows: 2 verified locally, 0 trusted, 0 falsified, 0 unsettled numpy.std 1 call, 4 rows: 4 verified locally, 0 trusted, 0 falsified, 0 unsettled ``` Your file is listed beside the bundled ones as `project`, and `ediff1d` has left the `no claims` line. A row in your file with the name of a bundled row replaces that row, and the other bundled rows for the function still apply. An installed package can ship compendium files too, through the `mathema.compendium` entry point ([Extending mathema](extending.md#registered-compendium-files) shows the declaration). Its files are listed beside the bundled ones as `package <name> <version>`, and its rows load after the bundled rows and before yours, each naming the distribution it came from. A package row adds to a function's rows; one with the name of a bundled row, or of another package's, that says something different is a conflict: neither row is used, and `mathema compendium status` lists both statements and where each comes from. Like every compendium row, a package's is testimony until `mathema verify` adjudicates it here. ## 5. When a row cannot be settled here A row `verify` cannot settle against the installed library is recorded `unknown` or `skipped`, and it fails the gate like any other. The decision is the team's: `mathema accept KEY CLAIM --as trusted` takes the compendium's word for the row at the level it claims, as testimony a later local verdict replaces, and `--as risk` records that the team owns the gap. [Gate a pipeline with mathema verify](gate-a-pipeline.md#4-decide-about-the-row-nobody-wrote) walks through one, and [`mathema accept`](modes/accept.md#-as-trusted) has the exact semantics. ## Behind this page - [Claims transfer](claims-transfer.md#in-the-compendium) is the reference for compendium files: the header fields, aliases, per-row version ranges, how defaults are held, and the two kinds of row. - [`mathema compendium`](modes/compendium.md) has `update`, which drafts rows for the calls your project makes, and `export`, for publishing a library's own verified claims. - [`mathema verify`](modes/verify.md#library-claims-lazy-by-default-a-file-up-front) explains the lazy sweep and how to adjudicate a whole claims file up front. - [The claim grammar](grammar.md) has one example per form used here: the `[a, b]^n` space and a `dim(returns) >= 2` premise written after `assuming`. - docs/licensing-policy.md (2152 bytes)
# Tetrion licensing policy for mathema Effective 2026-09-07. This policy accompanies the Business Source License 1.1 that mathema is distributed under (`LICENSE.md` in the repository); the license, including its Additional Use Grant, governs, and this policy states how Tetrion Ltd applies it. ## Free-use thresholds (the Additional Use Grant's floors) Production use is free of charge for any Organisation meeting **any** of the grant's conditions: 1. total Organisation revenue below **USD 10,000,000** in the most recently completed fiscal year; 2. use in connection with **at most three code repositories** across the Organisation; 3. research, teaching, personal, or other **non-commercial** use; 4. **evaluation**, for up to **90 days** from the Organisation's first use. "Organisation" is defined in the grant: the legal entity together with every entity that controls it, is controlled by it, or is under common control with it. The grant never permits providing third parties a product or service having substantially the same function as mathema or as a Tetrion product built on it. ## Cure period An Organisation that ceases to qualify (a revenue floor crossed at a fiscal year end, a fourth repository, an evaluation running past 90 days) has **60 days** from the date it ceased to qualify to either obtain a commercial license from Tetrion or end production use. Good-faith production use during that window is treated as licensed. Rights under the license terminate only when the window closes with neither having happened. ## Conversion schedule Each released version's Change Date is **four years from that version's release date**, computed at release time and written into that release's LICENSE.md. On its Change Date a version converts to the **GNU Affero General Public License v3.0 or later** and every restriction above stops applying to that version. (AGPL-3.0-or-later satisfies the license's Covenants of Licensor: it is compatible with GPL Version 3.0, a later version of GPL Version 2.0.) ## Contact Commercial licensing, threshold questions, and anything this page doesn't answer: [email protected].
- docs/mathema-docstring.md (25628 bytes)
# The mathema docstring A second, opinionated docstring convention, stricter than the loose quality checklist [`mathema audit`'s `quality` column](modes/audit.md#the-quality-score) scores. The idea: a function's own docstring becomes the *complete* authoring surface for intent, domain, and claims, no separate YAML file or decorator required to get real, checked evidence. In `ema.py`: <!-- example: ema file=ema.py --> ```python from typing import Annotated from mathema.types import Probability def ema(x: list[float], alpha: Annotated[float, Probability]) -> float: """Exponentially weighted moving average. Intent: Blends each new value with the running mean. Claims: bounded: for x in [0, 1]^n, alpha in [0, 1], f(x, alpha) <= 1 Raises: ValueError: x is empty. """ if not x: raise ValueError("ema of an empty series") y = x[0] for v in x[1:]: y = alpha * v + (1 - alpha) * y return y ``` `mathema.check(ema, claims=[])` checks exactly the claims the docstring declares, and `x in [0, 1]^n` samples lists of one or more entries, each in the unit interval: <!-- example: ema run --> ```python import mathema from ema import ema print(mathema.check(ema, claims=[])) ``` <!-- example: ema output --> ```text mathema.Record(ema) · source, no side effects · form py:a7f31dc48c43 bounded for x in ([0.0, 1.0] | {missing})^n : float, alpha in [0.0, 1.0] : float, f(x, alpha) <= 1 holds holds computation for x in ([0.0, 1.0])^n : float, alpha in [0.0, 1.0] : float, f(x, alpha) <= 1 742 entries across 162 draws, sizes (1, 1) to (8, 1) holds policy f(x=[]) holds policy f(x=[..., nan, ...]) no missing policy stated; assumed propagates ``` The claim's line carries the verdict, and the lines under it say what it rests on: the claim over the real numbers (the mathematics), what `ema` does with an empty list (it raises the `ValueError` its docstring declares), and what it does with a `nan` entry (nothing in the claim says, so mathema assumes the `nan` reaches the result, and checks that it does). This is additive, a docstring with none of these sections behaves exactly as before, and every existing authoring surface (a claims file, `@claims_decorator`, `Annotated` type hints) still works unchanged. ## The sections | Section | What it declares | |---|---| | `Intent:` | one or two sentences of prose, what the function computes | | `Claims:` | ordinary claims, see [Authoring claims](authoring.md#2-docstring-claims-block) | | `Notes:` | free-form limitations or design rationale, optional, see below | | `Concepts:` (or `Tags:`) | plain concept tags, comma- or newline-separated, optional, see below | | `Analysis:` / `Evidence:` / `Policy:` / `References:` (or `Refs:`) | role-labeled links, optional, see below | All five are Google-style blocks (a bare `Header:` line, body indented underneath, ending at the first line that dedents back to column zero), the same scanning shape `Claims:` already used. ### `Concepts:` and role-labeled links Concepts are TAGS: plain tokens naming what the function is about, normalized to kebab form (`Great Circle` becomes `great-circle`). `Tags:` is an accepted spelling for the same thing; internally everything is a concept. They land in the record's own `concepts` field and, per the CDD spec's meta example, in `meta.concepts` (the flat union) with the full provenance beside it under `mathema.concept_sources`, your declared tags never mixed indistinguishably with the mechanism-derived ones (what the proof machinery itself touched: a fold lift tags summation, an nlsat proof tags polynomial-arithmetic) or the inferred keyword hints. Entirely optional and never scored. References are LINKS, each labeled with the role its section states: `References:`/`Refs:` for citations, `Analysis:` for working notes (a notebook documenting a model assumption, say), `Evidence:` and `Policy:` for exactly what they sound like. One `- Title: URL` line per link (numpydoc `.. [1]` entries and bare DOIs also parse), landing in the record's `references` list with `via` carrying the role. ```python def power_uncertainty(x, sigma_x, n): """First-order uncertainty of x**n. Concepts: error-propagation, metrology Analysis: - Assumption notebook: https://nb.example.com/gum.ipynb """ ``` Both are also authorable from the declared spec: an entry-level `meta: {concepts: [...]}` and `references:` list beside the claims, and a per-claim `meta: {concepts: [...]}` that passes through to the recorded claim untouched, exactly as the spec's pass-through rule requires. ### `Notes:` Prose, same shape as `Intent:`, for anything worth recording that isn't itself intent, a domain, or a claim, a known limitation, why a particular approach was chosen, a caveat about the evidence. Never scored: an absent `Notes:` section costs nothing, unlike an absent `Intent:`. Written through to the verified record's `meta.notes` field (`mathema.write_spec(fn)`), record-schema.md's namespaced extension slot, nothing else currently lives there. ```python def half(x: float) -> float: """Halves x. Notes: Only tested for finite inputs. NaN handling is unspecified. """ return x / 2 ``` Inline `# note:` comments (any capitalisation, `# Note:`, `# NOTE:`) feed the same channel: every one in the function's body, plus the comment lines immediately following it, joins the docstring's own `Notes:` prose in `meta.notes`, deduped so a comment restating what the docstring already says never double-appends. The structured form (each note with its file line) is on `Facts.comment_notes` for anything that wants provenance rather than prose. ```python def scale(x: float) -> float: # note: precision loss above 1e15. return 2.0 * x ``` ### Where a domain goes (there is no `Domain:` block) A domain is stated in the claim that needs it, as that claim's own quantifier: ```python "for alpha in (0, 1], f(x, alpha) <= max(x)" ``` For an ordinary parameter, an `Annotated` marker in the signature (`Probability`, `Positive`, `Nonnegative`) states a bound once for every claim. The signature is the one place a type belongs; there is no docstring `Types:` block either. A `Domain:` docstring block used to sit beside these. It was removed: measured at zero real uses across a 313-file corpus, against 96% of claims carrying an inline quantifier, and it was a second declaration of the same fact that nothing ever adjudicated, free to disagree with the claims beneath it. One thing it could express that a signature marker cannot: a bound on a name with no signature slot at all, such as a fold's accumulator or a loop item. State that with a claim-level `let`: ```python "let total be [0, 1e6], for x in [0, 10], f(x) >= total" ``` ### Symbol coverage Every real parameter, plus every `for`/comprehension loop variable, is expected to appear literally somewhere in the docstring. This isn't mainly about readability; it's what feeds the derive route: a claim-level `let` declaring a bound for a fold's accumulator or item name gives the prover a sign/range assumption to work with that it otherwise has none of. An ordinary scratch local (a running total's starting value, an indexing-only loop counter) is exempt, only names whose *range* could plausibly matter to a proof are required. ```python def total(xs: list) -> float: """Sums a sequence. Claims: nonneg: for xs in [0, ...], f(xs) >= 0 """ t = 0.0 # ok: t is never checked for coverage for v in xs: # v is checked; it's a loop variable t += v return t ``` `xs` is annotated `list`, so its plain domain is the domain of each element. On an unannotated parameter the same binding is the domain of the value itself, so a parameter that takes a sequence is annotated as one. ## Checking a docstring against the schema <!-- example: ema repl --> ```python >>> import mathema >>> from mathema.docstring import parse_mathema_docstring >>> parsed = parse_mathema_docstring(ema) >>> parsed.score, parsed.applicable (2, 3) >>> parsed.conforms False >>> parsed.errors ["'v' used but not documented"] ``` `score`/`applicable` follow the same "N/M" pattern as `mathema.docstring_report()`; `conforms` requires a perfect score *and* zero structural `errors` (a `Claims:` header with nothing valid parsed underneath it, or an undocumented name, as here: a real authoring mistake, not just an incomplete docstring). `ema`'s own docstring never mentions `v`, the loop variable, anywhere in its text, so [symbol coverage](#symbol-coverage) genuinely fails for this example; that's the deliberate point, not an oversight. ## `docstring_sync()`: how well the docstring tracks the code `parse_mathema_docstring()` above checks the docstring's own internal shape, is `Intent:` there, does `Claims:` parse. It has no opinion on whether what's *declared* still matches the function it's attached to. `docstring_sync()` (`mathema.docstring.docstring_sync`) is the metric that does: it wraps `parse_mathema_docstring()` (as `.parsed`) and adds dimensions that compare the docstring against the function's actual structure; its branches, the exceptions it raises, its parameters and internal loop variables, the functions it calls, and (when one exists) its verified spec record. A docstring can satisfy every check above and still drift out of sync with the code as the code changes around it; this is the metric meant to catch that. <!-- example: ema repl --> ```python >>> from mathema.docstring import docstring_sync, docstring_sync_checklist >>> sync = docstring_sync(ema) >>> sync.score, sync.applicable (9, 11) >>> print("\n".join(docstring_sync_checklist(sync))) ✓ Intent: present ✓ intent concise (8 words) ✓ Claims: block in sync (names known, no surface conflicts) ✓ Claims: present (1 parsed) · claims {13 | 1 | -} floor | actual | expected (not scored) ✓ domain declared (1/1) ✗ domain enforced ✓ raises covered (1/1) ✗ symbol coverage (2/3) ✓ params typed (2/2) ✓ return typed docsync 90% (how much of what the function does is surfaced as context) ! 'v' used but not documented ``` What each dimension checks: | Dimension | Scored? | What it compares | |---|---|---| | Intent / Claims / symbol coverage | yes | same as `parse_mathema_docstring()`, folded in as-is | | claims <code>{floor | actual | expected}</code> | **no** | the floor is one claim per relevant claim family per target (`inventory.claim_floor()`), the actual is what the function carries, and the expected, how many a function of this shape typically carries; needs a corpus and reads `-`. Informational only, never subtracted from `score` | | domain declared / enforced | yes | declared: a bound exists (a signature `Annotated` marker, or the quantifier of a claim in the docstring's `Claims:`) for each real scalar/int parameter; enforced: the function is wrapped in `authoring.enforce_domain()`, checked at runtime, not just documented | | raises declared | yes | each exception the function's body can actually raise, covered by a `raises(f(x), ExcType)` claim, a prose `Raises:` mention, or a guard raise ENFORCING a declared domain (the declaration plus its own boundary check states the raise condition formally), counted once however many apply | | params / return typed | yes | every real parameter and the return value, each backed by *some* type information (an annotation, an `Annotated` marker, or a bound from a claim's quantifier) | | callees doc quality / docsync | yes | two points per direct callee: it documents itself (docstring plus a documented return), and its own layers are in sync (Claims: names known, record form fresh), a caller's docsync genuinely contains its callees' docsync, one hop deep and cycle-safe | `domain_enforced` is only applicable when at least one domain is declared in the first place (enforcing a domain nobody wrote down isn't meaningful); `ema` declares `alpha`'s domain via its `Annotated[float, Probability]` hint but never wraps itself in `enforce_domain()`, hence the `✗`. The "claims" line is deliberately never a checkmark; it's a hint, not a requirement. The floor is a real lower bound (a function carrying zero claims is always under it), but it is a floor and not a target: carrying more than it asks for is not an overrun, and there is nothing to divide by until a corpus can say what a function of this shape typically carries. Run this across a whole codebase with `mathema audit`: `docsync` is an ordinary analysis in the grid by default (`--exclude docsync` to skip it, like any analysis). The wide table adds one compact `docsync` column (`N/M`, from `docstring_sync()`); `mathema audit --docs` additionally prints a **second, separate table** underneath the loose `docs` checklist grid, not appended to the same row, since the two measure different things: <!-- example: ema run --> ```bash mathema audit ema --docs ``` <!-- example: ema output --> ```text quality: key || has_docstring | has_summary | params | returns | raises | quality_ratio | claims | concepts/tags ema.ema || yes | yes | 2/2 | no | 1/1 | 5/6 | 1 parsed | - 5/6 docstring quality criteria met (1 function). docsync: key || intent | notes | claims | {min_expected|actual|est_applicable} || domain_declared | enforced || raises_declared || params_typed | return_typed || callees_doc_quality | callees_docsync || sync_score ema.ema || yes | - | 1 parsed | {13 | 1 | -} || 1/1 | no || 1/1 || 2/2 | yes || - | - || 90% mean docsync 90% (how much of what each function does is surfaced as context) (1 function). ``` `domain_declared`/`enforced` sit together in one group, and `raises_declared` in its own single-column group, the `||` marks a group boundary, `|` a column boundary within one, same convention the loose `docs` table already uses. the claims column is `{min_expected|actual|est_applicable}`: the floor for `ema` is 13 (one claim per claim family relevant to a function of its shape), so its one parsed claim sits under it, and `expected` reads `-` until a corpus can say what a function of this shape typically carries. ## The docsync percentage One 0-100 number per function: how much of what the function actually does is surfaced as context a developer can read, intent at every level, domains, raise conditions, types, and the same for the immediate call surface. Deliberately NOT proveability: whether the claims themselves are enough is one dimension the score doesn't own. The claim floor stays a separate flag instead, the claims triplet cell renders red when the actual count sits under the floor and amber once it clears it, never green, since without a corpus nobody can say the count is *enough*. Weighted and renormalized over whichever componen - docs/matrix-structure.md (22252 bytes)
# Matrix structure and linear algebra A matrix parameter can carry more than a shape. Beyond *how many axes, how long* (see [Matrices, and named dimensions](conditional-claims.md)), mathema tracks a matrix's **structure**: symmetric, triangular, orthogonal, positive definite, finite. Structure is a claim kind in its own right, and it is also a type that narrows what a claim is checked over and what a linear-algebra identity may assume. The claim kinds form a hierarchy, cheapest first: | kind | example | cost | |---|---|---| | shape | `A ∈ ℝ^{n×n}` | axis bookkeeping | | element-wise | `is_finite(A)` | O(n²) direct | | structural | `A == A.T` | O(n²) direct | | spectral | `is_positive_definite(A)` | O(n³) eigen / Cholesky | | algebra | `det(A @ B) == det(A) * det(B)` | symbolic | ## Declaring structure A structure is a marker in the parameter's type, alongside its shape. The canonical spelling is an `Annotated` hint; `Mat(...)` is the sugar that produces an equivalent annotation: ```python from typing import Annotated from mathema.types import Mat, Shape, Symmetric, PositiveDefinite # canonical def f(A: Annotated[list, Shape("n", "n"), Symmetric]): ... # sugar (equivalent annotation) def g(A: Mat("n", "n", Symmetric)): ... ``` The markers, by level: `Real`, `Finite` (element-wise); `Symmetric`, `SkewSymmetric`, `Diagonal`, `UpperTriangular`, `LowerTriangular`, `Identity` (structural); `Orthogonal`, `PositiveDefinite`, `PositiveSemidefinite` (spectral). Each maps to a registry predicate (`Symmetric` to `is_symmetric`, and so on). A matrix parameter is drawn as nested lists unless its signature names another runtime type: `A: np.ndarray`, or `Mat("n", "n", runtime="numpy.ndarray")` beside the structure markers, samples it as a 2-D array, so `def transpose(A: np.ndarray): return A.T` holds `for A in R^(n,n), f(f(A)) == A` where a list of lists would raise at `.T`. Nested lists are drawn up to 64 per axis. See [runtime types](runtime-types.md). A declared structure is **entailment-closed**: `PositiveDefinite` also asserts `is_symmetric` (and everything symmetry implies), because a positive-definite matrix is symmetric. Declaring the specific property narrows the domain to everything it entails. ## Structure claims A structure predicate is a claim about a matrix VALUE. The canonical form is the predicate call; the postfix `is` reading is sugar for it: ``` is_symmetric(A) # a precondition on the argument is_symmetric(f(A)) # the output is symmetric A is symmetric # postfix, folds to is_symmetric(A) f(A) is symmetric # postfix on an output, folds to is_symmetric(f(A)) f(A) is positive definite # a multi-word predicate reads the same way ``` On a bare parameter (`is_symmetric(A)`) the claim asks whether the function GUARDS the property: does it reject an argument that lacks it, the value analogue of an out-of-domain rejection. On an expression (`is_symmetric(f(A))`, `is_symmetric(A @ B)`) it checks the resulting value. Both adjudicate on the `examine` route: a structural check on synthesised or real values, numpy-fast where numpy is present and a pure-Python fallback otherwise. A spectral check with no numpy declines (`skipped`) rather than guessing. `is_finite(A)` is the matrix-scale sibling of the missing-value axis: it narrows a domain away from `nan`/`inf`, fast via numpy. On an expression (`is_finite(f(x))`) the check reads the claim's `assuming` clause like every other claim, and a raise from `f` at a point inside it falsifies the claim, naming the exception. Both `is_finite` and `is_real` also read a result that is a single number, and they read every value the same way with or without numpy installed. A number is an int, a bool, a float, a complex, a Fraction or a Decimal. It is finite when it is neither an infinity nor a NaN (a complex number when both its parts are), and a bool or a Fraction is always finite. `is_real` reads the value, not its type: a complex number with a zero imaginary part, such as `1 + 0j`, is real, and a vector or matrix is real when every entry is. An empty vector or matrix is finite and real, since no entry is otherwise. A result that is not a number, nor a vector or matrix of numbers (None, a string, a ragged list, a list holding None), leaves the claim unknown with "the result is not a number" and the point that returned it, unless another point falsifies the claim. ## Narrowing the domain A structure marker, or an `assuming` premise, narrows the matrices a claim is sampled over. Under ``` assuming A is positive definite, f(A) == f(A.T) ``` the sampler synthesises `A` by construction as a positive-definite matrix (entailment-closed, so it is symmetric too), because a random matrix is almost never positive definite and rejection alone would never find one. The same premise becomes a sympy assumption on the derive route (below), so the two halves, sampling and proof, read one declaration the same way. ## The linear-algebra grammar The operation vocabulary is Python-flavoured, what a NumPy user writes: ``` A @ B matrix product A.T transpose det(A) determinant inv(A) inverse trace(A) trace I(n) the n-by-n identity x.T @ A @ x a quadratic form ``` ### What each operator means The operators read the way numpy reads them, whatever the function's own runtime type: a list-of-lists matrix is evaluated as an array, so `x + y` never concatenates two lists. | spelling | on vectors and matrices | |---|---| | `A @ B` | the matrix product; two vectors give their dot product | | `A * B` | elementwise (the Hadamard product); `c * A` scales | | `A ** k` | elementwise power; the matrix power is `matrix_power(A, k)` | | `A + B`, `A - B`, `-A` | elementwise; `A + c` shifts every element | | `abs(A)` | elementwise absolute value | | <code>|A|</code> | the determinant of a declared matrix (sugar, below) | | `norm(x)`, <code>||x||</code> | Euclidean on a vector, Frobenius on a matrix | | `norm(A, 2)`, `norm(A, 1)`, `norm(A, inf)` | spectral, largest column sum, largest row sum | | <code>||A||_2</code>, <code>||A||_1</code>, <code>||A||_inf</code> | the same orders with double bars, the order a subscript | | `A ~= B` | element by element, with the scalar tolerance | An ordering between a matrix or vector the claim writes and anything (`A >= 0`, `A * A >= 0`) is not defined, and the claim is refused as misspecified with the reason; compare a number drawn from it instead (`det`, `trace`, `norm`, an element). A value the function returned is read element by element: `f(A) >= 0` holds when it holds at every element, and does not hold over an empty result. An elementwise reading of a written matrix, spelled `all(...)`, is future work. The scalar derive route never reads a vector or matrix as a number: a claim that uses one as a value goes to the matrix algebra below or, when that cannot close it, to sampling. <!-- example: semantics run requires=numpy --> ```python from mathema.types import Mat, Vec def two(A: Mat("n", "n"), B: Mat("n", "n")): return A def vecs(x: Vec("n"), y: Vec("n")): return x ``` <!-- example: semantics verdicts fn=two --> ``` A * B == B * A # proven A @ B == B @ A # falsified A ** 2 == A * A # proven matrix_power(A, 2) == A @ A # proven matrix_power(A, 2) == A * A # falsified ``` <!-- example: semantics verdicts fn=vecs --> ``` norm(x + y) <= norm(x) + norm(y) # holds ‖x + y‖ ≤ ‖x‖ + ‖y‖ # holds norm(x + y)**2 == norm(x)**2 + norm(y)**2 # falsified ||x + y||^2 == ||x||^2 + ||y||^2 + 2*dot(x, y) # proven ||x||_inf <= ||x||_2 <= ||x||_1 # holds ``` ### The vocabulary Beyond `det`, `inv`, `trace`, `transpose` and `I(n)`: | word | meaning | |---|---| | `dot(x, y)`, `outer(x, y)`, `kron(A, B)` | inner, outer and Kronecker products | | `diag(A)`, `diag(v)` | the diagonal of a matrix; the diagonal matrix of a vector | | `rank(A)`, `cond(A)` | numerical rank; the 2-norm condition number | | `eigvals(A)`, `eigvalsh(A)` | eigenvalues (complex in general); of a symmetric matrix, real and ascending | | `solve(A, b)`, `pinv(A)` | the solution of `A @ x == b`; the pseudo-inverse | | `A[i, :]`, `A[:, j]` | a row, a column | | `sum(A, axis=0)`, `mean(A, axis=1)` | reductions along an axis (also `prod`, `min`, `max`) | | `x.T @ A @ x` | a quadratic form over a vector `x`, a number | A decomposition is a claim about its factors, with the numpy function bound by `let`: `let q = numpy.linalg.qr, q(A)[0] @ q(A)[1] ~= A`. A vector of the claim's own is declared with `let b be R^n`, and takes the size the parameters give `n`. In a premise, `x != 0` over a vector says it is not the zero vector, and a claim's own `x != 0` compares different shapes and holds. A premise that pins the whole of it to a value, `x == 0`, is not read yet, and the claim is `unknown`. <!-- example: vocabulary run requires=numpy --> ```python from mathema.types import Mat, Vec def one(A: Mat("n", "n")): return A def form(A: Mat("n", "n"), x: Vec("n")): return A ``` <!-- example: vocabulary verdicts fn=one --> ``` trace(A) ~= sum(eigvals(A)) # proven det(A) ~= prod(eigvals(A)) # proven trace(A) ~= prod(eigvals(A)) # falsified let b be R^n, assuming det(A) != 0, A @ solve(A, b) ~= b # proven A @ pinv(A) @ A ~= A # holds sum(A, axis=0) ~= sum(A.T, axis=1) # holds let q = numpy.linalg.qr, q(A)[0] @ q(A)[1] ~= A # holds let q = numpy.linalg.qr, q(A)[1] @ q(A)[0] ~= A # falsified ``` <!-- example: vocabulary verdicts fn=form --> ``` assuming A is positive definite and x != 0, x.T @ A @ x > 0 # holds assuming A is symmetric and x != 0, x.T @ A @ x > 0 # falsified ``` A structure premise and a relation premise combine with `and`: `assuming A is symmetric and det(A) != 0, inv(A) ~= inv(A).T`. The identity and skew-symmetric premises reach the derive route as exact rewrites (`A` is `I(n)`; `A.T` is `-A`), since sympy has no assumption for them; positive semidefiniteness has none either, so it narrows sampling only. ### Real matrices only Matrices and vectors are real in this release: a claim over `C^n` or `C^(m,n)` is refused as misspecified, with the reason "matrices and vectors are real-only in this release". Complex scalars are unaffected. A function may still return a vector or matrix of complex numbers, and that result is a value, read as a complex array with or without numpy. `is_finite` and `is_real` decide it by value, entry by entry, as they do a complex scalar. The structural properties (symmetric, triangular, diagonal, orthogonal, positive definite and the rest) are read over real matrices only, so on a complex result they leave the claim unknown with the reason "the result is a complex matrix, and is_symmetric is read over real matrices only in this release". With numpy installed, a real claim over `R^n` or `R^(m,n)` whose function returns a complex vector or matrix reads it as it reads a complex scalar: no real value there. ### Sugar Three math-paper spellings are accepted as sugar. Each is **ambiguous** against a scalar reading, so mathema resolves it from the operand's declared type: on a matrix it is the matrix operation, on a scalar the ordinary one. | sugar | on a matrix | on a scalar | |---|---|---| | `A^T` | `A.T` (transpose) | `A ** T` (power) | | <code>|A|</code> | `det(A)` | `abs(A)` | | `A^-1` | `inv(A)` | `1 / A` (reciprocal) | The type is known from a signature marker, an `R^(m,n)` domain, or a `let ... be R^(m,n)` declaration: ``` let A be R^(n,n), A^T == A # -> A.T == A for A in R^(n,n), |A| >= 0 # -> det(A) >= 0 ``` The bars are the determinant only as written: an explicit `abs(A)` is always elementwise, and a rendered claim keeps the `abs(...)` spelling for a matrix. Because the reading is per-operand, one expression can mix the two: with `A` a matrix and `c` a scalar, `inv(c * A) == c^-1 * A^-1` reads `c^-1` as a reciprocal and `A^-1` as an inverse, and the record writes it `inv(A*c) = inv(A)/c`. When a claim uses the matrix vocabulary, the record's `grammar` field is stamped `mathema/linalg`. This is informative only, a note that the parsing was matrix-aware; it is never required to round-trip, because the canonical statement (`det(A @ B) == det(A) * det(B)`) re-parses under the base grammar on its own. ## Proving identities and inequalities A matrix-algebra relation is an identity of the algebra, not a fact about a function's body. mathema lifts the claim's own expressions to `sympy.MatrixSymbol` terms, turns structure markers and premises into sympy assumptions (`Q.symmetric`, `Q.positive_definite`, ...), and decides the relation. Equalities are decided by simplifying the difference to zero; scalar comparisons of a determinant or trace are decided by sympy's assumption engine. The identities below are checked against a function of two square matrices of a shared dimension: <!-- example: identities run --> ```python from mathema.types import Mat def f(A: Mat("n", "n"), B: Mat("n", "n")): return A ``` <!-- example: identities verdicts fn=f --> ``` det(A @ B) == det(A) * det(B) # proven (A @ B).T == B.T @ A.T # proven trace(A + B) == trace(A) + trace(B) # proven assuming A is symmetric, A.T == A # proven assuming A is orthogonal, A.T @ A == I(n) # proven assuming A is positive definite, det(A) > 0 # proven assuming A is positive definite, trace(A) > 0 # proven ``` A relation sympy cannot close falls to the matrix-value probe: concrete matrices are sampled (structure-narrowed, as above), both sides evaluated, and the claim either holds across the draws or is falsified with the witnessing matrices. A strict `derive` route reports the honest `unknown` instead of sampling. ### Facts proven for every size sympy's matrix algebra does not apply every fact of real matrices on its own, so mathema adds a layer of lemmas, each true of real square matrices of any size, before the two sides are compared: | lemma | example | |---|---| | trace cyclicity (cyclic rotations of a product only) | `trace(A @ B @ C) == trace(C @ A @ B)` | | trace of a transpose | `trace(A @ B.T) == trace(B @ A.T)` | | linearity of trace | `trace(c*A + B) == c*trace(A) + trace(B)` | | `@` distributes over `+`, on both sides | `(A + B) @ C == A @ C + B @ C` | | scaling through a product | `(c*A) @ B == c*(A @ B)` | | transpose of a sum and of a product | `(A @ B).T == B.T @ A.T` | | a Gram product `A @ A.T` or `A.T @ A` is positive semidefinite | `det(A @ A.T) >= 0` | | the trace is the sum of the eigenvalues, the determinant their product | `det(A) == prod(eigvals(A))` | | the determinant of a scaled matrix | `det(c*A) == c**n * det(A)` | | the rank of a Gram product is the rank of its factor | `rank(A @ A.T) == rank(A)` | A proof that used one names it in its sketch and in the record's `mathema.matrix_lemmas` meta. Each lemma - docs/mean-of-nothing.md (9800 bytes)
# The mean of nothing A one-line function, the kind every analytics codebase has, and a question its tests never ask: what does it do when there is nothing to average? This page follows mathema from the first claim to the fix, showing the record at each step. <!-- example: mean file=returns.py --> ```python import pandas as pd def mean_return(xs: pd.Series) -> float: """The mean of a series of returns.""" return float(xs.mean()) ``` The series it will meet, slot by slot: <!-- illustration --> ```text [0.02, NaN, -0.01] slot 1 is a hole (member nan): pandas skips it, mean 0.005 [NaN, None] every slot a hole (members nan, null): pandas gives NaN [<NA>] every slot a hole (member NA): xs.mean() is pd.NA [] no slots at all: empty, not missing ``` ## The claim, and what pandas promised A mean of returns in `[-1, 1]` lies in `[-1, 1]`: <!-- example: mean run requires=pandas --> ```python import mathema from returns import mean_return value = mathema.claim("for xs in [-1, 1]^n, -1 <= f(xs) <= 1", name="bounded") print(mathema.check(mean_return, claims=[value])) ``` <!-- example: mean output --> ```text mathema.Record(mean_return) · source, no side effects · form py:b38d4613a6c4 bounded for xs in ([-1.0, 1.0] | {missing})^n : float, -1 <= f(xs) <= 1 falsified at xs = [] holds computation for xs in ([-1.0, 1.0])^n : float, -1 <= f(xs) <= 1 445 entries across 99 draws, sizes (1, 1) to (8, 1) falsified policy f([]) f(xs) returns nan at xs = []: no value for no data, and no empty policy is stated possible fixes: (i) if nan for no data is intended, state: mean_return([]) in {missing} (ii) guard the empty input at entry proven policy f([..., missing, ...]) assuming count(xs) >= 1 drops, from pandas.Series.mean's own policy row, which f calls falsified policy f([..., missing, ...]) assuming count(xs) == 0 f([NA]) raises TypeError; f([0.0]) returns 0.0 possible fixes: (i) exclude missing (ii) handle missing at entry ``` Read it from the top. The headline is the claim as mathema resolved it: a float slot may be missing, so `[-1, 1]^n` became `([-1.0, 1.0] | {missing})^n`. The `computation` line holds on every series of values it ran: a mean of numbers in `[-1, 1]` stays there. The `f([])` line is the empty series: its mean is `nan`, which counts as no value until a policy for the empty input is stated, and that is the headline's witness (the last section returns to it). The other two `policy` lines say what `mean_return` does with a slot that is not there. A pandas Series slot can be `nan`, `null` (a `None` element) or `NA`, and mathema put each one in. `mean_return` makes one library call, and pandas' own policy rows (bundled with mathema) say what `Series.mean` does: it drops holes while values remain, and gives a hole back when none do. Each line names its case after `assuming`. The first, a series with a value left (`count(xs) >= 1`), is that first row, proven. The second, a series with none (`count(xs) == 0`), is the second row, and it is falsified: at `xs = [NA]`, a series whose only slot is pandas' `NA`, `xs.mean()` is `pd.NA` and `float(pd.NA)` raises `TypeError`, where pandas' row says a hole comes back. ## The gate: is it missing-safe? `is_missing_safe(f)` asks whether every missing member has a policy the code follows: <!-- example: mean run --> ```python print(mathema.check(mean_return, claims=[value, mathema.claim("is_missing_safe(f)")])) ``` <!-- example: mean output --> ```text mathema.Record(mean_return) · source, no side effects · form py:b38d4613a6c4 bounded for xs in ([-1.0, 1.0] | {missing})^n : float, -1 <= f(xs) <= 1 falsified at xs = [] holds computation for xs in ([-1.0, 1.0])^n : float, -1 <= f(xs) <= 1 445 entries across 99 draws, sizes (1, 1) to (8, 1) falsified policy f([]) f(xs) returns nan at xs = []: no value for no data, and no empty policy is stated possible fixes: (i) if nan for no data is intended, state: mean_return([]) in {missing} (ii) guard the empty input at entry proven policy f([..., missing, ...]) assuming count(xs) >= 1 drops, from pandas.Series.mean's own policy row, which f calls falsified policy f([..., missing, ...]) assuming count(xs) == 0 f([NA]) raises TypeError; f([0.0]) returns 0.0 possible fixes: (i) exclude missing (ii) handle missing at entry falsified is_missing_safe[f]: is_missing_safe(f) xs (pandas.Series): nan and null follow pandas.Series.mean's own policy row (drops when values remain, propagates when every slot is missing); NA does not: f raises TypeError when every slot is NA counterexample f([NA]) raises TypeError; f([0.0]) returns 0.0 (i) if the raise is intended, state: assuming count(xs) == 0, missing(f, xs, NA) raises(TypeError) (ii) if not, change f ``` The value claim's block repeats above it, since the gate is checked beside it. `nan` and `null` follow pandas' rows. `NA` does not, and no claim says it may raise, so the gate is falsified with the call that shows it beside the call that runs, and with the claim that would state the raise if it is what you meant. ## And with no slots at all? An empty series has no slots, so no holes; it is a question of its own, `is_empty_safe(xs)`, and mathema builds the empty value as the parameter's own runtime type, an empty float Series: <!-- example: mean run --> ```python print(mathema.check(mean_return, claims=[value, mathema.claim("is_empty_safe(xs)")])) ``` <!-- example: mean output --> ```text mathema.Record(mean_return) · source, no side effects · form py:b38d4613a6c4 bounded for xs in ([-1.0, 1.0] | {missing})^n : float, -1 <= f(xs) <= 1 falsified at xs = [] holds computation for xs in ([-1.0, 1.0])^n : float, -1 <= f(xs) <= 1 445 entries across 99 draws, sizes (1, 1) to (8, 1) falsified policy f([]) f(xs) returns nan at xs = []: no value for no data, and no empty policy is stated possible fixes: (i) if nan for no data is intended, state: mean_return([]) in {missing} (ii) guard the empty input at entry proven policy f([..., missing, ...]) assuming count(xs) >= 1 drops, from pandas.Series.mean's own policy row, which f calls falsified policy f([..., missing, ...]) assuming count(xs) == 0 f([NA]) raises TypeError; f([0.0]) returns 0.0 possible fixes: (i) exclude missing (ii) handle missing at entry falsified is_empty_safe[xs]: is_empty_safe(xs) counterexample xs = [] (an empty float Series): f returned nan for the empty input; raise, or return a value ``` The mean of nothing is `nan` in pandas, as in numpy; `statistics.mean` raises, and polars gives `None`. A `nan` handed back for the empty input looks like a number to the caller and poisons whatever it touches next. ## The fix The function has no mean to give when no value is there, so it says so, once, for the empty series and the all-missing one alike: <!-- example: mean file=returns_fixed.py --> ```python import pandas as pd def mean_return(xs: pd.Series) -> float: """The mean of a series of returns.""" if xs.count() == 0: raise ValueError("no returns to average") return float(xs.mean()) ``` That raise is a choice, so it is stated as the policy for the calls with no value slot, beside the row pandas already gives for the rest: <!-- example: mean run --> ```python import returns_fixed print(mathema.check(returns_fixed.mean_return, claims=[ value, mathema.claim("assuming count(xs) == 0, missing(f, xs) raises(ValueError)", name="no_values"), mathema.claim("is_missing_safe(f)"), mathema.claim("is_empty_safe(xs)"), ])) ``` <!-- example: mean output --> ```text mathema.Record(mean_return) · source, no side effects · form py:8f26488fb001 bounded for xs in ([-1.0, 1.0] | {missing})^n : float, -1 <= f(xs) <= 1 holds holds computation for xs in ([-1.0, 1.0])^n : float, -1 <= f(xs) <= 1 531 entries across 124 draws, sizes (1, 1) to (8, 1) holds policy f([]) proven policy f([..., missing, ...]) assuming count(xs) >= 1 drops, from pandas.Series.mean's own policy row, which f calls proven is_empty_safe[xs]: is_empty_safe(xs) holds no_values: assuming count(xs) == 0, missing(f, xs) raises(ValueError) [stated; confirmed on the 124 draws of bounded] proven is_missing_safe[f]: is_missing_safe(f) xs (pandas.Series): nan, null and NA drop when values remain, from pandas.Series.mean's own policy row; raises ValueError when every slot is missing, stated ``` Every member now has a policy the code follows, from pandas' row where values remain and from the stated one where none do, so the gate is proven; the empty series meets the guard, a deliberate rejection, so `is_empty_safe` is proven too. The value claim holds, and its headline with it: the policy lines under it are the empty series, which meets the guard, and pandas' row for a series with values in it, and the stated `no_values` covers the rest. See [missing values](missing-values.md) for the two kinds, the five behaviours and the policy rows in general. - docs/missing-values.md (33859 bytes)
# Missing values Data arrives with gaps. A price feed skips a tick, a form leaves a field empty, a join finds no match. Python code meets those gaps as `None` and `nan`, and it usually treats them in one of a few ways without anyone deciding it should. This page shows how mathema reads a value that is not there, what a function can do with one, and how you write down what yours does, so the claims about the numbers a function computes and the claims about its gaps stay apart. Every output on the page is what the code beside it prints. ## Two kinds of no value Where the `None` sits decides what it means. <!-- illustration --> ```text price = None absent: the argument itself is not there prices = [0.2, None, 0.7] a list with three slots: slot 0 value 0.2 slot 1 hole, member null slot 2 value 0.7 prices = [0.2, nan, 0.7] slot 1 is a hole, member nan price = nan a hole: a float's own missing value ``` - **absent**: the object is not there. An argument, a field of a record, a whole list. Python spells it `None`. - **missing**: a slot holds no computable value. A `nan` in a float, a `None` element of a list, a `pd.NA` or `NaT` in a pandas Series, a polars `null`. A missing value is called a **hole**, and each spelling is a **member** of the hole class: `nan`, `null`, `NA`, `NaT`. A scalar argument has no slot inside it, so a scalar `None` is always absent, while `nan` is always a hole. Here is what Python does with each: <!-- example: kinds file=prices.py --> ```python import math def volatility(variance: float) -> float: """The standard deviation for a variance.""" return math.sqrt(variance) def total_exposure(positions: list) -> float: """The sum of every position.""" return sum(positions) ``` <!-- example: kinds run --> ```python from prices import total_exposure, volatility def outcome(expr): try: return repr(eval(expr)) except Exception as exc: return type(exc).__name__ for expr in ['volatility(None)', 'volatility(float("nan"))', 'total_exposure([0.2, None, 0.7])', 'total_exposure([0.2, float("nan")])', 'total_exposure(None)']: print(f"{expr:36} {outcome(expr)}") ``` <!-- example: kinds output --> ```text volatility(None) TypeError volatility(float("nan")) nan total_exposure([0.2, None, 0.7]) TypeError total_exposure([0.2, float("nan")]) nan total_exposure(None) TypeError ``` The first and last calls pass `None` where an object belongs: absent. The second passes a hole to a scalar, the third a list with a `null` hole in slot 1, the fourth a list with a `nan` hole. A claim states what its domain admits, completed from the annotation. A `float` may be `nan`, so a claim over one admits it and mathema calls the function there; an `Optional[float]` may also be absent; an `int` has no hole. You write the short form, and the record shows what it resolved to: <!-- example: admits file=admits.py --> ```python from typing import Optional def volatility(variance: float) -> float: return variance ** 0.5 def fee(amount: Optional[float]) -> float: return 0.01 * amount def lot_count(shares: int) -> int: return shares // 100 def exposure(positions: list) -> float: return sum(positions) ``` <!-- example: admits run --> ```python import mathema from admits import exposure, fee, lot_count, volatility def statement(fn, text): rec = mathema.check(fn, claims=[mathema.claim(text, name="c")]) return next(p.statement for p in rec.probes if p.name == "c") print(statement(volatility, "for variance in [0, 1], f(variance) >= 0")) print(statement(fee, "for amount in [0, 100], f(amount) <= 1")) print(statement(lot_count, "for shares in [0, 1000] subset Z, f(shares) >= 0")) print(statement(volatility, "for variance in [0, 1] \\ {missing}, f(variance) >= 0")) print(statement(exposure, "for positions in [0, 1]^n, f(positions) >= 0")) ``` <!-- example: admits output --> ```text for variance in [0.0, 1.0] : float|missing, f(variance) >= 0 for amount in [0.0, 100.0] : float|absent|missing, f(amount) <= 1 for shares in [0, 1000] : int, f(shares) >= 0 for variance in [0.0, 1.0] : float, f(variance) >= 0 for positions in ([0.0, 1.0] | {missing})^n : float, f(positions) >= 0 ``` `: float|missing` says the claim admits a float's hole; `\ {missing}` removes it, and the rendering keeps the exclusion because it says something the type does not. Inside the brackets of `(... | {missing})^n` the clause is about the slots of the vector. ## Five behaviours Given a hole or an absence, a function does one of five things. Each is defined by counting the missing and absent values in and out, so running the function decides which: | word | the output holds | |---|---| | `raises` | nothing: the call raises | | `drops` | no missing or absent value | | `propagates` | as many as the input, of the same kind | | `converts` | as many, of the other kind (a hole in, `None` out) | | `introduces` | any other count, including one from inputs that were all there | The ones that cause trouble are the quiet ones. Each of these returns an answer as if nothing had happened: <!-- example: traps run --> ```python from typing import Optional def clamp_discount(rate: float) -> float: """A discount rate held to [0, 1].""" return max(0.0, min(1.0, rate)) def risk_label(score: Optional[float]) -> str: """"high" above one half, else "low".""" return "high" if score > 0.5 else "low" def fee_rate(tier: int) -> Optional[float]: """The fee for a customer tier, None for a tier with no fee schedule.""" return {1: 0.05, 2: 0.07}.get(tier) print(clamp_discount(float("nan"))) # min(1.0, nan) is 1.0 print(risk_label(float("nan"))) # nan > 0.5 is False print(fee_rate(3)) # dict.get: None for a tier that exists ``` <!-- example: traps output --> ```text 1.0 low None ``` `clamp_discount` turns a missing rate into a full discount, and `risk_label` turns a missing score into `"low"`: both **drop** the hole by an accident of comparison. `fee_rate` **introduces** an absence from an input that was there. ## A value claim is judged on values A claim such as "`clamp_discount(rate)` stays in `[0, 1]`" is about the numbers the function computes. It is judged wherever the function returns a value, including the value it returns for a dropped hole, and never where the function returns no value or raises at a missing input. That call is sorted into one of the five behaviours instead, and the record says what happened there. A `nan` from inputs that were all there still fails a value claim: the mathematics has a value at that point, and the code gave none. ## One function at a time The functions below come from one file of pricing code: <!-- example: core file=pricing.py --> ```python import math from typing import Optional def volatility(variance: float) -> float: """The standard deviation for a variance.""" return math.sqrt(variance) def risk_label(score: Optional[float]) -> str: """"high" above one half, else "low".""" return "high" if score > 0.5 else "low" def clamp_discount(rate: float) -> float: """A discount rate held to [0, 1].""" return max(0.0, min(1.0, rate)) def log_return(ratio: float) -> float: """The log of a price ratio; a missing ratio is refused.""" if ratio != ratio: raise ValueError("ratio is missing") return math.log(ratio) def in_base_currency(amount: float, fx_rate: Optional[float] = None) -> float: """An amount converted at fx_rate; no rate means it is already in base.""" if fx_rate is None: fx_rate = 1.0 return amount * fx_rate def fee_rate(tier: int) -> Optional[float]: """The fee for a customer tier, None for a tier with no fee schedule.""" return {1: 0.05, 2: 0.07}.get(tier) ``` ### The silent drop Start with the failure. The claim is that a clamped rate lies in `[0, 1]`: <!-- example: core run --> ```python import mathema from pricing import clamp_discount print(mathema.check(clamp_discount, claims=[mathema.claim( "for rate in R, 0 <= clamp_discount(rate) <= 1", name="in_unit")])) ``` <!-- example: core output --> ```text mathema.Record(clamp_discount) · source, no side effects · form py:553f54a358ec in_unit for rate in R|missing, 0 <= clamp_discount(rate) <= 1 falsified at f(nan) proven mathematics for rate in R, 0 <= clamp_discount(rate) <= 1 holds computation for rate in R, 0 <= clamp_discount(rate) <= 1 43 draws falsified policy f(nan) f(nan) returns 1.0 no missing policy stated possible fixes: (i) if dropping nan is intended, run: mathema accept pricing.clamp_discount missing[rate] --as discovery --corrected "missing(f, rate) drops" (ii) exclude nan (iii) handle nan at entry ``` Read it from the top. The headline is the claim as mathema resolved it, `rate in R|missing` (a float may be `nan`), and its verdict. Under it, the `mathematics` line is the claim over the real numbers, proven; the `computation` line runs the real code in float64, and holds. The last line is a **policy line**: what `clamp_discount` does with a missing `rate`. No policy was stated, so mathema assumed the default for a float, that a hole comes back as a hole, and the code does something else: at `rate = nan` it returned `1.0`. That falsifies the headline, and the line under it lists the ways forward. If a full discount is what a missing rate should mean, state it: `missing(f, rate) drops`. If not, take `nan` out of the claim (`for rate in R \ {missing}`), or handle it at entry, giving the hole back (`if rate != rate: return rate`) or raising. ### Two bugs in one line <!-- example: core run --> ```python from pricing import risk_label print(mathema.check(risk_label, claims=[mathema.claim( 'for score in [0, 1], risk_label(score) in {"high", "low"}', name="labels")])) ``` <!-- example: core output --> ```text mathema.Record(risk_label) · source, no side effects · form py:3ae935da0351 labels for score in [0.0, 1.0] : float|absent|missing, risk_label(score) in {"high", "low"} falsified at f(nan) holds computation for score in [0.0, 1.0] : float, risk_label(score) in {"high", "low"} 34 draws falsified policy f(nan) f(nan) returns "low" no missing policy stated possible fixes: (i) if dropping nan is intended, run: mathema accept pricing.risk_label missing[score] --as discovery --corrected "missing(f, score) drops" (ii) exclude nan (iii) handle nan at entry falsified policy f(None) f(None) raises TypeError; f(0.959) returns "high" no absent policy stated possible fixes: (i) if the raise is intended, run: mathema accept pricing.risk_label absent[score] --as discovery --corrected "absent(f, score) raises(TypeError)" (ii) exclude None (iii) handle None at entry ``` The mathematics holds: every label is `"high"` or `"low"`. The two policy lines carry what it does not say, and both falsify the headline. A missing score becomes `"low"`, the same silent drop as above. And `Optional[float]` promises to take `None`, which the function cannot: `None > 0.5` raises. No claim says it may; if the raise is what you meant, state `absent(f, score) raises(TypeError)`. ### The code already says it A float that propagates through a library call, a guard, and `None` used as a flag each settle their own policy line: <!-- example: core run --> ```python from pricing import in_base_currency, log_return, volatility print(mathema.check(volatility, claims=[mathema.claim( "for variance in [0, 1], volatility(variance) >= 0", name="nonneg")])) print(mathema.check(log_return, claims=[mathema.claim( "for ratio in [0.5, 2], log_return(ratio) <= 1", name="bounded")])) print(mathema.check(in_base_currency, claims=[mathema.claim( "for amount in [0, 100], fx_rate in [0.5, 2], " "in_base_currency(amount, fx_rate) == amount * fx_rate", name="scales")])) ``` <!-- example: core output --> ```text mathema.Record(volatility) · source, no side effects · form py:c83d5a183be8 nonneg for variance in [0.0, 1.0] : float|missing, volatility(variance) >= 0 holds proven mathematics for variance in [0.0, 1.0] ⊂ ℝ, volatility(variance) >= 0 holds computation for variance in [0.0, 1.0] : float, volatility(variance) >= 0 43 draws proven policy f(nan) propagates, from math.sqrt's own policy row, which f calls mathema.Record(log_return) · source, no side effects · form py:409809bffd47 bounded for ratio in [0.5, 2.0] : float|missing, log_return(ratio) <= 1 holds proven mathematics for ratio in [0.5, 2.0] ⊂ ℝ, log_return(ratio) <= 1 holds computation for ratio in [0.5, 2.0] : float, log_return(ratio) <= 1 42 draws proven policy f(nan) raises(ValueError), from the guard on line 3 mathema.Record(in_base_currency) · source, no side effects · form py:dc28f008d9b6 scales for amount in [0.0, 100.0] : float|missing, fx_rate in [0.5, 2.0] : float|absent|missing, in_base_currency(amount, fx_rate) = amount*fx_rate holds holds computation for amount in [0.0, 100.0] : float, fx_rate in [0.5, 2.0] : float, in_base_currency(amount, fx_rate) = amount*fx_rate 161 draws; differs by 1.34e-14 at amount = 89.64787909445818, fx_rate = 1.5085973865860938, within the default tolerance (1.35e-05) holds policy f(amount=nan) no missing policy stated; assumed propagates holds policy f(fx_rate=nan) no missing policy stated; assumed propagates proven policy f(fx_rate=None) drops, from the guard on line 3 ``` `volatility` makes one call, to `math.sqrt`, and `math.sqrt` has its own policy row in the bundled compendium: the hole comes back. The policy line comes from it, proven. `log_return` raises on a missing ratio behind a guard, so the row comes from the guard. `in_base_currency` replaces an absent `fx_rate` with `1.0`, a drop, read from the same kind of guard. ### An absence the return type declares <!-- example: core run --> ```python from pricing import fee_rate print(mathema.check(fee_rate, claims=[mathema.claim( "for tier in [0, 3] subset Z, fee_rate(tier) < 1", name="below_one")])) ``` <!-- example: core output --> ```text mathema.Record(fee_rate) · source, no side effects · form py:f3dc7f1f8d03 below_one - docs/modes/accept.md (25345 bytes)
# `mathema accept` The human decision verb: annotate adjudicated claims of one function with an explicit acceptance. Prompted; the exact write is printed first and nothing happens without a yes. Deliberately CLI-only: acceptance is a human act, never exposed to agent tooling or any MCP surface. ```bash mathema accept KEY CLAIM [CLAIM ...] --as evidence|risk|discovery [--by NAME] [--note TEXT] mathema accept KEY --as reconciled [--from OLD_KEY] mathema accept KEY CLAIM [CLAIM ...] --transition [--by NAME] [--note TEXT] ``` Three acceptances cover the everyday loop (`evidence`, `risk`, `discovery`). Four more handle record housekeeping, each with its own section below: `historical` and `superseded` retire a claim with its history intact, `reconciled` restamps a record after a merge or rebase, and `trusted` records testimony from a source you vouch for. `--intent` and `--concepts` accept the function's stated intent and concept tags, and `--transition` acknowledges a claim's move since an earlier run. ## Arguments | Flag | Meaning | |---|---| | `key` | function key (the record under `.mathema/verified/`) | | `claim` | one or more claim names inside that record, accepted together under one prompt (omit for `--as reconciled`, which acts on the whole record). `--corrected` and `--format json` take one claim | | `--as` | `evidence`, `risk`, `discovery`, `historical`, `superseded`, `trusted`, or `reconciled` (see below). In text mode you can omit it and mathema reads the claim's verdict and proposes the natural kind; `--format json` never guesses, and without `--as` it exits 2 | | `--all` | with `--as reconciled` and no key: reconcile every record whose checksum no longer matches, in one act | | `--from OLD_KEY` | with `--as reconciled`: rename `OLD_KEY`'s record to `KEY`, for a function that moved (see [moved functions](#moved-functions-as-reconciled-from)) | | `--accept-form-change` | with `--from`: rename even though the record's form hash differs from the live function's | | `--transition` | acknowledge the open transitions on the named claims (a claim that regressed, weakened, strengthened or was fixed since an earlier run): the gate stops acting on them, and the record keeps who acknowledged each and when. Takes no `--as` | | `--by` | who decided (default: `git config user.name`) | | `--note` | free-text rationale, kept in the record | | `--yes` | skip the confirmation prompt (for scripted use by a human; never wire this into agent tooling) | | `--root` | project root (default `.`) | | `--format` | `text` (default) or `json`: emit the acceptance as data. Without `--yes` this is a preview that writes nothing; JSON mode never prompts | | `--output FILE` | write the report to a file instead of stdout | ## The three everyday acceptances - **`--as evidence`**: a `holds` verdict has enough empirical support for your purposes. The record keeps the acceptance alongside the verdict; a later run with weaker evidence warns. - **`--as risk`**: you own an `unknown` or `skipped` gap. The claim reclassifies to an accepted state that `verify` passes in both strict and lenient mode, named in the row as accepted risk; a `falsified` claim is never accepted as risk. This is the only way an unknown claim stops failing the gate, see [what fails the run](verify.md#what-fails-the-run). When the project's policy sets `accepted_risk_lifetime_days`, the acceptance records the date it `expires`; from that date verify fails the claim again and names the command that accepts it again (see [project policy](pin.md#project-policy)). Accepting a risk again keeps the acceptance it replaces in the claim's `acceptance_history`, as a `superseded` event. - **`--as discovery`**: a falsification that was right about the code and wrong about the claim: the function's actual behavior is the interesting fact. Accepting it retires the claim into the record's discoveries section, permanently, with the counterexample kept as the witness; every falsified claim can be accepted this way, whatever its shape, with one exception. A proof's computation line (`<name>[float]`) is accepted alone only where its loss is inherent in the inputs, so that no float64 computation could do better at the witness: the computed value is the exact result correctly rounded, or the condition number its note gives is above 10 (the problem itself amplifies rounding) and the loss is within what it explains. Where the code loses more than that, where a well-conditioned result is not the correctly rounded one (a different arrangement of the formula may lose less), or where the conditioning could not be read, the acceptance is refused with the cause and the ways out: fix the code, accept the whole claim as a discovery, or narrow the claim's domain knowingly, edit it and accept it `--as superseded`. Accepting the whole claim, `mathema accept KEY NAME --as discovery` on the proven claim itself, moves its row and its computation line to discoveries under one acceptance, with the computation's witness kept, and the claim no longer counts as proven (an `f =:= g` claim retires the same way); a proven claim whose computation holds has nothing to accept. A corrected claim is declared alongside only when it is verified first. State it yourself with `--corrected "<law>"` and mathema adjudicates it against the live function before anything is written (a correction that itself falsifies is refused, with the counterexample named). Without `--corrected`, a mechanically sound inverse (a bare single relation flipped, or a predicate through the grammar's `not` form) may be offered, but only after it has been adjudicated and holds; a chained comparison, an `assuming` premise, a `let` section, or an inverse that fails adjudication is never guessed at, and the discovery is simply recorded with no replacement. When a correction is written, it carries its real adjudicated verdict. The acceptance also keeps the declared layer honest: any claims file stating the retired law is rewritten as part of the act (the stanza replaced by the correction, or removed when there is none), because a leftover declaration would regenerate the falsification on the next real sweep. A docstring or decorator surface cannot be rewritten by an acceptance, so `verify` skips the retired law there with a non-fatal note naming the remedy until the source changes; a DIFFERENT law under the same name is new authorship and adjudicates normally. The claims file and the function's verified record are written in the same act, so a `mathema verify` straight after an acceptance finds the function unchanged and does not check it again. A claim added or edited before the acceptance is still checked by that verify. The exception is `--as superseded`, whose authored version is checked on the next verify by design. Several claims of one function can be accepted together, `mathema accept KEY claim_a claim_b --as discovery`: each is listed in the same shape, and one prompt (`write these 2 acceptances? [y/N]`) covers them all. **What is acceptance?** Verification says what the machine established; acceptance is where a *person* takes accountability for what to do about it. It is integral to the CDD loop, not an add-on: evidence is adjudicated by the tool, but the decision to rely on a `holds`, to own a gap, or to adopt a corrected claim is a human's, and the record carries whose. You do not have to learn the vocabulary first. Run `mathema verify` to see which records fail on an unknown or falsified claim, then type `mathema accept KEY CLAIM` with no `--as` (at a terminal; `--format json` always needs `--as`), and mathema reads the claim's verdict and proposes the natural kind (a `holds` is *evidence*, an `unknown` is a *risk*, a falsification is a *discovery*), then asks you to confirm. You take the decision by saying yes, not by memorising a vocabulary. A configured [PIN](pin.md) is prompted for before any acceptance writes, and the record's `accepted` block gains a `verified_by: {method, key}` stamp, evidence the decision was made by a person rather than an agent. Optional, and off until `mathema pin set`; a record with no human sign-off states `pin: none` in its identity block, so the absence is explicit, never inferred. There is deliberately **no accepting a bug**: if the code is wrong, fix the code, the recorded counterexample replays on every re-adjudication until the claim proves, so a falsified claim can't be waved through. ## Acknowledging a transition A claim whose verdict is weaker than in the previous record carries the move beside it, see [transitions](../verdicts.md#transitions-and-what-invalidated-names). `verify` fails on an open `regressed` move in every mode, on an open `weakened` move to `unknown` or `skipped` in every mode, and on an open `weakened` move from `proven` to `holds` in strict mode, and each failing line ends with the command that closes it. Acknowledging says a person has seen the move and the fresh verdict stands as it is; it does not change the verdict, and a falsified claim still fails the gate as falsified. The acknowledgement is kept on the transition (`acknowledged: {at, by, note}`), and the record drops the transition on the run after it closes. A move the claim recovers from on its own, by coming back to the level it fell from, closes without anyone's hand. On a supported claim that fell to `unknown` or `skipped`, the same command is a risk acceptance: the person accepts that the claim is no longer supported at the level it fell from. It is recorded as `acknowledged: {at, by, note, as: risk, level}`, `level` being the verdict it fell from, and goes through the project's [acceptance policy](pin.md#project-policy) like every other acceptance, so a required PIN applies when it is written and `mathema verify` checks it on every run. The claim is then accepted risk at that level, as `--as risk` makes it: both modes pass it, named in the row. Unlike a plain acknowledgement, the sign-off stays on the record while the claim is below the level it fell from, and closes as recovered when the claim is back there. Under a policy lifetime (`accepted_risk_lifetime_days`) the sign-off also records `expires`; from that date the transition is open again, its line names the date, and the same command accepts it again, keeping the lapsed sign-off in the claim's `acceptance_history` as a `superseded` event. <!-- illustration --> ```text $ mathema accept t.f nonneg --transition --by aaron --note "no solver on CI" acknowledge on t.f, by aaron: nonneg: weakened proven to skipped (nothing changed); accepting the risk at proven ``` ## Machine-readable acceptance `--format json` emits the acceptance as data, and **writes nothing unless `--yes` is also given**: without it you get the plan (`applied: false`, plus the `actions` that would run), so a client can render the decision for a human and only then commit it. JSON mode never prompts, so a non-interactive caller can't hang waiting on stdin, and the human gate stays exactly where it always was. A refusal comes back as `{"ok": false, "error": ...}` with the same exit code the prose path uses; `--output FILE` writes the payload to a file. The same envelope covers every acceptance path, claim, function intent, scope intent (module or `__project__`), and concepts, with `kind` naming which one. ## Form-bound Every acceptance binds to the function's `form` hash at the moment of the decision. Change the function and the acceptance goes stale outright; the gap or evidence you accepted was about different code, so the claim fails the gate again until someone re-decides. ## Worked example A running balance in `balances.py`, with three claims in `claims/running_total.claims.yaml`: <!-- example: balance file=balances.py --> ```python def running_total(xs: list, y0: float) -> float: """Add every value in xs to a starting balance y0.""" total = y0 for v in xs: total = v + total return total ``` <!-- example: balance file=claims/running_total.claims.yaml --> ```yaml balances.running_total: claims: - name: shifts_with_start statement: "f(xs, y0) == f(xs, 0) + y0" - name: nonneg_for_nonneg_steps statement: "for xs in [0, 1]^n, f(xs, 0) >= 0" - name: never_overshoots_much statement: "assuming nonneg_for_nonneg_steps is proven, for xs in [0, 1]^n, f(xs, 0) <= len(xs)" ``` `shifts_with_start` is proven; its `shifts_with_start[float]` companion is falsified at a cancelling pair of magnitude 1e300, where the float sum drops `y0` (the note gives the condition number at the witness and the ways out: a `let |inf|` binding, which bounds only the computation and never the proof, so the proof stays over the full domain, or accepting the computation line as a discovery, which is open to it because the loss is inherent in the inputs). `nonneg_for_nonneg_steps` only holds: the probe agrees, but derive cannot settle the sign of the lifted sum. `never_overshoots_much` rests on it being proven, so it comes back `unknown` with the note `prerequisite nonneg_for_nonneg_steps is holds, not proven, nothing to rest this claim on`, and `verify` fails on it (see [`mathema verify`](verify.md#unknown-claims-and-accepted-risk)): <!-- example: balance session --> ``` $ mathema verify --root . note balances.running_total: shifts_with_start[float] initially falsified: ill-conditioned here (κ ≈ 5e287): no float64 computation can deliver this result at inputs of magnitude 1e300: (i) if inputs this large are out of scope, bound the computation alone (the claim keeps its domain): let |inf| be 1e+21 (ii) if the loss is accepted, run: mathema accept balances.running_total "shifts_with_start[float]" --as discovery FAIL balances.running_total: no baseline record; 2 proven (1 claim, 1 built-in), 5 holds, 2 falsified, 1 unknown <- 1 policy row to settle: missing[xs, null], f raises TypeError at a null slot of xs where mathema's default says propagates (i) change f (ii) write: missing(f, xs, null) raises(TypeError) to list them, run: mathema claims balances.running_total 1 falsified claim(s) never_overshoots_much unknown: prerequisite nonneg_for_nonneg_steps is holds, not proven, nothing to rest this claim on 0 unchanged since the last run (not run again), 1 checked, 3 problem(s) grammars detected: mathema; verified by this run: mathema 1 intent to accept (1 function): mathema accept --intent ``` Owning that gap is a decision. At a terminal, mathema prints the exact write and asks `write this acceptance? [y/N]`; `--yes` answers it here: <!-- example: balance session --> ``` $ mathema accept balances.running_total never_overshoots_much --as risk --note "the premise only holds empirically; monitored" --by "Charles Babbage" --yes accept balances.running_total :: never_overshoots_much as a risk, by Charles Babbage verdi - docs/modes/audit.md (15356 bytes)
# `mathema audit` Population-level report: every function mathema can find under the given targets, whether it's claimed at all (any of the four authoring surfaces), whether it's liftable for a *derive-route* proof specifically, and if not, why not, distinct from `verify`'s per- function completeness view, which only ever reports on functions that already have at least one claim. A function with zero claims is invisible to `verify`/`status` by construction; `audit` is the tool that answers "where do I even start" on a real, existing codebase. ```bash mathema audit mypkg [mypkg.sub ...] ``` ## Arguments | Flag | Meaning | |---|---| | `target` | importable module or package name(s), must already be importable | | `--root` | project root holding `claims/` and any `coverage.json`/`.coverage` (default `.`) | | `--exclude ANALYSIS` | skip an analysis entirely, not just hide its column: `derivable`, `complexity`, `typing`, `scope`, `tested`, `docs`, `docsync` (comma-separated or repeatable) | | `--index` | write the global index record (`.mathema/index.yaml`) instead of the analysis table, and print what it wrote as a per-module table (overwriting the previous index is by design; it is a generated view nothing reads back into the declared or verified layers) | | `--docs` | skip the wide table and report per-function checkbox breakdowns of just the docs criteria, both the quality checklist and the docsync schema, see below | | `--deriv-report` | the full per-function detail below the table (off by default): underivability reasons with reason-code hints, and each function's complete module-state view, the names the grid's `vars`/`mutates` cells condense, with the file lines they appear at | | `--one-line` | one row per function with the full dotted key and no cell compression: the default tree layout (module line, class line, functions indented under their scope) plus its name ellipses and `+N` condensing all off | | `--compact` | column-oriented JSON instead of the grid: `{"prefix", "cols", "rows"}` with column names once, the shared key prefix factored out of every row, and raw values (JSON null for missing, never `-`); the same shape the MCP `audit_targets` tool returns | | `--filter TERM,...` | keep only matching rows (implies `--compact`): semantic terms, derive_unlock classes (`actionable`, `limitation`, `N/A`), `claimed`/`unclaimed`, `derivable`/`underivable` (what the derive route can do given the declared domain), `unconditional`/`needs-context` (whether the body lifts with nothing supplied), `underclaimed` (fewer claims than the function's own structural floor; the "what have I not evidenced" query), and columnar substring matches (`blocker~loop` scopes to one column, `~mutual` matches any column). Terms from the same dimension OR together (`actionable,limitation` keeps either, which is also how "everything except N/A" is spelled); dimensions and columnar terms AND across, and an empty match text (`~`, `col~`) is an error, never a keep-everything no-op. A filter's column references are computed even when not selected as output, so an empty result always means "nothing matched", never "never looked". Explicit by design, never a default, right for a lifting pass, wrong for a claims pass, since probe claims stay viable on every `limitation` row | | `--cols COL,...` | columns for `--compact` (implies it), e.g. `key,span,claims,derivable,unconditional,blocker,typed,tested` (the default set); also `min_expected_claims`, `claims_vs_floor` (the `[actual, floor]` pair, side by side), `blocker_params`, `blocker_more`, `blocker_hint` and `blocker_unlock` (the remedy and its derive_unlock class, carried in the row rather than needing a second `reason_code` lookup), `constructs`, `cx`, `quality` (alias `doc_quality`), `docsync` (the 0-100 percent), `intent`, `domain_declared`, `raises_declared`, `callees_doc_quality`, `callees_docsync`, `concepts`, `global_vars`, `mutates`, `unresolved`. The resolved selection is echoed back in the output's `cols` field; an unknown name exits 2 listing the vocabulary | ## What each column reports | Column | Meaning | |---|---| | `key` | the canonical dotted key, `module.qualname` | | `span` | the function's source span, sed-address style (`142:187p`), a ready-made `sed -n` range, so reading exactly one function needs no search | | `claims` | the claim triplet <code>{floor | actual | expected}</code>: the floor is the least this function's shape gives you to state (one claim per relevant claim family), the actual is how many claims it carries across the four authoring surfaces, and the expected is how many a function of this shape typically carries, which needs a corpus and so reads `-`. <code>{9 | 1 | -}</code> is a function with one claim against a floor of nine | | `cx` | cyclomatic complexity (branches + loops + 1), shown for every row | | `derives` (derive route group) | whether the derive route can work on this function **given the domain its signature, docstring and claims declare**. This is the provability question | | `reason` (derive route group) | the structural shape blocking an **unconditional** lift, the body with nothing supplied ("2 branches, 1 loop", "recursive (2 call sites)"); a dash means nothing blocks it even bare | | `code` (derive route group) | the compact underivability code, see [Reason codes](../reason-codes.md) | | `typed` | signature typing coverage | | `finite_domain` (typing group) | a `Literal[...]`/`Enum`/`bool` parameter annotation, surfaced as a finite domain (a bool's stated values are the real `False`/`True` objects, so identity guards behave) | | `vars` (globals group) | genuine global *variable* dependencies, real, hidden state; a claim about this function is only as reliable as that value | | `mutates` (globals group) | module state this function writes, the stronger relationship | | `funcs` (globals group) | references to a sibling function/class/module by name, ordinary code structure, not a state dependency | | `unresolved` (globals group) | free names with no binding mathema can find at all, almost always a real bug | | `tested` | whether an existing `coverage.json`/`.coverage` covers this function (never runs tests itself): `yes`, `no`, `no-report`, or `outdated` when the function's source file changed since the report measured it (by content hash when the report is stamped with `mathema coverage --stamp`, else by file modification time); a stale yes is not evidence | | `locked` | whether the function's form hash is [locked](lock.md): `yes` (with who pinned it) means the body cannot change until a human runs `mathema unlock`. Hidden when nothing in the population is locked; `--compact` carries the pinned form hash in a `locked` column on request | | `quality` (docs group) | the docstring quality-checklist score, see below | The grid prints a group-title row above the columns (`derive route`, `typing`, `globals`, `docs`), so the short names above always sit under their group's own heading, and the key column is a tree by default: one line for the module, one per enclosing class, each function indented under its scope (`--one-line` for the flat, fully-expanded table). Long name lists in the `vars`/`mutates`/ `funcs` cells condense (each long name ellipsized, at most three shown, then a bare `+N`), an overlong `reason` ellipsizes too, and the `unresolved` column drops entirely when nothing is unresolved across the whole population, `--deriv-report` and `--one-line` carry the full view. A concept-tag count rides the `--docs` report, not the wide grid. A mistyped function key suggests close matches ("did you mean: ..."). The compact/MCP column vocabulary is unchanged and additive-only (`global_vars`, `blocker`, ... stay the selection names there). Discovers module-level functions and a class's own methods (static and instance, `self`/`cls` intact; a read-only method derives like a plain function, and one that modifies instance state (or lets self escape) is reported `derivable: no <- stateful`). Only dunder names (`__init__`, ...) are excluded; a single-leading-underscore helper is included like any other function, since it's often the more claimable one (a public function frequently just dispatches to a private numeric core). ## `derivable` and `unconditional` are different questions `unconditional` asks whether the body lifts with **nothing supplied**: no declared domain, no claim context. It is a property of the code alone, and it is *not* a ceiling on what can be proven. `derivable` asks what the derive route can do **here**, given the domain the signature, docstring and claims declare. They differ constantly, and the difference is not an edge case. A function guarded by a branch reports: reason 1 branch code branch:needs-domain(theta) derives yes The blocker is real; the body does not lift bare, and the claim's own `for theta in [...]` quantifier prunes the branch, so the derive route proves it anyway. A repository read `2/75` on the unconditional number while carrying derive-route proofs on functions the column called underivable. Read `derivable` for "can this be proven", `unconditional` for "does this need help". Neither rules out a probe claim. ## The `code` column and the underivable detail The `reason` column reports the shape; `code` names the exact blocker as a compact, stable code, `loop:non-affine-update`, `branch:needs-domain(scale)`, `unsupported:unbound-name`, and `--deriv-report` adds a detail block below the table for every underivable function, one source line and code per blocking construct, plus each function's full module-state view. The full meaning, the `derive_unlock` tag, and the fix hint for every code live in [Reason codes](../reason-codes.md); `mathema describe --issue <key>` carries the same detail (plus the interpolated hints) as a structured payload. For a branch, each condition is classified independently, a function can have one resolvable branch and one structurally blocked one, and both get their own line. Against `strength_to_distance` (a real fixture in `tests/test_branch_pruning.py`), here in `mypkg.py`: <!-- example: branches file=mypkg.py --> ```python import math def strength_to_distance(r: float, scale: str = "info") -> float: if scale == "info": return math.sqrt(1.0 - r ** 2) if scale == "linear": return 1.0 - r raise ValueError(f"unknown scale {scale!r}, use 'info' or 'linear'") ``` `--deriv-report` closes the report with this block (the table above it trimmed here): <!-- example: branches session match=subset --> ``` $ mathema audit mypkg --deriv-report underivable functions: mypkg.strength_to_distance: line 2 branch:needs-domain(scale) line 4 branch:needs-domain(scale) codes explained: the reason-code reference in the docs, or `mathema describe --issue <key>` for the full details ``` Both branches are resolvable once `scale` has a declared domain, a claim like `for r in [0, 1], scale in {"info"}, f(r, scale) == sqrt(1.0 - r^2)` proves. A function whose branch condition depends on a *local* variable not traceable back to its own parameters (or one with an unrecognized condition shape) gets a `branch:untraceable-local` / `branch:unrecognized-shape` code instead. See [The derive route](../derive-route.md) for what resolvable and blocked mean in terms of derivability, and [Reason codes](../reason-codes.md) for the complete code table. ## The `quality` score `quality` is a quality checklist, not a style grade, every criterion is a presence check, not a correctness check, and a criterion that genuinely doesn't apply to a given function (no parameters, no `raise` anywhere in the body, no return value) shrinks the denominator instead of counting against the score. "documents its parameters" and "documents raising" are scored *per parameter/exception*, not as one all-or-nothing point each, a function with 3 parameters and 2 documented contributes 2 to the score and 3 to the denominator, not a flat 0 or 1, so the overall "N/M" reflects how close a docstring is, not just whether it's perfect. | Criterion | Applicable when | Passes when | |---|---|---| | has a docstring | always | the docstring is non-empty | | has a summary | the docstring is non-empty | there's real text before the first recognized section header (`Args`/`Parameters`/... or a numpydoc `Header\n----`) | | documents its parameters | the function has at least one real parameter (`self`/`cls` excluded) | every parameter's name appears literally somewhere in the docstring | | documents its return value | `analyze()` infers a non-`None`, non-unknown return kind | a `Returns:`/`Yields:` section exists | | documents raising | the body contains at least one `raise <Exception>(...)` with a resolvable exception type name | a `Raises:`/`Exceptions:` section exists **and** every distinct raised exception type is individually named in it, a section that exists but never mentions one of the actually-raised types still fails | Example: this function only partially satisfies "documents raising"; `ValueError` is named, `OverflowError` isn't, so `documents_raises` is `False` even though a `Raises:` section is present: <!-- example: half run --> ```python def half(x: float) -> float: """Halves x. Raises: ValueError: if x is negative. """ if x < 0: raise ValueError("x must be nonnegative") if x > 1e6: raise OverflowError("x too large") return x / 2 ``` Run this checklist against a single function without the `audit` CLI, useful in a notebook or a quick interactive check: <!-- example: half repl --> ```python >>> import mathema >>> mathema.docstring_report(half) mathema.DocstringReport(half) · 4/6 criteria met ✓ has a docstring ✓ has a summary ✓ params documented (1/1) ✗ documents its return value ✗ exceptions documented (1/2) ``` This is the same checklist `audit`'s `docs` column runs, a separate, much stricter, opinionated docstring convention also exists (claims, domain, and type declarations live *in* the docstring itself); see [The mathema docstring](../mathema-docstring.md). ## `--docs`: just the docs criteria, broken out Two labeled tables: `quality:` (the checklist, plus a `concepts/tags` count) and `docsync:` (the strict schema; its claims column header reads `{min_expected|actual|est_applicable}`). `mathema audit --docs` skips the wide table and every other analysis (nothing else is even computed) in favor of a colored grid, one row per function, with each checklist criterion as its own column (`has_docstring`, `has_summary`, `params`, `returns`, `raises`, `quality_ratio`, `claims`, `concepts/tags`) instead of one summary "N/M", the same per-parameter/per-exception counts described above, laid out so a whole package's docstring gaps are scannable at a glance rather than read one function-block at a time. The docsync sync grid is appended by default (see [docsync](docsync.md)); exclude it w - docs/modes/badges.md (24805 bytes)
# `mathema badges` Three orthogonal measures of a codebase, each 0-100, and one picture. Badges now come from [mathema-ci](https://github.com/tetrionlabs/mathema-ci): `pip install mathema-ci`, then `mathema-ci measure --out`, which runs your tests, scores the project and writes the badge files. The writer built into mathema is off by default, so `mathema badges` and the MCP `badges` tool only print a line saying this, write nothing and exit 0. Setting `MATHEMA_BADGES=on` in the environment turns it back on, as every command below assumes, and 0.6.5 removes it. The scores themselves are still mathema's, so the rest of this page describes what `mathema-ci measure` reports too. ``` MATHEMA_BADGES=on mathema badges [targets] # print the triangle + numbers MATHEMA_BADGES=on mathema badges [targets] --out .mathema/badges/ # also write artifacts MATHEMA_BADGES=on mathema badges [targets] --refresh # score every function again ``` Omit targets for the rootwide analogue of `verify` (every function the store knows under `--root`). A run reads the stores, the claims files and the library claims once, so its cost grows with the number of functions it scores. On a terminal it reports progress to stderr every 50 functions, with the count and the time elapsed, and prints nothing extra when stderr is not a terminal, so a CI log or an `--out` directory stays as it was. Each function's three steps stop at the badges step cap (60 seconds unless `MATHEMA_BADGES_STEP_TIMEOUT` sets another), and a function whose step stopped is named on stderr and in the snapshot's `capped` list: its implementation then counts only the lines a fresh test report covers, and its intent or clarity is left out of that score's roll-up. The functions are scored in `--jobs N` worker processes (the CPU count, up to 4, by default; `--jobs 1` scores them in the one process), and the results are rolled up in the same order whatever N is, so the scores do not depend on it. Each function's result is kept in `.mathema/cache/badges/`, which carries its own `.gitignore` and is never committed. A later run uses a kept result only when nothing that function's result is computed from has changed: - the function itself and everything it reaches: the functions and classes its source calls, theirs in turn, and any function a reached verified record lists among its dependencies, each by its source, its place in its file, its module docstring and the values of the module-level names it reads, with its verified record and its claims-file entry; - for implementation, whether the test report is fresh for the function's file and which of its lines the tests ran; - what every function shares: mathema's version and its own code, the sampling seeds, the Python version and platform, the `MATHEMA_*` environment, the installed packages and their versions, the library claims, `README.md`, `pyproject.toml`, `.mathema/index.yaml` and `.mathema/meta`. So editing one function scores that function and its callers again, and leaves every other function's result in place; a second run on an unchanged project takes seconds and gives the same numbers as a run without the cache. A result is never kept when any wall-clock cap fired while scoring it, a capped step or a proof cap inside its check, since that result depends on how loaded the machine was; such a function is scored again on every run. The reach is what the source names. A function reached only at run time, through a name the source does not bind (a callable looked up in a table, passed in, or built by `getattr`), is not part of it, so an edit to that function leaves its callers' kept results in place. `--refresh` is the full recomputation: it scores every function again and rewrites the cache. Deleting the directory clears the cache too. From Python, `repo_badges(cache="refresh")` does the same, and `repo_badges(cache=False)` neither reads nor writes the cache. ## The three scores - **implementation coverage** (code layer): the raw line ratio from `mathema coverage`, how many statements a test, a probe, or a derive proof exercises (their union). A physical ratio, so it is neither averaged nor weighted. - **intent** (spec layer): `docsync`, how much of what each function is meant to do is explicitly specified and up to date, so intent that lives only in someone's head shows up as a gap. - **clarity** (behaviour layer): how much is KNOWN about a function's behaviour, scored from its VERIFIED claims. See below. The two per-function-quality scores, intent and clarity, roll up to the repo by a centrality-weighted mean: a function the rest of the codebase depends on (by PageRank over the call graph) counts for more than a leaf helper. ## The test report behind implementation The test source of implementation comes from a coverage report that already exists at the root, `coverage.json` first, then a native `.coverage`. mathema reads it and never runs your tests, unless you ask: ``` mathema coverage [targets] --run-tests # re-run the tests under coverage first mathema coverage --stamp # stamp a report produced elsewhere ``` A report only counts while it still describes the code. Its lines are keyed by line number, so once a source file changes they can point at the wrong statements. Those lines are then left out of the score and reported as reclaimable by a re-run. Freshness is judged per source file, in one of two ways, and `mathema coverage` prints which one it used: - **by content hash**, when the report is stamped. `coverage.sources.json` sits beside the report and holds the sha256 of every file it measured, plus the report's own hash. A file's lines count exactly while its content still matches. This holds anywhere the report travels: a fresh checkout, a CI artifact, a cache. A stamp written for a different report is ignored. - **by file modification time**, when there is no stamp. A file is stale when it was modified after the report was written. That is only reliable on the machine that ran the tests, because a checkout resets file times. `--run-tests` stamps the report it produces. A report made by another tool, for example `pytest --cov` in CI, needs `mathema coverage --stamp` run once afterwards, in the same tree. Stamping costs a hash of each measured file, milliseconds even for a large package. When the tests run in parallel mode, or measure subprocesses, coverage writes one data file per process (`.coverage.<suffix>`). `--run-tests` combines them before exporting, so lines executed in a subprocess, such as a test that invokes the CLI, count. A test run that fails still produces the report: the lines every other test executed are kept. mathema's own functions get no probe source when mathema measures itself. Checking one of them runs mathema's machinery, which may call that same function, so a probe's lines cannot be told apart from the machinery's. Test and derive lines still count. ## How clarity is scored Clarity is an entropy measure, in the sense Shannon gave the word: entropy is uncertainty counted in bits, where one bit is the uncertainty of a single fair yes-or-no question, so a fair coin carries 1 bit, a choice among eight equally likely options carries 3 (`log2 8`), and an outcome you already know carries none. Evidence that rules possibilities out lowers it, which is exactly what a verified claim does. Before any evidence, a function carries an a-priori uncertainty about its behaviour: which map it computes, which inputs it takes, what its output looks like, how safely it runs and where it can fail. mathema splits that uncertainty into sources, gives each source an entropy in bits, and asks how much of the total your verified claims have removed: ``` H0 = sum over sources s of h(s) H_rem = sum over sources s of h(s) * (1 - r(s)) clarity = 1 - H_rem / H0 ``` Here `h(s)` is the a-priori entropy of source `s` and `r(s)`, between 0 and 1, is the fraction of it the strongest evidence bearing on that source has eliminated. Clarity is 0 when nothing is known and 100 when every source is settled by proof. It is a measure of how sharply the function is characterised, not a pass rate: whether the claims hold is reported separately. ### Sources and their entropy The sources fall into five dimensions, each a different kind of thing you can know: | dimension | the question it answers | sources and their entropy | a claim that removes it | |-----------|-------------------------|---------------------------|--------------------------| | **what it computes** | which function is this, exactly? | the map, 1 bit, plus 0.4 bits per branch region | `f(x) == 2*x`, an equivalence, a closed form | | **its bounds & shape** | what is the output's range and form? | the output envelope by return kind (a bool 0.5, a scalar 1, a sequence or mapping 1.5, a matrix 2) and its relational form (0.4 flat, 1 branched) | a bound, monotonicity, symmetry; a proof of *what it computes* settles these too | | **what it accepts** | which inputs are in and out of bounds? | each parameter's domain (below), and 0.5 bits for the absence an `Optional` admits | a domain stated on the function, a proof of what it computes, a `raises` or `is_defined` row; an `absent` row or policy for the absence | | **how safely it runs** | does it run cleanly and deterministically? | one source per safety family that can apply: state and determinism (0.15 bits each on a visibly pure function, 0.8 otherwise), numerical stability and representation (0.2 bits, plus 0.4 per loop), missing values for a sequence input (0.4), text for each string input whose domain is not a finite set (1) | the safety families (`is_state_safe`, `is_numerically_stable`, ...); a `missing` policy row for missing values | | **where it can go wrong** | how and where does it fail? | 0.5 bits per raise site, 2 bits per call into another function | a `raises` contract; for a call, the callee's own record | A dimension that cannot apply has no sources, so it carries no entropy: a pure, total function with nothing that can fail has nothing in *where it can go wrong* to count against it. A decorator is not a call the function makes, and a guard that states a parameter's domain (below) is charged as that domain, not also as a branch and a raise site, so `@enforce_domain({"side": {"buy", "sell"}})` and `if side not in {"buy", "sell"}: raise ValueError(side)` score the same. ### Clarity by aspect `mathema.badges.clarity_aspects(fn)` returns the same reading split into the five dimensions, as five aspects in a fixed order: `computes` (what it computes), `accepts` (what it accepts), `shape` (bounds and shape), `safety` (how safely it runs) and `failure` (where it can go wrong). Each aspect carries `bits`, the a-priori entropy of its sources, and `left`, the bits its verified claims and its callees' records leave, so its score is `1 - left / bits`. Its `weight` is its share of the function's bits, and the function's clarity is the mean of its aspect scores weighted that way, which is `1 - H_rem / H0` again. An aspect with no sources cannot apply: it is marked `applies: False`, with no score and a weight of 0, rather than read as 0 or as fully known. The 99 rule holds per aspect too: an aspect reads 100 only when nothing in it is left. `mathema.badges.repo_clarity_aspects(root)` rolls each aspect up across the functions the badges score by pooled bits, `1 - sum(w * left) / sum(w * bits)` with `w` each function's centrality weight, over the functions where the aspect applies. A large aspect left open therefore outweighs a small one settled: 0.1 bits settled in one function and 20 bits open in another read about 0.5%, not the 50% a mean of the two scores would give. Repo clarity itself is still a centrality-weighted mean of function scores, so the five rolled-up aspects do not yet roll up exactly into it; repo clarity moves to pooled bits in clarity 1.5. ### What a parameter accepts Each parameter's entropy is what its completed domain leaves unknown, read from the same domain every check uses. That domain is what the function itself states: its annotation, a guard in the body refusing every value outside a set (`if side not in {"buy", "sell"}: raise ValueError`), or an `@enforce_domain(...)` decorator, which takes the place of the annotation (two numbers there are the closed interval between them, a string is read in the domain grammar, and any other set, list or tuple is the finite set of its members): | what is known about the parameter | bits | |-----------------------------------|------| | nothing (no annotation, no binding) | 1.5 | | a type alone (`float`, `str`, a language admitting every string) | 1.0 | | a language narrowed to an alphabet | 0.8 | | a language narrowed by a predicate | 0.6 | | a refined language (`L[ascii, len <= 80]`) or a bounded range (`@enforce_domain({"x": (0.0, 1.0)})`) | 0.4 | | a finite set of `k` values (a `Literal`, a str `Enum`, a guard to a set, `@enforce_domain` to a set) | `min(0.3, log2(k) / 10)` | | any other guard in the body (its boundary is the unknown) | 1.0 | A finite set of `k` values is a choice carrying `log2(k)` bits, scaled by a tenth because a closed set is already most of the way to known. Every parameter starts at the 1.5 bits of nothing known, and whatever the function states about it (its annotation, a guard, `@enforce_domain`) counts as known, so annotating a parameter or stating its domain never lowers a score: only what the stated domain leaves is charged, and the claims clear part of that. Who states the domain matters. When a finite set is the function's own domain, a proof that visits every member covers every input the function accepts and clears the parameter entirely. When the set, or a range, comes only from a claim's binding, the function still accepts every other value of its type, so the claim speaks about its share of the inputs (below) and leaves the parameter charged for the rest. For example, `for name in {"Alice", " alice ", "ALICE"}, f(name) == "alice"` on `username_key(name: str)` settles three strings out of unboundedly many, which is a vanishing share, while the same proof on `username_key(name: Literal["Alice", " alice ", "ALICE"])` settles every input. A parameter guarded in the body by anything other than a set is charged as a guard, for its boundary, which a verified claim about what the guard refuses clears. ### How far a claim reaches A claim credits what it says about a function in proportion to the share of the function's inputs it ranges over. The share is counted in the values each parameter's type can actually hold: - a `float` holds float64 doubles, which crowd towards zero, so `[0, 1]` holds about 25% of them, `[0, 100]` about 25.2%, `[0, inf)` half, and `[0.5, 0.6]` about 0.005% (these shares are exact counts of doubles); - an `int` is unbounded, so a bounded stretch of integers is a vanishing sha - docs/modes/check.md (8587 bytes)
# `mathema check` One-off interactive verification of a single function, module, or package against its built-in laws and any inline `--claim`s, the way you'd use mathema from a notebook. Lenient by default. ```bash mathema check pkg.mod:fn [--claim "f(-x) == -f(x)"] mathema check path/to/file.py:fn [--claim "..."] ``` ## Arguments | Flag | Meaning | |---|---| | `target` | a dotted name (`pkg.mod`, `pkg.mod.fn`, `pkg.mod:fn`) or a file path (`file.py`, `file.py:fn`); files import with real package context, so relative imports inside them work, and report keys are always the canonical dotted `module.qualname` | | `--root` | project root to import dotted targets relative to (default `.`) | | `--claim LAW` | ad-hoc claim to adjudicate, e.g. `"f(-x) == -f(x)"` (repeatable) | | `--domain name=lo:hi` | declared parameter range (repeatable) | | `--strict` / `--lenient` | one strictness pair shared with `verify`; lenient is the default here (the authoring loop iterates while claims are still being written); strict additionally counts skipped (unverifiable) claims nobody accepted as failures, a reporting filter over already-computed verdicts, never an adjudication mode | | `--trials-downscale FACTOR` | shrink the trial budget by `FACTOR` (FACTOR > 0) for a faster dev loop; a value above 1 is clamped to 1, so it never scales upward | | `--format` | `text` (default), `json`, `compact`, `junit`, `github`, `md` | | `--output FILE` | write the report to a file instead of stdout | ## Report formats - **`text`**: human-readable, for a terminal. - **`json`**: for artifacts; includes `tool`/`version`/`CDD_spec_version`/ `functions`/`totals` fields. - **`compact`**: the same adjudication as `json`, minified onto one line with no envelope: a bare array of one object per function (`key`, `passed`, `problems`, `claims`). Each claim row carries `stance`, `verdict`, `route`, `source`, `gates`, `reason`, and its `evidence.n`, plus a `counterexample` when there is one. Built for a program reading the result rather than a human or a CI widget, and the closest CLI equivalent of what the [MCP](mcp.md) tools return, so an agent that shells out and one that calls a tool see the same shape. Note `source` and `gates`: a suggested claim appears in the rows but has `gates: false` and never affects the exit code, so a client filtering on `gates` sees exactly what the gate saw. - **`junit`**: for a GitLab test report widget. - **`github`**: GitHub Actions annotation format. - **`md`**: for a CI step summary. ## The trial budget The probe route's `n` isn't a flat constant. It's decided once per call, before any law runs, from the target function's own structure: - **Higher**, from a base of 128 up to a max of 256, for a structurally riskier function, more branches, more loops, a wider or unbounded domain (the claim's own binding, which replaces a `domain=` passed to `check` for the parameter it binds, or that `domain=` itself), or a language domain, which adds 32 for every 32 hazards its language brings (up to three steps), whether the language is written in the claim or inferred from an annotation. A language whose hazards still outnumber the budget raises `n` to the number of hazards, so each is tried once, and the record's sampling line says it did. - **Lower**, down to 32, only when the derive route can *prove* the function is affine (a constant slope in every parameter) *and* the domain doesn't itself need the extra density, a wide or float-precision-risky domain, or a language, skips the reduction even for a provably affine function. Every verdict reports the exact `n` it used, plus a `meta["mathema.confidence"]` score (1-4 stars, capped below the derive route's own 5; sampling evidence is never proof, however extensive) built from the same structural factors, so a reader can see *why* a verdict deserves more or less trust without re-deriving it. From the library, `mathema.check(fn, trials=N)` takes an exact count, with no adaptivity at all. `--trials-downscale FACTOR` shrinks the whole budget by a flat factor instead; `0.25` for a much faster dev loop, say, applied to *everything*, an explicit `trials=N` included, not just the adaptive default. It only ever shrinks (a value above 1 is accepted but has no effect; there's no good reason to scale upward when a structurally riskier function already gets more trials on its own), and it never drops the budget below a floor that still means something: at least 16 trials, and at least enough to guarantee every special sampled value (`0`, `±1`, `±1e-9`, `±1e6`, ...) is actually exercised once. `--trials-downscale 0` or a negative value is a clean CLI error, not a silent 0-trial `holds`. The budget above is the probe route's. The `computation` line under a proven claim runs on points of its own: every corner of the domain and points sampled inside it, with the count in its note (`ran at 43 points: every corner and 40 interior points`). `--trials-downscale` leaves it as it is. A finite domain small enough to run in about a second, an integer range or a small set, is swept point by point. A claim can carry its own budget, the `trials:` field of a claims-file entry or `mathema.claim(..., trials=N)`; it sets the count for that claim, and a finite domain whose points fit within it is swept in full. ## Exit code 1 if any row had a problem; 0 otherwise, suitable for a pre-commit check on a single target. A falsified or unknown claim is a problem in every mode; `--strict` additionally counts unverifiable (skipped) claims and a silently-unenforced declared domain. Only claims you actually stated gate the exit code: standard claims mathema itself volunteers (see [`mathema claims --suggest`](claims.md)) are shown for adoption but never fail a run pre-adoption. ```bash mathema check model.py --domain alpha=0:1 --claim 'excluded_outside_domain(alpha)' mathema check model.py --format json --output claim-coverage.json mathema check model.py --format junit --output claims.xml # GitLab test widget mathema check model.py --format github # Actions annotations ``` Worked pipeline configs for GitHub Actions and GitLab are in `examples/ci/` in the repo. ## Worked example: softmax, start to finish `softmax` takes a list of float scores and refuses an empty list with its own `ValueError` before `max()` can fail on it. mathema checks the empty input on its own line under each claim: a deliberate error at `[]` passes, while a crash the body merely stumbles into (`max()` of an empty list) falsifies the claim. <!-- example: softmax file=functions.py --> ```python # functions.py import math from typing import Annotated from mathema.types import Shape def softmax(scores: Annotated[list[float], Shape("n")]) -> Annotated[list, Shape("n")]: """Turn a vector of real-valued scores into a probability distribution. Claims: sums_to_one: sum(f(scores)) == 1 """ if not scores: raise ValueError("softmax needs at least one score") m = max(scores) exps = [math.exp(s - m) for s in scores] total = sum(exps) return [e / total for e in exps] ``` <!-- example: softmax session --> ``` $ mathema check functions.py:softmax --claim "sum(f(scores)) == 1" ok functions.softmax: source, no side effects; claims 6/6 checked (0 proven, 6 holds, 0 falsified) ``` Break it on purpose (drop the normalization, `return exps` instead of dividing by the total): <!-- example: softmax file=functions.py --> ```python # functions.py import math from typing import Annotated from mathema.types import Shape def softmax(scores: Annotated[list[float], Shape("n")]) -> Annotated[list, Shape("n")]: """Turn a vector of real-valued scores into a probability distribution. Claims: sums_to_one: sum(f(scores)) == 1 """ if not scores: raise ValueError("softmax needs at least one score") m = max(scores) exps = [math.exp(s - m) for s in scores] total = sum(exps) return exps ``` and `sums_to_one` correctly falsifies, the row fails and the exit code is 1 (see [CDD in one page](../cdd.md#verdict-vocabulary): the counterexample is kept as knowledge, *and* the run fails): <!-- example: softmax session --> ``` $ mathema check functions.py:softmax --claim "sum(f(scores)) == 1"; echo $? FAIL functions.softmax: source, no side effects; claims 6/6 checked (0 proven, 4 holds, 2 falsified) <- 2 falsified claim(s) 1 ``` See [mathema verify](verify.md) for the same regression caught from the CI-sweep angle instead. - docs/modes/claims.md (9707 bytes)
# `mathema claims` The claim authoring surface for one function: list what's declared, render the standard claims mathema suggests for it, and adopt a suggestion into the declared layer. Adoption is an explicit step, which a person or an agent may take; a suggestion never lives in any record until it is adopted. ```bash mathema claims KEY # list the declared claims mathema claims KEY --suggest # render the suggested standard claims mathema claims KEY --adopt NAME # write one into the declared layer mathema claims KEY --write # write the policy rows ``` ## Arguments | Flag | Meaning | |---|---| | `key` | module-qualified function key (`functions.softmax`) | | `--suggest` | render the suggested standard claims with laws, in three sections: individual claims, questions with candidate answers, and claims likely to be unknowable | | `--adopt NAME` | write the named suggestion into `claims/adopted.claims.yaml` | | `--write` | write the policy rows mathema suggests, what each parameter does with a value that is not there, into `claims/policies.claims.yaml`, each under the name the record prints, a contradicted one with the contradiction in its note | | `--root` | project root (default: the nearest ancestor holding `.mathema/` within the enclosing git repository, else that repository, else `.`; never the home directory) | | `--format` | `text` (default) or `json`: emit `--suggest`'s rows columnar, matching the MCP `suggest_claims` tool | | `--output FILE` | write the report to a file instead of stdout | ## Policy rows Beside the declared claims, `mathema claims KEY` lists the policy rows the record carries: what the function does with a missing or absent input, grouped by state ([missing values](../missing-values.md) says what each word means). `--write` writes them to `claims/policies.claims.yaml` under their record names (`missing[x]`, `missing[xs, null]`, `absent[x]`, `absent[d.note, unset]` for a key along a path), each with a note saying where it came from. A row the code contradicts is written too, its note saying so with the date, and the write line names the three ways out: change the word, change the code, or accept it as a discovery. A raise no claim accounts for has no word to write; the write line names the claim to state instead. Changing a policy is then editing one word. ## Where suggestions live (and where they never do) Suggestions are helpers for authoring standard claims, determinism, reproducibility, domain safety, a missing-value policy, inferred from the function's structure and types. They are rendered for a decision, not recorded as fact: - A verified record (`.mathema/verified/`) never contains a suggestion. `mathema check` displays suggested claims' adjudications so you can see whether one is worth adopting, but only claims you actually stated gate an exit code. A *falsified* suggestion is still shown prominently: it's real knowledge about the function, and a reason not to adopt. - The declared layer is a consolidation of authoring surfaces (docstring claims, decorators, declared YAML), so an adopted suggestion goes there, as an ordinary declared claim in `claims/adopted.claims.yaml`, indistinguishable from one you wrote by hand, and gated like one from then on. ## Worked example `functions.py` holds the `softmax` from the [`check` worked example](check.md#worked-example-softmax-start-to-finish), without its `Claims:` block: <!-- example: adopt file=functions.py --> ```python import math from typing import Annotated from mathema.types import Shape def softmax(scores: Annotated[list[float], Shape("n")]) -> Annotated[list, Shape("n")]: """Turn a vector of real-valued scores into a probability distribution.""" if not scores: raise ValueError("softmax needs at least one score") m = max(scores) exps = [math.exp(s - m) for s in scores] total = sum(exps) return [e / total for e in exps] ``` <!-- example: adopt session --> ``` $ mathema claims functions.softmax functions.softmax: no declared claims (to list candidates, run: mathema claims functions.softmax --suggest) $ mathema claims functions.softmax --suggest functions.softmax: 9 suggested claim(s) (adopt with: mathema claims KEY --adopt NAME) effects: no side effects individual claims: - is_deterministic: f(scores) == f(scores) [route best] - is_state_safe: f(scores) == f(scores) [route best] - is_empty_safe[scores]: is_empty_safe(scores) [route examine] - is_dimension_safe[f]: is_dimension_safe(f) [route examine] - preserves_length: dim(f(scores), 0) == dim(scores, 0) [route probe] - is_permutation_of_input: sorted(f(scores)) == sorted(scores) [route probe] - preserves_type: type(f(scores)) == type(scores) [route probe] - is_sorted_output: is_sorted_output(f(scores)) [route examine] - is_missing_safe[f]: is_missing_safe(f) [route examine] $ mathema claims functions.softmax --adopt is_deterministic --root . adopted is_deterministic into ./claims/adopted.claims.yaml: f(scores) == f(scores) $ mathema claims functions.softmax functions.softmax: 1 declared claim(s) - is_deterministic: f(scores) == f(scores) [route best] functions.softmax: 1 policy row about scores confirmed by the code (to write these, run: mathema claims functions.softmax --write): holds missing[scores]: missing(f, scores) propagates [default for a list[float] slot that may be nan; confirmed on 4 calls. Change the word to raises or drops if f should do otherwise; to keep it, run: mathema claims functions.softmax --write] ``` The adopted stanza is plain declared-claims YAML, so it's yours to edit or delete like anything else in the file: <!-- example: adopt run --> ```bash cat claims/adopted.claims.yaml ``` <!-- example: adopt output --> ```yaml functions.softmax: claims: - name: is_deterministic statement: f(scores) == f(scores) route: best grammar: mathema ``` ## The three sections `--suggest` lists its suggestions in three sections. - **Individual claims** stand alone: each answers a question no other suggestion answers. - **Questions with candidate answers.** The battery volunteers every candidate it knows, so a scalar function earns both monotonicity directions and all three curvature answers per parameter. Those are not independent claims: `monotonic_increasing[x]` and `monotonic_decreasing[x]` answer one question (which way does f move in x), and `affine[x]`, `convex[x]`, `concave[x]` answer another (which way does f bend in x). Each question is listed by its `aspect[target]` (`monotonicity[x]`, `shape[x]`, `symmetry`) with its candidate answers under it. More than one answer may hold (an affine function is convex and concave too), so adopt every answer that does; they are never contradictions. The table is `mathema.families.CLAIM_ASPECTS`. - **Likely to be unknowable.** `is_state_safe`, `is_deterministic` and `is_reproducible` are decided by reading the function's source. When that reading meets something it cannot read (`getattr`, a library function it has no entry for), the suggestion is listed here with that reason on the line below it. It is never adopted unless named. The effects the reading finds are always shown, on a line under the count. `is_state_safe` is suggested only for a function with no side effects at its default values: when the reading already sees a write, the effects line states it and there is nothing to adopt. For a function that stores a rate in the environment: <!-- example: env-write file=rates.py --> ```python import os def remember(rate: float) -> float: """Store the rate for later runs and return it.""" os.environ["R"] = str(rate) return rate ``` <!-- example: env-write run --> ```bash mathema claims rates.remember --suggest --root . ``` <!-- example: env-write output match=subset --> ```text rates.remember: 12 suggested claim(s) (adopt with: mathema claims KEY --adopt NAME) effects: changes os.environ (os.environ['R'] = ...) individual claims: ``` A stronger relation, a genuine contradiction where adopting a second member is not a refinement but a conflict, lives in the separate `mathema.families.EXCLUSIVE_GROUPS`: `--adopt` refuses a member whose exclusive group already has a declared member, naming the clash. No exclusive group is populated today, since every shipped family that shares a question does so as alternatives (affine implies both convex and concave, so those three are alternatives, not rivals), not as a contradiction. ## Relation to `enforce_domain` The [`enforce_domain` decorator](../authoring.md) works from the same declared layer in the other direction: it reads every parameter interval already declared on the function's claims and wraps the function with runtime guards, so arguments outside the declared domain raise `DomainError` instead of silently computing. A function whose domain is actually enforced has answered the domain-safety question a suggestion would otherwise be asking. ## `--format json` `mathema claims KEY --suggest --format json` emits the suggestions columnar, the same shape and columns the MCP `suggest_claims` tool returns: ``` cols: ["name", "statement", "route", "declared", "aspect", "section", "reason"] ``` `declared` is true when that name is already in the declared layer, and `aspect` names the question a suggestion answers (`""` when no other suggestion answers it, a computed-empty value, never null). `section` is `individual`, `question` or `unknowable`, and `reason` is the one-line reason for an `unknowable` row (`""` on every other row). `--output FILE` writes it to a file instead of stdout. - docs/modes/compendium.md (8031 bytes)
# `mathema compendium` A compendium is a claims file about a library's functions rather than your own (see [Claims transfer](../claims-transfer.md#in-the-compendium)). This verb has three actions: `status` and `update`, for a project that calls libraries, and `export`, for a library author publishing their own verified claims. ```bash mathema compendium status [<library>] [--root .] [--json] mathema compendium update [--root .] [--dry-run] mathema compendium export <library> [--out PATH] [--root .] ``` ## `status`: where the project stands with each library `status` reads every function the project's stores know, resolves each call it makes through its import aliases (`np.sqrt` is `numpy.sqrt`), and reports on every third-party library called. Standard-library calls are left out: `math`'s claims ship with mathema and are adjudicated like any others, but a standard library is not something you install or pin. For each library it prints one block, the most called first, headed by the library, its installed version and the number of calls (`numpy 2.5.3: 4 calls`, a call counted once per function that makes it): - the claims files about it, bundled with mathema or in your project, each with its `versions` range and whether the installed version is in range; - each called function that has rows, with how many are **verified locally** (proven or holds in this project's store), **trusted** (accepted with `mathema accept ... --as trusted`, at the level accepted), **falsified**, and **unsettled** (not yet adjudicated here, or adjudicated without a verdict), and under it a `not registered:` line for each row whose region cannot be stated over the call's arguments, with the reason. Such a row adds no guard. A row of your own claims file is also reported by a warning when it is loaded; a row mathema ships is reported here only; - the called functions no claims file states anything about. Two functions calling numpy, verified: <!-- example: status file=quant.py requires=numpy --> ```python import numpy as np def to_angle(x: float) -> float: """The angle whose sine is x.""" return float(np.arcsin(x)) def spread(x: float) -> float: """The square root of x, plus the mean of a unit grid.""" grid = np.linspace(0.0, 1.0, 5) return float(np.sqrt(x)) + float(np.mean(grid)) ``` <!-- example: status file=claims/quant.claims.yaml --> ```yaml quant.to_angle: claims: - name: bounded statement: "for x in [-1, 1], -2 <= f(x) <= 2" quant.spread: claims: - name: nonneg statement: "for x in [0, 4], f(x) >= 0" ``` <!-- example: status run --> ```bash mathema verify --root . > /dev/null mathema compendium status --root . ``` <!-- example: status output match=subset --> ``` claims files: mathema/compendium/numpy/bounds.claims.yaml (bundled, >=1.24,<3, in range) mathema/compendium/numpy/definitions.claims.yaml (bundled, >=1.24,<3, in range) mathema/compendium/numpy/reductions.claims.yaml (bundled, >=1.24,<3, in range) mathema/compendium/numpy/scalars.claims.yaml (bundled, >=1.24,<3, in range) numpy.arcsin 1 call, 2 rows: 2 verified locally, 0 trusted, 0 falsified, 0 unsettled numpy.mean 1 call, 6 rows: 6 verified locally, 0 trusted, 0 falsified, 0 unsettled numpy.sqrt 1 call, 2 rows: 2 verified locally, 0 trusted, 0 falsified, 0 unsettled no claims: numpy.linspace ``` `numpy.linspace` is called and nothing states a claim about it, so its failures are a black box to mathema. Writing the rows you rely on into `claims/numpy.claims.yaml` (a file with `compendium: numpy`) closes that gap, and `mathema verify` adjudicates them against the numpy you have installed. `status` reads the stores and claims files and writes nothing. `--json` prints the same report as data, and a library name confines it to that library. ## `update`: rows for the calls the project makes A library row states what a function does at its defaults. A call that passes something else, `np.mean(a, axis=1)` rather than `np.mean(a)`, is a different computation, and no row speaks for it until one pins the argument. `update` reads every call the project's functions make to a library function that has rows, the positional and keyword arguments as written, and for each call that passes a non-default literal no row pins yet it copies each of the function's rows with the arguments bound first: ```yaml numpy.mean: claims: - name: "is_defined" statement: "dim(a) >= 1" - name: "is_defined@axis=1" statement: "let axis be 1, dim(a) >= 1" note: "pinned for the call in quant.rows_mean (line 14), which passes axis=1" ``` A pinned row is named after the row it copies and the arguments it pins, `<row>@<parameter>=<value>`, with a comma between pins (`is_defined@axis=1,ddof=1`). A bracket after a claim name means something else: it names the computation a companion claim runs in (`[float]`). The rows go into the project's compendium file for the library, `claims/numpy.claims.yaml`, created with `compendium:` and a `versions:` range from the installed version when the project has none. Adding a function to that file shadows the bundled entry for it, so the bundled rows are copied in beside the pinned ones. New rows are unverified until `mathema verify` adjudicates them. An argument that is not a literal (`axis=k`) cannot be pinned, and `update` says so rather than guessing a value. A row can carry its own `versions:` range, which overrides the file's for that row. A row whose range excludes the installed version is still adjudicated by `mathema verify` when the project calls its function, and is never used as a fact (a guard, a sampling hint) meanwhile. Once verify has recorded such a row holding or proven on the installed version, `update` widens the row's range just enough to include it (`<2` becomes `<2.6` on numpy 2.5). A row of a function the project does not call keeps its range. `update` prints every change it makes, and writes nothing with `--dry-run`. Run it again and a call its rows already cover changes nothing. A rewritten file keeps the comment block at its top; any other YAML comment is lost, and `update` warns, naming the file, when a file it rewrites (or would, under `--dry-run`) has one. Keep a row's annotation in its `note:` field, which survives every rewrite. ## `export`: publishing a library's verified claims `export` is for the author of a library. Once `mathema verify` has run on your own package, its verified store holds your functions' proven and held claims. `mathema compendium export mylib` writes them as a compendium claims file (`compendium: mylib`, `versions: ">=<installed major.minor>"`), by default to `claims/mylib.claims.yaml` under `--root`, each row carrying the verdict it reached as its claimed level and the note your claims file gives it. Ship that file and a downstream project that calls your library drops it into its own `claims/` directory, where it reads exactly like a bundled one: its rows are testimony until the downstream `mathema verify` adjudicates them against the version installed there, or someone accepts them as trusted. The details are in [Claims transfer](../claims-transfer.md#out-exporting-your-own-verified-claims). An export transfers claims with a package to the projects downstream that consume it. It changes nothing for the package itself: in the package's own repository, a compendium file naming the package (`compendium: mylib` inside `mylib`'s project) is ignored, because there the claims are first-party, stated in the ordinary claims files and recorded in the verified store. `mathema verify` prints a note naming the ignored file. ## Installing third-party claims files mathema bundles claims files for the most used libraries (`math` and `numpy` today). Installing claims files for other libraries, published by their authors or by anyone else, through this verb is planned. Until then, a library's claims file goes into your project's own `claims/` directory by hand. - docs/modes/coverage.md (8113 bytes)
# `mathema coverage` Implementation coverage: the share of each function's own statements that some evidence has exercised. Three sources count, and their union is the score: a test run that executed the line, read from a coverage report that already exists; a mathema probe that executed it while checking the function; and a proof of a claim included for the function, which counts the lines the proof modelled (the whole body, unless the proof was over part of the domain and names its branches). A proof is one on the derive route or one from the function's structure (the examine route). A claim is included when it is declared on the function (a docstring or decorator claim), when it sits in a claims file, or when it is a suggestion you adopted into a claims file or accepted with `mathema accept --as evidence`. Wherever it lives, a claim counts only once it has a verified record (`mathema verify`, or `write_spec` for a claim in a docstring): the coverage run's own proof never counts until then, so coverage never certifies itself. The standard claims `coverage` checks while tracing, and suggestions nobody adopted, never count as proofs. ```bash mathema coverage [targets] [--root .] mathema coverage --stamp [--root .] mathema coverage [targets] --run-tests ``` Omit the targets to cover every function the store knows under `--root`, the rootwide analogue of `verify`. This is a separate pass, never part of `check`, and needs no third-party dependency: the probe source traces with the standard library and the statement count comes from the `ast` module. The `coverage` extra is needed only to read a native `.coverage` report; a `coverage.json` export is read without it. ## Arguments | Flag | Meaning | |---|---| | `targets` | importable module or package names; omit for every function the store knows | | `--root ROOT` | project root holding `.mathema/` and any coverage report to merge | | `--stamp` | record the content hash of every source file the existing report measured, so its freshness is judged by content rather than file times; run it after the tests that produced the report | | `--run-tests` | first re-run the project's tests under coverage to refresh the test source; needs the `coverage` extra | ## One line per function Each function gets one line: the percentage, the key, the sources that covered it in brackets and, below 100, the one action that would raise the score most. The running example is a ledger: a settlement function with a `gross` mode, and a running total with a proven claim. <!-- example: cov file=ledger.py --> ```python def settle(exposure: float, mode: str = "net") -> float: """The settlement amount for a signed exposure. Claims: nonneg: f(exposure, "net") >= 0 """ amount = abs(exposure) if mode == "gross": return amount * 1.5 return amount def running_total(xs: list, y0: float) -> float: """Add every value in xs to a starting balance y0. Claims: shifts_with_start: f(xs, y0) == f(xs, 0) + y0 """ total = y0 for v in xs: total = v + total return total ``` A proof counts only once the claim has a verified record, so record the two docstring claims first (`mathema verify` then keeps the records current): <!-- example: cov run requires=coverage --> ```python import mathema from ledger import running_total, settle for fn in (running_total, settle): mathema.write_spec(fn) ``` <!-- example: cov run --> ```bash mathema coverage ledger --root . ``` <!-- example: cov output --> ```text 100% ledger.running_total [probe+derive] 75% ledger.settle [probe] -> add a claim or test exercising line(s) 9 implementation coverage: 88% ``` `running_total` is covered twice over: the probe ran every line while checking `shifts_with_start`, and the claim, recorded and proved on the derive route, counts the whole body. `settle` is at 75%: nothing that ran the function passed `"gross"`, so line 9 was never reached, and the remedy names the line. The project figure is weighted by statements, not averaged over functions. ## The test source The tests you already run count too. mathema reads a coverage report that exists at the root, `coverage.json` first, then a native `.coverage`, and never runs your tests unless you ask with `--run-tests`. A test of the `gross` mode, run under coverage, reaches line 9: <!-- example: cov file=test_ledger.py --> ```python from ledger import settle def test_gross_settlement(): assert settle(-100.0, "gross") == 150.0 ``` <!-- example: cov run --> ```bash python -m coverage run -m pytest -q test_ledger.py python -m coverage json -q mathema coverage ledger --root . ``` <!-- example: cov output match=subset --> ```text 1 passed in 0.02s 100% ledger.running_total [probe+derive] 100% ledger.settle [test+probe] implementation coverage: 100% test report freshness: by file modification time (to judge by content, after the tests run: mathema coverage --stamp) ``` ## When a report stops counting A report keys its lines by line number, so once a source file changes those lines can point at the wrong statements. A stale file's lines are left out of the score and reported as reclaimable by a re-run of the tests. Freshness is judged per source file in one of two ways, and the last line of the report says which: - **by file modification time**, when there is no stamp: a file is stale when it was modified after the report was written. That is reliable only on the machine that ran the tests, because a checkout resets file times. - **by content hash**, once the report is stamped: `coverage.sources.json` beside the report holds the sha256 of every file it measured and of the report itself, so a file's lines count exactly while its content still matches, in a fresh checkout or a CI artifact as much as here. A stamp written for a different report is ignored. <!-- example: cov run --> ```bash mathema coverage --stamp --root . ``` <!-- example: cov output --> ```text stamped coverage.sources.json: the report's freshness is now judged by each source file's content hash ``` Add a flat fee to `ledger.py` and the report is stale for that file: <!-- example: cov file=ledger.py --> ```python def settle(exposure: float, mode: str = "net") -> float: """The settlement amount for a signed exposure. Claims: nonneg: f(exposure, "net") >= 0 """ amount = abs(exposure) if mode == "gross": return amount * 1.5 return amount def running_total(xs: list, y0: float) -> float: """Add every value in xs to a starting balance y0. Claims: shifts_with_start: f(xs, y0) == f(xs, 0) + y0 """ total = y0 for v in xs: total = v + total return total def fee(x: float) -> float: """A flat fee.""" return 2.0 ``` <!-- example: cov run --> ```bash mathema coverage ledger --root . ``` <!-- example: cov output --> ```text 100% ledger.fee [probe] 100% ledger.running_total [probe+derive] 75% ledger.settle [probe] -> re-run tests: reclaims +25% (stale coverage report) implementation coverage: 89% (up to 100% after re-running the tests) test report freshness: by content hash (coverage.sources.json) ``` The test lines for `settle` are not lost, only set aside until the tests run again. `--run-tests` does that in one step: it re-runs the tests under coverage, combines the data files a parallel or subprocess run leaves behind, exports the report and stamps it. A report made by another tool, `pytest --cov` in CI for example, needs `mathema coverage --stamp` run once afterwards in the same tree. ## Where the number goes The project figure is the implementation corner of the [badges](badges.md), which come from `mathema-ci measure` (the built-in `mathema badges` is off unless `MATHEMA_BADGES=on` is set), and the MCP tool `implementation_coverage` returns the same per-function rows to an agent. mathema's own functions get no probe source when mathema measures itself, since a probe's lines cannot be told apart from the machinery's; test and derive lines still count. - docs/modes/describe.md (7335 bytes)
# `mathema describe` The read-only look at what mathema sees in your code. Nothing is adjudicated, nothing is written, and no claim is checked: `describe` answers "what is here, and what does mathema make of it" before you commit to the cost of `check` or `verify`. ```bash mathema describe TARGET... [--root .] [--tier NAME|1-5] [--depth 3] mathema describe TARGET --issue [--include-source] [--include-falsified] ``` ## Two modes, chosen by the target A target that resolves to **exactly one function** (a full dotted key like `funcs.midpoint`, or the `module:name` shorthand) prints that function's detail view. Anything else, a package, a module, several targets, lists every function found, one per line, with its rendered signature. With the [tutorial](../tutorial.md) project's `funcs.py`: <!-- example: tutorial file=funcs.py --> ```python def settle(x: float) -> float: """Settlement amount for a signed exposure x.""" return x def midpoint(a: float, b: float) -> float: """The midpoint of two values.""" return (a + b) / 2.0 ``` <!-- example: tutorial run --> ```bash mathema describe funcs ``` <!-- example: tutorial output --> ```text funcs.midpoint(a: float, b: float) -> float funcs.settle(x: float) -> float 2 functions found ``` That list is deliberately lighter than [`mathema audit`](audit.md): no declared-claims lookup, no coverage report, no docstring scoring, no derivability analysis. It is discovery plus a signature, which makes it the cheap way to check that a target string resolves to the functions you meant before pointing an expensive verb at it. ## The detail view Here the tutorial's `claims/demo.claims.yaml` also gives `midpoint` a `mean_bound` claim: <!-- example: tutorial file=claims/demo.claims.yaml --> ```yaml funcs.settle: claims: - name: nonneg statement: "for x in [-5, 5], f(x) >= 0" route: probe - name: symmetric_in_sign statement: "for x in [-5, 5], f(x) == f(-x)" route: probe - name: negative_exposure_negative statement: "for x in [-5, -1], f(x) <= 0" route: probe funcs.midpoint: claims: - name: commutative statement: "f(a, b) == f(b, a)" route: derive - name: mean_bound statement: "for a in [0, 1], b in [0, 1], f(a, b) <= 1" ``` and after one sweep: <!-- example: tutorial run --> ```bash mathema verify --root . ``` <!-- example: tutorial session match=subset --> ``` $ mathema describe funcs:midpoint funcs.midpoint(a: float, b: float) -> float sig_hash: 6e64b8a7a1f0 form_hash: py:fc59a558f9d7 Domains: (none inferred) Claims: commutative: f(a, b) == f(b, a) [proven] latex: f{\left(a,b \right)} = f{\left(b,a \right)} mean_bound: for a in [0, 1], b in [0, 1], f(a, b) <= 1 [proven] latex: \forall a \in \left[0, 1\right],\ b \in \left[0, 1\right]:\ f{\left(a,b \right)} \leq 1 Concepts: symmetry ``` The two hashes are the identity a record binds to: `form_hash` over the function's structure (a rename or a reformat leaves it alone, a behavior change does not) and `sig_hash` over its parameter shape. Domains are listed with the source each was inferred from, so a domain that came from a claim is distinguishable from one read off a guard in the code. Claims come from the declared and verified layers together, each showing its verified verdict when a record exists for it. Below the claims, the detail view may print `careful:` lines: edges mathema knows about that lie just outside a domain the function declares, where a claim over that domain passes but a slightly wider one would not. A function calling `np.exp(x)` with a claim over `[0, 700]` gets `careful: numpy.exp overflows past x = 709.78 (the domain stops at 700)`. The edges are a covered library call's overflow-safe region (from its compendium), a restricted builtin's range (`sqrt needs x >= 0`), and a pole of the lifted body, and an edge is shown only when it lies within a factor of 10 of the nearest bound, or within 1 of a bound near zero. A claim whose recorded verdict is `falsified` contributes no line, since its domain does not pass. The lines are information only: they are never a verdict, never gate anything, and appear nowhere but `describe`, not in `check`, `verify` or the record. ## The tier ladder The detail view then prints the same function at each of five tiers, which is the derive route's own pipeline made visible: | Tier | Name | What it shows | |---|---|---| | 1 | `source` | the function body as written | | 2 | `normalized` | parameters renamed to positional `v0`, `v1`, ... | | 3 | `structural` | the statement skeleton with expressions dropped | | 4 | `lifted` | the sympy expression tree the body lifted to | | 5 | `canonical` | that tree simplified | With `--tier`, the header above is followed by that one tier alone (shown here without the header): <!-- example: tutorial session match=subset --> ``` $ mathema describe funcs:midpoint --tier lifted --- lifted --- Add Mul Half(1/2) Symbol(a) Mul Half(1/2) Symbol(b) ``` `--tier` takes either the name or the ladder position (`--tier 4` is `--tier lifted`), and without it all five print in order. A tier that is unavailable prints its own real reason rather than a silent gap, which is usually the fastest way to see *where* in the pipeline a function stops being derivable, if `lifted` reports a blocker, the matching [reason code](../reason-codes.md) explains it and says whether it is actionable. `--depth` controls how far callees are inlined while building the ladder (default 3). ## `--issue` A structured failure report for exactly one function, printed and then offered for writing under `.mathema/issues/`: ```bash mathema describe funcs:settle --issue ``` It collects the reason codes, the blocked constructs, and the claim state into one payload you can paste into a bug report. `--include-source` adds the function's source to that one payload and is never remembered between runs; `--include-falsified` widens the report to an undiagnosed falsified claim, where the default covers only skipped ones. Declining the write, or running it on a function that turns out to be perfectly derivable, is a normal outcome and exits 0. It never makes a network request: the payload is yours to send, or not. ## Arguments | Flag | Meaning | |---|---| | `target` | importable module, package, or `module:function` name(s), the same convention as `audit` | | `--root` | project root to import targets relative to (default: the nearest ancestor holding `.mathema/` within the enclosing git repository, else that repository, else `.`; never the home directory) | | `--tier` | narrow the ladder to one tier, by name or by position 1-5 (single-function mode only) | | `--depth` | callee-inlining depth for the ladder (default 3, single-function mode only) | | `--issue` | build the structured failure report for one function | | `--include-source` | with `--issue`: include the source in this one payload | | `--include-falsified` | with `--issue`: also report an undiagnosed falsified claim | ## Exit codes `describe` reports rather than gates, so a successful run is always 0, including the run that finds no functions at all. A target that does not resolve exits 2, like every other verb (see [exit codes](../cdd.md#exit-codes)). - docs/modes/docsync.md (7391 bytes)
# `mathema docsync` The sync pass over the layered store. Authoring surfaces are transitory input; the declared layer is the materialized intermediary; the verified layer is the append-only memory; the index is the generated map. `docsync` is the verb that keeps them coherent. ```bash mathema docsync [mypkg ...] [--root .] [--yes] [--write-docstrings] [--report] [--write] ``` ## The layer model - **Authoring surfaces**: docstrings (`Intent:`/`Claims:`/`Notes:`/ `Concepts:` blocks and inline `#tag` spellings), decorators, claims files, module docstrings, READMEs. All input, all transitory. - **Declared layer** (`.mathema/declared/<key>.yaml`): a **materialized view**, the canonical rendering of every surface merged, regenerated by this verb. It is output, never input: people and agents read it (the index points here for the complete claim set per function), the engine never does, and an edit made in it is overwritten at the next sync without ever taking effect. To change a claim, edit an authoring surface. - **Verified layer** (`.mathema/verified/<key>.yaml`): machine-written records, append-only in membership: a claim, once verified, never vanishes. Deleting it from every authoring surface just means the next sweep repopulates it from the record and keeps adjudicating (its exits are the discovery flow, `mathema accept --as historical`, or `--as superseded`, never silent removal). A quantified derive row carries its region as a rendered `condition` (`∀ x ∈ [0.0, 5.0] ⊂ ℝ ∪ {∅}`), the proof's own quantifier; a probe row carries none, since there it would only restate the statement and domain. Grammar output round-trips, so the rendered region is the canonical form and repopulation parses it back. Records carry the git commit at adjudication and an [integrity checksum](../governance.md#the-integrity-checksum) over each claim's statement, verdict and acceptance, and over the retirement rows; a hand-edit is reported as "altered outside mathema" (an acceptance write is mathema's own hand and restamps). Concepts are the one deliberate exception to append-only: recomputed fresh each run, since tags are removable context, not evidence. - **Curation** (`.mathema/meta/`): the small human-decision files, `concepts.yaml` (dismissed suggestions, per key) and `intent.yaml` (module- and project-scope intent acceptances). - **Record file names**: `<key>` in both layers is the function key with every character other than a letter, a digit or one of `_.-~` percent-encoded. A dotted key keeps its spelling (`.mathema/verified/pricing.discounted.yaml`), and a key holding `/`, `:` or `#` is one file directly in the layer: the key `lang:src/ema.src#ema` is `.mathema/verified/lang%3Asrc%2Fema.src%23ema.yaml`. The key itself is also the top-level field of the record, which is where a reader takes it from. A record still under its earlier file name (the key used as the path as it stood) is read, and renamed the next time that layer is written. - **Index** (`.mathema/index.yaml`): generated, system intent (top README), module intents (module docstrings/READMEs), function intents, keys, a sed-ready `span` per function, verified-record paths, concepts, and each scope intent's acceptance rung. The whole `.mathema/` directory is part of the source tree: commit it, so the verified layer travels with the code it is evidence about. ## What one run does 1. Materializes every function's declared entry, docstring intent winning over a declared-file intent (the declared intent is the skeleton only when no docstring exists). 2. Surfaces **conflicts** in the three-tier model. A claim name has one owner per state: - Name **in the verified layer**, authored differently anywhere: the record wins; the verified version keeps adjudicating and reverse-syncs into the declared layer; adopting the change is the explicit `mathema accept <key> <claim> --as superseded` ([accept](accept.md#-as-superseded)). docsync prints the command, never resolves this itself. - Name **not yet verified**, docstring and declared file disagree: a per-conflict prompt shows both versions and lets you keep either (`[d/f/s]`); the docstring's version is written into the declared file structured (domain field), never as display text, and its route tag transfers only when the docstring stated one explicitly. `--yes` takes the docstring everywhere. The declared file is rewritten from its parsed form, so YAML `#` comments in it do not survive; docsync warns before writing such a file. Keep a claim's annotation in its `note:` field instead, which persists through every rewrite (see [authoring](../authoring.md#4-a-claims-file-on-disk)). - Name **unknown everywhere**: added to declared, no ceremony. An unresolved conflict of either kind is a `verify` gate failure. 3. Reports **docstring drift**: Claims:-block names unknown to declared∪verified, and verified claims not listed in the block. 4. Regenerates the index. ## Editing source is always explicit The default run never touches a `.py` file. `--write-docstrings` appends verified-but-unlisted claim names (with canonical statements) to an EXISTING `Claims:` block; it never creates a block and never rewrites a human's prose; the claim NAMES are the keys, the statement text in a docstring is free for humans to rephrase (the docstring is not the record). `--write` offers a generated docstring for functions that have none, prompted per function. `--report` prints the per-function sync checklist. ## The score The audit `docsync` column (in the grid by default, `--exclude docsync` to skip) measures the docstring against the OTHER layers, not just itself: Intent/Claims/symbol coverage, intent conciseness, intent-in-sync with the declared layer, Claims-block-in-sync (names known, zero conflicts), raises coverage (claim-first), domain declared/enforced, typing, callee documentation (direct callees only, a central undocumented callee already compounds through each caller's own row, so depth adds noise, not signal). The claim triplet `{floor | actual | expected}` reads declared∪verified and stays informational; a stale verified record (form changed since it was written) is flagged, never silently used. ## Intent and acceptance An intent's docstring SHAPE is labelled `explicit` (the paragraph following an `Intent:` marker) or `implicit` (the first paragraph stands in); the same rule reads module docstrings and README sections. Shape is not rung: both start at `declared`, and `documented` is a human act: ```bash mathema accept mypkg.mod.fn --intent --by "lovelace" ``` The acceptance binds to the signature, the raised-exception surface, and the intent text; a body-only refactor keeps it; changing any of the three marks it stale and drops the rung until re-accepted. The same verb accepts scope intents (`mathema accept mypkg.mod --intent`, `mathema accept __project__ --intent`), bound to the text alone and stored in `.mathema/meta/intent.yaml`; the index annotates each scope with `documented` or `stale`. Concepts ride the same verb: `--concepts a,b` earns tags the documented rung, `--dismiss-concepts c` records a dismissal in `.mathema/meta/concepts.yaml` so the suggestion never returns. - docs/modes/init.md (6970 bytes)
# `mathema init` Additive and idempotent setup: scaffold the git ergonomics for a tracked `.mathema/` store; for any targets, stub scaffolding for the unclaimed functions [`mathema audit`](audit.md) finds (a concrete, enumerated task list to fill in, not a claim itself); and, on request, vendor the [mathema-agents](https://github.com/tetrionlabs/mathema-agents) skills for your agent tool. ```bash mathema init [mypkg mypkg.sub ...] [--agents [TOOL]] ``` ## Arguments | Flag | Meaning | |---|---| | `target` | zero or more importable module or package name(s), same as `audit`; omit to scaffold only the git files | | `--root` | project root to write `.gitattributes`, `.mathema/.gitignore`, and `claims/` under (default: the nearest ancestor holding `.mathema/` within the enclosing git repository, else that repository, else `.`; never the home directory) | | `--agents [TOOL]` | also vendor the mathema-agents skills for TOOL (`claude`, `codex`, `gemini`, `cursor`, `copilot`, `windsurf`, `cline`); bare `--agents` auto-detects the one your project already uses | | `--agents-url` | git URL for the skills repo (default the public mathema-agents repository; also read from `MATHEMA_AGENTS_URL`) | | `--agents-ref` | branch or tag of the skills repo to fetch (default: the branch matching your mathema minor line, such as `v0.6`, falling back to the repo's default branch); an explicit ref is never substituted | | `--force` | overwrite vendored agent files that already exist (default: leave them) | | `--ci [PROVIDER]` | also scaffold the verify-gate CI fragment (`github`, `gitlab`); bare `--ci` means github. Written only where absent, then it is yours to edit | ## The git scaffold With or without a target, `init` writes (only where absent) the two files a tracked store wants: - **`.gitattributes`** marking `.mathema/verified/**/*.yaml` `linguist-generated`, so a records diff collapses by default and the store drops out of the repository's language stats, while staying expandable when you do want to read it. (`linguist-generated`, not `-diff`: the record stays reviewable.) - **`.mathema/.gitignore`** tracking the durable evidence and required artifacts (`verified/`, `meta/`, `badges/`) and ignoring regenerated state (`declared/`, `issues/`). The evidence is meant to be committed: a verified record is the durable statement of what was checked, and reviewers read it (by claim, with [`mathema review`](review.md)) the way they read tests. A project that would rather regenerate the store from its examples and tests can ignore all of `.mathema/` instead; that is a local choice, not the default. ## The function stubs For every discovered function with zero claims, writes a bare `claims: []` declared entry, an explicit, empty placeholder, not a claim, to `claims/<module>.claims.yaml`. Given a package whose one module holds two unclaimed functions: <!-- example: stubs file=mypkg/__init__.py --> ```python """A small package.""" ``` <!-- example: stubs file=mypkg/mod.py --> ```python def pure_fn(x: float) -> float: return 2.0 * x + 1.0 def branchy_fn(x: float) -> float: if x < 0: return -x return x ``` <!-- example: stubs session --> ``` $ mathema init mypkg mathema init: scaffolded git files: .gitattributes .mathema/.gitignore mathema init: wrote stub entries to: claims/mypkg.mod.claims.yaml $ cat claims/mypkg.mod.claims.yaml # mathema init: bare declared stubs for mypkg.mod (fill in claims; an empty list means nothing declared yet) mypkg.mod.branchy_fn: claims: [] mypkg.mod.pure_fn: claims: [] ``` Additive and idempotent by construction: reads any existing file first and only appends keys not already present (claimed *or* already stubbed), so a hand-written claim sitting next to a stub is never touched by a later re-run as the target package grows. Running it again once the git files are in place and every stub has either been filled in or left alone: <!-- example: stubs session --> ``` $ mathema init mypkg mathema init: git files already in place mathema init: no stubs needed, every discovered function already has a claim, or none were found mathema init: nothing to do ``` ## The agent skills (`--agents`) `mathema init --agents <tool>` vendors the [mathema-agents](https://github.com/tetrionlabs/mathema-agents) skills, the agent-facing procedures for writing and checking claims, and copies the one adapter your tool reads. Where each piece lands depends on the tool, so name yours (or let bare `--agents` detect it): | tool | `skills/` lands in | adapter copied | |---|---|---| | `claude` | `.claude/skills/` | (none; the skills dir is the adapter) | | `codex` (also `zed`, `aider`, `jules`) | `./skills/` | `AGENTS.md` | | `gemini` | `./skills/` | `GEMINI.md` | | `cursor` | `./skills/` | `.cursor/rules/` | | `copilot` | `./skills/` | `.github/copilot-instructions.md` | | `windsurf` | `./skills/` | `.windsurf/rules/` | | `cline` (also `roo`) | `./skills/` | `.clinerules/` | ``` $ mathema init --agents claude mathema init: git files already in place mathema init: vendored mathema-agents skills for claude: .claude/skills/clear-the-gate/SKILL.md .claude/skills/design-claims/SKILL.md .claude/skills/start-from-claims/SKILL.md .claude/skills/use-mathema-mcp/SKILL.md from v0.6, matching mathema 0.6.6.2 ``` The last line names the skills branch fetched: the one matching your mathema minor line, or the repo's default branch when that line has none yet. Only the skills and your tool's adapter are copied, never the skills repo's own notes or history; every copied file carries its Apache-2.0 licence line. A file already present is left as it is (`--force` overwrites), so a re-run is safe and a local edit survives. Bare `--agents` with no tool detected (or several) vendors `skills/` neutrally and prints the table above so you finish by hand. **mathema reaches the network only when you ask it to.** Every other command is offline; `--agents` is the one that fetches, and it does so through your `git`, so a fork or mirror named with `--agents-url` works whenever your git can read it. If the fetch cannot happen (no network, `git` missing, or you lack access to the repo), init says so plainly, prints the manual steps, and still exits cleanly, its own scaffolding is already done. ## The CI gate (`--ci`) `mathema init --ci` writes the verify-gate workflow an adopting repo would otherwise write from scratch: `.github/workflows/mathema-verify.yml` (or, with `--ci gitlab`, a `.gitlab-ci.mathema.yml` fragment plus the `include:` line to add). The job installs your project and mathema, then runs `mathema verify --root .`, whose strict default is the gate: exit 0 clean, 1 gate failure, 2 broken invocation, so CI can tell a failing gate from a broken job without parsing output. The file is written only where absent and is yours to edit from then on; the one line you will likely change is the install step, marked in the file. - docs/modes/library.md (18387 bytes)
# Library usage `import mathema` and call it directly, for interactive or programmatic use (a notebook, a script, an agent's own tool calls), as opposed to the [CLI](check.md). ## The core calls ```python mathema.claim("f(-x) == -f(x)") # state a claim mathema.check(fn, claims=[...]) # verify it, return a Record mathema.write_spec(fn, claims=[...]) # verify + write the record mathema.status() # fresh/stale sweep mathema.track_claims # optional bare tag, zero overhead mathema.claims.check(fn, [...]) # the conjecture pipeline directly mathema.registry.load_specs(root) # read the whole spec store mathema.registry.load_claims(path) # parse an authoring-shape claims file ``` ## `check(fn, claims=None, domain=None, trials=None, trials_downscale=None, extensive=False, declared=None, known_premises=None, pseudo_infinity=None, runtime_types=None, trials_scale=None)` Verify a function's claims, each adjudicated against the real function: mathema's suggested standard claims when `claims` is omitted, otherwise the claims you pass in. ```python mathema.check(ema) # suggested claims mathema.check(ema, claims=["f(x, 1.0) == x[-1]"]) # add a claim mathema.check(ema, domain={"alpha": (0, 1)}) # sample inside a declared domain mathema.check(ema, claims=["excluding"], domain={"alpha": (0, 1)}) ``` `domain` declares parameter limits, and the algebraic probes sample inside the declared domain rather than across the whole real line. Whether the code itself *rejects* an out-of-domain input is a separate question: opt into it with the `excluding` keyword, which adds an `excluded_outside_domain[param]` claim per declared parameter. Domains are per claim. `domain=` and the signature's `Annotated` markers form the function-level parent domain, which every claim inherits; a claim's own `for` binding overrides the parent for that parameter. One claim's quantifier never reaches another claim, so `f(x) >= 0` checked beside `for x in [0, 1e6], f(x) >= 0` still means every x. Each record states what it was adjudicated over: the claim's own bindings in its `domain` and `condition`, the parent's share in `meta["mathema.parent_domain"]`. The `excluding` keyword reads the parent domain only: a parameter bounded only inside one claim has no function-level outside to exclude. `trials` sets the probe's trial budget for this call (left out, mathema decides it from the function's structure and domain, see [the trial budget](check.md#the-trial-budget)). `trials_downscale`, a factor no greater than 1, shrinks the budget for a fast development loop; it never raises it. `trials_scale` is the old spelling of `trials_downscale`, still accepted with a deprecation warning until 0.7. `pseudo_infinity` is the function level of the operational infinity: how far the computation of each claim (the probe route and the computation line) is exercised along an unbounded direction, unless the claim binds its own `let |inf| be`. Left out, a `declared=` entry's `pseudo_infinity:` field applies, then the project's `MATHEMA_PSEUDO_INFINITY`, then float64's own maximum. A proof never reads it; see [operational infinity](../grammar.md#operational-infinity-let-inf-be). `runtime_types` names the [runtime type](../runtime-types.md) of a parameter whose signature names none, for code that cannot be annotated: `runtime_types={"returns": "pandas.Series"}`. Left out, a `declared=` entry's `runtime_types:` field applies. A parameter or return type hinted with a mathema type marker (`Annotated[float, Probability]`, `Annotated[list, Shape("m", "n")]`) contributes its own claims automatically; see [Authoring claims](../authoring.md). A `@claims_decorator(...)`-tagged function, or a docstring `Claims:` block, also contributes its claims automatically. `claims=` passed here is unioned with those, winning per claim name on a collision. With `claims=None` (the default), mathema also adjudicates and displays its own *suggested* standard claims (every row in the transcript below is one of these), candidates for adoption that never gate an exit code and are never written into a spec record (see [`mathema claims`](claims.md)). `claims=[]` means declared surfaces only: type markers, decorator, and docstring claims still run, but no suggestions are added. Returns a `Record`: the facts read off the function, and one `Probe` per claim adjudicated. For the exponential moving average of the [first look](../first-look.md): <!-- example: ema run slow --> ```python import mathema def ema(x: list[float], alpha: float) -> float: """Exponentially weighted moving average.""" y = x[0] for v in x[1:]: y = alpha * v + (1 - alpha) * y return y ``` <!-- example: ema repl --> ```python >>> mathema.check(ema, domain={"x": (-1e6, 1e6), "alpha": (-10, 10)}) mathema.Record(ema) · source, no side effects · form py:72e6a357d7bb monotonic_increasing[alpha] d(f(x, alpha), alpha) >= 0 falsified at alpha = 8.459992498903986 -> -4.930559650170467e+304, alpha = 8.70201321389522 -> -5.772547268351122e+304 at x = [1e+300, -1e+300, -2.7255878198803085, 1.4703849054783387, 4.922577492583454, -8.999703650149867] (not increasing) falsified computation d(f(x, alpha), alpha) >= 0 counterexample alpha = 8.459992498903986 -> -4.930559650170467e+304, alpha = 8.70201321389522 -> -5.772547268351122e+304 at x = [1e+300, -1e+300, -2.7255878198803085, 1.4703849054783387, 4.922577492583454, -8.999703650149867] (not increasing) falsified policy f(x=[]) f(x, alpha) raises IndexError at x = [], alpha = 5.159088058806049 with no emptiness guard in the body: the empty input is stumbled into, not handled possible fixes: (i) if the IndexError is the intended refusal, state: raises(ema([], alpha), IndexError) (ii) guard the empty input at entry monotonic_decreasing[alpha] d(f(x, alpha), alpha) <= 0 falsified at alpha = -9.83680626493992 -> -1796.0154991652923, alpha = 0 -> -9.630119309794798 at x = [-9.630119309794798, 6.4611233807873525, -2.4056272554860447] (not decreasing) falsified computation d(f(x, alpha), alpha) <= 0 counterexample alpha = -9.83680626493992 -> -1796.0154991652923, alpha = 0 -> -9.630119309794798 at x = [-9.630119309794798, 6.4611233807873525, -2.4056272554860447] (not decreasing) falsified policy f(x=[]) f(x, alpha) raises IndexError at x = [], alpha = 5.159088058806049 with no emptiness guard in the body: the empty input is stumbled into, not handled possible fixes: (i) if the IndexError is the intended refusal, state: raises(ema([], alpha), IndexError) (ii) guard the empty input at entry affine[alpha] d(f(x, alpha), alpha, alpha) = 0 falsified at alpha = 0.5942120819077363, h = 0.000594 falsified computation d(f(x, alpha), alpha, alpha) = 0 counterexample alpha = 0.5942120819077363, h = 0.000594: curvature estimate -4.01335 does not settle affine falsified policy f(x=[]) f(x, alpha) raises IndexError at x = [], alpha = 5.159088058806049 with no emptiness guard in the body: the empty input is stumbled into, not handled possible fixes: (i) if the IndexError is the intended refusal, state: raises(ema([], alpha), IndexError) (ii) guard the empty input at entry convex[alpha] d(f(x, alpha), alpha, alpha) >= 0 falsified at alpha = 4.553442718560774, h = 0.00455 falsified computation d(f(x, alpha), alpha, alpha) >= 0 counterexample alpha = 4.553442718560774, h = 0.00455: curvature estimate -849.761 does not settle convex falsified policy f(x=[]) f(x, alpha) raises IndexError at x = [], alpha = 5.159088058806049 with no emptiness guard in the body: the empty input is stumbled into, not handled possible fixes: (i) if the IndexError is the intended refusal, state: raises(ema([], alpha), IndexError) (ii) guard the empty input at entry concave[alpha] d(f(x, alpha), alpha, alpha) <= 0 falsified at alpha = 4.709760826489109, h = 0.00471 falsified computation d(f(x, alpha), alpha, alpha) <= 0 counterexample alpha = 4.709760826489109, h = 0.00471: curvature estimate 10716.6 does not settle concave falsified policy f(x=[]) f(x, alpha) raises IndexError at x = [], alpha = 5.159088058806049 with no emptiness guard in the body: the empty input is stumbled into, not handled possible fixes: (i) if the IndexError is the intended refusal, state: raises(ema([], alpha), IndexError) (ii) guard the empty input at entry proven is_deterministic: f(x, alpha) = f(x, alpha) proven is_state_safe: f(x, alpha) = f(x, alpha) unknown is_numerically_stable: let g = mathema.f.accurate, g(f, x, alpha) = 1 derive could not decide it; the probe could not decide it either (accuracy against the exact value is read for scalar parameters only) holds is_representation_safe[alpha]: is_representation_safe(alpha) (20 draws) holds is_dimension_safe[f]: is_dimension_safe(f) (192 draws) bounded_lower min(x) <= f(x, alpha) falsified at x = [222791.29884554766, -852156.6094995309, -647122.5636467072, -772598.9379420548, 854595.3224724911, 999998], alpha = 4.542301584683122 falsified computation min(x) <= f(x, alpha) counterexample x = [222791.29884554766, -852156.6094995309, -647122.5636467072, -772598.9379420548, 854595.3224724911, 999998], alpha = 4.542301584683122: -852156.6094995309 vs -656298366.2095869 falsified policy f(x=[]) f(x, alpha) raises IndexError at x = [], alpha = 5.159088058806049 with no emptiness guard in the body: the empty input is stumbled into, not handled possible fixes: (i) if the IndexError is the intended refusal, state: raises(ema([], alpha), IndexError) (ii) guard the empty input at entry bounded_upper f(x, alpha) <= max(x) falsified at x = [216941.53207844822, -368274.1184160299, 682330.1826507892], alpha = 1.7838785067417557 falsified computation f(x, alpha) <= max(x) counterexample x = [216941.53207844822, -368274.1184160299, 682330.1826507892], alpha = 1.7838785067417557: 1865471.1484383387 vs 682330.1826507892 falsified policy f(x=[]) f(x, alpha) raises IndexError at x = [], alpha = 5.159088058806049 with no emptiness guard in the body: the empty input is stumbled into, not handled possible fixes: (i) if the IndexError is the intended refusal, state: raises(ema([], alpha), IndexError) (ii) guard the empty input at entry permutation_invariant let g = mathema.f.reverse_seq, f(x, alpha) = f(g(x), alpha) falsified at x = [850043.9278135903, 905210.656449008, 782687.5954072354], alpha = 6.752137638609439 falsified computation let g = mathema.f.reverse_seq, f(x, alpha) = f(g(x), alpha) counterexample x = [850043.9278135903, 905210.656449008, 782687.5954072354], alpha = 6.752137638609439: -1747388.2882860936 vs -3521213.9192287754 falsified policy f(x=[]) f(x, alpha) raises IndexError at x = [], alpha = 5.159088058806049 with no emptiness guard in the body: the empty input is stumbled into, not handled possible fixes: (i) if the IndexError is the intended refusal, state: raises(ema([], alpha), IndexError) (ii) guard the empty input at entry scale_equivariant let g = mathema.f.scale_seq, let c be [-5.0, 5.0], c*f(x, alpha) = f(g(x, c), alpha) falsified at x = [], alpha = 5.159088058806049 proven mathematics let g = mathema.f.scale_seq, let c be [-5.0, 5.0], c*f(x, alpha) = f(g(x, c), alpha) holds computation let g = mathema.f.scale_seq, let c be [-5.0, 5.0], c*f(x, alpha) = f(g(x, c), alpha) 288 entries across 68 draws, sizes (1, 1) to (8, 1); differs by 0.00131 at x = [1000000.0, 1000000.0, 1000000.0, 1000000.0, -1000000.0, 1000000.0, 1000000.0, 1000000.0], alpha = -9.99998, c = -1.4095238757810247, within the default tolerance (3.75e+03) falsified policy f(x=[]) f(x, alpha) raises IndexError at x = [], alpha = 5.159088058806049 with no emptiness guard in the body: the empty input is stumbled into, not handled possible fixes: (i) if the IndexError is the intended refusal, state: raises(ema([], alpha), IndexError) (ii) guard the empty input at entry translation_equivariant let g = mathema.f.shift_seq, let c be [-5.0, 5.0], c + f(x, alpha) = f(g(x, c), alpha) falsified at x = [], alpha = 5.159088058806049 proven mathematics let g = mathema.f.shift_seq, let c be [-5.0, 5.0], c + f(x, alpha) = f(g(x, c), alpha) holds computation let g = mathema.f.shift_seq, let c be [-5.0, 5.0], c + f(x, alpha) = f(g(x, c), alpha) 288 entries across 68 draws, sizes (1, 1) to (8, 1); differs by 0.00292 at x = [906106.1434297902, -154913.5463164954, 814855.4958683907, -224511.23675302154, -399682.6736009131, -354945.7160463119, 999998.0, 105862.45522526401], alpha = -9.99998, c = 1.7939528529796345, within the default tolerance (1.91e+06) falsified policy f(x=[]) f(x, alpha) raises IndexError at x = [], alpha = 5.159088058806049 with no emptiness guard in the body: the empty input is stumbled into, not handled possible fixes: (i) if the IndexError is the intended refusal, state: raises(ema([], alpha), IndexError) (ii) guard the empty input at entry ``` Read the falsified claims as facts about `ema`, not as bugs in it. The suggestions ask standard questions of any function, and a falsified suggestion is an answer, with the witness to prove it: an exponential average really is neither monotone nor order-independent in its inputs, and it really does fail on an empty list, which every claim over `x` reports on its `policy` line. Under each claim, the `mathematics` line is the claim over the real numbers and the `computation` line is the same claim run through the real code in floating point inside the stated domain. Two of the answers change once the smoothing factor's real domain is stated. Checked with `alpha` in `(0, 1)`, the bounds that failed for an `alpha` outside it are proven outright, and their computation lines hold (an excerpt; the headline stays falsified by the emp - docs/modes/lock.md (6798 bytes)
# `mathema lock` / `mathema unlock` Permissions for the agentic age: control what an agent may change at the granularity that actually matters, the **function**. File permissions cannot do this. A file is the wrong unit: one module holds twenty functions, and making the file read-only to protect one settled implementation blocks the other nineteen, every docstring fix, and every new function anyone wants to add beside them. Git can tell you a file changed; it cannot say *which function was off-limits*, and it only speaks after the damage is committed. A lock is the granular version: this function's implementation is settled, everything around it stays editable, and the CDD loop itself enforces it. A lock records the function's form hash; from then on `mathema verify` fails if the body moves, and refuses to re-adjudicate until either the body is restored or a human unlocks. The agent iterating in the loop gets a clean, named stop instead of silently rewriting something a person had signed off. ```bash mathema lock KEY [--note WHY] [--root .] mathema unlock KEY [--root .] ``` ## What a lock pins, exactly The **body**, nothing else. The form hash is computed over the function's alpha-normalised AST with the docstring stripped, and written `py:<sha>` for a Python function (a lock taken at a bare hash by a release before 0.6.3 still holds at the same body), so: - **Docstring edits never trip a lock.** Rewriting the prose, the `Intent:`, the `Notes:`, even the `Claims:` block leaves the form hash where it was. Claims re-authored on a locked function adjudicate normally. - A rename or a reformat never trips it either, for the same reason a record's form binding survives them. - Any change to what the function *computes* trips it. ## What verify does with a tripped lock Take the [tutorial](../tutorial.md) project once `settle` is fixed: <!-- example: tripped file=funcs.py --> ```python def settle(x: float) -> float: """Settlement amount for a signed exposure x.""" return abs(x) def midpoint(a: float, b: float) -> float: """The midpoint of two values.""" return (a + b) / 2.0 ``` with its `claims/demo.claims.yaml` (the tutorial's, less the claim that was simply wrong): <!-- example: tripped file=claims/demo.claims.yaml --> ```yaml funcs.settle: claims: - name: nonneg statement: "for x in [-5, 5], f(x) >= 0" route: probe - name: symmetric_in_sign statement: "for x in [-5, 5], f(x) == f(-x)" route: probe funcs.midpoint: claims: - name: commutative statement: "f(a, b) == f(b, a)" route: derive ``` Verify it, and lock `settle`: <!-- example: tripped run --> ```bash mathema verify ``` <!-- example: tripped session --> ``` $ mathema lock funcs.settle --note "settled implementation" locked funcs.settle at form py:00e53f2b3d0a the body can no longer change under a CDD loop; docstring edits are unaffected. A human unlocks with: mathema unlock funcs.settle ``` A later loop iteration rewrites the body: <!-- example: tripped file=funcs.py --> ```python def settle(x: float) -> float: """Settlement amount for a signed exposure x.""" return x if x > 0 else -x def midpoint(a: float, b: float) -> float: """The midpoint of two values.""" return (a + b) / 2.0 ``` <!-- example: tripped session --> ``` $ mathema verify; echo $? FAIL funcs.settle: locked at form py:00e53f2b3d0a but the code is now py:f9e7630d83cd; the record is unchanged. Restore the function, or a human runs: mathema unlock funcs.settle 1 unchanged since the last run (not run again), 0 checked, 1 problem(s) grammars detected: mathema; verified by this run: mathema 2 intents to accept (2 functions): mathema accept --intent 1 ``` Three things, deliberately together: the run fails (exit 1, so a CI gate or an agent loop stops), the message names both hashes and the two ways forward, and **the record is byte-identical to before the edit**. The verified baseline never moves onto code a human did not sanction, so a failing loop cannot pile up regressions against an implementation that was never supposed to change. A function can be locked before it has any record or declared claim. The sweep checks that lock too, and a changed body fails the same way, with the line saying `there is no record to compare` in place of `the record is unchanged`. ## Who locks, who unlocks **An agent may lock.** Locking is the safe direction: a settled implementation is worth protecting from later loop iterations, and the MCP surface exposes `lock_target` for exactly that. An agent that has just proven a function's claims and locked it has done something genuinely useful: it has narrowed its own future blast radius. `pending_decisions` shows any `locked-changed` rows, so an agent always sees why its sweep is failing and what the remedy is. **Only a person unlocks.** `mathema unlock` is CLI-only, prompts `[y/N]` with deliberately no `--yes`, and, when a [PIN is configured](pin.md), requires it. The released lock leaves an audit event in the record (`lock_history`, with the `verified_by` stamp when a PIN verified it), so a reviewer can see who thawed what and when. ## Seeing what is locked `mathema audit` shows a `locked` column whenever anything in the population is locked (`yes`, with who pinned it), and counts locks in the summary line, so what is locked is visible at a glance rather than buried in a YAML file. `--compact --cols ...,locked` carries the pinned form hash for machines. ## Where the lock lives `.mathema/meta/locks.yaml`, committed with the store: ```yaml # locked functions: the form hash each is pinned at. # `mathema lock KEY` adds one; only `mathema unlock KEY` # (a human act) removes one. funcs.settle: at: '2026-09-24' by: Alan Turing form: py:00e53f2b3d0a note: settled implementation ``` The verified record carries a `locked` reflection of the same entry, covered by the integrity checksum, which is what makes hand-deletion detectable: a record that says locked with no meta entry behind it fails the sweep as a lock removed outside `mathema unlock`, and a meta entry whose `form` no longer matches the record's stamp fails it as a lock moved outside `mathema unlock`. Either way the record is left as it was, stamp included, so the failure stands on every sweep until the entry is restored or a human unlocks. ## The honest threat model An agent with unrestricted shell can edit `locks.yaml`, the record, or mathema itself, so a lock is a tripwire, not a wall. What it guarantees is that a locked body cannot change *through the normal CDD loop*: the sweep fails loudly, the record stands still, and every legitimate exit leaves a trace (the unlock event, the PIN key id). Subversion is possible and visible; that is the design. - docs/modes/mcp.md (10345 bytes)
# `mathema mcp` mathema's library surface served as MCP tools, so an agent connects to the same machinery every other mode uses, the one resolver, the one gate, the reason-code registry, instead of shelling out and parsing tables. ```bash pip install "mathema[mcp]" mathema mcp serve [--root .] ``` `serve` runs the server on stdio. Without the optional extra installed the command prints the install hint and exits 2. [Set up mathema for a coding agent](../agent-setup.md) has the configuration block for each client and the PIN and policy that go with it. ## Tools | Tool | What it does | |---|---| | `resolve_target` | any target spelling (dotted name, `module:function`, file path) to its function keys and signatures | | `adjudicate_target` | adjudicate one function, gated, with agent-shaped claim rows. `include` selects the row set: `declared` (default; what the surfaces actually state, which is what a re-check asks about), `suggested`, or `all`. Statements in `claims` are LINTED first, so a statement that does not parse comes back at parse cost with nothing adjudicated | | `adjudicate_targets` | the same adjudication over SEVERAL targets in one call, column-oriented (`{prefix, cols, rows}`): the declared and verified stores are read once for the batch instead of once per target, and one envelope is returned instead of N | | `verify_project` | the CI sweep: freshness, re-adjudication, record refresh, the gate; `keys` carries the sweep as structured per-key data (why, gate counts, claim rows) so nothing needs `lines` parsed | | `describe_target` | one function's full detail view: identity, domains, claims with verdicts, tier ladder | | `audit_targets` | the population report in the column-oriented compact shape; `cols` selects the columns, `filter` (explicit, never a default) keeps rows by derive_unlock class, claim status, or columnar substring (`blocker~loop`, `~mutual`), same-dimension terms OR together, dimensions AND across, and a filter's column references are always computed so an empty result means "nothing matched", never "never looked" | | `reason_code` | selective code lookup: names, numeric ids (`2.18`), or whole groups (`loop`, `2`), singly or comma-separated; no argument returns the compact id/code/fixable index, never the full table, the machine twin of [Reason codes](../reason-codes.md) | | `claim_grammar` | the claim-language lexicon, exactly as the library states it | | `parse_claim` | parse and validate one claim statement without adjudicating, the authoring-loop linter: resolved name/statement/relation/route/domain rendered back explicitly, or the grammar's own error. Pass `target` and it also checks the statement against that function's real signature (arity, parameter names, quantified names) by inspection | | `suggest_claims` | candidate claims for one function, `[name, statement, route, declared, aspect, section, reason]` rows, declares, never verifies, and a suggestion never gates until adopted; identical columns to `mathema claims --suggest --format json` | | `pending_decisions` | the human-decision queue, read-only: `[key, claim, kind, detail]` rows for pending supersessions, stale acceptances, stale intent acceptances, standing accepted risks, unaccepted unknowns and falsifications, locked functions whose body moved, and `moved` rows for a record whose key no longer resolves while an unrecorded function has its form hash (the detail carries the `mathema accept NEW --as reconciled --from OLD` command a human runs); acceptance and unlock themselves stay CLI-only | | `lock_target` | pin a function's form hash so `verify` fails if the body changes; the safe direction, so agents may do it. There is deliberately no unlock tool: a person runs `mathema unlock` | | `project_index` | the generated `.mathema/index.yaml` map: system/module/function intents with acceptance rungs, keys, a sed-ready `span` per function, verified-record paths, concepts; run `mathema audit --index` (or `mathema docsync`) first if it reports the index missing | | `implementation_coverage` | per-function implementation coverage without running the test suite: mathema's own probes and proofs supply the `probe` and `derive` sources, as `[key, percent, potential, sources, test_stale, traced, remedy]` rows plus the repo score; `run_tests=true` re-runs the suite under coverage first (slow, and it runs your tests) | | `badges` | by default scores nothing and returns only `notice`, the line saying badges now come from `mathema-ci measure --out`; with `MATHEMA_BADGES=on` in the server's environment, the three [badges](badges.md) (`implementation`, `intent`, `clarity`) and their `overall`, scored in worker processes and kept in the badges cache, over a target set, or rootwide when it is omitted or empty, with `[key, implementation, intent, clarity]` rows, the ASCII triangle, and `capped`, the functions a step of which stopped at the wall-clock cap | ## Which row set you get `adjudicate_target` defaults to `include="declared"`, the set a re-check after editing a claim is asking about. `include="all"` adds the suggestion battery, which is adjudicated in full, not only listed, so the call is slower and its payload larger. A function with no declared claims returns no rows plus a `hint` naming `include="suggested"`, rather than silently handing back a different kind of row than the one you asked for. ## The two agent payload shapes Adjudication rows (`adjudicate_target`, and `mathema check --format compact`) carry, per claim: `stance` (a closed four-value fold of the open verdict, `supported`/`refuted`/`undecided`/`blocked`, to branch on, with the verbatim `verdict` beside it for fidelity), `source` (which authoring surface the claim came from: `declared`, `docstring`, `decorator`, `types`, `suggested`, `builtin`, `ad_hoc`), and `gates` (whether the row counts toward `passed`, a falsified *suggestion* never does, and the flag makes that self-evident in the payload). Envelope rule: `counterexample` is present iff the row is refuted, `blocked_by` iff it is blocked; presence is the signal, so a missing key can't be misread the way null or "" can. The adjudication rows are also what `mathema verify --format json` emits per key, so a CI artifact and an agent call carry the same vocabulary. Population output (`audit_targets`, and `mathema audit --compact`) is column-oriented: `{"prefix": ..., "cols": [...], "rows": [[...], ...]}`, column names once, the shared dotted key prefix factored out of every row, and `span` in the sed-ready `start:endp` form so the follow-up read is targeted; it is a ready-made `sed -n` range, not a line count. (`verify_project` separately returns `report`, the human prose, which is a different thing.) The caller names the columns it wants (`cols`); the resolved selection is echoed back either way, and analyses no chosen column needs are never computed at all. One null policy across every cell: **null means the analysis was not computed**; a computed-but-empty result is its typed empty value; `[]` for lists, `0` for counts, `""` for the blocker of a derivable function. `blocker` holds exactly a bare reason-code key (a real enum over the code table), with its decorations split into `blocker_params` (the domain parameters a resolvable branch names) and `blocker_more` (the +N further-blocked-kinds count). `typed` and `doc_quality` are `[n, m]` pairs, never "n/m" strings to parse; `docsync` is the weighted 0-100 CDD-compliance percent (one int); `mutates` lists the module-level names the function writes through (the strongest scope relationship); `tested` is the closed enum `"yes"`/`"no"`/`"no-report"`/`"outdated"` (a missing coverage report is a different fact from an uncovered function, and a report older than the function's own source file supports neither answer). ## Resources and prompts The server also registers reference material and procedures, not just tools. A tool answers a question the agent already knew to ask; a resource is what it reads when it does not, and a prompt is a procedure delivered at the moment it chooses what to do. | Resource | Content | |---|---| | `mathema://reference/grammar` | the claim language by example, generated from `lexicon.LEXICON` | | `mathema://reference/codes` | the reason-code table with each code's `derive_unlock` and hint | | `mathema://reference/verdicts` | how to read a verdict: the stance fold, why `skipped` is not `falsified`, and why `passed` can be true beside a refuted row | | Prompt | Bound to | |---|---| | `claim_this_function(target)` | the authoring procedure with that function's real signature and current candidates resolved into it | | `triage_repository(targets)` | orient, then narrow to what is both risky and unevidenced | | `diagnose_falsification(target, claim)` | the code-wrong / claim-wrong fork, and why the judgement is handed back | Everything served is generated from what core already owns, so it cannot drift from the code it describes. The rule for tools covers it too: no resource or prompt takes a `verdict`/`accepted`/`stance`/`gates`/ `pin`/`verified_by` parameter, none is named to suggest accepting, unlocking or PIN entry, and the material says plainly that acceptance, unlocking and the [PIN](pin.md) are human acts done in the CLI. A test asserts that over everything registered, not only over `TOOLS`. `lock_target` is the deliberate one-way door: an agent may lock, and only a person may unlock. ## Wire format Tool payloads go over the wire as compact JSON, serialised at the server boundary without indentation. The tools themselves return dicts, so they stay directly callable from Python, and nothing is duplicated into a structured content block. ## What is deliberately absent No tool makes an LLM call. No tool accepts a caller-supplied verdict: claims are statements mathema adjudicates, and every verdict in every payload is mathema's own. And there is no `accept` tool at all, accepting evidence, owning risk, or marking a discovery is a human act, done in the CLI ([`mathema accept`](accept.md)), never exposed to agent tooling. ## Plugins A mathema plugin can contribute tools by exposing an entry point in the `mathema.mcp_tools` group whose callable returns plain functions. The hook is fail-soft: a plugin that errors contributes nothing and never breaks the server. - docs/modes/pin.md (8747 bytes)
# `mathema pin`: human-verified decisions The claim record answers what was verified and how hard. This answers the other question a reviewer, an auditor, or a regulator asks about a codebase agents help build: **was the sign-off actually made by a person?** `by:` alone cannot answer it; a free string is typed by an agent as easily as by a person. A PIN can: a person knows it, an agent does not, so an acceptance (or an [unlock](lock.md)) that carries the stamp was authorised by someone at a keyboard, and the record proves it rather than asserts it. The verification is written into the record twice, permanently: the `accepted` block carries `verified_by: {method, key}`, and so does every event in the claim's `acceptance_history`, so the audit trail survives later re-decisions. ```bash mathema pin set # choose a PIN (4-12 digits), prompted twice mathema pin status # method and key id, never the secret mathema pin rotate # replace it (verifies the current one first) mathema pin remove # delete it (also verifies first) ``` Entirely **optional**: with no PIN set, nothing prompts and nothing changes. Set one and every acceptance path (claim, intent, scope intent, concepts) and every unlock asks for it before writing. ## What it looks like ```text $ mathema accept funcs.settle nonneg --as evidence accept funcs.settle :: nonneg as evidence, by Alonzo Church holds over 130 trials the claim is accepted as evidence at n=130, bound to form py:3eb01e1d9919 write this acceptance? [y/N] y PIN: written. ``` and in the record (trimmed): ```yaml accepted: as: "evidence" at: "2026-09-24" n: 130 form: "py:3eb01e1d9919" by: "Alonzo Church" verified_by: method: "pin" key: "a3f2c1" ``` `verified_by` names the method and the credential's **key id**. The key id is why a PIN reset is auditable: rotating or replacing the credential produces a new id, so an acceptance signed by a key that is not the currently configured one is visible to any reviewer. ## The rules that make it mean something - **The code is read from the controlling terminal only.** A pipe, a captured subprocess, a caller with no `/dev/tty`: refused outright, never silently read from stdin. `--yes` still skips the y/N prompt; it never skips the PIN. `--format json` without a terminal refuses to apply and says why (the plan-only preview still works). - **The gate sits at the write boundary, not at the prompts.** Every acceptance path funnels through one library chokepoint, so the JSON path, scripted use, and the concepts curation path (which previously wrote without any prompt) are all covered. - **Rotate and remove verify the current PIN first.** Otherwise an agent could reset the credential to one it knows. - **The secret never enters the project.** It lives in `~/.config/mathema/auth.yaml` (mode 0600, respecting `XDG_CONFIG_HOME`), outside any repository an agent works in. Records and policy files carry only the key id. Lost PIN: delete that file and set a new one; the old key id stops matching, which is itself the audit trail working. ## The honest threat model This is a tripwire and an attestation, not a cryptographic barrier. An agent with unrestricted shell could delete the credential file or edit mathema itself; what it cannot do is produce a valid `verified_by` stamp in the normal course of work, and every subversion leaves a visible trace: a missing credential, a key id mismatch, an integrity checksum failure (see [what the checksum covers](../governance.md#the-integrity-checksum)). Calibrate trust accordingly, the same way the evidence ladder asks you to. The record's integrity checksum is unkeyed. It catches accidental changes, a stray edit or a merge that combined two versions of a record, but anyone who can run mathema can recompute it, so it does not stop a record forged on purpose. The gate against a forged record is re-adjudication in CI: `mathema verify --all` re-checks every claim against the code instead of trusting the verdicts stored in the record, so a forged verdict does not survive the pipeline. A sign-off is a decision rather than a verdict and cannot be re-derived; its `verified_by` stamp names a public key id, so review of the store's changes (`mathema review`) is where a sign-off nobody made shows up. ## Project policy `.mathema/meta/policy.yaml`, committed and human-owned, holds the public constraints: ```yaml acceptance: require_verification: true # every acceptance must carry verified_by methods: [totp] # allowed methods; omitting pin disables the static PIN keys: [a3f2c1] # optional allowlist of key ids accepted_risk_lifetime_days: 90 # optional: a risk acceptance expires after 90 days ``` `accepted_risk_lifetime_days` gives risk acceptances a lifetime. With no key there is none, and a risk acceptance stands until the claim changes. With the key set, every risk acceptance written from then on (`mathema accept --as risk`, and a risk sign-off on a transition) records `expires`, the date that many days after it was written. From that date `mathema verify` treats the acceptance as lapsed: the claim fails again in both modes, and its line names the date and the command that accepts it again, which is running the same acceptance again. The acceptance it replaces stays in the claim's `acceptance_history` as a `superseded` event, with its `at`, `by`, `note`, `level` and `expires`. The lifetime is time only; nothing else makes an acceptance lapse. An acceptance written before the key was set carries no `expires` and never lapses, and evidence acceptances (`--as evidence`) never expire. A value that is not a positive whole number is refused: `mathema verify` and `mathema accept` stop with exit 2, naming the key and the value as an unreadable policy, as they do for a `transitions:` entry they cannot read. The same file sets what the gate does with an unacknowledged [transition](../verdicts.md#transitions-and-what-invalidated-names) of each kind, one action for both modes or one per mode, where an action is `fail`, `warn` or `pass`; the defaults are `regressed` fails in both modes, `weakened` from `proven` to `holds` fails strict and warns lenient, `weakened` to `unknown` or `skipped` fails in both modes until a person accepts the risk, and `strengthened` and `fixed` pass: ```yaml transitions: weakened: fail regressed: {strict: fail, lenient: warn} ``` An entry sets the action for every move of its kind: `weakened: {lenient: warn}` makes a fall to `unknown` or `skipped` warn under `--lenient` too. A risk acceptance on a transition (`mathema accept KEY CLAIM --transition` on a claim that fell to `unknown` or `skipped`) is an acceptance under the `acceptance:` section, held to the same required verification, methods and keys at write time and at verify time. It stays on the record while the claim is below the level it fell from, so every run checks it. Enforced twice. At **write time**, an acceptance the policy forbids is refused: no credential when one is required, a static PIN where only stronger methods are allowed, a key outside the allowlist. At **verify time**, every *standing* acceptance in the record is checked too, so an unverified sign-off cannot ride in through a hand-edited YAML file: `mathema verify` fails the run, which is the CI gate. That includes the rows of the `discoveries`, `historical` and `superseded` sections, since each one takes a claim out of the gate. Under `require_verification` a record whose integrity checksum no longer matches its contents also fails the run, where without a policy it only warns. ### CI, GitHub, GitLab Acceptances happen locally, at a terminal, and travel as commits; CI never holds the PIN. The pipeline runs `mathema verify`, and with a policy present that alone enforces that every acceptance was human-verified by an allowed credential. Platform protections compose on top: branch protection plus a CODEOWNERS rule on `.mathema/verified/` makes any change to acceptance blocks require a human PR approval, with the forge's own login 2FA as the second factor. `verified_by` is the record-level half that survives outside any forge. ## Planned enhancement: authenticator-app codes Authenticator-app codes (RFC 6238 TOTP, the 6-digit codes that change every 30 seconds) are planned but not offered in this release; the static PIN is the method. A code an agent observes in a transcript would be dead half a minute later, which is why the method is on the roadmap. The `verified_by: {method, key}` stamp is an open seam: a stronger backend verifies its own way and records its own method and key. - docs/modes/review.md (7771 bytes)
# `mathema review` Read the verified store by CLAIM, not by raw YAML diff. `mathema review` compares the records at a git ref (the base, default `HEAD`) against the working tree and reports the handful of facts a reviewer actually needs: which verdicts flipped, which claims were added or removed, which are newly falsified, and which records a human reconciled. ```bash mathema review [<ref>] [--root .] [--format text|json] [--output FILE] ``` ## Arguments | Flag | Meaning | |---|---| | `ref` | the base git ref to compare the working tree against (default `HEAD`) | | `--root` | project root holding `.mathema/verified` (default `.`) | | `--format` | `text` (default) or `json`: the delta as data, for a CI job to post as a PR comment | | `--output FILE` | write the report to a file instead of stdout | ## What it reports Keyed by function (`module.qualname`), and within each, by claim name: - **verdict flips** (`old -> new`), with a flip into `falsified` marked `!!`, - **claims added** and **claims removed** between the two states, - **newly falsified** claims (a flip into `falsified`, or an added claim that lands `falsified`), - **reconciled** records (a human blessed the current contents with [`mathema accept --as reconciled`](accept.md#-as-reconciled-after-a-merge-rebase-or-a-declared-claim-edit)), - **restated** claims (the same name, a different statement), - **retirement rows** added to or dropped from a record's `discoveries`, `historical` and `superseded` sections. A dropped row is marked `!!`: it is the usual trace of a merge conflict resolved to one side, and it puts a retired claim back in play. The summary names restated claims and retirement rows only when there are some. A `ref` that does not name a commit exits 2. The closing summary counts each movement across the whole store. ## Why not a raw diff A `git diff` over `.mathema/verified/` shows every re-anchored lineage line and every reordered row, burying the one verdict that actually changed. `review` reads both states as records and diffs their claims, so a flip from `holds` to `falsified` reads as one line, not a wall of YAML. It is the reviewer-facing counterpart to the CI badge snapshot: a human summary, and a `--format json` a pipeline can post on the pull request. ## Worked example The `softmax` of the [`check` worked example](check.md#worked-example-softmax-start-to-finish), with its claim in `claims/softmax.claims.yaml`: <!-- example: delta file=functions.py --> ```python import math from typing import Annotated from mathema.types import Shape def softmax(scores: Annotated[list[float], Shape("n")]) -> Annotated[list, Shape("n")]: """Turn a vector of real-valued scores into a probability distribution.""" if not scores: raise ValueError("softmax needs at least one score") m = max(scores) exps = [math.exp(s - m) for s in scores] total = sum(exps) return [e / total for e in exps] ``` <!-- example: delta file=claims/softmax.claims.yaml --> ```yaml functions.softmax: claims: - name: sums_to_one statement: "sum(f(scores)) == 1" ``` verified and committed as the base: <!-- example: delta run --> ```bash git init -q git config user.name "Ada Lovelace" git config user.email [email protected] mathema verify --root . git add -A git commit -qm "softmax, verified" ``` <!-- example: delta output --> ```text ok math.exp: library claims from mathema/compendium/math.claims.yaml; no baseline record; 1 proven, 3 holds, 0 falsified ok functions.softmax: no baseline record; 1 proven, 4 holds, 0 falsified 0 unchanged since the last run (not run again), 2 checked, 0 problem(s) grammars detected: mathema; verified by this run: mathema 1 intent to accept (1 function): mathema accept --intent ``` A change then drops the normalization (`return exps`) and declares a new claim beside the old one: <!-- example: delta file=functions.py --> ```python import math from typing import Annotated from mathema.types import Shape def softmax(scores: Annotated[list[float], Shape("n")]) -> Annotated[list, Shape("n")]: """Turn a vector of real-valued scores into a probability distribution.""" if not scores: raise ValueError("softmax needs at least one score") m = max(scores) exps = [math.exp(s - m) for s in scores] total = sum(exps) return exps ``` <!-- example: delta file=claims/softmax.claims.yaml --> ```yaml functions.softmax: claims: - name: sums_to_one statement: "sum(f(scores)) == 1" - name: bounded statement: "max(f(scores)) <= 1" ``` The sweep fails, and the reviewer reads the delta by claim: <!-- example: delta run --> ```bash mathema verify --root . mathema review HEAD ``` <!-- example: delta output --> ```text FAIL functions.softmax: form changed; 1 proven, 5 holds, 1 falsified <- sums_to_one regressed holds to falsified (this function changed); to acknowledge it, run: mathema accept functions.softmax sums_to_one --transition; 1 falsified claim(s) 1 unchanged since the last run (not run again), 1 checked, 2 problem(s) grammars detected: mathema; verified by this run: mathema 1 intent to accept (1 function): mathema accept --intent Claim changes since HEAD: 1 function(s), 1 verdict flip(s), 1 added, 0 removed, 1 newly falsified, 0 reconciled. functions.softmax sums_to_one: holds -> falsified !! + bounded ``` `sums_to_one` regressed and a new `bounded` claim was declared; the reviewer sees exactly that, and nothing else. A claim that held at the base and now has a counterexample is newly falsified, and the record it came from keeps the move from `holds` beside the verdict. ## The record shape it reads A verified record is deliberately self-contained (everything needed to read and re-check a claim rides its row) but not verbose. Empty and derivable fields are omitted rather than written as null placeholders: a claim carries `n`, `counterexample`, `note`, `sketch`, `tolerance`, and `meta` only when they say something; `condition` rides a derive row (where it is the proof's own quantifier) but not a probe row (where it merely restates the statement and domain); a per-row `grammar` appears only when it differs from the record's grammar. Claim rows are sorted by name, so a non-deterministic probe order never shows up as a diff. None of this touches the [integrity checksum](../governance.md#the-integrity-checksum), which covers what a decision rests on, not its presentation. **Surface versus author.** Two provenance facts are kept apart, because they answer different questions: - **`authored.surface`** is *where* the claim was written, the load-bearing gating fact: `docstring`, `claims-file` (a declared claims file), `decorator`, `annotation`, `inline`, `suggested` (mathema volunteered it, and a suggestion never gates until it is adopted), `builtin` (the structural battery), or `compendium`. - **`authored.by`** is *who* proposed the claim, an optional identity: an AI model, a harness, or a git username. It is absent unless stated, either on the claim's own `authored` statement or through the `MATHEMA_CLAIM_SOURCE` environment a harness sets when an agent proposes claims. It is never stamped on a surface mathema itself generated (`builtin`/`suggested`/`compendium`), which mathema authored, not the agent that ran the verification. Neither is the `route` (`probe`/`derive`/`examine`), which is *how* the claim was checked. The route the claim *asked* for (`probe`, `derive`, or `best` when none was named) rides beside them as `authored.route`, so a claim restored from its row is checked the way it was written. Where a claim came from, who wrote it, and how it was adjudicated are three separate axes, and the record keeps them so. - docs/modes/verify.md (23234 bytes)
# `mathema verify` The test-runner face and the CI gate: sweeps the spec store, re-adjudicates every function whose `form` hash no longer matches its record (new or changed code), and refreshes the machine records so the next run has a baseline. ```bash mathema verify [<key> | <claims file> ...] [--root .] ``` Given one or more store keys (canonical dotted `module.qualname`), the sweep is confined to exactly those records, re-adjudicating and re-stamping each in place. Freshness never skips a key you named: the form-hash short-circuit is an optimisation for a whole-store sweep, so asking about one key always re-checks it (this is the fix the integrity-mismatch warning points at): the single-key form the reconcile workflow points you at (`mathema verify mypkg.mod.fn` after a merge touched one record). With no key it sweeps the whole store as before. A key that names no record fails as a clear per-key problem line, exit 2. ## Arguments | Flag | Meaning | |---|---| | `<key> ...` | zero or more store keys to confine the sweep to; omit for the whole store | | `<claims file> ...` | a claims file path: every entry in it is adjudicated up front, a library's [compendium](../claims-transfer.md#in-the-compendium) file included (see [Library claims](#library-claims-lazy-by-default-a-file-up-front)) | | `--root` | project root holding `.mathema/verified` and `claimspec.yaml` (default `.`) | | `--all` | re-adjudicate everything, ignoring form-hash freshness | | `--strict` / `--lenient` | one strictness pair shared with `check`; strict is the default here (CI gates a settled store), `--lenient` reports unverifiable claims instead of failing on them; accepted risk passes in both | | `--status [TARGET]` | report fresh/stale per `@track_claims`-tagged function, adjudicate nothing, exit 0; an optional TARGET (dotted name or file path) is imported first so its tagged functions register | | `--format` | `text` (default) or `json`: the whole sweep as data; per-key entries with `why`, gate `counts`, and claim rows in the same vocabulary `check --format compact` and the MCP tools speak (`stance`/`verdict`/`route`/`source`/`gates`, `counterexample` iff refuted, `supersession` iff the claim was re-authored after it was verified: the new text and the `mathema accept` command that adopts it); `totals.skip_reasons` counts the skipped claims per reason. Exit codes are identical either way | | `--output FILE` | write the report to a file instead of stdout | | `--verbose` | list every function in the text report; by default it lists only the functions checked again or with a problem, then the summary, which counts the unchanged ones. JSON always carries every function | Store keys are canonical dotted `module.qualname` names, resolved by importing from `--root`; the target must be importable there, and a bare-name key fails as a clear per-key problem line. ## What fails the run | Finding | Default (strict) | `--lenient` | |---|---|---| | `falsified` claim | fails | fails | | open transition, `regressed` (a supported claim fell to `falsified`) | fails | fails | | open transition, `weakened` `proven` to `holds` | fails | warns, named in the row | | open transition, `weakened` to `unknown` or `skipped` (a supported claim no longer supported), until the risk is accepted | fails | fails | | `unknown` or `skipped` claim whose fall carries a risk sign-off | passes, named in the row | passes, named in the row | | `unknown` claim, not accepted | fails | fails | | `unknown` or `skipped` claim, accepted as risk | passes, named in the row | passes, named in the row | | risk acceptance or risk sign-off past its `expires` date ([lifetime](pin.md#project-policy)) | fails, naming the date and the command that accepts it again | fails, naming the date and the command that accepts it again | | `skipped` (unverifiable) claim, not accepted | fails | passes, informational | | unresolved global name | fails | fails | | silently-unenforced declared domain | fails | passes, informational | | record whose function no longer resolves | fails (names the rename when an unrecorded function has its form hash) | fails | | [locked](lock.md) function whose body changed | fails, record untouched | fails, record untouched | | lock removed outside `mathema unlock` | fails | fails | | acceptance the [policy](pin.md#project-policy) rejects | fails | fails | A falsified claim fails in every mode: the record keeps the counterexample permanently (refutation is knowledge), but knowledge of a broken claim is exactly what a gate is for. An unknown claim also fails in every mode; in an agentic loop a claim nobody could adjudicate is indistinguishable from one that would have failed, until a human explicitly owns the gap with [`mathema accept --as risk`](accept.md). Accepted risk is visible relaxation, not laundering: both modes pass it and the row names it as accepted risk. The acceptance is still held to the project's [acceptance policy](pin.md#project-policy) in both modes. A supported claim that falls to `unknown` or `skipped` fails in both modes as an open transition, even though `--lenient` passes a claim that was always `skipped`. The failing line names the move, what changed, and the command that accepts the risk at the level it fell from (`mathema accept KEY CLAIM --transition`, see [acknowledging a transition](accept.md#acknowledging-a-transition)). A `transitions:` entry in the project's [policy](pin.md#project-policy) sets one action per kind, and an entry for `weakened` applies to every weakened move, whatever it fell to. Freshness never bypasses the gate: a function whose `form` hash is unchanged skips re-adjudication, but its *stored* verdicts are still checked, a record carrying a falsified or open-unknown claim fails the run even when nothing was re-run. Exit codes: 0 clean; 1 gate failure; 2 usage/target/store error; 130 interrupted. ## Worked example Continuing from [`mathema check`](check.md)'s `softmax` example: <!-- example: sweep file=functions.py --> ```python import math from typing import Annotated from mathema.types import Shape def softmax(scores: Annotated[list[float], Shape("n")]) -> Annotated[list, Shape("n")]: """Turn a vector of real-valued scores into a probability distribution. Claims: sums_to_one: sum(f(scores)) == 1 """ if not scores: raise ValueError("softmax needs at least one score") m = max(scores) exps = [math.exp(s - m) for s in scores] total = sum(exps) return [e / total for e in exps] ``` with its record written by `write_spec()`: <!-- example: sweep run --> ```python import mathema from functions import softmax mathema.write_spec(softmax) ``` <!-- example: sweep session --> ``` $ mathema verify --root . ok math.exp: library claims from mathema/compendium/math.claims.yaml; no baseline record; 1 proven, 3 holds, 0 falsified 1 unchanged since the last run (not run again), 1 checked, 0 problem(s) grammars detected: mathema; verified by this run: mathema 1 intent to accept (1 function): mathema accept --intent ``` `softmax` calls `math.exp`, and the bundled [compendium](../claims-transfer.md) states claims about it, so the sweep adjudicates those against the installed library too (once, and fresh from then on), which is what a premise resting on them reads. It adjudicates no other `math` function: see [Library claims](#library-claims-lazy-by-default-a-file-up-front). The last line counts the stated intents that no one has accepted yet, here `softmax`'s summary line, which sits at the `declared` rung until a person accepts it. It is information only and never changes the exit code; `mathema accept --intent` walks each one (see [Intent at every level](../mathema-docstring.md#intent-at-every-level)). Drop the normalization on purpose (`return exps` instead of dividing by the total): <!-- example: sweep file=functions.py --> ```python import math from typing import Annotated from mathema.types import Shape def softmax(scores: Annotated[list[float], Shape("n")]) -> Annotated[list, Shape("n")]: """Turn a vector of real-valued scores into a probability distribution. Claims: sums_to_one: sum(f(scores)) == 1 """ if not scores: raise ValueError("softmax needs at least one score") m = max(scores) exps = [math.exp(s - m) for s in scores] total = sum(exps) return exps ``` and re-run: <!-- example: sweep session --> ``` $ mathema verify --root . FAIL functions.softmax: form changed; 1 proven, 3 holds, 1 falsified <- sums_to_one regressed holds to falsified (this function changed); to acknowledge it, run: mathema accept functions.softmax sums_to_one --transition; 1 falsified claim(s) 1 unchanged since the last run (not run again), 1 checked, 2 problem(s) grammars detected: mathema; verified by this run: mathema 1 intent to accept (1 function): mathema accept --intent ``` `sums_to_one` now fails, and because it held before the record keeps the move beside the fresh verdict, `regressed holds to falsified (this function changed)`, with the command that acknowledges it. The counterexample is kept in the record, and the exit code is 1. Restore the fix (the first version of `functions.py` above) and re-verify: <!-- example: sweep file=functions.py --> ```python import math from typing import Annotated from mathema.types import Shape def softmax(scores: Annotated[list[float], Shape("n")]) -> Annotated[list, Shape("n")]: """Turn a vector of real-valued scores into a probability distribution. Claims: sums_to_one: sum(f(scores)) == 1 """ if not scores: raise ValueError("softmax needs at least one score") m = max(scores) exps = [math.exp(s - m) for s in scores] total = sum(exps) return [e / total for e in exps] ``` <!-- example: sweep session --> ``` $ mathema verify --root . ok functions.softmax: form changed; 1 proven, 4 holds, 0 falsified 1 unchanged since the last run (not run again), 1 checked, 0 problem(s) grammars detected: mathema; verified by this run: mathema 1 intent to accept (1 function): mathema accept --intent ``` Back to clean, and the baseline is refreshed; the next `verify` will be fresh again until the code or the claim set actually changes. ## Library claims: lazy by default, a file up front The default sweep is lazy about the claims mathema bundles for libraries: only the library functions your project uses are adjudicated, the ones a swept function calls (through its import aliases, so `np.sqrt` is `numpy.sqrt`) or a claim rests a premise on, plus any already in the store. A project that never calls numpy verifies none of numpy's rows, and a new call brings its callee's rows in on the next sweep. A compendium file in your own project is a claims file in the tree like any other, and the sweep adjudicates all of it. To adjudicate a whole claims file up front, name it. Every entry in the file is adjudicated and recorded like any sweep, whether or not your code calls it: ```bash mathema verify claims/numpy.claims.yaml ``` A bundled file is named by the path records give it, `mathema/compendium/...`: <!-- example: eager session --> ``` $ mathema verify mathema/compendium/math.claims.yaml --root . ok math.exp: library claims from mathema/compendium/math.claims.yaml; no baseline record; 1 proven, 3 holds, 0 falsified FAIL math.log: library claims from mathema/compendium/math.claims.yaml; no baseline record; 1 proven, 0 holds, 0 falsified, 1 unknown <- log_monotone unknown: derive could not decide it compendium:math declares 'log_monotone' for math.log; mathema verify recorded it unknown against the installed library: (i) to take it on its word, run: mathema accept math.log log_monotone --as trusted (ii) to decide it, restate the row, then run: mathema check math.log --claim "..." ok math.sqrt: library claims from mathema/compendium/math.claims.yaml; no baseline record; 1 proven, 3 holds, 0 falsified 0 unchanged since the last run (not run again), 3 checked, 1 problem(s) grammars detected: mathema; verified by this run: mathema ``` The run gates like any other: `math.log`'s derivative row cannot be settled against a function with no Python source, so it fails, naming the two ways forward. A file whose library is not importable, or is installed at a version outside the file's `versions` range, adjudicates nothing and says so on one line (`note claims/numpy.claims.yaml: numpy 1.20.0 is outside the file's range >=1.24,<3; nothing in it was adjudicated`). An ordinary claims file named the same way confines the sweep to its entries. ## Unknown claims and accepted risk A claim neither route could decide stays `unknown` and fails the run. Add a running balance in `balances.py`, with three claims in `claims/running_total.claims.yaml`: <!-- example: sweep file=balances.py --> ```python def running_total(xs: list, y0: float) -> float: """Add every value in xs to a starting balance y0.""" total = y0 for v in xs: total = v + total return total ``` <!-- example: sweep file=claims/running_total.claims.yaml --> ```yaml balances.running_total: claims: - name: shifts_with_start statement: "f(xs, y0) == f(xs, 0) + y0" - name: nonneg_for_nonneg_steps statement: "for xs in [0, 1]^n, f(xs, 0) >= 0" - name: never_overshoots_much statement: "assuming nonneg_for_nonneg_steps is proven, for xs in [0, 1]^n, f(xs, 0) <= len(xs)" ``` `never_overshoots_much` rests on `nonneg_for_nonneg_steps` being proven, and that one only holds (the probe agrees; derive cannot settle the sign of the lifted sum), so the dependent claim is `unknown`. `shifts_with_start` proves on the derive route, and every proof spawns a `shifts_with_start[float]` companion, the same law checked in floating point (see [the evidence ladder](../evidence-ladder.md#a-proof-is-the-mathematics-float-is-the-computation)). The companion is falsified: at `xs = [1e300, -1e300, ...]` the float sum cancels and drops `y0`, a result no float64 computation can deliver at inputs of that magnitude. The note says so, with the condition number at the witness, and gives the ways out. Since `xs` and `y0` run along unbounded directions, the first is `let |inf| be 1e+21`, which bounds only the computation and never the proof, so the proof still covers every real input; mathema ran the claim with that binding before offering it, and its computation line holds. A computation line failing along an unbounded direction is offered such a binding whenever a run under it holds, whatever the conditioning says, B being the largest power of ten that holds where the conditioning gives none. The second accepts the computation line alone as a discovery, which mathema allows because the loss is inherent in the inputs rather than the code's. The second proven claim in the count is `dependencies_current`, which `verify` adds to every record: <!-- example: sweep session --> ``` $ mathem - docs/multi-function-claims.md (10242 bytes)
# Multi-function claims Most claims speak about one function, spelled `f`. A claim may also bind further function symbols and state laws that relate them: a composition against a library function, a comparison against a sibling in the same module, or full behavioural equivalence between two implementations. ## Binding a second function Three spellings, from most to least explicit: ``` let g = math.sqrt, for x in (0, 100], g(x) >= 0 ``` The `let` spelling binds `g` to an importable function by its dotted path and is the form the record keeps: it survives every store round trip, because the path is text. ```python mathema.check(mine, claims=[mathema.claims.claim("f(x) == g(x)", funcs={"g": other})]) ``` `funcs=` on `claim()` binds a live callable and adjudicates identically. When the callable is a module-level function importable by its own dotted path, the record stores the binding in the `let` spelling (`let g = mymodule.other, f(x) = g(x)`), so the claim rebuilds from the record alone. A callable with no such path (a lambda, a nested function, a function defined in `__main__`) has no text spelling: the record keeps the law but not the binding, and a later run reconstructing the claim from the record cannot re-bind `g`. A bare call name (`g(x)` with no `let` and no `funcs=`) binds automatically when a function of that name is defined in `f`'s module or the calling scope. The record keeps the bare name, which binds the same way again from `f`'s module; a function found only in the calling scope (a notebook cell, a script) is not there for a later run to find. ## Laws over two functions Once bound, the second symbol participates like any expression: ``` for x in [0, 4], f(x) == g(x) + 1 for x in [1, 8], f(g(x)) >= 0 ``` Both routes handle these: derive substitutes each function's lifted body and decides the combined expression; probe executes both real functions on shared draws. ## Behavioural equivalence ``` f =:= g f equiv g ``` The equivalence relation asks whether two implementations are the same mathematics, which is the question behind every rewrite, refactor and port: an agent's new version against the one it replaces, or another runtime's implementation against the Python reference. Between two Python functions the claim records two lines, as a value claim does, and it is falsified when either line is. The mathematics line is derive's, and it climbs a ladder, strongest rung first, where each rung may decline: 1. **Identical canonical form.** Both functions lift to the same alpha-renamed shape, and the claim is proven by the form hash alone: two spellings of one computation. 2. **Symbolic difference.** The two lifts, positionally aligned, subtract to zero under the declared domain. Where both sides raise, this rung proves the equivalence when they raise the same exception on exactly the same region and their lifts agree everywhere else (for a function of one parameter). A disproof stands once both functions, run at derive's witness and compared exactly, disagree there, however small the difference, so `sqrt(x)` against `sqrt(x) + 1e-12` is falsified on this line although no float tolerance would notice the gap; a disproof that exact evaluation does not confirm is `unknown`, with the flag that marks a likely mathema bug. 3. **Closed forms.** Where both bodies provably never raise, their closed forms are compared directly. The computation line, the row `NAME[float]` under the claim, runs both real functions on the same 96 seeded draws from the declared domain, and at least 24 of them must agree before it `holds`. Two results agree within the claim's own [tolerance](grammar.md#how-close-counts-as-equal), so an equivalence between a float and a fixed-point implementation is stated, not guessed. A draw where both sides raise the same exception agrees, and so does a draw where both sides overflow to the same infinity. A NaN computed from non-missing inputs is no value and agrees with nothing, another NaN included, and an infinity disagrees with a value or with the opposite infinity: each is a counterexample. A draw with a missing input, or where either side returns something non-numeric, is not compared, and both kinds of uncompared draw are counted in the record rather than dropped. Sampling never proves, so the line's ceiling is `holds`. The two lines answer different questions, and they can disagree: `(x + 1e20) - 1e20` against `x` over `[0, 1]` is proven on the mathematics line and falsified on the computation, since in float64 the large sum swallows `x`. When derive cannot decide (a function with no source to read, a body it cannot lift, or a difference it cannot settle), there is no mathematics line, and the shared draws are the claim's only row, a computation line, exactly as the probe's row is for a value claim. `f =:= g` claims `f(x) == g(x)` at every point of the domain, so a point where one side raises and the other returns a value is a counterexample, and the executed raise is its witness. `x / x` and `1.0` agree everywhere except `x = 0`, and both lines find it: <!-- example: ratio run --> ```python import mathema def ratio(x: float) -> float: return x / x def one(x: float) -> float: return 1.0 for p in mathema.claims.check(ratio, [mathema.claim("f =:= g", funcs={"g": one})]): print(p.name, p.verdict, p.counterexample) ``` <!-- example: ratio output --> ```text f_equiv_g falsified x = 0: f raised ZeroDivisionError, g returned 1 f_equiv_g[float] falsified x = 0: f raised ZeroDivisionError, g returned 1 ``` `=:=` compares behaviour, so a point where both sides raise the same exception type is a point where they agree: `1 / x` and `2 / (2 * x)` are proven equivalent over `[-1, 1]`, both raising `ZeroDivisionError` at `x = 0`. Different exception types at the same point are a disagreement, and the executed pair is the witness: against a version that raises `ValueError` at zero, the claim is falsified with `x = 0: f raised ZeroDivisionError, g raised ValueError`. A complex result from one side counts as a raise, unless that side is annotated `complex` or the claim is over `C`. A tolerance applies to the computation line alone, since the mathematics line is exact whatever the tolerance: `x + 1e-3 =:= x` with a tolerance of `1e-2` is falsified there while its computation holds. With no tolerance declared, each of the two computed values may miss the exact one by the allowance every computation line uses (1e-7 of its magnitude plus a small absolute part, at most 1e-9), and the two are added, so they may differ by about `2e-7` times the larger magnitude plus `2e-9`; below magnitudes of 1e-2 the absolute part shrinks with the values, so two values near 1e-3 apart by 1e-9 disagree. To judge the computation by another rule, declare one: a bare number is an absolute allowance that replaces the default whole, and a kind (`{abs: x}`, `{rel: x}` or `{ulp: n}`, each with an optional `floor: x` that adds to it, as [Tolerance kinds](grammar.md#tolerance-kinds) describes) is judged at each pair of values. The record shows the tolerance as written. A rate that runs `1e-8` high is falsified on the mathematics line under every tolerance, and its computation line follows the rule declared: <!-- example: equiv-tolerance run --> ```python import mathema def rate(x: float) -> float: return x * (1 + 1e-8) def reference(x: float) -> float: return x for tolerance in [None, 1e-9, {"rel": 1e-9}, {"rel": 1e-7}]: rows = mathema.claims.check(rate, [mathema.claim( "for x in [1, 2], f =:= g", funcs={"g": reference}, tolerance=tolerance)]) print(f"{str(tolerance):14}", [(p.name, p.verdict) for p in rows]) ``` <!-- example: equiv-tolerance output --> ```text None [('f_equiv_g', 'falsified'), ('f_equiv_g[float]', 'holds')] 1e-09 [('f_equiv_g', 'falsified'), ('f_equiv_g[float]', 'falsified')] {'rel': 1e-09} [('f_equiv_g', 'falsified'), ('f_equiv_g[float]', 'falsified')] {'rel': 1e-07} [('f_equiv_g', 'falsified'), ('f_equiv_g[float]', 'holds')] ``` Agreement within a tolerance is a different claim, `f(x) ~= g(x)`, and accepting such a falsification as a discovery (`mathema accept KEY NAME --as discovery`) offers it at the tolerance the computation compared under: a declared number or kind as written, or, with none declared, `{rel: 2e-7, floor: 2e-9}`, which is the default exactly for values of magnitude 1e-2 and above and slightly wider below. It is written only when it holds or is proven. Either way the whole claim retires with both its lines: the computation row alone is never accepted, since the computation is what runs. The record annotates both sides' structural complexity, so an equivalence between a one-liner and a loop reads as what it is. ## Another language on the other side What an equivalence licenses, and what it never does, is the subject of [Claims transfer](claims-transfer.md). How an implementation in another language is reached is a [target resolver](extending.md#target-resolvers), an extension point that maps a key such as `cpp:` or `ts:` to a callable. Because `g` may be any callable, the other implementation need not be Python. The ladder above compares two Python forms, so it runs only when the Python frontend read both sides. When either side's facts came from another frontend, as for a function a runtime adaptor serves, `f =:= g` is answered by the equivalence family: a claim family registered under the name `equivalence`, which can bring that runtime's own reading of a refusal, a tolerance and a region. With no such family, or one that declines, the claim is `skipped` with the reason `equivalence across runtimes needs the equivalence family`. Whatever the family finds, safety claims never transfer between implementations, because they are facts about an implementation and its language rather than about the mathematics. ## Premises over bound functions The `assuming` machinery composes with bindings: a premise may reference the bound function's own claims, and the definedness machinery reads registered partiality lemmas for functions the body calls (see [Conditional claims and lemmas](conditional-claims.md)). - docs/pandas-function.md (14708 bytes)
# Claims about a pandas function The [quick start](quickstart.md) took a claim about a scalar function from falsified to proven. This page does the same for a function that takes a pandas `Series`, and shows the two things that change: how mathema hands the function a real `Series`, and how a claim about it is proven for every length of the series, with nothing missing in it, by reading the pandas calls in the body. It needs the `pandas` extra (`pip install "mathema[pandas]"`). ## The function A strategy's daily returns, and two numbers a desk computes from them: <!-- example: pandas file=returns.py --> ```python import numpy as np import pandas as pd def average_return(returns: pd.Series) -> float: """The mean of a series of periodic returns.""" return float(returns.mean()) def sharpe(returns: pd.Series) -> float: """The annualised Sharpe ratio of daily returns, at a zero risk-free rate.""" return returns.mean() / returns.std(ddof=1) * np.sqrt(252) ``` ## A first claim, and what the function received The average of a series lies between its smallest and its largest value. `returns in [-0.1, 0.1]^n` says: a vector of one or more entries, every entry between a 10 percent loss and a 10 percent gain. A float entry may also be missing (`nan`, or pandas' `NA`), and `\ {missing}` takes those out, so this claim is about series with every day present. What a function does with a missing day is a separate question, with its own page: [Missing values](missing-values.md). <!-- example: pandas run requires=pandas --> ```python import mathema from returns import average_return record = mathema.check(average_return, claims=[ "for returns in [-0.1, 0.1]^n \\ {missing}, min(returns) <= f(returns) <= max(returns)"]) print(record) ``` <!-- example: pandas output wrap=80 --> ```text mathema.Record(average_return) · source, no side effects · form py:b38d4613a6c4 min_returns_le_f_returns_le_max_returns for returns in [-0.1, 0.1]^n : float, min(returns) <= f(returns) <= max(returns) falsified at returns = [] proven mathematics for returns in [-0.1, 0.1]^n ⊂ ℝ, min(returns) <= f(returns) <= max(returns) holds computation for returns in [-0.1, 0.1]^n : float, min(returns) <= f(returns) <= max(returns) 208 entries across 44 draws, sizes (1, 1) to (8, 1) falsified policy f([]) f(returns) returns nan at returns = []: no value for no data, and no empty policy is stated possible fixes: (i) if nan for no data is intended, state: average_return([]) in {missing} (ii) guard the empty input at entry ``` The `mathematics` line is `proven` over every series with entries in the range, of every length of at least one, with nothing missing, and the `computation` line holds. The headline is falsified by the empty series alone: the mean of no returns is `nan`, which counts as no value until a policy for the empty input is stated. The `: float` after the range is what mathema resolved `[-0.1, 0.1]^n \ {missing}` to: float entries, none of them missing. The signature says `returns: pd.Series`, so whenever mathema runs the function it first builds a `Series` from the vector it drew; had the parameter been annotated `np.ndarray`, it would build an array instead, and a parameter nothing names is passed as a list. The proof itself came from reading the body. `returns.mean()` is a call mathema knows: it ships a definition row for `pandas.Series.mean`, a claim stating what the method computes in the grammar's own words, and with the call read through that row the claim becomes a statement about sums over a sequence of symbolic length: <!-- example: pandas run requires=pandas --> ```python import textwrap print(textwrap.fill(record.probes[0].sketch, 78)) ``` <!-- example: pandas output --> ```text link 1: min(returns) <= f(returns): taking pandas.Series.mean as mean(a) (axiom, bundled with mathema, pandas 2.2 to 3.x); through the pandas.Series.mean definition row, read as sums over returns at a symbolic length: the relation holds for every length of at least one (min(returns) is at most mean(returns)); link 2: f(returns) <= max(returns): taking pandas.Series.mean as mean(a) (axiom, bundled with mathema, pandas 2.2 to 3.x); through the pandas.Series.mean definition row, read as sums over returns at a symbolic length: the relation holds for every length of at least one (max(returns) is at least mean(returns)) ``` ## A claim that is wrong, and the witness A Sharpe ratio is unchanged by leverage: scale every return by the same positive `c` and the ratio comes out the same. `let s = mathema.f.scale_seq` names that scaling, `let c be [0.1, 10]` the range of leverage, and `~=` asks for equality up to floating-point tolerance: <!-- example: pandas run requires=pandas --> ```python from returns import sharpe record = mathema.check(sharpe, claims=[mathema.claim( "for returns in [-0.1, 0.1]^n \\ {missing}, let s = mathema.f.scale_seq, " "let c be [0.1, 10], f(s(returns, c)) ~= f(returns)", name="leverage_invariant")]) print(record) ``` <!-- example: pandas output wrap=80 --> ```text mathema.Record(sharpe) · source, no side effects · form py:7f6096e11ff8 leverage_invariant let s = mathema.f.scale_seq, let c be [0.1, 10.0], for returns in [-0.1, 0.1]^n : float, f(s(returns, c)) ~= f(returns) falsified at returns = pandas.Series([0.0], index=pandas.bdate_range('2020-01-01', periods=1)), c = 4.2636586502253655 falsified mathematics let s = mathema.f.scale_seq, let c be [0.1, 10.0], for returns in [-0.1, 0.1]^n ⊂ ℝ, f(s(returns, c)) ~= f(returns) counterexample returns = pandas.Series([0.0], index=pandas.bdate_range('2020-01-01', periods=1)), c = 4.2636586502253655: the computation returns NaN here (f returned nan) falsified policy f([]) f(returns) returns nan at returns = []: no value for no data, and no empty policy is stated possible fixes: (i) if nan for no data is intended, state: sharpe([]) in {missing} (ii) guard the empty input at entry ``` The headline carries the witness, and the lines under it say where it came from. The `mathematics` line is falsified at that point; the `policy` line covers the empty series, tried separately, and is falsified too: the Sharpe ratio of no returns is `nan`. Read the witness. `returns = pandas.Series([0.0], index=pandas.bdate_range('2020-01-01', periods=1))` is a series of one day, written as the call received it, so pasting it back into Python replays the call. Its standard deviation with `ddof=1` is undefined, pandas returns NaN, and `sharpe` returns NaN with it. NaN is no value, so the claim has no value at that point, and a claim with no value at a point inside its domain is falsified there. The code is right: a one-day series has no Sharpe ratio. The claim was too wide, because it never said which series it was about. ## Say what the claim is about A premise, written after `assuming`, names the series the ratio is defined for: here `std(returns, ddof=1) > 0`. <!-- example: pandas run requires=pandas --> ```python record = mathema.check(sharpe, claims=[mathema.claim( "for returns in [-0.1, 0.1]^n \\ {missing}, let s = mathema.f.scale_seq, " "let c be [0.1, 10], assuming std(returns, ddof=1) > 0, " "f(s(returns, c)) ~= f(returns)", name="leverage_invariant")]) print(record) ``` <!-- example: pandas output wrap=80 --> ```text mathema.Record(sharpe) · source, no side effects · form py:7f6096e11ff8 leverage_invariant assuming std(returns, ddof=1) > 0, let s = mathema.f.scale_seq, let c be [0.1, 10.0], for returns in [-0.1, 0.1]^n : float, f(s(returns, c)) ~= f(returns) falsified at returns = pandas.Series([-0.02405627255486044, -0.024056272554860435, -0.02405627255486044, -0.024056272554860435, -0.02405627255486044], index=pandas.bdate_range('2020-01-01', periods=5)), c = 10 proven mathematics assuming std(returns, ddof=1) > 0, let s = mathema.f.scale_seq, let c be [0.1, 10.0], for returns in [-0.1, 0.1]^n ⊂ ℝ, f(s(returns, c)) ~= f(returns) falsified computation assuming std(returns, ddof=1) > 0, let s = mathema.f.scale_seq, let c be [0.1, 10.0], for returns in [-0.1, 0.1]^n : float, f(s(returns, c)) ~= f(returns) counterexample returns = pandas.Series([-0.02405627255486044, -0.024056272554860435, -0.02405627255486044, -0.024056272554860435, -0.02405627255486044], index=pandas.bdate_range('2020-01-01', periods=5)), c = 10 conditioning unknown here: derive cannot read f, so whether this loss is inherent is not decided possible fixes: (i) fix the code (ii) to accept the whole claim as a discovery, keeping both lines, run: mathema accept returns.sharpe leverage_invariant --as discovery (iii) to narrow the domain knowingly, edit leverage_invariant, then run: mathema accept returns.sharpe leverage_invariant --as superseded ``` The `mathematics` line is proven. The `computation` line runs the same claim through the real code in floating point and is falsified at a series of five returns that differ only in their last digit: their standard deviation is about `2.5e-18`, the ratio about `-1.6e17`, and scaling the series by 10 moves the float result to about `-1.9e17`. That is a fact about the computation, not the mathematics. A loss like this is either inherent in the inputs (no float64 computation could do better there) or the code's own; the line says which when mathema can read the condition number at the witness, and says it cannot here, since the function's body is pandas rather than arithmetic derive can read. Undecided counts as the code's, so the record does not offer to accept the computation line on its own; the ways out it gives are fixing the code, accepting the whole claim as a discovery (its proven row and its computation line retire together, the witness kept), and narrowing the claim knowingly. The premise took the one-day series out, and mathema reads it exactly. The standard deviation of equal returns is 0 over the reals, so a constant series is outside the claim too, on both lines alike: mathema computes the premise's `std` exactly rather than through the function's floating point, so a constant series whose float standard deviation rounds to `1e-17` is still outside. The proof rested on two rows this time. The record names each one, with the file it came from: <!-- example: pandas run requires=pandas --> ```python proof = record.probes[0] print(textwrap.fill(proof.sketch, 78)) for row in proof.meta["mathema.definitions"]: print(row["key"], row["source"]) ``` <!-- example: pandas output --> ```text taking pandas.Series.mean as mean(a) (axiom, bundled with mathema, pandas 2.2 to 3.x); taking pandas.Series.std as std(a, ddof=1) (axiom, bundled with mathema, pandas 2.2 to 3.x); through the pandas.Series.mean definition and pandas.Series.std definition rows, read as sums over returns at a symbolic length: the relation holds for every length pandas.Series.mean mathema/compendium/pandas/series.claims.yaml pandas.Series.std mathema/compendium/pandas/series.claims.yaml ``` Narrowing knowingly, the second way out the computation line gives, means here saying which series the claim is about. With `std(returns, ddof=1) > 1e-6` as the premise, the claim leaves out series this close to constant, and both lines come back: <!-- example: pandas run requires=pandas --> ```python narrowed = mathema.check(sharpe, claims=[mathema.claim( "for returns in [-0.1, 0.1]^n \\ {missing}, let s = mathema.f.scale_seq, " "let c be [0.1, 10], assuming std(returns, ddof=1) > 1e-6, " "f(s(returns, c)) ~= f(returns)", name="leverage_invariant")]) for row in narrowed.probes: if row.name.startswith("leverage_invariant"): print(row.name, row.verdict) ``` <!-- example: pandas output --> ```text leverage_invariant proven leverage_invariant[float, pandas.Series] holds ``` In a claims file, that edit is followed by `mathema accept returns.sharpe leverage_invariant --as superseded`, as the record's second fix says. ## A claim that is false and stays false Adding a constant to every return is a different matter: the mean moves and the standard deviation does not, so the ratio changes. State it as if it were invariant, and the witness shows both sides: <!-- example: pandas run requires=pandas --> ```python record = mathema.check(sharpe, claims=[mathema.claim( "for returns in [-0.1, 0.1]^n \\ {missing}, let s = mathema.f.shift_seq, " "let c be [0.1, 10], assuming std(returns, ddof=1) > 0, " "f(s(returns, c)) ~= f(returns)", name="shift_invariant")]) print(record.probes[0].verdict) print(record.probes[0].counterexample) ``` <!-- example: pandas output --> ```text falsified returns = pandas.Series([-0.03634407021233441, 0.03649461504266753, 0.02979742176821469, -0.09999979999999999], index=pandas.bdate_range('2020-01-01', periods=4)); c = 4.718034171081078: 1164.6923472459507 vs -4.339350392263283 ``` Four days of returns, each shifted up by about 4.72: a Sharpe ratio of about 1,165 against the original's -4.3. Sampling is seeded, so the same witness comes back on every run. ## Where next - [Runtime types](runtime-types.md) is the reference behind this page: how a parameter's runtime type is read from the signature, the hint mathema prints when a body uses a list as a `Series`, and claims over `DataFrame` columns. - [The evidence ladder](evidence-ladder.md) places `proven` and the computation line under it on their rungs. - [See what mathema knows about a library you call](library-claims.md) shows which of the pandas and numpy calls your code makes have rows like the two above, and how to state one for a call nothing covers. - [The claim grammar](grammar.md) has one example per form used here: `[a, b]^n`, `let c be [0.1, 10]`, `let s = mathema.f.scale_seq`, a premise such as `std(returns, ddof=1) > 0` written after `assuming`, and `~=`. - docs/quickstart.md (8707 bytes)
# Quick start Five minutes, one function, and a claim that goes from falsified to proven. Everything below is real output from a fresh install, so you can follow along by pasting it. ## Install Work inside a virtual environment rather than against a system Python: ```bash python3 -m venv .venv && source .venv/bin/activate pip install "mathema[all]" ``` `[all]` adds numpy, the z3 proof rung, the MCP server, the coverage reader and mathema-language; `pip install mathema` is the minimal core, enough for everything on this page except the exact counterexample below, which was found with z3 installed (the `smt` extra). Without it the claim is still falsified, but the witness reported may be a different point. mathema is fully offline. The one command that reaches the network is `mathema init --agents`, which you run by name to fetch the optional agent tooling with `git`. There is no account and no API key, and the only required dependencies are sympy for the symbolic route and pyyaml for the record store. ## Write a function Put this in `pricing.py`: <!-- example: falsify file=pricing.py --> ```python def discounted(price: float, rate: float) -> float: """The price after applying a discount rate.""" return price * (1 - rate) ``` ## State a claim about it A claim is a specific, checkable statement about what the function does. The obvious one here is that discounting never makes something more expensive: <!-- example: falsify run --> ```bash mathema check pricing.py:discounted --claim "for rate in [0, 1], f(price, rate) <= price" ``` <!-- example: falsify output --> ```text FAIL pricing.discounted: source, no side effects; claims 3/3 checked (0 proven, 2 holds, 1 falsified) <- 1 falsified claim(s) ``` Falsified, on the first try. That is not a bad start, it is the point. Asking for the counterexample says why: <!-- example: falsify run requires=z3 --> ```python import mathema from pricing import discounted (p,) = mathema.claims.check_conjectures( discounted, [mathema.claim("for rate in [0, 1], f(price, rate) <= price", name="never_raises_price")]) print(p.verdict, p.counterexample) ``` <!-- example: falsify output --> ```text falsified price = -1, rate = 1 ``` The claim is wrong, not the code. A negative price multiplied by something smaller than one gets *larger*, and the claim never said prices are positive. mathema found the gap by looking, not by being told where to look. ## Fix the claim Say the thing the claim was assuming: <!-- example: falsify run --> ```python (p,) = mathema.claims.check_conjectures( discounted, [mathema.claim("for price in [0, 1e6], rate in [0, 1], f(price, rate) <= price", name="never_raises_price")]) print(p.verdict) print(p.condition) ``` <!-- example: falsify output --> ```text proven where x=price, y=rate: ∀ x ∈ [0.0, 1000000.0] ⊂ ℝ, y ∈ [0.0, 1.0] ⊂ ℝ ``` `proven`, not `holds`. mathema did not run `discounted` on a thousand random prices and shrug, it lifted the body to a symbolic expression and decided the inequality algebraically, so the result covers every price in that range rather than the ones a sampler happened to pick. The region it proved over is printed back explicitly, and it is over the reals: the NaN a `price: float` admits is not a real number, so the proof leaves it to the float computation, whose record lists what f did at nan. That difference is the whole idea: `holds` is evidence, `proven` is proof, and mathema always tells you which one you have. The full ladder is in [the evidence ladder](evidence-ladder.md), and every verdict word in [Verdicts and exit codes](verdicts.md). ## Move it into the code A claim is worth more next to the function than in a shell history. Put it in the docstring: <!-- example: docstring file=pricing.py --> ```python def discounted(price: float, rate: float) -> float: """The price after applying a discount rate. Claims: never_raises_price: for price in [0, 1e6], rate in [0, 1], f(price, rate) <= price """ return price * (1 - rate) ``` <!-- example: docstring run --> ```bash mathema check pricing.py ``` <!-- example: docstring output --> ```text ok pricing.discounted: source, no side effects; claims 4/4 checked (1 proven, 3 holds, 0 falsified) ``` One claim, four checks. The first is the proof over the real numbers. The second runs the same claim through the real code in floating point, since a proof is about the mathematics and whether the computation keeps up in float64 is a separate question. The last two say what `discounted` does when `price` or `rate` is `nan`, a value a float may carry: nothing in the claim says, so mathema assumes the `nan` propagates to the result, and checks that it does. See [the evidence ladder](evidence-ladder.md). The docstring is one of four places a claim can live, alongside a decorator, a claims file, and an annotation. See [authoring claims](authoring.md) for the precedence order between them. ## Keep the record <!-- example: docstring run --> ```python import mathema from pricing import discounted mathema.write_spec(discounted) print(open(".mathema/verified/pricing.discounted.yaml").read()) ``` That writes `.mathema/verified/pricing.discounted.yaml`, which is the durable artifact: the claim, its verdict, the region it was proved over, the proof sketch, the floating-point run's row (`[float]`), the two `nan` rows (`missing[price]`, `missing[rate]`), and the identity hash it binds to (an excerpt): <!-- example: docstring output match=subset --> ```yaml # machine record; binds to form py:33f04232830d pricing.discounted: identity: form: "py:33f04232830d" claims: - name: "missing[price]" statement: "missing(f, price) propagates" verdict: "holds" n: 1 note: "default for a float, which may be nan; confirmed on the 49 draws of never_raises_price[float]. Change the word to raises or drops if f should do otherwise; to keep it, run: mathema claims pricing.discounted --write" route: "probe:counterfactual" - name: "missing[rate]" statement: "missing(f, rate) propagates" verdict: "holds" n: 1 note: "default for a float, which may be nan; confirmed on the 49 draws of never_raises_price[float]. Change the word to raises or drops if f should do otherwise; to keep it, run: mathema claims pricing.discounted --write" route: "probe:counterfactual" - name: "never_raises_price" statement: "for price in [0.0, 1000000.0] : float|missing, rate in [0.0, 1.0] : float|missing, f(price, rate) <= price" verdict: "proven" sketch: "interval evaluation over the declared domain: price*rate ∈ AccumBounds(0, 1000000), never negative" condition: "where x=price, y=rate: ∀ x ∈ [0.0, 1000000.0] ⊂ ℝ, y ∈ [0.0, 1.0] ⊂ ℝ" route: "derive" - name: "never_raises_price[float]" statement: "for price in [0.0, 1000000.0] : float|missing, rate in [0.0, 1.0] : float|missing, f(price, rate) <= price" verdict: "holds" n: 49 note: "the float64 computation of never_raises_price ran at 49 points: every corner and 40 interior points" route: "probe" ``` The record binds to `form`, a hash of the function's *structure*, so renaming a variable or reformatting the body leaves it valid while a real change to behaviour marks it stale. Commit `.mathema/` along with your code: the evidence should travel with the thing it is evidence about. ## Check it in CI ```bash mathema verify ``` `verify` re-adjudicates every recorded function whose form hash moved, and exits 1 if a claim is falsified, unknown, skipped, or accepted as risk (`--lenient` lets the last two through, named in the report), so it drops into a pipeline exactly where a test runner would. Exit code 2 means mathema could not run at all, which is worth keeping distinct from a real finding. See [exit codes](verdicts.md#exit-codes). You do not have to write the workflow yourself: `mathema init --ci` scaffolds the GitHub Actions verify gate (or `--ci gitlab` the GitLab fragment) with the install step marked for your project, see [mathema init](modes/init.md#the-ci-gate-ci). ## Where to go next - [Tutorial: the CDD loop](tutorial.md) walks the full cycle, including what to do with a falsification you disagree with. - [Writing claims](authoring.md) covers the four authoring surfaces. - [The claim grammar](grammar.md) is the reference for everything you can say in a claim, with a runnable example of each. - [The derive route](derive-route.md) explains exactly which function shapes can reach `proven`, and what happens to the ones that cannot. - docs/reason-codes.md (14191 bytes)
# Reason codes The stable vocabulary for *why* a function is underivable, as printed in `mathema audit`'s `blocked` column and detail block, carried in `diagnostic_report()`/`describe --issue` payloads, and served by the MCP `reason_code` tool. Look one up programmatically with `mathema.reason_codes.describe_code(code)`. A code reads `family:detail`: `loop:` codes come from the fold recognizer, `branch:` codes from branch pruning (the resolvable kind, `branch:needs-domain(...)`, names the parameters a claim should declare a domain for), `unsupported:` codes from the expression reader, and the bare codes (`stateful`, `recursion`, ...) from the structural read. The `implementation:` group is different in kind: its codes are not derivability blockers but falsification causes, attached to a `falsified` claim whose failure is pinned on the implementation stratum (an overflow, a recursion ceiling, float instability) rather than on the mathematics; they ride the claim row's `reason` field the same way, so tooling separates a broken number representation from broken mathematics without parsing prose. A `+N` suffix on a branch code means N further distinct blocked kinds occur in the same function; the detail block lists each one. The `derive_unlock` tag says what would unlock the derive route, and whose move it is, nothing is broken either way, since a probe-route claim adjudicates regardless: `actionable` (the code or the claim can change to unlock it), `limitation` (the construct is fine, the derive route doesn't reach it yet, the claim still adjudicates empirically), or `N/A` (the derive route fundamentally doesn't apply). Once released, a code is never renamed or repointed; new codes only ever join. Codes carry a stable numeric id, `major.minor`: majors are the structural groups (1 structural blockers, 2 loop, 3 branch, 4 unsupported, 5 implementation), so a lookup can fetch a whole group ("2", or "loop") or a single code ("2.18") instead of the full table. Ids are additive only: a new code appends the next minor in its group, and a released id is never renumbered. | Id | Code | Derive unlock | Meaning | Hint | |---|---|---|---|---| | 3.2 | `branch:bare-local-name` | limitation | a bare local name's truthiness guards the branch | only comparisons are traced through locals; compare explicitly ('if flag == 1:') | | 3.11 | `branch:composite` | limitation | an and/or chain with several distinct blocked parts | each joined condition must be prunable on its own; see the per-branch detail | | 3.1 | `branch:needs-domain` | actionable | every branch resolves once the named parameters have declared domains | declare a domain for the named parameter(s) in the claim, e.g. 'for x in [0, 1], s in {"a"}, ...' | | 3.7 | `branch:no-parameter-dependence` | limitation | the condition's TRACED form contains no unmodified parameter; either it genuinely uses none (a module flag, a constant guard) or the trace lost the dependence on the way | a claim's domain can only settle conditions over unmodified parameters; rewrite the condition over them, or accept the branch as unprunable | | 3.8 | `branch:non-affine-essential` | limitation | the condition is transcendental in the parameters | no reparameterization linearizes it; a domain whose interval evaluation settles the guard outright can still work | | 3.9 | `branch:non-affine-refinable` | actionable | the condition is polynomial but not affine | reparameterize to one combined variable, or declare a tighter domain that settles the guard | | 3.4 | `branch:non-literal-compare` | limitation | the comparand is not a literal value | compare against a literal, or bind the comparand as its own parameter | | 3.6 | `branch:opaque-expression` | limitation | neither side reduces to parameters or a literal | rewrite the condition over the function's own parameters | | 3.3 | `branch:two-names-compare` | limitation | two names compared and at least one is not an unmodified parameter | pruning supports 'param <op> literal' and 'param <op> param' between unmodified parameters | | 3.10 | `branch:unrecognized-shape` | limitation | the condition's shape is outside the grammar | only and/or/not, a bare parameter, or a single comparison are recognized | | 3.5 | `branch:untraceable-local` | limitation | the condition's local is not traceable to unmodified parameters | only straight-line assignments from unmodified parameters are traced before the first branch | | 5.1 | `implementation:overflow` | N/A | the call overflowed at an admitted point | the number representation is too narrow for the domain; widen the representation, guard the range, or narrow the claim's domain below the overflow threshold | | 5.2 | `implementation:recursion-depth` | N/A | the call exhausted the recursion limit at an admitted point | an iterative rewrite removes the ceiling; otherwise narrow the claim's domain below the depth that exhausts the stack | | 5.3 | `implementation:memory` | N/A | the call exhausted memory at an admitted point | narrow the claim's domain, or bound the allocation the input size drives | | 5.4 | `implementation:nan` | N/A | the call returned a non-finite value where the exact value is finite | stated only when an exact-arithmetic result exists to compare against; clamp or reorder the operation that loses the value | | 5.5 | `implementation:numerical-instability` | N/A | proven exactly in real arithmetic, numerically unstable in the declared domain | where the loss is inherent in the inputs, bound the computation with a pseudo infinity binding along an unbounded direction, or narrow a bounded domain; where it is the code's, reorder or clamp the fragile operation; or widen the tolerance to accept the risk | | 5.6 | `implementation:sub-epsilon-boundary` | N/A | a raise at a floating-point boundary; the same inputs nudged within epsilon evaluate cleanly | a clamp at the raising operation's argument removes the fragility | | 5.7 | `implementation:representation` | N/A | machine spellings of one mathematical point disagree (int versus float versus bool) | normalize the input representation at entry, or state the intended representation in the claim | | 5.8 | `implementation:accidental-crash` | N/A | an unguarded crash on arbitrary input, not a deliberate rejection | guard the input and raise the declared exception, or narrow the claim to the inputs the function accepts | | 5.9 | `implementation:absent` | N/A | the call returned an absent value (None) from present inputs where the declared return type promises one | declare Optional[T] if None is an answer the function gives, or return a value | | 1.5 | `internal-error` | limitation | the derivability analysis itself failed | worth reporting: describe --issue builds the payload | | 2.19 | `loop:additive-constant-update` | limitation | the linear update carries a constant term | a pure linear combination of item and accumulator is recognized today; the constant-term extension is tractable but not built | | 2.5 | `loop:branch-elsewhere` | limitation | a non-guard branch outside the loop | leading raise-guards are stripped and proved around; any other branching alongside a loop blocks the fold read | | 2.13 | `loop:external-init-wrong-iteration` | actionable | constant init but the loop skips part of the sequence | a constant-initialized fold should iterate the whole sequence; change the loop, or initialize from xs[0] | | 2.8 | `loop:extra-statements` | limitation | statements besides init, loop, and return | extra work outside the loop is not part of a recognized fold; move it out or fold it into the return expression | | 2.11 | `loop:first-element-init-wrong-iteration` | actionable | acc starts at xs[0] but the loop iterates all of xs | iterating the whole sequence double-counts xs[0]; change the loop to iterate xs[1:] | | 2.4 | `loop:guarded-fold` | limitation | the accumulator update sits under an if | a conditional update has no single closed form; state the guarded region as its own claim instead | | 2.15 | `loop:multi-statement-loop-body` | limitation | more than one statement in the loop body | only a single accumulator update per iteration is recognized; inline temporaries into the update | | 2.2 | `loop:multiple-loops` | limitation | more than one loop in the body | only a single-loop body is recognized; split the function so each loop is its own function | | 2.1 | `loop:no-loop` | limitation | the loop analysis ran on a function with no loop | usually a sign the body's shape confused the recognizer; worth reporting | | 2.17 | `loop:no-return-value` | limitation | the function does not return the accumulator | a fold is recognized by returning a value built from its accumulator | | 2.18 | `loop:non-affine-update` | limitation | the update is not linear in item and accumulator | only 'acc = A*item + B*acc' updates have the recognized closed form; a multiplicative fold does not derive today | | 2.9 | `loop:non-simple-init` | limitation | the accumulator's initialization is not a single assignment | initialize the accumulator in one plain assignment before the loop | | 2.10 | `loop:non-simple-loop-header` | limitation | the for-header does not iterate a plain name or recognized slice | iterate the sequence parameter directly (or xs[1:]) | | 2.16 | `loop:non-simple-update` | actionable | the update is not a single assignment to the accumulator | write the update as one 'acc = <expr>' (or augmented) assignment | | 2.3 | `loop:not-a-fold` | limitation | the loop is not an accumulator fold | only 'acc = f(acc, item)' accumulation loops are recognized | | 2.12 | `loop:partial-seq-init` | actionable | acc starts from part of the sequence | initialize from xs[0] and iterate xs[1:], or from a constant and iterate all of xs | | 2.6 | `loop:recursion` | limitation | the loop body also recurses | not derivable regardless of the loop's own shape | | 2.20 | `loop:tuple-in-expression` | limitation | a tuple value inside the loop's own expressions | track one scalar accumulator per function | | 2.21 | `loop:unclassified` | limitation | the fold recognizer declined without a specific reason | worth reporting: describe --issue builds the payload | | 2.14 | `loop:unrecognized-loop-header` | actionable | the iterated expression is not a recognized shape | iterate the sequence parameter, xs[1:], or range(<expr>) with a derivable <expr> | | 2.7 | `loop:wrong-sequence-param-count` | limitation | not exactly one sequence parameter | the fold read needs one sequence parameter to iterate | | 1.3 | `no-parameters` | N/A | nothing to quantify over | a zero-parameter function has no input space to state claims about; probing can still check a constant value claim | | 1.4 | `non-scalar-parameters` | limitation | a sequence parameter outside the recognized shapes | sequence functions derive only through the recognized loop shapes (fold, dot product, pure sum); anything else stays empirical | | 1.2 | `recursion` | limitation | the function calls itself | a single-parameter recurrence of the recognized shape is solved, and a claim over a small integer range is checked exhaustively; any other recursion is not derivable, and an iterative or closed-form equivalent is | | 1.1 | `stateful` | N/A | the method modifies instance state, or lets self escape the read-only field/sibling-call vocabulary | reading fields and calling sibling methods derives fine; a write to self (or passing self elsewhere) does not; keep the numeric core read-only, or extract it into a stateless function | | 4.10 | `unsupported:array-index-mismatch` | limitation | an array indexed inconsistently with its construction | only same-length elementwise array reads derive | | 4.9 | `unsupported:invalid-tuple-index` | limitation | a tuple indexed outside its known length | usually a real bug in the code being read | | 4.11 | `unsupported:non-numeric-constant` | limitation | a non-numeric constant in a numeric position | string/bytes/None values have no numeric reading; a finite domain claim can still cover them | | 4.12 | `unsupported:unsupported-statement` | limitation | a statement kind the derive route has no reading for where only assignment/return/if/for/raise belong (a while, try, with, del, ...) | the named statement is the blocker; restructure around it or rely on probe evidence | | 4.13 | `unsupported:missing-return` | actionable | the function body never returns a value | a derive-route claim is about the returned value; add the return (or the claim belongs on a function that has one) | | 4.7 | `unsupported:ternary` | limitation | a conditional expression in an unsupported position | an if/else statement over a prunable condition can take its place | | 4.8 | `unsupported:tuple-in-expression` | limitation | a tuple value used inside an expression | return and compute one scalar per function | | 4.6 | `unsupported:unbound-name` | actionable | a name with no binding anywhere | define or import the name; an unresolved name also fails the gate | | 4.5 | `unsupported:unsupported-attribute` | limitation | an attribute access with no symbolic meaning | only mapped module attributes (math.pi, ...) derive | | 4.2 | `unsupported:unsupported-comprehension` | limitation | a comprehension outside the recognized sum(...) shapes (a built list/dict value, a dict/set comp) | sum(<generator>) derives; rewrite the aggregation as sum(...) or an explicit accumulator loop; a comprehension VALUE is vector-valued and out of scope | | 4.3 | `unsupported:unsupported-lambda` | limitation | a lambda outside the recognized shapes | assign the lambda to a local and call it, bind it via funcs=, or use it inside sum(map/filter(...)) | | 4.4 | `unsupported:unsupported-call` | limitation | a call with no symbolic mapping | only the mapped math vocabulary derives; the claim still adjudicates empirically | | 4.1 | `unsupported:unsupported-syntax` | limitation | a statement or expression outside the derive route's read | the named statement is the blocker; the rest of the body reads fine | Probe-route claims remain viable on any function regardless of these codes; they gate proof-strength (derive-route) evidence only, never whether a claim can be written at all. - INSTRUCTIONS.md (72 bytes)
Claim-Driven Development: turn software intent into verifiable evidence.
- LICENSE.md (7850 bytes)
Business Source License 1.1 Parameters Licensor: Tetrion Ltd Licensed Work: mathema 0.6.6.2 The Licensed Work is (c) 2026 Tetrion Ltd. Additional Use Grant: 1. Grant. You may make production use of the Licensed Work, without charge, if at the time of that use any of the following applies: (a) Revenue. The total revenue of your Organisation in its most recently completed financial year was less than USD 10,000,000 (or the equivalent in any other currency at the exchange rate prevailing at the end of that year); or (b) Repositories. The Licensed Work is used in connection with no more than three Repositories across your Organisation in aggregate; or (c) Non-commercial use. Your use is for research, teaching, personal, or other non-commercial purposes, and not for the benefit of any commercial product, service or operation; or (d) Evaluation. Your use is for the purpose of evaluating the Licensed Work, for a single period of no more than 90 days beginning on the date your Organisation first uses the Licensed Work for evaluation. 2. Scope. Whether or not any of paragraphs 1(a) to 1(d) applies, this Additional Use Grant does not extend to making the Licensed Work available to any third party, whether or not for a fee, as part of or in support of a Competing Product. 3. Use on behalf of others. Where you use the Licensed Work on behalf of, or for the benefit of, another person or entity, the Organisation of that person or entity is treated as your Organisation for the purposes of paragraphs 1(a) and 1(b), and the Repositories of that person or entity count toward the limit in paragraph 1(b). 4. Definitions. In this Additional Use Grant: "Organisation" means the legal entity you act for, together with every entity that controls it, is controlled by it, or is under common control with it, and where you act for no legal entity, means you. "Repository" means a distinct source-code repository, under any version-control system, whose contents the Licensed Work reads, analyses, or produces output about. For purposes of paragraph 1(b), a single Repository containing multiple independently deployable applications, products, or services will be treated as a separate Repository for each such application, product, or service that uses the Licensed Work, regardless of whether they are maintained within the same version-control repository. "Competing Product" means a product or service, made available to third parties, whose primary function is (i) the adjudication, verification or certification of claims about the behaviour or correctness of software, including software produced with the assistance of artificial intelligence; or (ii) substantially the same as the primary function of a product or service that the Licensor makes commercially available using the Licensed Work. "Production Use" means use of the Licensed Work in connection with the development, testing, verification, analysis, build, deployment, maintenance, or assurance of software or systems intended for production or other real-world use. Production Use applies regardless of whether the Licensed Work itself is run in a production environment, development environment, CI/CD system, or other environment. 5. Commercial licences. Production use outside the scope of this Additional Use Grant requires a commercial licence from the Licensor. Enquiries: [email protected]. Change Date: 2030-11-24 (four years from the 2026-11-24 release of version 0.6.6.2) Change License: GNU Affero General Public License v3.0 or later (AGPL-3.0-or-later) For information about alternative licensing arrangements for the Licensed Work, please contact [email protected]. ----------------------------------------------------------------------- License text copyright © 2024 MariaDB plc, All Rights Reserved. “Business Source License” is a trademark of MariaDB plc. Terms The Licensor hereby grants you the right to copy, modify, create derivative works, redistribute, and make non-production use of the Licensed Work. The Licensor may make an Additional Use Grant, above, permitting limited production use. Effective on the Change Date, or the fourth anniversary of the first publicly available distribution of a specific version of the Licensed Work under this License, whichever comes first, the Licensor hereby grants you rights under the terms of the Change License, and the rights granted in the paragraph above terminate. If your use of the Licensed Work does not comply with the requirements currently in effect as described in this License, you must purchase a commercial license from the Licensor, its affiliated entities, or authorized resellers, or you must refrain from using the Licensed Work. All copies of the original and modified Licensed Work, and derivative works of the Licensed Work, are subject to this License. This License applies separately for each version of the Licensed Work and the Change Date may vary for each version of the Licensed Work released by Licensor. You must conspicuously display this License on each original or modified copy of the Licensed Work. If you receive the Licensed Work in original or modified form from a third party, the terms and conditions set forth in this License apply to your use of that work. Any use of the Licensed Work in violation of this License will automatically terminate your rights under this License for the current and all other versions of the Licensed Work. This License does not grant you any right in any trademark or logo of Licensor or its affiliates (provided that you may use a trademark or logo of Licensor as expressly required by this License). TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON AN “AS IS” BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS, EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND TITLE. MariaDB hereby grants you permission to use this License’s text to license your works, and to refer to it using the trademark “Business Source License”, as long as you comply with the Covenants of Licensor below. Covenants of Licensor In consideration of the right to use this License’s text and the “Business Source License” name and trademark, Licensor covenants to MariaDB, and to all other recipients of the licensed work to be provided by Licensor: To specify as the Change License the GPL Version 2.0 or any later version, or a license that is compatible with GPL Version 2.0 or a later version, where “compatible” means that software provided under the Change License can be included in a program with software provided under GPL Version 2.0 or a later version. Licensor may specify additional Change Licenses without limitation. To either: (a) specify an additional grant of rights to use that does not impose any additional restriction on the right granted in this License, as the Additional Use Grant; or (b) insert the text “None” to specify a Change Date. Not to modify this License in any other way. Notice The Business Source License (this document, or the “License”) is not an Open Source license. However, the Licensed Work will eventually be made available under an Open Source License, as stated in this License. For more information on the use of the Business Source License for MariaDB products, please visit the MariaDB Business Source License FAQ. For more information on the use of the Business Source License generally, please visit the Adopting and Developing Business Source License FAQ. - LICENSING.md (2891 bytes)
# Licensing mathema is source-available under the [Business Source License 1.1](LICENSE.md), copyright Tetrion Ltd. This page is a plain-language restatement plus Tetrion's licensing policy; the license text in [LICENSE.md](LICENSE.md) is what governs (including its Additional Use Grant, where the free-use permissions below actually live) and wins if the two ever disagree. That covers the software. The **documentation prose and examples are [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/)**: quote them, adapt them and republish them, commercially or not, with attribution. ## Free production use: who qualifies The Additional Use Grant in LICENSE.md permits production use without charge when **any** of these applies to your Organisation (your legal entity together with everything that controls it, is controlled by it, or is under common control with it): - **Revenue floor**: total Organisation revenue under **USD 10,000,000** in your most recently completed fiscal year; or - **Repository floor**: mathema is used in connection with **no more than three code repositories** across the Organisation; or - **Non-commercial**: research, teaching, personal, or other non-commercial use; or - **Evaluation**: up to **90 days** from the Organisation's first use. Whatever your size: the grant never permits providing third parties a product or service that substantially does what mathema does, or what any Tetrion product built on mathema does. Everything short of production use (copying, modifying, creating derivative works, redistributing, non-production use) is granted to everyone by the license's own Terms, no grant needed. ## Above the floor If none of the grant's conditions applies to you, production use requires a commercial license, contact [email protected]. ## Cure policy If your Organisation drifts out of the grant (crosses the revenue floor at a fiscal year end, exceeds the three-repository floor, or an evaluation runs past 90 days), you have **60 days** from the date the condition ceased to apply to either obtain a commercial license or end production use. Tetrion treats good-faith use during that window as licensed; rights under the license terminate only after the window closes without either happening. ## Conversion schedule Every released version of mathema converts to the **GNU Affero General Public License v3.0 or later** on its Change Date: **four years after that version's release**, computed at release and written into the release's own LICENSE.md. After conversion the version is under an OSI-approved copyleft licence and the restrictions above stop applying to it entirely. ## The policy document The operative statement of the cure policy, the floors, and the conversion schedule is published at [docs/licensing-policy.md](docs/licensing-policy.md); this page restates it alongside the license summary.
- mkdocs.yml (7303 bytes)
site_name: mathema site_description: "Claim-Driven Development: turn software intent into verifiable evidence." site_url: https://mathema.tetrionlabs.com repo_name: tetrionlabs/mathema repo_url: https://github.com/tetrionlabs/mathema # The deployed footer carries the company's legal details from the # DOCS_LEGAL_FOOTER repository variable (set in the repo's Actions # settings, passed by docs.yml); every other build uses the short line. copyright: !ENV [DOCS_LEGAL_FOOTER, "Copyright 2026 Tetrion Ltd"] theme: name: material custom_dir: overrides logo: assets/tetrion-mark-light.svg favicon: assets/favicon.ico font: false icon: repo: octicons/mark-github-24 # Ink is the ground whatever the reader's system preference: with no # media query on either entry, the first palette is the default and # the toggle switches to the second. palette: - scheme: slate primary: custom accent: custom toggle: icon: octicons/sun-24 name: Switch to light mode - scheme: default primary: custom accent: custom toggle: icon: octicons/moon-24 name: Switch to dark mode features: - navigation.tabs - navigation.sections - navigation.top - navigation.footer - content.code.copy - content.code.annotate extra_css: - stylesheets/tokens.css - stylesheets/extra.css # the mathema-language package's reference, under /language/reference/, # when its docs are present at build time (see the hook's docstring) hooks: - docs_hooks/language_reference.py markdown_extensions: - admonition - pymdownx.details - pymdownx.superfences - pymdownx.highlight - tables - toc: permalink: true plugins: - search - llmstxt: markdown_description: >- mathema is a System 0 engine for Claim-Driven Development: a verification engine with zero models between the code and its verdict. You state claims about Python functions; mathema proves them symbolically where the function lifts, tests them against the real code where it does not, and keeps a record bound to the exact code it verified. Verdicts are proven, holds (n trials), falsified (with an executed witness), invalidated, unknown and skipped, and each means exactly what the guarantees page says. Agents propose claims; mathema adjudicates; people accept. full_output: llms-full.txt sections: Start here: - index.md: What mathema is and why it exists - install.md: Installing mathema - quickstart.md: State a claim, see it falsified, fix it, record it, gate CI - tutorial.md: The full claim-driven development loop on a real function Concepts: - guarantees.md: What each verdict establishes and does not, and the glossary - evidence-ladder.md: How proof and sampled evidence are kept apart - cdd.md: The method, its vocabulary and exit codes - derive-route.md: What the symbolic route can lift and prove - claims-transfer.md: Moving claims between projects and implementations - reason-codes.md: Stable reason codes and their remedies Trust and governance: - governance.md: Who decides what, the integrity checksum, the CI gate - security.md: What runs when a claim is checked, and how to contain it Writing claims: - authoring.md: The authoring surfaces and their precedence - grammar.md: The claim grammar, domains and tolerance - grammar-words.md: What each of the grammar's words computes - multi-function-claims.md: Binding functions and the equivalence ladder - lemmas.md: Claims that rest on other claims Commands: - modes/check.md: Check a function's claims - modes/verify.md: The CI gate over the committed store - modes/accept.md: Human acceptance of a verdict - modes/review.md: The claim-level delta of a change Coding agents: - agents.md: Working with coding agents - modes/mcp.md: The MCP interface - mkdocstrings: handlers: python: options: show_source: true show_root_heading: true docstring_style: google nav: - Home: index.md - Start here: start.md - Get started: - Install: install.md - Quick start: quickstart.md - See what mathema finds: findings.md - A first look: first-look.md - The CDD loop, end to end: tutorial.md - Claims about a pandas function: pandas-function.md - Case studies: case-studies.md - "Case study: the mean of nothing": mean-of-nothing.md - How-to guides: - Gate a pipeline with mathema verify: gate-a-pipeline.md - See what mathema knows about a library you call: library-claims.md - Add claims to an existing codebase: existing-codebase.md - From a pytest test to a claim: from-a-pytest-test.md - Concepts: - Guarantees and limits: guarantees.md - Verdicts and exit codes: verdicts.md - The evidence ladder: evidence-ladder.md - Intent, implementation and behaviour: three-layers.md - Claims transfer: claims-transfer.md - "The method: claim-driven development": cdd.md - The derive route: derive-route.md - Reason codes: reason-codes.md - Writing claims: - Authoring claims: authoring.md - The claim grammar: grammar.md - "The grammar's words": grammar-words.md - The mathema docstring: mathema-docstring.md - Conditional claims: conditional-claims.md - Lemmas: lemmas.md - Matrix structure and linear algebra: matrix-structure.md - "Runtime types: numpy, pandas, polars": runtime-types.md - Missing values: missing-values.md - Language domains: language.md - Multi-function claims: multi-function-claims.md - Command reference: - mathema check: modes/check.md - mathema verify: modes/verify.md - mathema compendium: modes/compendium.md - mathema audit: modes/audit.md - mathema claims: modes/claims.md - mathema accept: modes/accept.md - mathema lock and unlock: modes/lock.md - mathema pin: modes/pin.md - mathema review: modes/review.md - mathema badges: modes/badges.md - mathema coverage: modes/coverage.md - mathema describe: modes/describe.md - mathema docsync: modes/docsync.md - mathema init: modes/init.md - Using mathema from code: - Library usage: modes/library.md - API reference: api.md - Symbology and rendering: symbology.md - Extending mathema: extending.md - Trust and governance: - Governance and audit: governance.md - Security and execution: security.md - Coding agents: - Working with coding agents: agents.md - Set up mathema for a coding agent: agent-setup.md - The MCP interface: modes/mcp.md - Project: - Licensing: licensing-policy.md - Versioning and stability: stability.md - Security policy: https://github.com/tetrionlabs/mathema/blob/main/SECURITY.md - Changelog: https://github.com/tetrionlabs/mathema/blob/main/CHANGELOG.md - pyproject.toml (9607 bytes)
[build-system] requires = ["setuptools>=68"] build-backend = "setuptools.build_meta" [project] name = "mathema" dynamic = ["version"] description = "A Python verification engine for Claim-Driven Development: state explicit mathematical claims about code and adjudicate them against symbolic and empirical evidence." readme = "README.md" requires-python = ">=3.10" # BUSL-1.1 is a known SPDX identifier (a recognized non-OSI, # source-available license), so metadata and headers classify cleanly. license = "BUSL-1.1" license-files = ["LICENSE.md", "LICENSING.md"] authors = [{ name = "Tetrion Ltd", email = "[email protected]" }] # sympy is bounded below the next major: a derive-route verdict # depends on sympy's own simplification and canonical ordering, so a # major release can change what proves without any change here. dependencies = ["sympy>=1.12,<2", "pyyaml>=6"] keywords = ["claim-driven-development", "spec-driven-development", "test-driven-development", "software-verification", "property-based-testing", "design-by-contract", "specification", "proof", "ai-assisted-development", "mcp"] classifiers = [ # source-available under BUSL 1.1, converting to AGPL-3.0-or-later # four years after each release: deliberately NOT an OSI licence, # and PEP 639 forbids a License:: classifier beside the `license` # expression above, so none is given "Development Status :: 4 - Beta", "Intended Audience :: Developers", "Intended Audience :: Science/Research", "Operating System :: OS Independent", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", "Programming Language :: Python :: 3.14", "Topic :: Scientific/Engineering :: Mathematics", "Topic :: Software Development :: Testing", "Typing :: Typed", ] [project.urls] Homepage = "https://mathema.tetrionlabs.com" Documentation = "https://mathema.tetrionlabs.com" Repository = "https://github.com/tetrionlabs/mathema" Issues = "https://github.com/tetrionlabs/mathema/issues" Changelog = "https://github.com/tetrionlabs/mathema/blob/main/CHANGELOG.md" [project.optional-dependencies] # Documentation site tooling only, not needed to use mathema itself. # One documentation plugin needs Python 3.11.5 or later: the patched releases # of the HTML selector library it parses with no longer support earlier versions. docs = ["mkdocs>=1.6", "mkdocs-material>=9.5", "mkdocstrings[python]>=0.25", "mkdocs-llmstxt>=0.2; python_full_version >= '3.11.5'"] # numpy is not a runtime dependency of mathema itself; installed, it # turns on the array fast paths (matrix structure checks, array-shaped # parameter synthesis) and is exercised unconditionally by the tests. numpy = ["numpy>=2.0"] # pandas and polars are optional like numpy: installed, a parameter # annotated `pd.Series`, `pd.DataFrame`, `pl.Series` or `pl.DataFrame` # is sampled as one (its runtime type adapter); absent, that adapter is # inert. pandas = ["pandas>=2.2"] polars = ["polars>=1.0"] # Needed to run the test suite. pytest-xdist parallelises it, which # matters here because proof attempts are capped on the WALL clock: # oversubscribing the machine starves a proof of CPU and turns a # `proven` into a `holds`, a spurious failure in a test that asserts # the verdict. Measured on 8 cores: `-n 4` runs the suite in 2:41 fully # green, `-n auto` in 3:10 with one drifted verdict, and one process in # 8:15. Leave the machine headroom rather than claiming every core. test = ["pytest>=7", "pytest-xdist>=3", "pytest-cov>=7", "mathema[numpy,pandas,polars,coverage,smt]", # tomllib is stdlib only from 3.11, and the packaging-metadata # test reads pyproject directly, so it needs the backport on # the declared floor "tomli>=2; python_version < '3.11'"] # Local development and release tooling: the gates `.pre-commit-config # .yaml` runs, and the two commands the release workflow needs. Not a # runtime capability, so it stays out of `all`. # The dev extra (build, publish, pre-commit, lint, types) needs Python 3.11 or # later: its tools' current releases no longer support 3.10. mathema itself # still runs and is tested on 3.10. dev = ["build>=1; python_version >= '3.11'", "twine>=5; python_version >= '3.11'", "pre-commit>=3; python_version >= '3.11'", "ruff>=0.6; python_version >= '3.11'", "mypy>=1.8; python_version >= '3.11'", "filelock>=4.2.1; python_version >= '3.11'"] # The MCP interface (mathema mcp serve), the official MCP SDK, only # needed to actually serve; the tool functions themselves are SDK-free. # Upper bound deliberately: `mcp>=1.2` unbounded resolves to 2.x, # where FastMCP was renamed to MCPServer. server.py handles both, but # an unbounded major is a fresh-install hazard. mcp = ["mcp>=1.2,<3"] # The nlsat extensive rung, z3's nonlinear-real-arithmetic decision # procedure as an optional proof backend (a ~100 MB native library; # the ladder silently skips the rung without it). smt = ["z3-solver>=4.12"] # Reading a NATIVE `.coverage` report for the test source of `mathema # coverage` (Apache-2.0, no transitive deps). The pass itself needs no # third-party dependency: it traces with the stdlib `sys.settrace` and # reads a `coverage.json` export with plain json; this extra only adds # support for the binary `.coverage` format. coverage = ["coverage>=7"] # A "symbology" capability provider (see docs/symbology.md), # optional: this project's own convention names for common # parameters, installed separately. symbology = ["mathema-symbology>=0.3"] # String and structured-value domains, the `L[...]` languages a claim # names (see docs/language.md), installed separately. language = ["mathema-language>=0.2.0,<0.5"] # Every runtime CAPABILITY at once (not the docs/test dev tooling): # `pip install "mathema[all]"`. smt pulls z3-solver (~100 MB native). all = ["mathema[numpy,smt,mcp,coverage,language]"] [project.scripts] mathema = "mathema.cli:main" [tool.setuptools.packages.find] # Automatic discovery, not a hand-maintained package list: mathema has # subpackages (mathema.symbolic, mathema._devtools), and a fixed list # is the kind of thing that silently stops matching reality the next # time one is added. include = ["mathema*"] # repo tooling, not consumer surface: these shell out to `git ls-files` # and are meaningless inside an installed wheel exclude = ["mathema._devtools*"] [tool.setuptools.package-data] # the bundled compendium ships with the package, top-level files and # the per-library subdirectories alike (mathema/compendium/**/*.yaml); # the loader reads the files beside its own source "mathema.compendium" = ["*.yaml", "**/*.yaml"] # the short names for KOINE's operations, read beside the source "mathema.koine" = ["data/*.yaml"] # PEP 561: without this marker a type checker ignores the annotations # in the installed package and every imported name resolves to Any, # however carefully the source is typed "mathema" = ["py.typed"] [tool.setuptools.dynamic] version = { attr = "mathema.__version__" } [tool.pytest.ini_options] # `-n 4`, not `-n auto`: proof attempts are capped on the wall clock, # so oversubscribing the machine turns a `proven` into a `holds` and # fails an assertion about the verdict rather than about the code. # It is deliberately not forced through addopts, since xdist lives # only in the `test` extra and one test file is slower under four # workers than one. CI passes it explicitly. testpaths = ["tests"] # The repo root on sys.path, so test files that import a sibling as # `tests.test_x` collect under bare `pytest`, `python -m pytest` and # `mathema-ci measure` alike. pythonpath = ["."] [tool.coverage.run] # Measuring mathema itself. Many tests drive the CLI as a subprocess, so # subprocesses are measured too, each writing its own data file # (`parallel`), combined before the report is exported. `sysmon` is the # low-overhead backend on Python 3.12 and later: traced proofs then stay # inside their wall-clock caps. Earlier interpreters warn and fall back to # the default tracer. source = ["mathema"] patch = ["subprocess"] parallel = true core = "sysmon" [tool.ruff] target-version = "py310" [tool.ruff.lint] # pyflakes plus a handful of pycodestyle error checks, ruff's own # documented default selection, not its full plugin universe (bandit, # pylint, refurb, ...), several of which flag patterns this project # uses on purpose (a broad `except Exception:` for graceful # degradation, for one). select = ["E4", "E7", "E9", "F"] [tool.mypy] # 3.12: the version the dev environment and CI actually run. numpy's # stubs use PEP 695 `type` statements (numpy 2.5+), which are a fatal # parse error under an earlier python_version, and a stub syntax error # cannot be excluded or skipped. The declared 3.10 floor in # requires-python is unchanged; note it has no checking gate anywhere # (CI tests one version), so this setting does not remove one. python_version = "3.12" ignore_missing_imports = true # The AST-walking and sympy-expression-building modules (symbolic/, # grammar.py, audit.py, inventory.py) narrow an ast.AST/sympy.Basic # node's type through isinstance checks and duck typing in ways mypy's # static analysis doesn't follow. These codes are disabled repo-wide # rather than per-module so real regressions of every other kind still # fail CI. disable_error_code = ["attr-defined", "index", "arg-type", "assignment", "misc", "union-attr"] - README.md (19771 bytes)
# mathema Proofs and counterexamples for Python functions, kept as records bound to the exact code they were checked against. [](https://pypi.org/project/mathema/) [](https://pypi.org/project/mathema/) [](https://github.com/tetrionlabs/mathema/actions/workflows/tests.yml) [](https://github.com/tetrionlabs/mathema/blob/main/LICENSING.md) [](https://mathema.tetrionlabs.com/)  mathema checks Python functions against claims, short mathematical statements of what a function is meant to do, and keeps each result as a record bound to the code. It proves the mathematics of a claim over its whole domain where the body reads as mathematics, and checks the computation by running the real function on inputs chosen to break it, keeping proof and evidence apart. The name is Greek, μάθημα, that which is learned. ## Highlights - Proofs of the mathematics over a whole domain, not a sample of it: the function body is lifted to a symbolic expression and the claim decided in exact real arithmetic, with an opt-in z3 step for nonlinear inequalities. - Inputs that break code are searched for directly (poles, domain corners, the largest double, empty and degenerate containers), and every falsification carries a counterexample that was executed against the real function. - A bare `mathema.check(fn)` runs [built-in claims](https://mathema.tetrionlabs.com/first-look/#step-1-the-built-in-claims-before-you-write-one) of both kinds with no claim written: mathematical ones about the formula (where it is defined, its poles, monotonicity, convexity, symmetry) and computational ones about the code as it runs (side effects, determinism, overflow, numerical stability). - Each claim is judged twice: its mathematics exactly over the reals, and its computation as the code runs in float64. When the computation misses, the record names the condition number and says whether the inputs or the code lost the precision. - Functions that call [numpy](https://mathema.tetrionlabs.com/runtime-types/#proofs-on-pandas-and-numpy-code), [pandas](https://mathema.tetrionlabs.com/pandas-function/) or [polars](https://mathema.tetrionlabs.com/runtime-types/#the-built-in-runtime-types) are checked through [bundled claims about those libraries](https://mathema.tetrionlabs.com/library-claims/), and parameters annotated as a `Series` or `DataFrame` are run on real ones. - Records are bound to the code by a hash of its form, so `mathema verify` re-checks a function when it or anything it calls changes. A claim that held before and fails now keeps its fresh verdict, and the record keeps the move beside it until a person acknowledges it. - CI gets distinct exit codes, GitHub Actions and JUnit output, a claim-level diff of a pull request (`mathema review`) and a population report over a package (`mathema audit`). - Coding agents connect through an MCP server and agent skills, and can propose and check claims while accepting a verdict stays with a person. - Claims about strings and structured records take their domains from the mathema-language package. When mathema cannot settle a claim it says `unknown` and records why, rather than reporting a pass. ## Install ```bash pip install "mathema[all]" pip install mathema ``` The first adds numpy, z3, the MCP server, the coverage reader and mathema-language; the second is the core alone, which needs only sympy and pyyaml. mathema supports Python 3.10 to 3.14 and runs offline, with no account or API key. ## Quick start <!-- example: quick run requires=z3 --> ```python import mathema def discounted(price: float, rate: float) -> float: """The price after applying a discount rate.""" return price * (1 - rate) print(mathema.check(discounted, claims=[ mathema.claim("for rate in [0, 1], f(price, rate) <= price", name="at_most_price"), mathema.claim("for price in [0, 1e6], rate in [0, 1], f(price, rate) <= price", name="at_most_price_when_positive"), ])) ``` <!-- example: quick output match=subset wrap=88 --> ```text mathema.Record(discounted) · source, no side effects · form py:33f04232830d at_most_price for rate in [0.0, 1.0] : float|missing, f(price, rate) <= price falsified at price = -1, rate = 1 falsified mathematics for rate in [0.0, 1.0] ⊂ ℝ, f(price, rate) <= price counterexample price = -1, rate = 1 [mathematics unsound, blame claim] at_most_price_when_positive for price in [0.0, 1000000.0] : float|missing, rate in [0.0, 1.0] : float|missing, f(price, rate) <= price holds proven mathematics for price in [0.0, 1000000.0] ⊂ ℝ, rate in [0.0, 1.0] ⊂ ℝ, f(price, rate) <= price holds computation for price in [0.0, 1000000.0] : float, rate in [0.0, 1.0] : float, f(price, rate) <= price 49 draws ``` The first claim never said prices are positive, and a negative price discounted by the whole rate breaks it. The second states the domain, and its `mathematics` line is proven for every price and rate in range. The `computation` line runs the same claim through float64 and holds on every draw, which is evidence rather than proof, so the headline reports `holds`. ## A tour ### Proving <!-- example: parity file=options.py --> ```python import math def put_call_parity_gap(s: float, k: float, r: float, t: float, sigma: float) -> float: """A European call minus a European put on the same strike.""" root_t = math.sqrt(t) d1 = (math.log(s / k) + (r + 0.5 * sigma * sigma) * t) / (sigma * root_t) d2 = d1 - sigma * root_t phi = lambda z: 0.5 * (1.0 + math.erf(z / math.sqrt(2.0))) call = s * phi(d1) - k * math.exp(-r * t) * phi(d2) put = k * math.exp(-r * t) * phi(-d2) - s * phi(-d1) return call - put ``` The code prices a call and a put through logarithms, square roots and the normal distribution, yet their difference should always be `s - k*exp(-r*t)`, with volatility dropping out entirely. That is put-call parity, and the claim states it over realistic ranges: <!-- example: parity run --> ```bash mathema check options.py --claim "for s in [50,150], k in [50,150], \ r in [0.0,0.1], t in [0.1,2], sigma in [0.05,0.8], \ f(s,k,r,t,sigma) == s - k*exp(-r*t)" ``` <!-- example: parity output --> ```text ok options.put_call_parity_gap: source, no side effects; claims 7/7 checked (1 proven, 6 holds, 0 falsified) ``` mathema lifted the body to an expression in which both Gaussian terms cancel and `sigma` drops out, so the identity is proven over the whole region. The six that hold are the same identity run in float64 and five rows recording what the function does with a `nan` in each parameter. [The derive route](https://mathema.tetrionlabs.com/derive-route/) lists what can be lifted and how each proof is named. ### Falsifying Before any claim is written, mathema already asks the questions that apply to every function: does it have a value for every input it accepts, does it divide by zero anywhere, does it touch anything outside itself? Here is what that finds: <!-- example: pole run --> ```python import mathema def discount_factor(x: float) -> float: """A discount factor that divides by one minus the rate.""" return 1 / (1 - x) print(mathema.check(discount_factor)) ``` <!-- example: pole output match=subset --> ```text mathema.Record(discount_factor) · source, no side effects · form py:bc2becbbf4fb proven is_defined: 1 - x != 0 falsified is_pole_safe[x]: is_pole_safe(x) counterexample x = 1 is admitted by the declared domain but sits at or beside a pole: the call raised ZeroDivisionError ``` These are two of fourteen rows. `is_defined` is a mathematical claim, proven from the formula itself; `is_pole_safe` is a computational one, falsified by running the code at the point the formula says is dangerous. Uniform sampling over the reals lands on `x = 1` with probability zero, so mathema solves the lifted expression for where the denominator vanishes and makes sure that point is tried. [See what mathema finds](https://mathema.tetrionlabs.com/findings/) has more. ### The mathematics and the computation The function below is correct on paper, since `(x + 1) - x` is 1 for every real `x`. mathema proves that, then runs it in float64, where it is not true: <!-- example: step run --> ```python import mathema def step(x: float) -> float: """The distance from x to x + 1.""" return (x + 1.0) - x print(mathema.check(step, claims=[ mathema.claim("for x in [0, 1e16], f(x) == 1", name="unit_step")])) ``` <!-- example: step output --> ```text mathema.Record(step) · source, no side effects · form py:fc901991b36b unit_step for x in [0.0, 1e+16] : float|missing, f(x) = 1 falsified at x = 1e+16 proven mathematics for x in [0.0, 1e+16] ⊂ ℝ, f(x) = 1 falsified computation for x in [0.0, 1e+16] : float, f(x) = 1 counterexample x = 1e+16 [mathematics sound, implementation:numerical-instability] f loses more than the conditioning explains (κ ≈ 0, error 1) possible fixes: (i) fix the code (ii) to accept the whole claim as a discovery, keeping both lines, run: mathema accept step unit_step --as discovery (iii) to narrow the domain knowingly, edit unit_step, then run: mathema accept step unit_step --as superseded holds policy f(nan) no missing policy stated; assumed propagates ``` At `1e16` the spacing between doubles is 2, so `x + 1.0` rounds back to `x` and the function returns 0.0. A condition number near zero says the exact problem is well conditioned, so the precision was lost by the code and not by the inputs. That is why the record does not offer to accept the computation line on its own: the fixes it gives are to change the arithmetic, to accept the whole claim as a discovery (the proven mathematics and the failing computation retire together, with the witness), or to narrow the claim's domain knowingly and supersede it. [Guarantees](https://mathema.tetrionlabs.com/guarantees/#mathematics-and-computation) sets out what each line establishes. ### Library code <!-- example: pandas file=returns.py --> ```python import pandas as pd def average_return(returns: pd.Series) -> float: """The mean of a series of periodic returns.""" return float(returns.mean()) ``` <!-- example: pandas run requires=pandas --> ```python import mathema from returns import average_return record = mathema.check(average_return, claims=[mathema.claim( "for returns in [-0.1, 0.1]^n \\ {missing}, assuming dim(returns) >= 1, " "min(returns) <= f(returns) <= max(returns)", name="between")]) proof = record.probes[0] print(proof.verdict, proof.route) print(proof.sketch.split("; link 2")[0]) ``` <!-- example: pandas output wrap=88 --> ```text proven derive link 1: min(returns) <= f(returns): taking pandas.Series.mean as mean(a) (axiom, bundled with mathema, pandas 2.2 to 3.x); through the pandas.Series.mean definition row, read as sums over returns at a symbolic length: the relation holds for every length of at least one (min(returns) is at most mean(returns)) ``` The proof covers a series of every length, not the handful a test would build. It reads `Series.mean` through a claim about pandas that ships with mathema, then confirms the result by running the function on real `Series`. `mathema compendium status` lists which library calls in a project have rows and which are a black box, as [library claims](https://mathema.tetrionlabs.com/library-claims/) shows. ### Knowledge that goes stale <!-- example: stale file=rates.py --> ```python def rate_for(years: int) -> float: """The loyalty discount for a customer of this many years.""" return 0.05 * years ``` <!-- example: stale file=pricing.py --> ```python from rates import rate_for def discounted(price: float, years: int) -> float: """The price after the customer's loyalty discount. Claims: never_raises: for price in [0, 1e6], years in [0, 10] subset Z, f(price, years) <= price """ return price * (1 - rate_for(years)) ``` <!-- example: stale run --> ```python import mathema, pricing, rates mathema.write_spec(rates.rate_for) mathema.write_spec(pricing.discounted) ``` A result is only worth keeping while the code still matches it. `write_spec` records each result against a hash of the function and of everything it calls, so a later change anywhere in that chain is noticed. Here the helper changes: <!-- example: stale file=rates.py --> ```python def rate_for(years: int) -> float: """The loyalty discount, counted from the second year.""" return 0.05 * (years - 1) ``` <!-- example: stale session --> ``` $ mathema verify; echo "exit $?" FAIL pricing.discounted: dependency changed; 1 proven, 1 holds, 1 falsified <- never_raises regressed proven to falsified (a callee changed); to acknowledge it, run: mathema accept pricing.discounted never_raises --transition; 1 falsified claim(s) ok rates.rate_for: form changed; 1 proven, 0 holds, 0 falsified 0 unchanged since the last run (not run again), 2 checked, 2 problem(s) grammars detected: mathema; verified by this run: mathema 2 intents to accept (2 functions): mathema accept --intent exit 1 ``` `discounted` did not change, but a new customer now gets a negative rate, and the claim that held is falsified. The record says it regressed from `proven` because a callee changed, `verify` exits 1, and the move stays on the record until someone acknowledges it or the code is fixed. [mathema verify](https://mathema.tetrionlabs.com/modes/verify/) covers the rest. ### CI and review ```bash mathema init --ci github # scaffold the workflow step mathema verify # 0 clean, 1 a finding, 2 could not run mathema check src --format github # inline annotations on the pull request mathema review origin/develop # what the change did to what is known mathema audit src # every function: claimed, pure, liftable, tested ``` A reviewer sees what a pull request did to what is known about the code, not only to the code itself. `review` lists each claim whose verdict moved, and `--format json` gives a pipeline the same list. Accepting a verdict (`m - SECURITY.md (1417 bytes)
# Security ## Supported versions | Version | Supported | |---|---| | 0.6.x | Yes | | < 0.6 | Not applicable; 0.6.0 is the first public release | Security fixes land on the current minor version. See [versioning and stability](https://mathema.tetrionlabs.com/stability/) for the wider support policy. ## Reporting a vulnerability Please report a suspected security vulnerability privately rather than through a public GitHub issue. Email: [email protected] Include, if you can: - A description of the vulnerability and its potential impact. - Steps to reproduce it, or a minimal example. - The mathema version (`mathema.__version__`) and Python version you found it on. ## Response You'll receive an acknowledgment within 5 business days. We aim to provide an initial assessment (confirmed, not a vulnerability, or need more information) within 14 days of acknowledgment, and to keep you updated on progress toward a fix after that. ## Scope mathema is fully offline: no core function makes a network call (see [Security and execution](https://mathema.tetrionlabs.com/security/)). A vulnerability report is most useful when it identifies a concrete way that guarantee, or another of mathema's stated behaviors, doesn't hold, or a way that running `mathema check` against untrusted input (a claim string, a function someone else wrote, a YAML spec file) could do something other than what's documented.
- SUPPORT.md (1998 bytes)
# Support ## Documentation first Most questions are answered at [mathema.tetrionlabs.com](https://mathema.tetrionlabs.com): - [Quick start](https://mathema.tetrionlabs.com/quickstart/): five minutes, one function, one claim. - [The claim grammar](https://mathema.tetrionlabs.com/grammar/): everything you can say in a claim. - [The derive route](https://mathema.tetrionlabs.com/derive-route/): which function shapes can reach `proven`, and what happens to the ones that cannot. Read this first if a claim you expected to prove came back `holds`. - [Versioning and stability](https://mathema.tetrionlabs.com/stability/): what may change, and which versions are supported. ## Asking a question Open a [GitHub issue](https://github.com/tetrionlabs/mathema/issues) using the question or bug template. There is no separate forum or chat channel, deliberately: issues are searchable, and the next person with your question finds the answer. ## Reporting a problem with a verdict If mathema reports a verdict you believe is wrong, that is the most useful kind of report and it has its own flow: ```bash mathema describe <target> --issue ``` This generates a structured failure report, including the claim, the evidence, and the engine's own diagnostic codes, which you can attach to a new issue. A verdict disagreement with a reproducible report is treated as a correctness bug, not a support question. ## Security Do not open a public issue for a security vulnerability. See [SECURITY.md](SECURITY.md) for private disclosure. ## Licensing mathema is source-available under the Business Source License 1.1. Production use is free for organisations under the thresholds set out in [LICENSING.md](LICENSING.md); beyond them it requires a commercial licence, for which contact **[email protected]**. ## What to expect This is a small project. Issues are read, and bugs affecting correctness of a verdict take priority over everything else. There is no response-time commitment.