diff --git a/README.md b/README.md index 2f205b5a..45e8af04 100644 --- a/README.md +++ b/README.md @@ -2,13 +2,13 @@ [![CI](https://github.com/ascalva/mind-palace/actions/workflows/ci.yml/badge.svg)](https://github.com/ascalva/mind-palace/actions/workflows/ci.yml) [![Lean](https://github.com/ascalva/mind-palace/actions/workflows/lean.yml/badge.svg)](https://github.com/ascalva/mind-palace/actions/workflows/lean.yml) -[![laws](https://img.shields.io/badge/laws-106_rows_in_16_families-blue)](docs/LAWS.md) -[![Lean statements](https://img.shields.io/badge/Lean-380_statements_judged-blue)](formal/README.md) +[![laws](https://img.shields.io/badge/laws-113_rows_in_16_families-blue)](docs/LAWS.md) +[![Lean statements](https://img.shields.io/badge/Lean-460_statements_judged-blue)](formal/README.md) [![sorry](https://img.shields.io/badge/sorry-0-brightgreen)](formal/sorry-budget) [![kernels](https://img.shields.io/badge/kernel_replay-6_checkers-6f42c1)](formal/check.sh) -[![attacks](https://img.shields.io/badge/attacks-232_with_controls-blue)](formal/PalaceTest) -[![tests](https://img.shields.io/badge/tests-3721-brightgreen)](docs/runbook.md) -[![coverage](https://img.shields.io/badge/coverage-77%25-green)](pyproject.toml) +[![attacks](https://img.shields.io/badge/attacks-253_with_controls-blue)](formal/PalaceTest) +[![tests](https://img.shields.io/badge/tests-3757-brightgreen)](docs/runbook.md) +[![coverage](https://img.shields.io/badge/coverage-78%25-green)](pyproject.toml) [![mypy](https://img.shields.io/badge/mypy-0_errors_in_core-brightgreen)](pyproject.toml) [![sealed core](https://img.shields.io/badge/sealed_core-zero_egress-6f42c1)](scripts/check_imports.py) [![python](https://img.shields.io/badge/python-3.15-blue)](pyproject.toml) @@ -33,7 +33,7 @@ read "reference:openai-math:Local-smoothing" chunk 3 There are five sorts: a *field* (a score on every node), a *region* (a set of nodes), *chains* (paths that spell a word over the edge types), a *witness* (the commit that minted an edge) and a *text* (one record). The verbs move between them: `near`, `diffuse`, `reach`, `relate`, `trace`, `walk … via`, `witness`, `read`. The connectives compose them: `and`, `or`, `minus`, `then`; `within`, `over` and `as of` restrict; `top k`, `atleast t`, `far` and `not` bound; `assume … in` evaluates a sentence under a hypothesis, and its answer is a `Hyp` beside the actual answer, never a fact. The grammar is `core/sentence/grammar.py`; [`docs/query/asking.md`](docs/query/asking.md) is the guide to writing a sentence. -Two surfaces share one grant. `mind-palace query ""` runs a sentence read-only from the live checkout. The Ambassador's MCP server has one read tool, `query`, and the Open WebUI bridge serves the same manifest. Both hold the Ambassador's grant with the hypothetical overlay the owner switched on; `--as ` labels the asker in the query log and grants nothing. A third surface holds a narrower grant: `scripts/palace_mcp.py --role guest` serves an external agent `query` and `overview` alone, read-only over the dialogue, the repository's code and docs, the papers and the observed records, never the notes or the interpretations derived from them (SCO-9, `docs/design-notes/dn-guest-principal.md`); it is how the code instance below serves a coding agent. A sentence that cannot be answered is refused with the reason: the production that failed to parse, the sort rule it broke, the plane no grant covers, the note that matched twice. It is not answered with nearest neighbours instead. +Two surfaces share one grant. `mind-palace query ""` runs a sentence read-only from the live checkout. The Ambassador's MCP server has two read tools, `query` and `cut`, the algebra of cuts over the landing log (`agents/ambassador/cut_tool.py`, which reads the store as of a cut), and the Open WebUI bridge serves its manifest without `cut`. Both hold the Ambassador's grant with the hypothetical overlay the owner switched on; `--as ` labels the asker in the query log and grants nothing. A third surface holds a narrower grant: `scripts/palace_mcp.py --role guest` serves an external agent `query` and `overview` alone, read-only over the dialogue, the repository's code and docs, the papers and the observed records, never the notes or the interpretations derived from them (SCO-9, `docs/design-notes/dn-guest-principal.md`); it is how the code instance below serves a coding agent. A sentence that cannot be answered is refused with the reason: the production that failed to parse, the sort rule it broke, the plane no grant covers, the note that matched twice. It is not answered with nearest neighbours instead. ## From a sentence to an answer @@ -121,12 +121,12 @@ A law has one row in [`docs/LAWS.md`](docs/LAWS.md): its statement, the structur | | | |---|---| | toolchain | Lean `v4.36.0-rc2`, Mathlib; Plausible for the attacks | -| the library | 38 proof modules, 37 models, 27 statement files; 25,700 lines of models and proofs, 3,841 of statements, 5,757 of attacks | -| theorems | 1,544 proved in `formal/Palace`; 380 statements in `formal/Spec` judged identical by the comparator | -| the ledger | 106 rows in 16 families, 386 cited declarations, 93 law markers checked against the rows | -| attacks | 232 Plausible attacks and 206 negative controls over 33 modules, fixed seeds | +| the library | 39 proof modules, 38 models, 28 statement files; 27,136 lines of models and proofs, 4,452 of statements, 6,185 of attacks | +| theorems | 1,654 proved in `formal/Palace`; 460 statements in `formal/Spec` judged identical by the comparator | +| the ledger | 113 rows in 16 families, 466 cited declarations, 100 law markers checked against the rows | +| attacks | 253 Plausible attacks and 223 negative controls over 34 modules, fixed seeds | | axioms | `propext`, `Classical.choice`, `Quot.sound`; `sorry` 0 | -| the replay | 56,238 declarations accepted by all six checkers on the run of `formal/check.sh` this commit was built with | +| the replay | 56,530 declarations accepted by all six checkers on the run of `formal/check.sh` this commit was built with | | families | memberships · Laplacian, balance and spectral · cut and conductance · curvature · the global event clock · the shared prose plane · capability scopes · the abstraction ultrametric σ* · bridges · the retrieval curve · the query sentence algebra · the ingress · stored vectors · the growth readout · the utility field · the temporal snapshot | ## The mathematics @@ -149,7 +149,7 @@ Utility is a side effect and is treated as one. What the project optimizes for i ## Architecture -- **The query algebra.** `core/sentence/`: the grammar, the sorts, the compiler and planner, the universe builder, the executor, the trace, the surfaces. The one read. +- **The query algebra.** `core/sentence/`: the grammar, the sorts, the compiler and planner, the universe builder, the executor, the trace, the surfaces. The read by sentence; the other read is the algebra of cuts (`core/stores/cuts.py`, the `cut` tool), over the versions the landing log holds at cuts and between them. - **Ambassador.** The reasoning layer, over MCP and the web bridge. Computationally light, deterministic where exactness matters, and plain about how much effort an answer took. - **Dreamer.** The offline layer that works over the structure of what is stored. Deterministic clustering feeds model synthesis; the outputs are content-addressed proposals that cannot silently become beliefs. - **The store and its typed views.** The shared prose plane with its clearances, the curated literature store held structurally apart, the ledger of the repository's own history (three million citations over 1,487 commits), the version chains, the causal edges. A read-only reflection of memory and a write-only path to the world, distinct by type. @@ -177,7 +177,7 @@ The build's own history is a dataset. Every commit's structure is snapshotted in ```sh uv sync --extra dev -uv run pytest -q -m 'not live and not podman and not needs_vault and not needs_restic' # the deterministic tier: 3,721 tests +uv run pytest -q -m 'not live and not podman and not needs_vault and not needs_restic' # the deterministic tier: 3,757 tests uv run mypy # strict core: 0 errors (the 67 in tests/ are pinned) uv run python scripts/check_imports.py # the sealed core names no network module uv run python -m ops.type_gate # every core-reaching package is type-checked @@ -185,7 +185,7 @@ uv run python -m ops.type_gate # every core-reaching package bin/mind-palace query 'top 5 near "sleep" and diffuse S from "health.md"' --trace # from the live checkout ``` -The suite is tiered by intent (unit, integration, property, metamorphic, adversarial, integrity, longitudinal, emergent), so an invariant regression reads differently from a flaky assertion; the property tier is the ledger's Python falsifiers. Live axes (`-m live`, `-m podman`, a dev-Vault CI service) verify against the real substrates and are skipped when absent. Line-and-branch coverage over the deterministic tier is 77%, reported rather than gated: a structural test that deletes an illegal state matters more than a line touched. +The suite is tiered by intent (unit, integration, property, metamorphic, adversarial, integrity, longitudinal, emergent), so an invariant regression reads differently from a flaky assertion; the property tier is the ledger's Python falsifiers. Live axes (`-m live`, `-m podman`, a dev-Vault CI service) verify against the real substrates and are skipped when absent. Line-and-branch coverage over the deterministic tier is 78%, reported rather than gated: a structural test that deletes an illegal state matters more than a line touched. ## Running it diff --git a/agents/ambassador/cut_tool.py b/agents/ambassador/cut_tool.py new file mode 100644 index 00000000..4baae567 --- /dev/null +++ b/agents/ambassador/cut_tool.py @@ -0,0 +1,456 @@ +"""The `cut` tool: the algebra of cuts on the palace's MCP surface (dn-temporal-snapshot §7.5). + +One tool, `cut`, over the engine (`core/stores/cuts.py`). A call names an operator, `op`, and its +operands: `a` and `b`, each a cut's name or a call of the tool written as an object with its own +`op`, whose result is the operand, and `cuts`, a family of them. So a result is an operand again, +and a whole call composes to one expression. What a call reads, in order: the heads of the chains +when it starts; the horizon of a chain, once, when a position under the chain's head is named on +it (§7.1); and then what its outermost operator needs, a set of any depth by one statement. A cut +is named `head`, `bottom`, or by its positions, `land.@` one a chain, separated by +spaces, a chain left out standing at 0; every answer prints the cuts it read that way, so a cut is +copied from an answer into a question. An operand left out is the head, read once when the call +starts, and every operand that is the head is that one cut (D27). `over` names the provenance +classes whose chains are read, every class the asker's grant reads by default; `list` returns the +rows beside the counts, the first `limit` of them. + +Union and intersection have both meanings under different names (D22, D26): `join` and `meet` +take cuts and return a cut, `union` and `intersection` take sets and return a set. A cut given +where a set is expected is the set it holds; a set, a signed difference or a number given where a +cut is expected is refused, and the refusal names what was given and what the operator takes. + +The answer is one object: `op` and `type`, `cuts` (every cut the call read, in the order the +expression names them, each by its positions on the chains read, and once beside each cut asked +for it where the two differ), the result, `rows` when `list` is set, and `note`. A position past a +chain's head is refused with the head; a chain the grant does not read is refused in the words used +for a chain that does not exist; a position under a chain's horizon is read at the chain's empty +prefix, and the note says so. A cut over two chains or more that is neither the head nor the +bottom can split a change of class, which writes a `leave` in one chain and the `store` in +another, and the note says that too (§3.5). A call's sets name at most `TERMS` cuts, counted each +time their statement names one, so a short call cannot ask for a statement of any size. The +handler reads through the connection it is given, which the server opens to only read +(`core.stores.cuts.read_only`): it takes no lock a writer waits on and writes nothing. It is not +yet the graph: edges and graph mathematics at a cut arrive with SN-4. +""" + +from __future__ import annotations + +import sqlite3 +from collections.abc import Iterable, Mapping +from dataclasses import dataclass, field +from typing import Any + +from core.stores.cuts import ( + BOTTOM, + Columns, + Cut, + CutError, + Delta, + Evaluation, + Events, + Series, + Table, + Versions, +) + +# What each operator takes, by argument: "cut", "set" (a cut is the set it holds), "delta", or +# "family" (a list of cuts in `cuts`). An operand an operator does not take is refused. +OPERATORS: dict[str, dict[str, str]] = { + "head": {}, "bottom": {}, + "join": {"a": "cut", "b": "cut"}, "meet": {"a": "cut", "b": "cut"}, + "order": {"a": "cut", "b": "cut"}, "between": {"a": "cut", "b": "cut"}, + "held": {"a": "cut"}, + "union": {"a": "set", "b": "set"}, "intersection": {"a": "set", "b": "set"}, + "difference": {"a": "set", "b": "set"}, "symmetric_difference": {"a": "set", "b": "set"}, + "delta": {"a": "cut", "b": "cut"}, + "apply": {"a": "set", "b": "delta"}, "compose": {"a": "delta", "b": "delta"}, + "persisted": {"cuts": "family"}, "existed": {"cuts": "family"}, + "count": {"a": "set"}, + "in_how_many": {"cuts": "family", "a": "set"}, + "measure": {"cuts": "family", "of": "measure"}, + "pairwise": {"cuts": "family"}, +} +ARGUMENTS = ("op", "a", "b", "cuts", "of", "over", "list", "limit") +OUTER = ("over", "list", "limit") # arguments of the call, not of an operand +MEASURES = ("count",) # SN-4 adds the measures of a graph +DEPTH = 32 # calls nested in one call, at most +FAMILY = 64 # cuts in a family, at most +LIMIT = 1000 # rows listed, at most +# Cuts a call's sets name, counted each time their statement names one (`Versions.terms`), at +# most: the bound on the statement's size, which DEPTH does not give, since an operator that +# repeats an operand, as a composition of differences does, makes the expression larger than the +# call that asks for it. +TERMS = 256 +LISTED = ("source_path", "doc_id", "digest", "title", "version") +GRAPH = ("The result is of the versions the landing log holds. It is not yet the graph: edges " + "and graph mathematics at a cut arrive with SN-4.") +# Said when a result of what cuts hold read two chains or more at a cut that is neither the head +# nor the bottom (dn-temporal-snapshot §3.5, §7.5): such a cut is read as asked, and it can split +# the two rows a change of class writes. +SPLIT = ("A cut that is neither the head nor the bottom can split a change of class, which " + "writes a leave in the chain a path leaves and then a store in the chain of its new " + "class: read at such a cut, a path that changed class there is held in both chains or " + "in neither.") + +_OPERAND = {"type": ["string", "object"], + "description": "a cut: head, bottom, or land.@ one a chain; or a call " + "{op, a, b, cuts, of}, whose result is the operand. Left out: the head"} +DESCRIPTION = ( + "The algebra of cuts: a cut is the palace as of one position a landing chain, read only when " + "an operator needs it. Name a cut head, bottom, or by its positions, land.@ " + "separated by spaces (a chain left out stands at 0), as every answer prints it; an operand " + "left out is the head, read once a call. Operators: head, bottom; join and meet of two cuts " + "(a cut: the union and intersection on positions); order; between (the events after a and " + "up to b); held (the versions a cut holds); union, intersection, difference and " + "symmetric_difference of two sets (a cut is the set it holds: the union on contents keeps " + "both versions of an edited note, where join keeps the later); delta (the signed " + "difference: removed, added, replaced); apply (a set and a delta); compose (two deltas that " + "share a cut between them); persisted and existed over cuts; count; in_how_many; measure " + "(of: count) and pairwise over cuts. An operand may be a call written as an object. list: " + "true lists the rows. The versions only: edges and graph mathematics at a cut arrive later.") +SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "op": {"enum": sorted(OPERATORS)}, + "a": _OPERAND, + "b": _OPERAND, + "cuts": {"type": "array", "items": _OPERAND, "maxItems": FAMILY}, + "of": {"enum": list(MEASURES)}, + "over": {"type": "array", "items": {"type": "string"}, + "description": "the provenance classes read; every class the grant reads " + "by default"}, + "list": {"type": "boolean", "description": "list the rows beside the counts"}, + "limit": {"type": "integer", "minimum": 1, "maximum": LIMIT}, + }, + "required": ["op"], +} + + +@dataclass +class _Call: + """One call's evaluation: the engine's evaluation, which read the head once, and what the + answer says of the cuts it read.""" + + ev: Evaluation + # each cut read, in the order the expression names them, with every cut asked for it that + # is not the cut itself: two names lowered to one cut are both kept + read: dict[Cut, list[Cut]] = field(default_factory=dict) + lowered: list[tuple[int, int]] = field(default_factory=list) + headed: bool = False # an operand was left out + + def saw(self, c: Cut, asked: Cut | None = None) -> Cut: + names = self.read.setdefault(c, []) + if asked is not None and asked != c and asked not in names: + names.append(asked) + return c + + +@dataclass(frozen=True) +class _Count: + """A count of a set, asked and not yet read: a number, and no operand of any operator.""" + + of: Versions + + +@dataclass(frozen=True) +class _Counted: + """In how many cuts of a family each row of a set is held, asked and not yet read: the rows + are read when the answer is written, the first `limit` of them.""" + + of: Versions + cuts: tuple[Cut, ...] + + +def _bounded(v: object) -> object: + """`v`, refused when its sets name more than `TERMS` cuts: checked on every value a call + builds, before a statement is written.""" + match v: + case Versions(): + n = v.terms + case Delta(): + n = v.gone.terms + v.come.terms + case _Count() | _Counted(): + n = v.of.terms + case _: + return v + if n > TERMS: + raise CutError(f"a call's sets name at most {TERMS} cuts, counted each time the statement " + f"they run as names one, and this call's name {n}") + return v + + +def _kind(v: object) -> str: + match v: + case Cut(): + return "a cut" + case Versions(): + return "a set of versions" + case Delta(): + return "a signed difference" + case Events(): + return "the events between two cuts" + case Series(): + return "a series" + case Table(): + return "a table" + case _Counted(): + return "rows counted over a family" + case _Count(): + return "a number" + case str(): + return "an order" + case int(): + return "a number" + return type(v).__name__ + + +def _operand(call: _Call, x: object, depth: int) -> object: + """An operand's value: the head for none, a cut for a name, a call's result for an object.""" + if x is None: + call.headed = True + return call.saw(call.ev.head) + if isinstance(x, str): + asked = call.ev.named(x) + read, lowered = call.ev.served(asked) + call.lowered += [w for w in lowered if w not in call.lowered] + return call.saw(read, asked) + if isinstance(x, Mapping): + return _evaluate(call, x, depth + 1) + raise CutError(f"an operand is a cut's name or a call written as an object, not " + f"{type(x).__name__}") + + +def _cut(op: str, which: str, v: object) -> Cut: + if isinstance(v, Cut): + return v + raise CutError(f"{op} takes a cut as {which}, and {_kind(v)} was given") + + +def _set(call: _Call, op: str, which: str, v: object) -> Versions: + if isinstance(v, Cut): + return call.ev.held(v) + if isinstance(v, Versions): + return v + raise CutError(f"{op} takes a set of versions or a cut as {which}, and {_kind(v)} was given") + + +def _delta(op: str, which: str, v: object) -> Delta: + if isinstance(v, Delta): + return v + raise CutError(f"{op} takes a signed difference as {which}, and {_kind(v)} was given") + + +def _evaluate(call: _Call, args: Mapping[str, Any], depth: int = 0) -> object: + """One call's result, lazy where it is a cut, a set, a signed difference or events, and + refused when its sets name more than `TERMS` cuts.""" + return _bounded(_value(call, args, depth)) + + +def _value(call: _Call, args: Mapping[str, Any], depth: int) -> object: + if depth > DEPTH: + raise CutError(f"a call nests at most {DEPTH} calls") + op = args.get("op") + if not isinstance(op, str) or op not in OPERATORS: + raise CutError(f"op is one of {', '.join(OPERATORS)}, not {op!r}") + unknown = [k for k in args if k not in ARGUMENTS] + if unknown: + raise CutError(f"no argument {', '.join(map(str, unknown))}; a call takes " + f"{', '.join(ARGUMENTS)}") + if depth and any(k in args for k in OUTER): + raise CutError(f"{', '.join(OUTER)} are arguments of the outermost call, not of an " + "operand") + takes = OPERATORS[op] + extra = [k for k in ("a", "b", "cuts", "of") if k in args and args[k] is not None + and k not in takes] + if extra: + raise CutError(f"{op} takes {', '.join(takes) or 'no operand'}, and was given " + f"{', '.join(extra)}") + if op == "head": + return call.saw(call.ev.head) + if op == "bottom": + return call.saw(BOTTOM) + if "cuts" in takes: + fam = _family(call, op, args.get("cuts"), depth) + if op == "persisted": + return call.ev.persisted(fam) + if op == "existed": + return call.ev.existed(fam) + if op == "pairwise": + return call.ev.pairwise(fam) + if op == "measure": + of = args.get("of") or "count" + if of not in MEASURES: + raise CutError(f"the one measure at this stage is count, not {of!r}; the " + "measures of a graph arrive with SN-4") + return call.ev.count_series(fam) + return _Counted(_set(call, op, "a", _operand(call, args.get("a"), depth)), tuple(fam)) + a = _operand(call, args.get("a"), depth) + if op == "held": + return call.ev.held(_cut(op, "a", a)) + if op == "count": + return _Count(_set(call, op, "a", a)) + b = _operand(call, args.get("b"), depth) + if takes["a"] == "cut": + x, y = _cut(op, "a", a), _cut(op, "b", b) + if op == "join": + return call.saw(x.join(y)) + if op == "meet": + return call.saw(x.meet(y)) + if op == "order": + return x.order(y) + if op == "between": + return call.ev.between(x, y) + return call.ev.delta(x, y) + if op == "apply": + return _delta(op, "b", b).apply(_set(call, op, "a", a)) + if op == "compose": + return _delta(op, "a", a).then(_delta(op, "b", b)) + p, q = _set(call, op, "a", a), _set(call, op, "b", b) + return {"union": p | q, "intersection": p & q, "difference": p - q, + "symmetric_difference": p ^ q}[op] + + +def _family(call: _Call, op: str, cuts: object, depth: int) -> list[Cut]: + if cuts is None or cuts == []: + call.headed = True + return [call.saw(call.ev.head)] + if not isinstance(cuts, list): + raise CutError(f"{op} takes cuts as a list of cuts") + if len(cuts) > FAMILY: + raise CutError(f"a family has at most {FAMILY} cuts, and {len(cuts)} were given") + return [_cut(op, "a member of cuts", _operand(call, x, depth)) for x in cuts] + + +def _row(cols: Columns, i: int) -> dict[str, object]: + """One row as the answer lists it: its chain and position, path, identity, digest, title, + version number, and its kind for an event.""" + raw = cols.row(i) + names = {"source_path": "path", "doc_id": "identity"} + return {names.get(k, k): v for k, v in raw.items() + if k in ("chain", "seq", "kind", *LISTED)} + + +def _rows(cols: Columns, limit: int) -> list[dict[str, object]]: + return [_row(cols, i) for i in range(min(len(cols), limit))] + + +def _answer(call: _Call, value: object, listing: bool, + limit: int) -> tuple[dict[str, Any], int | None]: + """The result's part of the answer, and the holes in the ranges it read (`None` where it + read no range).""" + out: dict[str, Any] = {} + holes: int | None = None + chains = call.ev.chains + if isinstance(value, Cut): + out["type"], out["cut"] = "cut", value.name(chains) + elif isinstance(value, str): + out["type"], out["order"] = "order", value + elif isinstance(value, Events): + out["type"] = "events" + out["count"], holes = value.tally() + if listing: + cols = value.columns("kind", *LISTED, limit=limit) + out["rows"], out["truncated"] = _rows(cols, limit), out["count"] > limit + elif isinstance(value, _Count): + out["type"] = "number" + out["value"], holes = value.of.tally() + elif isinstance(value, Versions): + n, holes = value.tally() + out["type"], out["count"] = "set", n + if listing: + cols = value.columns(*LISTED, limit=limit) + out["rows"], out["truncated"] = _rows(cols, limit), n > limit + elif isinstance(value, Delta): + counts = value.counts() + holes = counts.holes + out["type"] = "delta" + out["removed"], out["added"], out["replaced"] = (counts.removed, counts.added, + counts.replaced) + if listing: + s = value.sorted(*LISTED, limit=limit) + old, new = s.replaced + out["rows"] = {"removed": _rows(s.removed, limit), "added": _rows(s.added, limit), + "replaced": [{"from": _row(old, i), "to": _row(new, i)} + for i in range(len(old))]} + out["truncated"] = max(counts.removed, counts.added, counts.replaced) > limit + elif isinstance(value, _Counted): + out["type"] = "rows" + n, holes = value.of.tally() + out["count"] = n + counted = call.ev.in_how_many(value.of, value.cuts, names=LISTED, limit=limit) + out["rows"] = [{**_row(counted.rows, i), "cuts_holding": int(counted.counts[i])} + for i in range(len(counted.rows))] + out["truncated"] = n > limit + out["held_by_every_cut"] = (value.of & call.ev.persisted(value.cuts)).count() + elif isinstance(value, Series): + out["type"] = "series" + out["series"] = [{"cut": c.name(chains), "value": v} + for c, v in zip(value.cuts, value.values, strict=True)] + holes = call.ev.existed(list(value.cuts)).holes() + elif isinstance(value, Table): + out["type"] = "table" + out["table"] = {"cuts": [c.name(chains) for c in value.cuts], + "sizes": [list(r) for r in value.sizes]} + holes = call.ev.existed(list(value.cuts)).holes() + return out, holes + + +# The results that read what cuts hold, and so can show a change of class split (SPLIT). +CONTENTS = (Versions, Delta, _Count, _Counted, Series, Table) + + +def cut(conn: sqlite3.Connection, classes: Iterable[str], arguments: Mapping[str, Any] + ) -> dict[str, Any]: + """The `cut` tool's answer to one call, read through `conn`, a connection to the catalog's + file that the server opens to only read (`core.stores.cuts.read_only`), under a grant that + reads `classes`: the arguments as the server's dispatch passes them, decoded from the call's + JSON.""" + unknown = [k for k in arguments if k not in ARGUMENTS] + if unknown: + raise CutError(f"no argument {', '.join(map(str, unknown))}; the tool takes " + f"{', '.join(ARGUMENTS)}") + readable = sorted({str(c) for c in classes}) + over = arguments.get("over") + if over is None: + over = readable + elif not isinstance(over, list) or not all(isinstance(c, str) for c in over): + raise CutError("over is a list of provenance classes") + elif any(c not in readable for c in over): + unread = ", ".join(sorted(set(over) - set(readable))) + raise CutError(f"over names a class this grant does not read: {unread}; it reads " + f"{', '.join(readable)}") + listing = arguments.get("list", False) + if not isinstance(listing, bool): + raise CutError("list is true or false") + limit = arguments.get("limit", 50) + if not isinstance(limit, int) or isinstance(limit, bool) or not 1 <= limit <= LIMIT: + raise CutError(f"limit is a whole number from 1 to {LIMIT}") + op = str(arguments.get("op")) + call = _Call(Evaluation(conn, over)) + value = _evaluate(call, arguments) + result, holes = _answer(call, value, listing, limit) + chains = call.ev.chains + answer: dict[str, Any] = { + "op": op, "type": result.pop("type"), + "cuts": [{"read": c.name(chains), **({"asked": a.name(chains)} if a is not None else {})} + for c, asked in call.read.items() for a in (asked or (None,))], + **result, + } + note = [] + if call.headed: + note.append(f"No cut was named for an operand, so the head was read, once for the " + f"whole call: {call.ev.head.name(chains)}.") + for k, p in call.lowered: + note.append(f"land.{k} was read at 0, below the position asked, {p}: the positions under " + "a chain's horizon are its genesis, which is not history, and are not " + "served.") + if (len(chains) > 1 and isinstance(value, CONTENTS) + and any(c not in (call.ev.head, BOTTOM) for c in call.read)): + note.append(SPLIT) + if holes is not None: + note.append("No row of the ranges read is a hole." if holes == 0 else + f"{holes} {'row' if holes == 1 else 'rows'} of the ranges read " + f"{'is a hole' if holes == 1 else 'are holes'}: versions a purge emptied, " + "which no set holds.") + note.append(GRAPH) + answer["note"] = " ".join(note) + return answer diff --git a/agents/ambassador/handoff.py b/agents/ambassador/handoff.py index 84679279..01152c39 100644 --- a/agents/ambassador/handoff.py +++ b/agents/ambassador/handoff.py @@ -12,12 +12,14 @@ requests/.json = {"id", "name", "arguments", "ts"} responses/.json = {"id", "text", "is_error", "ts"} -The web client gets a narrower tool set than OpenCode's: every read, plus capture and the two -syncs — never `dream`/`relate` (long synthesis-model jobs) or `link` (interpreted edges) from a -chat window. `WEB_TOOLS` is enforced HERE; the edge's advertised list is a copy for the client, -not the gate. `query` reads, and since the ingress (dn-ingress) it can also speak a command -(`do …`): from the web client it may speak only the commands its tools already allow -(`web_admits`), so the narrowing holds whatever tool carries the sentence. +The web client gets a narrower tool set than OpenCode's: `query` and `overview`, capture, the two +syncs and the loop's bookkeeping (status, the tasks, the reminders). It never gets `dream` or +`relate` (long synthesis-model jobs) or `link` (interpreted edges) from a chat window, nor `cut`, +the algebra of cuts, which only the Ambassador's MCP server serves. `WEB_TOOLS` is enforced HERE; +the edge's advertised list is a copy for the client, not the gate. `query` reads, and since the +ingress (dn-ingress) it can also speak a command (`do …`): from the web client it may speak only +the commands its tools already allow (`web_admits`), so the narrowing holds whatever tool carries +the sentence. One responder runs at a time (`responder.lock`, which is also how the edge sees it is up); it exits after `idle_exit_s` with no calls, and the edge starts it again on the next one. """ diff --git a/agents/ambassador/mcp.py b/agents/ambassador/mcp.py index d00620fd..65260218 100644 --- a/agents/ambassador/mcp.py +++ b/agents/ambassador/mcp.py @@ -4,12 +4,16 @@ A harness (OpenCode, or anything that speaks MCP over stdio) spawns this process; it has no listener and no socket of its own, and it seals itself (Invariant 1) before it opens a store. It is -the Ambassador's client of the core: every read is ONE command, `query` — a sentence of the query -algebra (`core.sentence`, dn-query-sentence-algebra) compiled under the Ambassador's grant, widened -by the hypothetical overlay the owner granted on 2026-11-04 — so an ill-scoped read is refused in -code, not by the prompt, and the plan rides with every answer; writes are only the ones the -grant's W_Σ allows — dialogue capture (provenance fixed by role, never by the text) and -interpreted relation edges. Long operations (dream, relate, sync) wake models and run on demand. +the Ambassador's client of the core, with two reads. `query` reads the palace by a sentence of the +query algebra (`core.sentence`, dn-query-sentence-algebra) compiled under the Ambassador's grant, +widened by the hypothetical overlay the owner granted on 2026-11-04, so an ill-scoped read is +refused in code, not by the prompt, and the plan rides with every answer. `cut` reads the algebra +of cuts (`agents/ambassador/cut_tool.py`, dn-temporal-snapshot §7.5): the palace as of a cut and +the operators on cuts, over the landing log and the classes the Ambassador's grant reads, through +a connection that only reads; it is not yet the graph, and edges and graph mathematics at a cut +arrive with SN-4. Writes are only the ones the grant's W_Σ allows: dialogue capture (provenance +fixed by role, never by the text) and interpreted relation edges. Long operations (dream, relate, +sync) wake models and run on demand. `--role guest` serves an external agent instead (dn-guest-principal): `query` under the read-only `GUEST` grant, over the dialogue, the repo's code and docs, the papers and the observed records, @@ -37,6 +41,9 @@ from pathlib import Path from typing import TYPE_CHECKING, Any, TextIO +from agents.ambassador.cut_tool import DESCRIPTION as CUT_DESCRIPTION +from agents.ambassador.cut_tool import SCHEMA as CUT_SCHEMA + if TYPE_CHECKING: from core.query import QueryEngine @@ -97,7 +104,7 @@ def launcher(self) -> Any: self._launcher = build_launcher() return self._launcher - # the one read ------------------------------------------------------------------------------ + # the reads --------------------------------------------------------------------------------- def query(self, sentence: str, trace: bool = False) -> dict[str, Any]: """A sentence of the query algebra (dn-query-sentence-algebra) under `sentence_grant()` — the Ambassador's grant with the overlay the owner granted: the plan rides with the answer, @@ -137,6 +144,24 @@ def overview(self) -> dict[str, Any]: out["code"] = code return out + def cut(self, **arguments: Any) -> dict[str, Any]: + """The algebra of cuts over the landing log (`agents/ambassador/cut_tool.py`, + dn-temporal-snapshot §7.5), under the classes the Ambassador's grant reads: the cut as a + value, the versions a cut holds and the operators on them. It reads the instance's + catalog through a connection that only reads (`core.stores.cuts.read_only`), so it + takes no lock a writer waits on and writes nothing: opening the catalog itself would + run its migration, a write transaction.""" + from agents.ambassador import cut_tool + from core.kernel.clearance import classes_of + from core.query import AMBASSADOR + from core.stores.cuts import read_only + + conn = read_only(self.engine.config.paths.vault_catalog) + try: + return cut_tool.cut(conn, [str(c) for c in classes_of(AMBASSADOR.strata)], arguments) + finally: + conn.close() + # writes and on-demand work ----------------------------------------------------------------- def _run(self, fn: Callable[[], int]) -> dict[str, Any]: buf = io.StringIO() @@ -487,7 +512,7 @@ def _schema(props: dict[str, Any], required: list[str]) -> dict[str, Any]: TOOLS: list[tuple[str, str, dict[str, Any], str]] = [ ( "query", - "The one read: a sentence of the query algebra, not keywords. Verbs: " + "Read the palace by a sentence of the query algebra, not keywords. Verbs: " 'near "text" | diffuse S from [beta b] | reach F from [depth n] ' "[back|forward] | relate | trace | walk from [to ] via | witness "" | read "" [chunk n] (the full text; read before ' @@ -512,6 +537,9 @@ def _schema(props: dict[str, Any], required: list[str]) -> dict[str, Any]: _schema({}, []), "overview", ), + # the algebra of cuts (dn-temporal-snapshot §7.5): the Ambassador's alone until the owner + # rules on what a guest may call (D34) + ("cut", CUT_DESCRIPTION, CUT_SCHEMA, "cut"), ( "sync_dialogue", "Sync new Open WebUI and OpenCode chats into the palace now.", diff --git a/config/defaults.toml b/config/defaults.toml index 0e533104..b7235bb5 100644 --- a/config/defaults.toml +++ b/config/defaults.toml @@ -274,6 +274,9 @@ keep_replies = true # The query sentence algebra's surface (dn-query-sentence-algebra §4 — QL-3). The Ambassador's MCP # server speaks ONE command, `query`: a sentence of the algebra under the Ambassador's grant (the # owner's order, 2026-11-04); `mind-palace query ""` is the same algebra from the terminal. +# Since SN-1b the server has a second read beside it, `cut`, the algebra of cuts over the landing +# log (dn-temporal-snapshot §7.5; D28 there, for the owner to confirm), which takes no sentence and +# no switch of this section. # `hypotheticals` is the owner's grant of the hypothetical overlay to those surfaces (granted # 2026-11-04, §4 d): on, `assume in ` is admitted and answered as a `Hyp` # beside the actual answer — never an `Inv`; off, it is refused as ill-scoped. Either surface records diff --git a/core/kernel/config/loader.py b/core/kernel/config/loader.py index fe361f1c..e05cff31 100644 --- a/core/kernel/config/loader.py +++ b/core/kernel/config/loader.py @@ -293,10 +293,11 @@ class AmbassadorConfig: @dataclass(frozen=True) class QueryConfig: """The query sentence algebra's surface (dn-query-sentence-algebra §4, QL-3). The Ambassador's - MCP server speaks one command, `query` — a sentence under the Ambassador's grant — and - `palace query` is the owner's hand. `hypotheticals` is the owner's grant of the overlay - (2026-11-04, §4 d): on, `assume` sentences are admitted and answered as `Hyp`, never `Inv`; - off, they are refused as ill-scoped.""" + MCP server speaks one command, `query`, a sentence under the Ambassador's grant, and + `palace query` is the owner's hand. Since SN-1b the server has a second read beside it, `cut`, + the algebra of cuts (dn-temporal-snapshot §7.5, D28), which takes no sentence. + `hypotheticals` is the owner's grant of the overlay (2026-11-04, §4 d): on, `assume` sentences + are admitted and answered as `Hyp`, never `Inv`; off, they are refused as ill-scoped.""" hypotheticals: bool = True diff --git a/core/stores/catalog.py b/core/stores/catalog.py index d9b4a4f9..56eb5ac1 100644 --- a/core/stores/catalog.py +++ b/core/stores/catalog.py @@ -28,14 +28,15 @@ genesis, every write that appends a row (`record` and `tombstone` when they change the map, the re-key) and `remove` refuse, loudly, and nothing is written unkeyed; `relabel_provenance` and `remove_digest` append no row and need none. The reads of the log (`chains`, `head`, `read_at`, -`state_at`, `history_at`, `heads_at`, `read_between`, `verify`) have no reader yet; the two by -path, `state_at` and `history_at`, need the secret. +`state_at`, `history_at`, `read_between`, `verify`) have no reader yet; the two by path, +`state_at` and `history_at`, need the secret. What a cut holds, every head of a class at once, is +the contents of the cut (`cuts`, `core/stores/cuts.py`), which need none; the cut tool reads them. """ from __future__ import annotations import sqlite3 -from collections.abc import Iterator, Mapping +from collections.abc import Iterable, Iterator, Mapping from contextlib import contextmanager from dataclasses import dataclass, field from datetime import UTC, datetime @@ -43,6 +44,7 @@ from core.kernel.provenance import Provenance from core.stores.authored_supersession import OwnerDeclaration, verify_owner_declaration +from core.stores.cuts import Evaluation from core.stores.landings import ( ChainCheck, Landing, @@ -438,16 +440,18 @@ def history_at(self, provenance: Provenance | str, source_path: str, the order the versions landed in (`LandingLog.history_at`).""" return self._log.history_at(str(provenance), source_path, c) - def heads_at(self, provenance: Provenance | str, c: Mapping[int, int] | int) -> list[Landing]: - """Every head of a class at the cut: the `store` rows alive there, through the closing - stamp, a hole returned as a hole with its position and no name.""" - return self._log.heads_at(str(provenance), c) - def verify(self, chain: int) -> ChainCheck: """A chain's hashes recomputed from its first row, and every commitment that still has its salt: the first position where one fails, or none.""" return self._log.verify(chain) + def cuts(self, provenances: Iterable[Provenance | str]) -> Evaluation: + """An evaluation of the algebra of cuts over the chains these classes hold now, the head + of each read once, now (`core/stores/cuts.py`, dn-temporal-snapshot §4.4): the cut as a + value, the versions a cut holds and the operators on them. It reads the log's rows as + they are and needs no secret.""" + return Evaluation(self._conn, (str(p) for p in provenances)) + def close(self) -> None: self._conn.close() diff --git a/core/stores/cuts.py b/core/stores/cuts.py new file mode 100644 index 00000000..ee89b9e3 --- /dev/null +++ b/core/stores/cuts.py @@ -0,0 +1,1039 @@ +"""The cut as a value, and its algebra over the landing log (dn-temporal-snapshot §4.4, SN-1b). + +A cut is a frontier: one position a chain of the landing log (`core/stores/landings.py`), a few +integers that can be compared, hashed, stored and printed (`Cut`). It stands for what the store +held as of it, and holding it reads no store: the log is read when an operation asks for +something of the cut. Every read happens inside an `Evaluation`: the log's connection, the chains +of the classes the asker reads, and the head of each, read once when the evaluation starts. An +operation that names no cut uses that head, so every part of one answer reads one cut, and every +result names the cuts it reads (D27). + +**On positions** the cuts inside the log are a lattice: `Cut.join` and `Cut.meet` are the +pointwise maximum and minimum, the bottom is the empty cut, and the head is the one cut that moves +(SNP-11). The difference of two cuts on positions is the events between them (`Events`). + +**On contents** a cut holds its versions: the `store` rows of the log that no purge emptied, each +alive from its position up to, and not at, its closing stamp (SNP-12). A set of versions +(`Versions`) is an expression over the contents of cuts under union, intersection and difference, +with no complement (SNP-14). Combining two sets runs no statement: whether a row is in a set is a +predicate on its position and its closing stamp, so a set of any depth is read by one statement. +A count builds no row, and the rows come back as columns, one buffer a column (`Columns`). The +signed difference of two cuts (`Delta`) is two such sets, the versions gone and the versions come, +whose statements walk what changed between the two cuts (SNP-13); read, they sort by path within a +chain into removed, added and replaced. + +Union and intersection are kept in both meanings, under different names and types (D22, D26): +`Cut.join` and `Cut.meet` take cuts and return a cut, and `|` and `&` on `Versions` take sets +and return a set. The two differ: the union of the contents of two cuts holds both versions of a +note edited between them, where the contents of their join hold the later one (SNP-15). + +**The interface.** An operator is a function of one cut's read (`Evaluation.apply`), of two +(`Evaluation.combine`), of each cut of a family (`Evaluation.map`), or an accumulation over a +family (`Evaluation.fold`). The named operations are written on these four, and so is any other. +A read (`Read`) is a cut with what it holds and the events up to it. + +Every statement names the chains of the evaluation and no other, so a result under a grant is a +function of the chains the grant reads (SNP-16), and a row a purge emptied is in no set (SNP-17). +An evaluation needs only a connection, and one that only reads (`read_only`) takes no lock a +writer waits on. +It is not yet the graph: edges and graph mathematics at a cut arrive with SN-4. Apart from the +cut tool (`agents/ambassador/cut_tool.py`), nothing in the palace reads this module yet. +""" + +from __future__ import annotations + +import re +import sqlite3 +from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, ClassVar, Literal + +import numpy as np +import numpy.typing as npt + +type IntArray = npt.NDArray[np.int64] +type Order = Literal["equal", "before", "after", "unordered"] + +# The version's own test: a landing that a purge has not emptied (§4.4). A tombstone, a `leave`, +# the genesis and the horizon carry no version; a hole is a `store` without its salt. +VERSION = "kind = 'store' AND salt IS NOT NULL" +# The columns a read of rows can ask for, by the log's own names (§3.2), and how each is read: an +# integer, the 32 bytes of a path's key, or text. An integer that is null reads -1 (positions and +# version numbers are positive); a key that is null reads 32 zero bytes; text keeps a null mask. +INTEGER = ("chain", "seq", "version", "closed_at") +KEY = ("path_key",) +TEXT = ("kind", "source_path", "doc_id", "digest", "title") +COLUMNS = (*INTEGER, *KEY, *TEXT) +_NAME = re.compile(r"land\.([0-9]+)@([0-9]+)") +_NO_KEY = "0" * 64 + + +class CutError(ValueError): + """A cut or an operand the algebra refuses. The message says what was given and what is + taken, in words that are safe to show the asker.""" + + +# --- the cut ------------------------------------------------------------------------------------- + +@dataclass(frozen=True, slots=True) +class Cut: + """A frontier: one position a landing chain, as `(chain, position)` pairs in chain order. A + chain the cut leaves out stands at 0, its empty prefix, so a cut keeps no zero and two equal + cuts are one value and one key (D24). The order is the pointwise one.""" + + positions: tuple[tuple[int, int], ...] = () + + def __post_init__(self) -> None: + chains = [k for k, _ in self.positions] + if chains != sorted(set(chains)) or any( + type(k) is not int or type(p) is not int or k <= 0 or p <= 0 + for k, p in self.positions): + raise CutError("a cut is one positive position a chain, in chain order; use Cut.of") + + @classmethod + def of(cls, positions: Mapping[int, int]) -> Cut: + """The cut at these positions; a position of 0 is the chain's empty prefix.""" + out: list[tuple[int, int]] = [] + for k, p in sorted(positions.items()): + if type(k) is not int or type(p) is not int or k <= 0 or p < 0: + raise CutError(f"a cut's chain is a positive integer and its position one at " + f"least 0, not {k!r} at {p!r}") + if p: + out.append((k, p)) + return cls(tuple(out)) + + @classmethod + def parse(cls, text: str) -> Cut: + """A cut from its positions written as an answer prints them, `land.@` one a + chain, separated by spaces (§7.5). A chain the text leaves out stands at 0.""" + found: dict[int, int] = {} + for word in text.split(): + m = _NAME.fullmatch(word) + if m is None: + raise CutError(f"{word!r} is not a position; a cut is named head, bottom, or its " + "positions, land.@ one a chain, as land.3@412 " + "land.5@97") + k, p = int(m.group(1)), int(m.group(2)) + if k in found: + raise CutError(f"land.{k} is named twice; a cut has one position a chain") + found[k] = p + if not found: + raise CutError("a cut is named head, bottom, or its positions, land.@") + return cls.of(found) + + def at(self, chain: int) -> int: + """The cut's position on a chain: 0 where it leaves the chain out.""" + for k, p in self.positions: + if k == chain: + return p + return 0 + + @property + def chains(self) -> tuple[int, ...]: + """The chains the cut stands above 0 on.""" + return tuple(k for k, _ in self.positions) + + def as_dict(self) -> dict[int, int]: + return dict(self.positions) + + def join(self, other: Cut) -> Cut: + """The union on positions: on each chain the later of the two, so everything that had + happened by either cut (SNP-11). A cut.""" + a, b = self.as_dict(), other.as_dict() + return Cut.of({k: max(a.get(k, 0), b.get(k, 0)) for k in a.keys() | b.keys()}) + + def meet(self, other: Cut) -> Cut: + """The intersection on positions: on each chain the earlier of the two, so everything + that had happened by both cuts (SNP-11). A cut.""" + a, b = self.as_dict(), other.as_dict() + return Cut.of({k: min(a.get(k, 0), b.get(k, 0)) for k in a.keys() & b.keys()}) + + def __le__(self, other: Cut) -> bool: + """Whether the cut is at or under `other` on every chain.""" + return all(p <= other.at(k) for k, p in self.positions) + + def __ge__(self, other: Cut) -> bool: + return other <= self + + def order(self, other: Cut) -> Order: + """How the cut stands to `other` on positions: equal, before (under it), after, or + unordered (under it on one chain and over it on another).""" + if self == other: + return "equal" + if self <= other: + return "before" + if other <= self: + return "after" + return "unordered" + + def restrict(self, chains: Iterable[int]) -> Cut: + """The cut on the chains given and on no other.""" + keep = set(chains) + return Cut(tuple((k, p) for k, p in self.positions if k in keep)) + + def name(self, chains: Sequence[int] | None = None) -> str: + """The cut's positions as an answer prints them (§7.5): on the chains given, zeros + included, or on the chains it stands on; `bottom` when there is none to print.""" + ks = list(chains) if chains is not None else list(self.chains) + return " ".join(f"land.{k}@{self.at(k)}" for k in ks) or "bottom" + + def __str__(self) -> str: + return self.name() + + +BOTTOM = Cut() + + +def join_all(cuts: Iterable[Cut]) -> Cut: + """The join of a family: on each chain the greatest of its positions.""" + out = BOTTOM + for c in cuts: + out = out.join(c) + return out + + +def meet_all(cuts: Sequence[Cut]) -> Cut: + """The meet of a family that is not empty: on each chain the least of its positions.""" + out = cuts[0] + for c in cuts[1:]: + out = out.meet(c) + return out + + +# --- a set of versions, named and not read -------------------------------------------------------- + +@dataclass(frozen=True, slots=True) +class _Held: + """What a cut holds.""" + + cut: Cut + terms: ClassVar[int] = 1 + + +@dataclass(frozen=True, slots=True) +class _Node: + """What either set holds, what both hold, what the first holds and the second does not, or + what exactly one of the two holds. `terms` is how many times the statement the set runs as + names a cut, the size of the predicate on a chain: an operand the expression shares is + counted each time, since the statement writes it out each time.""" + + op: Literal["union", "inter", "diff", "xor"] + p: _Expr + q: _Expr + terms: int = field(init=False, compare=False) + + def __post_init__(self) -> None: + object.__setattr__(self, "terms", self.p.terms + self.q.terms) + + +type _Expr = _Held | _Node + + +def _atoms(e: _Expr) -> Iterator[Cut]: + if isinstance(e, _Held): + yield e.cut + else: + yield from _atoms(e.p) + yield from _atoms(e.q) + + +def _predicate(e: _Expr, chain: int) -> tuple[str, list[int]] | None: + """Whether a row of `chain` is in the set, as SQL on its position and its closing stamp and + nothing else (`Held.has`); `None` where the set holds no row of the chain whatever the rows.""" + if isinstance(e, _Held): + c = e.cut.at(chain) + if c == 0: # nothing is alive at the empty prefix + return None + return "(seq <= ? AND (closed_at IS NULL OR closed_at > ?))", [c, c] + p, q = _predicate(e.p, chain), _predicate(e.q, chain) + if e.op in ("union", "xor"): + if p is None or q is None: + return p if q is None else q + # a predicate is never null (`seq` is not, and a stamp is tested for null first), so two + # of them differ exactly when one row is in one set: each operand is written once + return f"({p[0]} {'OR' if e.op == 'union' else '<>'} {q[0]})", p[1] + q[1] + if e.op == "inter": + if p is None or q is None: + return None + return f"({p[0]} AND {q[0]})", p[1] + q[1] + if p is None or q is None: + return p + return f"({p[0]} AND NOT {q[0]})", p[1] + q[1] + + +@dataclass(frozen=True, slots=True) +class _Range: + """Bounds every row of a set on one chain lies in: its position in `(lo, hi]` and its closing + stamp in `(died_lo, died_hi]`, `None` for no upper bound (a row still open).""" + + lo: int + hi: int + died_lo: int + died_hi: int | None + + def empty(self) -> bool: + return self.lo >= self.hi or (self.died_hi is not None and self.died_lo >= self.died_hi) + + +def _negated(e: _Expr) -> list[Cut]: + """Cuts a row of `diff(p, e)` is known not to be alive at: `e`'s, when `e` is a cut or a union + of cuts, and none otherwise (the bounds stay sound, only looser).""" + if isinstance(e, _Held): + return [e.cut] + if e.op == "union": + return _negated(e.p) + _negated(e.q) + return [] + + +def _range(e: _Expr, chain: int) -> _Range | None: + """The bounds of a set on one chain, from the intervals (SNP-12): a row alive at `c` has + `seq <= c < closed_at`, so the rows come between two cuts are a range of positions and the + rows gone a range of closing stamps, which the statement then reads by the primary key or by + `landings_closed`. `None` where the bounds hold no row.""" + if isinstance(e, _Held): + c = e.cut.at(chain) + return _Range(0, c, c, None) if c else None + p, q = _range(e.p, chain), _range(e.q, chain) + if e.op in ("union", "xor"): # what exactly one holds lies inside what either does + if p is None or q is None: + return p if q is None else q + hi = None if p.died_hi is None or q.died_hi is None else max(p.died_hi, q.died_hi) + return _Range(min(p.lo, q.lo), max(p.hi, q.hi), min(p.died_lo, q.died_lo), hi) + if e.op == "inter": + if p is None or q is None: + return None + his = [h for h in (p.died_hi, q.died_hi) if h is not None] + r = _Range(max(p.lo, q.lo), min(p.hi, q.hi), max(p.died_lo, q.died_lo), + min(his) if his else None) + return None if r.empty() else r + if p is None: + return None + r = p + for cut in _negated(e.q): + c = cut.at(chain) + if c == 0: # a row is never alive at the empty prefix: nothing to learn + continue + lo, died_hi = r.lo, r.died_hi + if r.died_lo >= c: # alive past `c` and not alive at it: stored after it + lo = max(lo, c) + if r.hi <= c: # stored by `c` and not alive at it: closed by it + died_hi = c if died_hi is None else min(died_hi, c) + r = _Range(lo, r.hi, r.died_lo, died_hi) + if r.empty(): + return None + return r + + +def _where(e: _Expr, chain: int) -> tuple[str, list[int]] | None: + """The statement's condition for the rows of `chain` in the set, the version's test aside: + the chain, the bounds as ranges an index can take, and the predicate itself.""" + pred, rng = _predicate(e, chain), _range(e, chain) + if pred is None or rng is None: + return None + sql = ["chain = ?", "seq <= ?"] + args: list[int] = [chain, rng.hi] + if rng.lo > 0: + sql.append("seq > ?") + args.append(rng.lo) + if rng.died_hi is not None: + sql += ["closed_at > ?", "closed_at <= ?"] + args += [rng.died_lo, rng.died_hi] + elif rng.died_lo > 0: + sql.append("(closed_at IS NULL OR closed_at > ?)") + args.append(rng.died_lo) + sql.append(pred[0]) + return " AND ".join(sql), args + pred[1] + + +class Versions: + """A set of versions, named and not read (SNP-14): the contents of a cut, or the union, the + intersection, the difference or the symmetric difference of two sets (`|`, `&`, `-`, `^`). + There is no complement, so a set lies inside the contents of the cuts it names. Combining + reads nothing; `count` runs one statement and builds no row, and `columns` reads the rows as + one buffer a column. The statement grows with `terms`, which an operator adds and never + multiplies: each names its operands once.""" + + __slots__ = ("_ev", "_e") + + def __init__(self, ev: Evaluation, e: _Expr) -> None: + self._ev = ev + self._e = e + + @property + def terms(self) -> int: + """How many times the set's statement names a cut: the size of its predicate on a + chain, which bounds the statement's text and its parameters (two a cut a chain).""" + return self._e.terms + + def _with(self, op: Literal["union", "inter", "diff", "xor"], other: Versions) -> Versions: + if not isinstance(other, Versions): + raise CutError(f"a set of versions combines with a set of versions, not with " + f"{_kind(other)}") + if other._ev is not self._ev: + raise CutError("two sets combine inside one evaluation, which reads one head") + return Versions(self._ev, _Node(op, self._e, other._e)) + + def __or__(self, other: Versions) -> Versions: + """What either set holds: the union on contents (D22).""" + return self._with("union", other) + + def __and__(self, other: Versions) -> Versions: + """What both sets hold: the intersection on contents (D22).""" + return self._with("inter", other) + + def __sub__(self, other: Versions) -> Versions: + """What this set holds and `other` does not.""" + return self._with("diff", other) + + def __xor__(self, other: Versions) -> Versions: + """What exactly one of the two sets holds: the rows of `Held.symm`, the union less the + intersection (`Held.has_symm`), as a node of its own whose statement names each operand + once. Written as `(a - b) | (b - a)` it would name both twice, and nested, double.""" + return self._with("xor", other) + + @property + def cuts(self) -> tuple[Cut, ...]: + """The cuts the set names, in the order it names them, each once.""" + return tuple(dict.fromkeys(_atoms(self._e))) + + def _parts(self) -> list[tuple[str, list[int]]]: + return [w for k in self._ev.chains if (w := _where(self._e, k)) is not None] + + def tally(self) -> tuple[int, int]: + """The versions in the set, and the holes it would hold: the `store` rows a purge emptied + that its predicate takes (D33). One statement, which builds no row.""" + parts = self._parts() + if not parts: + return 0, 0 + sql = " UNION ALL ".join( + "SELECT count(salt) AS n, count(*) - count(salt) AS h FROM landings " + f"WHERE kind = 'store' AND {w}" for w, _ in parts) + n, h = self._ev.one(f"SELECT coalesce(sum(n), 0), coalesce(sum(h), 0) FROM ({sql})", + [a for _, args in parts for a in args]) + return int(n), int(h) + + def count(self) -> int: + """How many versions the set holds: a number, and no operand of a set operator.""" + return self.tally()[0] + + def holes(self) -> int: + return self.tally()[1] + + def columns(self, *names: str, limit: int | None = None) -> Columns: + """The set's rows as columns, `chain` and `seq` always among them, in position order + chain by chain; the first `limit` rows when it is given.""" + parts = self._parts() + return self._ev.columns([(f"{VERSION} AND {w}", args) for w, args in parts], names, + limit) + + def __repr__(self) -> str: + return f"Versions({' '.join(str(c) for c in self.cuts) or 'bottom'})" + + +# --- the events between two cuts ------------------------------------------------------------------ + +@dataclass(frozen=True, slots=True) +class Events: + """The events after one cut and up to another, chain by chain: the difference of two cuts on + positions (SNP-11, `readBetween`). On a chain where the first cut is not under the second + there are none, so the events between two cuts are those between their meet and the second. + Every kind of row is an event: a landing, a tombstone, a `leave`, a hole.""" + + ev: Evaluation + since: Cut + upto: Cut + + def after(self, cut: Cut) -> Events: + """These events after `cut` as well: the read past the length of the first (§4.4).""" + return Events(self.ev, self.since.join(cut), self.upto) + + def _parts(self) -> list[tuple[str, list[int]]]: + out = [] + for k in self.ev.chains: + lo, hi = self.since.at(k), self.upto.at(k) + if lo < hi: + out.append(("chain = ? AND seq > ? AND seq <= ?", [k, lo, hi])) + return out + + def tally(self) -> tuple[int, int]: + """How many events, and how many of them are holes: one statement.""" + parts = self._parts() + if not parts: + return 0, 0 + sql = " UNION ALL ".join( + "SELECT count(*) AS n, count(*) - count(salt) AS h FROM landings " + f"WHERE {w}" for w, _ in parts) + n, h = self.ev.one(f"SELECT coalesce(sum(n), 0), coalesce(sum(h), 0) FROM ({sql})", + [a for _, args in parts for a in args]) + return int(n), int(h) + + def count(self) -> int: + return self.tally()[0] + + def columns(self, *names: str, limit: int | None = None) -> Columns: + return self.ev.columns(self._parts(), names, limit) + + +# --- columns -------------------------------------------------------------------------------------- + +@dataclass(frozen=True, slots=True) +class Text: + """A column of text read as one buffer: the UTF-8 bytes of every value end to end, the offset + of each, and which are null. A value is decoded when it is asked for.""" + + data: bytes + offsets: IntArray + null: npt.NDArray[np.bool_] + + def __len__(self) -> int: + return len(self.null) + + def __getitem__(self, i: int) -> str | None: + if self.null[i]: + return None + return self.data[int(self.offsets[i]):int(self.offsets[i + 1])].decode("utf-8") + + def take(self, index: IntArray) -> Text: + """The values at `index`, in its order, as a new buffer: no value is decoded.""" + lengths = np.diff(self.offsets)[index] + offsets = np.zeros(len(index) + 1, dtype=np.int64) + np.cumsum(lengths, out=offsets[1:]) + starts = self.offsets[:-1][index] + gather = np.repeat(starts - offsets[:-1], lengths) + np.arange(offsets[-1]) + data = np.frombuffer(self.data, dtype=np.uint8)[gather].tobytes() + return Text(data, offsets, self.null[index]) + + +type Column = IntArray | npt.NDArray[np.void] | Text + + +@dataclass(frozen=True, slots=True) +class Columns: + """Rows read as columns: one buffer a column, aligned, in position order chain by chain, with + fewer than one Python object a row. An integer that is null reads -1, a path's key that is + null 32 zero bytes, and text keeps a null mask (`Text`).""" + + values: Mapping[str, Column] + + def __len__(self) -> int: + return len(self.values["seq"]) + + def __getitem__(self, name: str) -> Column: + return self.values[name] + + def ints(self, name: str) -> IntArray: + col = self.values[name] + if name not in INTEGER or isinstance(col, Text): + raise KeyError(f"{name} is not an integer column") + return col.astype(np.int64, copy=False) + + def keys(self) -> npt.NDArray[np.void]: + """Each row's chain and its path's key as one 40-byte value: what pairs a row gone with + a row come (D32).""" + chain = self.ints("chain").astype(">i8").view(np.uint8).reshape(-1, 8) + key = self.values["path_key"] + if isinstance(key, Text): + raise KeyError("path_key is not a key column") + raw = key.view(np.uint8).reshape(-1, 32) + return np.ascontiguousarray(np.hstack([chain, raw])).view("V40").ravel() + + def take(self, index: IntArray) -> Columns: + """The rows at `index`, in its order.""" + out: dict[str, Column] = {} + for name, col in self.values.items(): + out[name] = col.take(index) if isinstance(col, Text) else col[index] + return Columns(out) + + def row(self, i: int) -> dict[str, object]: + """One row as plain values, for a listing: an integer that reads -1 is null.""" + out: dict[str, object] = {} + for name, col in self.values.items(): + if isinstance(col, Text): + out[name] = col[i] + elif name in INTEGER: + v = int(col[i]) + out[name] = None if v < 0 else v + else: + out[name] = bytes(col[i].tobytes()).hex() + return out + + +def _ints(text: str | None) -> IntArray: + if not text: + return np.zeros(0, dtype=np.int64) + return np.fromstring(text, dtype=np.int64, sep=",").astype(np.int64, copy=False) + + +def _read_columns(row: Sequence[object], names: Sequence[str]) -> Columns: + """The aggregates of one statement decoded into columns, in the order `_aggregates` wrote + them.""" + values: dict[str, Column] = {} + it = iter(row) + for name in names: + if name in INTEGER: + values[name] = _ints(_text(next(it))) + elif name in KEY: + raw = bytes.fromhex(_text(next(it)) or "") + values[name] = np.frombuffer(raw, dtype="V32") + else: + data = (_text(next(it)) or "").encode("utf-8") + lengths = _ints(_text(next(it))) + offsets = np.zeros(len(lengths) + 1, dtype=np.int64) + np.cumsum(np.maximum(lengths, 0), out=offsets[1:]) + values[name] = Text(data, offsets, lengths < 0) + return Columns(values) + + +def _text(v: object) -> str | None: + return None if v is None else str(v) + + +def _aggregates(names: Sequence[str]) -> str: + out = [] + for c in names: + if c in INTEGER: + out.append(f"group_concat(coalesce({c}, -1))") + elif c in KEY: + out.append(f"group_concat(coalesce(hex({c}), '{_NO_KEY}'), '')") + else: + out += [f"group_concat(coalesce({c}, ''), '')", + f"group_concat(coalesce(length(CAST({c} AS BLOB)), -1))"] + return ", ".join(out) + + +# --- the signed difference ------------------------------------------------------------------------ + +@dataclass(frozen=True, slots=True) +class Counts: + """A signed difference counted: the paths removed, added and replaced, and the holes among the + rows its two range reads take (D33).""" + + removed: int + added: int + replaced: int + holes: int + + +@dataclass(frozen=True, slots=True) +class Sorted: + """A signed difference read and sorted by path within a chain (D32): the rows of the paths + removed, of those added, and the two rows of each path replaced, aligned.""" + + removed: Columns + added: Columns + replaced: tuple[Columns, Columns] + + +@dataclass(frozen=True, slots=True) +class Delta: + """The signed difference of two cuts on contents (SNP-13): the versions `a` holds and `b` does + not (`gone`) and the converse (`come`), each a set and an operand again. Each side's + statement walks what changed between the two cuts, chain by chain in its own direction.""" + + a: Cut + b: Cut + gone: Versions + come: Versions + + def sizes(self) -> tuple[int, int]: + """How many versions are gone and how many came: one statement.""" + g, c = self.gone._parts(), self.come._parts() + if not g and not c: + return 0, 0 + sides = [f"SELECT {i} AS side FROM landings WHERE {VERSION} AND {w}" + for i, parts in ((0, g), (1, c)) for w, _ in parts] + n_gone, n_come = self.gone._ev.one( + "SELECT coalesce(sum(side = 0), 0), coalesce(sum(side = 1), 0) " + f"FROM ({' UNION ALL '.join(sides)})", + [a for parts in (g, c) for _, args in parts for a in args]) + return int(n_gone), int(n_come) + + def counts(self) -> Counts: + """The paths removed, added and replaced, and the holes in the two ranges: one statement, + which pairs the two sides by path within a chain and builds no row.""" + g, c = self.gone._parts(), self.come._parts() + if not g and not c: + return Counts(0, 0, 0, 0) + + def side(parts: list[tuple[str, list[int]]]) -> str: + if not parts: + return "SELECT NULL AS chain, NULL AS path_key, 0 AS v WHERE 0" + return " UNION ALL ".join( + "SELECT chain, path_key, salt IS NOT NULL AS v FROM landings " + f"WHERE kind = 'store' AND {w}" for w, _ in parts) + + n_gone, n_come, paired, holes = self.gone._ev.one( + f"WITH g AS MATERIALIZED ({side(g)}), c AS MATERIALIZED ({side(c)}) " + "SELECT (SELECT count(*) FROM g WHERE v), (SELECT count(*) FROM c WHERE v), " + "(SELECT count(*) FROM g JOIN c USING (chain, path_key) WHERE g.v AND c.v), " + "(SELECT count(*) FROM g WHERE NOT v) + (SELECT count(*) FROM c WHERE NOT v)", + [a for parts in (g, c) for _, args in parts for a in args]) + return Counts(int(n_gone) - int(paired), int(n_come) - int(paired), int(paired), + int(holes)) + + def sorted(self, *names: str, limit: int | None = None) -> Sorted: + """The two sides read, every row of each (what changed), and sorted by path within a + chain: a path with a row on each side is replaced, one with a row gone only removed, one + with a row come only added (`removedOf`, `addedOf`, `replacedOf`). Each class in position + order, its first `limit` entries when `limit` is given.""" + want = (*dict.fromkeys((*names, "path_key")),) + gone, come = self.gone.columns(*want), self.come.columns(*want) + # each key is on a side once (a cut holds one row a path on a chain), so after one sort + # of both sides' keys a key on both is two neighbours, the row gone first + keys = np.concatenate([gone.keys(), come.keys()]) + order = np.argsort(keys, kind="stable").astype(np.int64) + twin = np.flatnonzero(keys[order][1:] == keys[order][:-1]) + rg, rc = order[twin], order[twin + 1] - len(gone) + paired = np.zeros(len(keys), dtype=np.bool_) + paired[rg], paired[rc + len(gone)] = True, True + removed = np.flatnonzero(~paired[:len(gone)])[:limit] + added = np.flatnonzero(~paired[len(gone):])[:limit] + by_position = np.argsort(rg, kind="stable") # the pairs in the gone rows' order + rg, rc = rg[by_position][:limit], rc[by_position][:limit] + return Sorted(gone.take(removed), come.take(added), (gone.take(rg), come.take(rc))) + + def apply(self, s: Versions) -> Versions: + """The difference applied to a set: the set less the versions gone, with those come. + Applied to what `a` holds it gives what `b` holds (`Held.has_cut_eq_apply`).""" + return (s - self.gone) | self.come + + def then(self, other: Delta) -> Delta: + """This difference composed with one from the cut it ends at: the difference from `a` to + `other.b` (`Held.has_come_trans`, `Held.has_gone_trans`), a row that came and went on + the way on neither side. Refused unless `other` starts where this one ends, at a cut + that lies between the two outer ones on every chain, in either direction: through a cut + outside them the composition is not the difference (`Witness.delta_through_outside`).""" + if not isinstance(other, Delta): + raise CutError(f"a signed difference composes with a signed difference, not with " + f"{_kind(other)}") + if other.a != self.b: + raise CutError(f"two signed differences compose through the cut they share: one " + f"ends at {self.b.name()} and the other starts at {other.a.name()}") + ev = self.gone._ev + for k in ev.chains: + a, b, c = self.a.at(k), self.b.at(k), other.b.at(k) + if not (min(a, c) <= b <= max(a, c)): + raise CutError(f"the shared cut is not between the outer two on land.{k}: " + f"{b} is not between {a} and {c}, and through a cut outside " + "them the composition is not the difference") + return Delta(self.a, other.b, self.gone | (other.gone - self.come), + (self.come - other.gone) | other.come) + + +# --- a family's results --------------------------------------------------------------------------- + +@dataclass(frozen=True, slots=True) +class Series[T]: + """A value at each cut of a family, in the family's order: a series, and no operand of a set + operator.""" + + cuts: tuple[Cut, ...] + values: tuple[T, ...] + + +@dataclass(frozen=True, slots=True) +class Table: + """The sizes of the pairwise differences of a family: `sizes[i][j]` is how many versions cut + `i` holds and cut `j` does not. `sizes[i][j] - sizes[j][i]` is the difference of the two + counts (`Held.length_rows_delta`), and `sizes[i][k] <= sizes[i][j] + sizes[j][k]`, since a + row gone from `i` to `k` is gone from `i` to `j` or from `j` to `k` + (`Held.has_gone_triangle`, which states the rows; the sizes follow).""" + + cuts: tuple[Cut, ...] + sizes: tuple[tuple[int, ...], ...] + + +@dataclass(frozen=True, slots=True) +class Counted: + """The rows of a set, each with the number of a family's cuts that hold it (`countIn`).""" + + cuts: tuple[Cut, ...] + rows: Columns + counts: IntArray + + +@dataclass(frozen=True, slots=True) +class Read: + """One cut's read, as an operator is handed it: the cut, the versions it holds and the events + up to it. Nothing is read until one of the two is. SN-4 adds the graph at the cut here.""" + + cut: Cut + versions: Versions + events: Events + + +# --- the evaluation ------------------------------------------------------------------------------- + +class Evaluation: + """One evaluation of the algebra: the log's connection, the chains of the classes the asker + reads (the classes' chains now, §6.3), and the head of each, read once when the evaluation + starts. Every operation takes its cuts as optional: one left out is that head (D19, D27). + Every cut given is taken on the evaluation's chains alone, and refused past the head.""" + + def __init__(self, conn: sqlite3.Connection, classes: Iterable[str]) -> None: + self._conn = conn + wanted = sorted({str(c) for c in classes}) + rows = conn.execute( + "SELECT chain, class, (SELECT max(seq) FROM landings l WHERE l.chain = c.chain) " + f"FROM landing_chains c WHERE class IN ({', '.join('?' * len(wanted))}) " + "ORDER BY chain", wanted).fetchall() if wanted else [] + self.classes: dict[int, str] = {int(k): str(cls) for k, cls, _ in rows} + self.chains: tuple[int, ...] = tuple(self.classes) + self.head = Cut.of({int(k): int(h or 0) for k, _, h in rows}) + self.bottom = BOTTOM + # what `served` has learnt of each chain's horizon, so that it walks a chain once: the + # horizon found, or the greatest position found to lie under it + self._horizon: dict[int, int] = {} + self._under: dict[int, int] = {} + + # reading ----------------------------------------------------------------------------------- + + def one(self, sql: str, args: Sequence[object]) -> tuple[Any, ...]: + """The one row a statement of aggregates returns.""" + return tuple(self._conn.execute(sql, list(args)).fetchone()) + + def columns(self, parts: Sequence[tuple[str, list[int]]], names: Sequence[str], + limit: int | None) -> Columns: + """The rows the conditions take, one condition a chain, as columns in one statement.""" + bad = [n for n in names if n not in COLUMNS] + if bad: + raise CutError(f"no column {', '.join(bad)}; the columns are {', '.join(COLUMNS)}") + want = tuple(dict.fromkeys(("chain", "seq", *names))) + if not parts: + return _read_columns([None] * sum(1 + (c in TEXT) for c in want), want) + body = " UNION ALL ".join(f"SELECT {', '.join(want)} FROM landings WHERE {w}" + for w, _ in parts) + args: list[object] = [a for _, ps in parts for a in ps] + if limit is not None: + body = f"{body} ORDER BY chain, seq LIMIT ?" + args.append(int(limit)) + cols = _read_columns(self.one(f"SELECT {_aggregates(want)} FROM ({body})", args), want) + chain, seq = cols.ints("chain"), cols.ints("seq") + if len(seq) > 1 and not bool(np.all((chain[1:] > chain[:-1]) | ( + (chain[1:] == chain[:-1]) & (seq[1:] > seq[:-1])))): + cols = cols.take(np.lexsort((seq, chain)).astype(np.int64)) + return cols + + # cuts -------------------------------------------------------------------------------------- + + def cut(self, c: Cut | None = None) -> Cut: + """`c` on the evaluation's chains, or the head when it is `None`. Refused past the head: + a cut inside the log is at or under it.""" + if c is None: + return self.head + if not isinstance(c, Cut): + raise CutError(f"a cut is expected, and {_kind(c)} was given") + c = c.restrict(self.chains) + for k, p in c.positions: + h = self.head.at(k) + if p > h: + raise CutError(f"land.{k}@{p} is past the chain's head, land.{k}@{h}") + return c + + def named(self, name: str) -> Cut: + """A cut by its name (§7.5): `head`, `bottom`, or its positions. A position past a chain's + head is refused with the head, and a chain the evaluation does not read is refused in the + words used for a chain that does not exist.""" + text = name.strip() + if text == "head": + return self.head + if text == "bottom": + return self.bottom + c = Cut.parse(text) + for k in c.chains: + if k not in self.classes: + read = " ".join(f"land.{j}" for j in self.chains) or "none" + raise CutError(f"there is no chain land.{k}; the chains read here are {read}") + return self.cut(c) + + def serves(self, chain: int, position: int) -> bool: + """Whether a chain serves a position under its head: whether the position is at or + after the chain's horizon. A chain's positions before its horizon are its genesis block, + which is not history, and are not served (§8). At this stage a chain has one horizon + row, at the end of its genesis block, and no index finds it, so the statement walks the + rows from the position back to it, or to the chain's first row when the position lies + under it. No row is walked twice in one evaluation: the horizon found answers every later + position on its chain, a later position under one found to lie under the horizon needs no + walk, and one above it walks only down to it.""" + if chain in self._horizon: + return position >= self._horizon[chain] + under = self._under.get(chain, 0) + if position <= under: + return False + row = self._conn.execute( + "SELECT horizon FROM landings WHERE chain = ? AND seq <= ? AND seq > ? " + "AND kind = 'horizon' ORDER BY seq DESC LIMIT 1", [chain, position, under]).fetchone() + if row is None or row[0] is None: + self._under[chain] = position + return False + self._horizon[chain] = int(row[0]) + return position >= int(row[0]) + + def served(self, c: Cut) -> tuple[Cut, list[tuple[int, int]]]: + """The cut read for the cut asked (§7.1): each chain at the greatest position it serves at + or under the one asked. A position under a chain's horizon is not served, and the chain is + read at its empty prefix (`serves`); the head serves itself and needs no walk. No + reference of §3.5 lowers a landing chain before SN-2, so nothing else is lowered. One + pair of rows is not among those references: a change of class writes a `leave` in the + old class's chain and then the `store` in the new class's chain, and a cut of two chains + or more that is neither the head nor the bottom can hold one of the two rows without the + other, and so the path in both classes or in neither (§3.5, §7.5). It is read as asked. + Returns the cut read and the chains read below the position asked, with that position.""" + lowered: list[tuple[int, int]] = [] + out = c.as_dict() + for k, p in c.positions: + if p == self.head.at(k) or self.serves(k, p): + continue + lowered.append((k, p)) + out[k] = 0 + return Cut.of(out), lowered + + # the interface: apply, combine, map and fold -------------------------------------------------- + + def read(self, c: Cut | None = None) -> Read: + """One cut's read; the head's when `c` is `None`.""" + c = self.cut(c) + return Read(c, Versions(self, _Held(c)), Events(self, BOTTOM, c)) + + def apply[T](self, f: Callable[[Read], T], c: Cut | None = None) -> T: + """A function of one cut's read (`view`).""" + return f(self.read(c)) + + def combine[T](self, f: Callable[[Read, Read], T], a: Cut | None = None, + b: Cut | None = None) -> T: + """A function of two cuts' reads (`combine`).""" + return f(self.read(a), self.read(b)) + + def family(self, cuts: Sequence[Cut] | None = None) -> tuple[Cut, ...]: + """A family's cuts on the evaluation's chains: the head alone when none is given.""" + return tuple(self.cut(c) for c in cuts) if cuts else (self.head,) + + def map[T](self, f: Callable[[Read], T], cuts: Sequence[Cut] | None = None) -> Series[T]: + """A function at each cut of a family (`series`): a series.""" + fam = self.family(cuts) + return Series(fam, tuple(f(self.read(c)) for c in fam)) + + def fold[T](self, g: Callable[[T, Read], T], init: T, + cuts: Sequence[Cut] | None = None) -> T: + """An accumulation over the cuts of a family, each read in its turn (`foldOver`).""" + acc = init + for c in self.family(cuts): + acc = g(acc, self.read(c)) + return acc + + # the named operations, each one of the four forms --------------------------------------------- + + def held(self, c: Cut | None = None) -> Versions: + """The versions a cut holds (an apply): the contents of every class the evaluation reads + at the cut, a set and an operand of every set operator.""" + return self.apply(lambda r: r.versions, c) + + def between(self, a: Cut | None = None, b: Cut | None = None) -> Events: + """The events after `a` and up to `b` (a combine): the difference on positions.""" + return self.combine(lambda ra, rb: rb.events.after(ra.cut), a, b) + + def delta(self, a: Cut | None = None, b: Cut | None = None) -> Delta: + """The signed difference from `a` to `b` (a combine): what `a` holds and `b` does not, + and the converse.""" + return self.combine(lambda ra, rb: Delta(ra.cut, rb.cut, ra.versions - rb.versions, + rb.versions - ra.versions), a, b) + + def persisted(self, cuts: Sequence[Cut] | None = None) -> Versions: + """What every cut of a family holds (a fold): what the family's meet and its join both + hold, two positions a chain whatever the size of the family (`Held.has_all_eq_kept`).""" + fam = self.family(cuts) + lo, hi = self.fold(lambda acc, r: (acc[0].meet(r.cut), acc[1].join(r.cut)), + (fam[0], fam[0]), fam) + return self.held(lo) & self.held(hi) + + def existed(self, cuts: Sequence[Cut] | None = None) -> Versions: + """What some cut of a family holds (a fold): the union of their contents.""" + + def step(acc: Versions | None, r: Read) -> Versions | None: + return r.versions if acc is None else acc | r.versions + + out = self.fold(step, None, self.family(cuts)) + assert out is not None # a family has one cut at least + return out + + def count_series(self, cuts: Sequence[Cut] | None = None) -> Series[int]: + """The count at each cut of a family (a fold): the first cut counted, and each next count + from the last by the signed difference between the two, which walks what changed + (`Held.length_rows_delta`).""" + fam = self.family(cuts) + type Walk = tuple[Read | None, tuple[int, ...]] + + def step(acc: Walk, r: Read) -> Walk: + last, values = acc + if last is None: + return r, (r.versions.count(),) + gone, come = Delta(last.cut, r.cut, last.versions - r.versions, + r.versions - last.versions).sizes() + return r, (*values, values[-1] - gone + come) + + start: Walk = (None, ()) + return Series(fam, self.fold(step, start, fam)[1]) + + def in_how_many(self, s: Versions, cuts: Sequence[Cut] | None = None, + names: Sequence[str] = (), limit: int | None = None) -> Counted: + """The rows of `s`, each with the number of the family's cuts that hold it: a row is held + at `c` exactly when `seq <= c < closed_at`, read off its interval (`countIn`). Only the + first `limit` rows are read when it is given; how many rows every cut holds is a count, + `s & self.persisted(cuts)`, and needs none of them.""" + fam = self.family(cuts) + rows = s.columns(*dict.fromkeys((*names, "closed_at")), limit=limit) + return Counted(fam, rows, self._held_by(rows, fam).sum(axis=1).astype(np.int64)) + + def pairwise(self, cuts: Sequence[Cut] | None = None) -> Table: + """The sizes of the pairwise differences of a family: one read of what some cut of it + holds, each row counted into the table by the cuts its interval covers.""" + fam = self.family(cuts) + held = self._held_by(self.existed(fam).columns("closed_at"), fam).astype(np.int64) + sizes = held.T @ (1 - held) + return Table(fam, tuple(tuple(int(x) for x in row) for row in sizes)) + + def _held_by(self, rows: Columns, fam: Sequence[Cut]) -> npt.NDArray[np.bool_]: + """For each row and each cut of the family, whether the cut holds the row: its position + at or under the cut's on the row's chain, and its closing stamp, if any, above it.""" + chain, seq = rows.ints("chain"), rows.ints("seq") + died = rows.ints("closed_at") + died = np.where(died < 0, np.iinfo(np.int64).max, died) + at = np.array([[c.at(k) for c in fam] for k in self.chains], dtype=np.int64).reshape( + len(self.chains), len(fam)) + # every row is of a chain of the evaluation, and the chains are in order + pos = at[np.searchsorted(np.array(self.chains, dtype=np.int64), chain)] + held: npt.NDArray[np.bool_] = (seq[:, None] <= pos) & (pos < died[:, None]) + return held + + +def read_only(path: Path) -> sqlite3.Connection: + """A connection that only reads a catalog's file, for an evaluation that writes nothing. It + takes no lock a writer waits on, and a writer's transaction does not hold it up: it reads + the log as the last commit left it. Opening the catalog itself (`VaultCatalog`) runs its + migration, a write transaction at every open, and may write the log's genesis.""" + return sqlite3.connect(f"{Path(path).resolve().as_uri()}?mode=ro", uri=True) + + +def _kind(v: object) -> str: + """What a value is, as a refusal names it.""" + match v: + case Cut(): + return "a cut" + case Versions(): + return "a set of versions" + case Delta(): + return "a signed difference" + case Events(): + return "the events between two cuts" + case Series(): + return "a series" + case Table(): + return "a table" + case bool(): + return "a truth value" + case int() | float(): + return "a number" + case None: + return "nothing" + return type(v).__name__ diff --git a/core/stores/landings.py b/core/stores/landings.py index d2946ebc..d1d16f94 100644 --- a/core/stores/landings.py +++ b/core/stores/landings.py @@ -37,7 +37,9 @@ secret that is not the one a chain was written with is refused as well, by the chain's `key_check`, so a chain is never keyed two ways. -Nothing reads the log yet: the reads below are the ones the later stages build on. +The reads below are by chain and by path. What a cut holds over a class, every head at once, is +the contents of the cut in `core/stores/cuts.py`, read through the closing stamp as a count or as +columns (dn-temporal-snapshot §4.4, stage SN-1b); the cut tool is their one reader yet. """ from __future__ import annotations @@ -600,20 +602,6 @@ def history_at(self, cls: str, path: str, c: Mapping[int, int] | int) -> list[La [r for r in rows if r.kind == "store"])) return [r for _, _, stores in sorted(parts, key=lambda p: (p[0], p[1])) for r in stores] - def heads_at(self, cls: str, c: Mapping[int, int] | int) -> list[Landing]: - """Every head of the class at the cut: the `store` rows with `seq ≤ c` whose closing - stamp is absent or above `c`, over the class's chains (§4.2), a hole returned as a hole - with its position and no name.""" - chains = self.chains(cls) - out: list[Landing] = [] - for chain in chains: - pos = cut_position(c, chain, chains) - out.extend(_landing(r) for r in self._conn.execute( - f"SELECT {_COLUMNS} FROM landings WHERE chain = ? AND seq <= ? " - "AND kind = 'store' AND (closed_at IS NULL OR closed_at > ?) ORDER BY seq", - [chain, pos, pos])) - return out - def rows(self, chain: int) -> Iterator[Landing]: """Every row of the chain, in order.""" for r in self._conn.execute( diff --git a/docs/LAWS.md b/docs/LAWS.md index c14bae63..f2f041b8 100644 --- a/docs/LAWS.md +++ b/docs/LAWS.md @@ -318,7 +318,15 @@ among them. The same file checks what no row states yet: `verify` failing on an row without its salt that keeps content (SNP-9, which enters with stage SN-2), what a purge empties, and the secret the keyed hash of a path needs. SNP-6 to SNP-10 stay design theorems of `Snapshot.lean`, cited from the note until the stage that relies on each is -built (dn-temporal-snapshot §12). Nothing reads the log yet. The family was opened on 2026-11-11. +built (dn-temporal-snapshot §12). SNP-11 to SNP-17 are the algebra of cuts (§4.4 of the note): a cut +as a value that stands for what the store held as of it, the lattice of its positions, and the sets +of rows its contents generate, proved in `formal/Palace/SnapshotAlgebra.lean` over the model +`formal/Palace/SnapshotAlgebra/Defs.lean` and stated in `formal/Spec/SnapshotAlgebra.lean`. Their +code is stage SN-1b's, the cut and its algebra over the landing log (`core/stores/cuts.py`), built +on 2026-11-13: `tests/property/test_cut_algebra.py` checks each law against a fold of the log kept +in the test, over the same random catalog writes, and `tests/unit/test_cut_tool.py` checks the +cut tool's handler, the log's one reader. The family was opened on 2026-11-11, the seven rows were +added on 2026-11-12, and their code on 2026-11-13. | law | statement | structure | anchor | label | falsifier | formal | |---|---|---|---|---|---|---| @@ -326,4 +334,11 @@ built (dn-temporal-snapshot §12). Nothing reads the log yet. The family was ope | SNP-2 | monotonicity: the read at an earlier cut is a prefix, chain by chain, of the read at a later one, an event read at a cut is read at every later cut, a cut of a cut is the meet of the two, and the head of the read at a cut is the meet of the cut and the head; so are the read under an erasure, the history of a key with no seal, and the filtered read (exact: finite lists; on the code, every read of a chain is a prefix of the read at its head, and the rows between a cut and the head are the rest; a path's history is a prefix chain by chain, and across two chains of one class, which only a change of class and a relabel make, it is ordered by a rule of the prefixes and need not be) | the prefix order on lists; cuts as a lattice | `core/stores/catalog.py::VaultCatalog.read_at`; `core/stores/catalog.py::VaultCatalog.read_between`; `core/stores/catalog.py::VaultCatalog.history_at` | Claim | `tests/property/test_landing_log.py::test_the_catalog_is_the_fold_of_the_log_and_the_laws_hold`, `tests/property/test_landing_log.py::test_a_history_over_two_chains_of_a_class_follows_a_rule_of_the_prefixes` | `Snapshot.lean::readAt_mono`, `Snapshot.lean::mem_readAt_of_le`, `Snapshot.lean::readAt_readAt`, `Snapshot.lean::head_readAt`, `Snapshot.lean::visible_mono`, `Snapshot.lean::landingsAt_mono`, `Snapshot.lean::Kept.mono` | | SNP-3 | composition: the read at `a` followed by the read between `a` and `b` is the read at `b`, and two adjacent reads-between compose, so a fold continued from a checkpoint over the delta is the fold of the prefix, for a store and for a chain of keyed writes; an event, or a pair of events, read at the later cut was read at the earlier one or lies in the delta, and a key the delta does not write has one state at both cuts (exact: finite lists; on the code, the catalog folded from every cut taken and continued over the rows since is the catalog) | a left fold over a concatenation | `core/stores/catalog.py::VaultCatalog.read_between`; `core/stores/catalog.py::VaultCatalog.read_at` | Claim | `tests/property/test_landing_log.py::test_the_catalog_is_the_fold_of_the_log_and_the_laws_hold` | `Snapshot.lean::readAt_append_readBetween`, `Snapshot.lean::readBetween_append`, `Snapshot.lean::foldAt_readBetween`, `Snapshot.lean::stateAt_eq_foldl`, `Snapshot.lean::mem_readAt_iff`, `Snapshot.lean::pair_readAt`, `Snapshot.lean::stateAt_eq_of_not_written` | | SNP-4 | idempotence: a cut at or past the head reads the store, so the read at the head is the store and every derived view at it is the present's: the generations read the store rewritten in place, a grant's snapshot and what an asker is shown are the grant's restriction of the store, what is visible is the store without the erased events, the history of a key with no seal is its every landing, and each seal serves at the head what the key holds live (exact: finite lists; on the code, a cut at or past a chain's head reads the whole chain, and the state of a path at the head is its catalog row; the genesis is the catalog, tombstoned paths included, and ends at a horizon) | the identity read: `as of` the head is no `as of` | `core/stores/catalog.py::VaultCatalog.head`; `core/stores/catalog.py::VaultCatalog.state_at`; `core/stores/landings.py::LandingLog.genesis` | Claim | `tests/property/test_landing_log.py::test_the_catalog_is_the_fold_of_the_log_and_the_laws_hold`, `tests/property/test_landing_log.py::test_the_genesis_is_the_catalog_and_ends_at_a_horizon` | `Snapshot.lean::readAt_head`, `Snapshot.lean::readAt_of_head_le`, `Snapshot.lean::view_head`, `Snapshot.lean::genRead_gens_length`, `Snapshot.lean::snapshot_head`, `Snapshot.lean::shown_head`, `Snapshot.lean::landingsAt_length`, `Snapshot.lean::visible_head`, `Snapshot.lean::servedAt_length`, `Snapshot.lean::servedNow_length`, `Snapshot.lean::historyAt_length` | -| SNP-5 | a derived view is a function of the prefixes: a reader is append invariant exactly when it reads only the prefixes, exactly when it is a derived view; for a chain of keyed writes the generational store read at a cut is the state recomputed from the prefix, which is the key's last write inside it, and at most one generation of a key is alive at a cut; the control: the store rewritten in place determines no read at a past cut (exact: finite lists; on the code, the catalog is the fold of the log after every write, each of the six writes killed or failed between the catalog's row and the log's leaving neither, in a batch too when its caller goes on while the batch's other writes commit, a batch carrying its log rows, a record that changes nothing and a store the UNCHANGED check skips appending nothing, the writer, its batched landing too, and the sync carrying each landing's version, and a change of identity landing after a `move`; at every position of every chain the seek on the key index, the closing-stamp read and the fold of the prefix give each path the same row, a purged version a hole in its place that keeps none of its content, and no path has two rows alive; a path none of whose versions keeps its content is named by no row; a relabel into a class that has rows changes no row) | three ways of holding a derived view, recomputed, journaled and kept by generation, that agree | `core/stores/catalog.py::VaultCatalog.record`; `core/stores/catalog.py::VaultCatalog.state_at`; `core/stores/catalog.py::VaultCatalog.heads_at`; `core/stores/catalog.py::VaultCatalog.history_at`; `core/stores/landings.py::LandingLog.store` | Claim | `tests/property/test_landing_log.py::test_the_catalog_is_the_fold_of_the_log_and_the_laws_hold`, `tests/property/test_landing_log.py::test_a_record_that_changes_nothing_appends_nothing`, `tests/property/test_landing_log.py::test_a_store_the_unchanged_check_skips_appends_nothing`, `tests/property/test_landing_log.py::test_the_sync_carries_the_version_each_landing_is`, `tests/property/test_landing_log.py::test_a_batched_landing_carries_the_version_each_landing_is`, `tests/property/test_landing_log.py::test_a_change_of_identity_moves_first_and_a_rekey_carries_the_version`, `tests/property/test_landing_log.py::test_each_write_killed_or_failed_between_its_two_rows_leaves_neither`, `tests/property/test_landing_log.py::test_a_deferred_batch_carries_its_log_rows`, `tests/property/test_landing_log.py::test_a_relabel_into_a_class_with_rows_changes_no_row_and_every_chain_verifies`, `tests/property/test_landing_log.py::test_a_purged_old_version_of_a_live_path_is_a_hole_by_the_three_reads`, `tests/property/test_landing_log.py::test_a_purge_of_every_version_of_a_deleted_note_leaves_no_row_that_names_it` | `Snapshot.lean::prefixOnly_view`, `Snapshot.lean::view_congr`, `Snapshot.lean::appendInvariant_iff_prefixOnly`, `Snapshot.lean::appendInvariant_iff_exists_view`, `Snapshot.lean::genRead_gens`, `Snapshot.lean::stateAt_eq_lastWrite`, `Snapshot.lean::length_filter_selects_le_one`; the control: `Snapshot.lean::Witness.stateOf_forgets` | +| SNP-5 | a derived view is a function of the prefixes: a reader is append invariant exactly when it reads only the prefixes, exactly when it is a derived view; for a chain of keyed writes the generational store read at a cut is the state recomputed from the prefix, which is the key's last write inside it, and at most one generation of a key is alive at a cut; the control: the store rewritten in place determines no read at a past cut (exact: finite lists; on the code, the catalog is the fold of the log after every write, each of the six writes killed or failed between the catalog's row and the log's leaving neither, in a batch too when its caller goes on while the batch's other writes commit, a batch carrying its log rows, a record that changes nothing and a store the UNCHANGED check skips appending nothing, the writer, its batched landing too, and the sync carrying each landing's version, and a change of identity landing after a `move`; at every position of every chain the seek on the key index, the closing-stamp read and the fold of the prefix give each path the same row, a purged version a hole in its place that keeps none of its content, and no path has two rows alive; a path none of whose versions keeps its content is named by no row; a relabel into a class that has rows changes no row) | three ways of holding a derived view, recomputed, journaled and kept by generation, that agree | `core/stores/catalog.py::VaultCatalog.record`; `core/stores/catalog.py::VaultCatalog.state_at`; `core/stores/cuts.py::Evaluation.held`; `core/stores/catalog.py::VaultCatalog.history_at`; `core/stores/landings.py::LandingLog.store` | Claim | `tests/property/test_landing_log.py::test_the_catalog_is_the_fold_of_the_log_and_the_laws_hold`, `tests/property/test_landing_log.py::test_a_record_that_changes_nothing_appends_nothing`, `tests/property/test_landing_log.py::test_a_store_the_unchanged_check_skips_appends_nothing`, `tests/property/test_landing_log.py::test_the_sync_carries_the_version_each_landing_is`, `tests/property/test_landing_log.py::test_a_batched_landing_carries_the_version_each_landing_is`, `tests/property/test_landing_log.py::test_a_change_of_identity_moves_first_and_a_rekey_carries_the_version`, `tests/property/test_landing_log.py::test_each_write_killed_or_failed_between_its_two_rows_leaves_neither`, `tests/property/test_landing_log.py::test_a_deferred_batch_carries_its_log_rows`, `tests/property/test_landing_log.py::test_a_relabel_into_a_class_with_rows_changes_no_row_and_every_chain_verifies`, `tests/property/test_landing_log.py::test_a_purged_old_version_of_a_live_path_is_a_hole_by_the_three_reads`, `tests/property/test_landing_log.py::test_a_purge_of_every_version_of_a_deleted_note_leaves_no_row_that_names_it` | `Snapshot.lean::prefixOnly_view`, `Snapshot.lean::view_congr`, `Snapshot.lean::appendInvariant_iff_prefixOnly`, `Snapshot.lean::appendInvariant_iff_exists_view`, `Snapshot.lean::genRead_gens`, `Snapshot.lean::stateAt_eq_lastWrite`, `Snapshot.lean::length_filter_selects_le_one`; the control: `Snapshot.lean::Witness.stateOf_forgets` | +| SNP-11 | the lattice of cuts: the cuts inside a store are closed under the pointwise meet and join, with the empty cut at the bottom and the head at the top, and no cut leaves as the store grows; the meet distributes over the join; the read at the join is, chain by chain, the later of the two reads and the read at the meet the earlier; the difference of two cuts on positions is the events between them, read from their meet or to their join, the symmetric difference is the events between their meet and their join, and the difference is a function of the two reads; the meet and the join of two cuts that are consistent and served are read as asked, the consistency by CLK-2 (exact: finite lists and ℕ; on the code, cuts as values satisfy the lattice laws as equalities under the pointwise order, with the empty cut at the bottom, the join and the meet of two cuts inside a random log are inside it, and the events between two cuts are a fold's rows in the range, read alike from their meet and to their join) | a bounded distributive lattice, the product of chains; cuts as down-sets (CLK-2) | `core/stores/cuts.py::Cut.join`; `core/stores/cuts.py::Cut.meet`; `core/stores/cuts.py::Cut.order`; `core/stores/cuts.py::Evaluation.between` | Claim | `tests/property/test_cut_algebra.py::test_cuts_are_a_lattice_on_positions`, `tests/property/test_cut_algebra.py::test_the_join_and_meet_are_cuts_and_the_events_between_read_from_either` | `SnapshotAlgebra.lean::resolvesIn_sup`, `SnapshotAlgebra.lean::resolvesIn_inf`, `SnapshotAlgebra.lean::readAt_sup`, `SnapshotAlgebra.lean::readAt_inf`, `SnapshotAlgebra.lean::readAt_bot`, `SnapshotAlgebra.lean::readAt_inf_sup`, `SnapshotAlgebra.lean::readBetween_inf_left`, `SnapshotAlgebra.lean::readBetween_sup_right`, `SnapshotAlgebra.lean::readBetween_inf_sup`, `SnapshotAlgebra.lean::bot_mem_cutsIn`, `SnapshotAlgebra.lean::head_mem_cutsIn`, `SnapshotAlgebra.lean::cutsIn_mono`, `SnapshotAlgebra.lean::readBetween_eq_combine` | +| SNP-12 | a row lives on an interval: a row of a chain kept by generation is alive from its position up to, and not at, its closing stamp, so a row alive at two cuts is alive at every cut between them; what the later of two cuts holds and the earlier does not is the rows stored after the earlier and alive at the later, what the earlier holds and the later does not the rows alive at the earlier and closed at or under the later, what both hold the rows stored at or under the earlier and not closed at or under the later; a row is alive at every cut of a family exactly when it is alive at the least and at the greatest, and at some position of a range exactly when it was stored by its end and not closed by its start; on the generations of a chain a row records the chain's event at its position, its stamp is the position of its key's next event, and a cut holds each key's state once; the control: a value has no interval (exact: ℕ and finite lists; on the code, at every position of every chain of a random log a cut's contents are a fold's, one row a path, the positions a row is held at are one run, and at every pair of positions the rows come, the rows gone and the rows both hold are the fold's set operations, read on the primary key and on `landings_closed`; what persisted through a family and what existed in it are the fold's) | half-open intervals of a linear order; a transversal of the keys | `core/stores/cuts.py::Evaluation.held`; `core/stores/cuts.py::_range`; `core/stores/cuts.py::_predicate` | Claim | `tests/property/test_cut_algebra.py::test_a_version_lives_on_an_interval_and_the_four_reads_are_its_statements`, `tests/property/test_cut_algebra.py::test_each_side_of_a_difference_walks_what_changed` | `SnapshotAlgebra.lean::Gen.aliveAt_iff`, `SnapshotAlgebra.lean::Gen.aliveAt_of_between`, `SnapshotAlgebra.lean::Gen.aliveAt_and_not`, `SnapshotAlgebra.lean::Gen.aliveAt_and_not'`, `SnapshotAlgebra.lean::Gen.aliveAt_and`, `SnapshotAlgebra.lean::Gen.forall_aliveAt_iff`, `SnapshotAlgebra.lean::Gen.exists_aliveAt_iff`, `SnapshotAlgebra.lean::getElem?_of_mem_gens`, `SnapshotAlgebra.lean::exists_next_of_mem_gens`, `SnapshotAlgebra.lean::proper_of_mem_gens`, `SnapshotAlgebra.lean::map_val_filter_key_contentAt`, `SnapshotAlgebra.lean::eq_of_key_eq_of_mem_contentAt`; the control: `SnapshotAlgebra.lean::Witness.value_not_contiguous` | +| SNP-13 | the signed difference of two cuts: its two sides, the rows the first holds and the second does not and the converse, are each one range read between two cuts in order; applied to what the first holds it gives what the second holds; differences compose through a cut between the two, a row that came and went on the way cancelling, and a row gone from a first cut to a third is gone in one of the two steps through any cut, from which their sizes obey the triangle inequality; a sum over the rows, a count among them, at the second cut is the sum at the first less the rows gone, with the rows come; the rows sort by key into removed, added and replaced: each row gone is removed or the first of a replaced pair and not both, and each row come is added or the second of one; every row of the difference belongs to a key the events between the two cuts name; the controls: a composition through a cut outside the two, and a key the events name that the difference does not hold (exact: finite lists; on the code, for random cuts in either order and neither under the other, the two sides are a fold's set differences, sorted into removed, added and replaced, disjoint and covering, one row a path a side; applied they give the second cut's contents; they compose through a cut between, and through one outside the composition is refused and is not the difference; every path of the difference is one the events between name; and the count walked along a family is the count read) | set differences of interval families, composed along a chain of cuts; a quasi-metric of their sizes | `core/stores/cuts.py::Evaluation.delta`; `core/stores/cuts.py::Delta.counts`; `core/stores/cuts.py::Delta.sorted`; `core/stores/cuts.py::Delta.then`; `core/stores/cuts.py::Evaluation.count_series` | Claim | `tests/property/test_cut_algebra.py::test_the_signed_difference_is_the_folds_and_composes_through_a_cut_between`, `tests/property/test_cut_algebra.py::test_a_composition_through_a_cut_outside_the_two_is_not_the_difference` | `SnapshotAlgebra.lean::Held.has_come`, `SnapshotAlgebra.lean::Held.has_gone`, `SnapshotAlgebra.lean::Held.has_cut_eq_apply`, `SnapshotAlgebra.lean::Held.has_come_trans`, `SnapshotAlgebra.lean::Held.has_gone_trans`, `SnapshotAlgebra.lean::Held.has_trans_of_transient`, `SnapshotAlgebra.lean::Held.has_gone_triangle`, `SnapshotAlgebra.lean::Held.sum_rows_delta`, `SnapshotAlgebra.lean::Held.length_rows_delta`, `SnapshotAlgebra.lean::mem_gone_iff`, `SnapshotAlgebra.lean::not_replacedOf_of_removedOf`, `SnapshotAlgebra.lean::mem_come_iff`, `SnapshotAlgebra.lean::key_mem_of_mem_delta`; the controls: `SnapshotAlgebra.lean::Witness.delta_through_outside`, `SnapshotAlgebra.lean::Witness.changed_not_delta` | +| SNP-14 | closure: a set of rows is an expression over the contents of cuts under union, intersection and difference, with no complement, and a set read is the set operation on the reads, so every set they give is an operand again; whether a row is in a set is a function of the row's position and its closing stamp alone; a set lies inside the contents of the cuts it names; a row's own test commutes with it; it is append invariant, and a derived view of the read at its cuts; what every cut of a family holds is what its least and its greatest cut both hold, and what some cut holds and in how many a row is alive are read off the same intervals; a function of two reads, a measure at each cut and a fold over a family are append invariant; the control: a complement grows with the store (exact: finite lists; on the code, random expressions of any depth are composed with no statement run and read by one as a fold's set operations, the sets the other operators give (the sides of a signed difference, what persisted, what existed, a difference applied) are operands of the set operators, a count is one statement that builds no row and the rows are one buffer a column, every set, difference and count at cuts inside the log is unchanged by later writes up to the holes a later purge leaves, an evaluation reads one head in every part, and the family operations are the fold's) | the generalized Boolean algebra the contents of cuts generate: relative complements and no top | `core/stores/cuts.py::Versions`; `core/stores/cuts.py::Columns`; `core/stores/cuts.py::Evaluation.apply`; `core/stores/cuts.py::Evaluation.combine`; `core/stores/cuts.py::Evaluation.map`; `core/stores/cuts.py::Evaluation.fold` | Claim | `tests/property/test_cut_algebra.py::test_a_set_of_any_depth_is_read_lazily_as_the_folds_set`, `tests/property/test_cut_algebra.py::test_a_count_builds_no_row_and_the_rows_are_one_buffer_a_column`, `tests/property/test_cut_algebra.py::test_every_result_at_cuts_inside_the_log_is_unchanged_by_later_writes`, `tests/property/test_cut_algebra.py::test_an_evaluation_reads_one_head_in_every_part_and_names_it`, `tests/unit/test_cut_tool.py::test_a_call_reads_the_heads_a_horizon_once_and_one_statement_for_its_result` | `SnapshotAlgebra.lean::Held.mem_rows_union`, `SnapshotAlgebra.lean::Held.mem_rows_inter`, `SnapshotAlgebra.lean::Held.mem_rows_diff`, `SnapshotAlgebra.lean::Held.has_symm`, `SnapshotAlgebra.lean::Held.has_inter_union`, `SnapshotAlgebra.lean::Held.has_diff_diff`, `SnapshotAlgebra.lean::Held.has_eq_of_interval`, `SnapshotAlgebra.lean::Held.exists_atom_of_has`, `SnapshotAlgebra.lean::Held.rows_filter`, `SnapshotAlgebra.lean::Held.has_kept`, `SnapshotAlgebra.lean::Held.has_all`, `SnapshotAlgebra.lean::Held.has_any`, `SnapshotAlgebra.lean::Held.has_all_eq_kept`, `SnapshotAlgebra.lean::countIn_pos_iff`, `SnapshotAlgebra.lean::countIn_eq_length_iff`, `SnapshotAlgebra.lean::Held.rows_gens_append`, `SnapshotAlgebra.lean::Held.rows_gens_take`, `SnapshotAlgebra.lean::combine_grow`, `SnapshotAlgebra.lean::series_grow`, `SnapshotAlgebra.lean::foldOver_grow`; the control: `SnapshotAlgebra.lean::Witness.complement_grows` | +| SNP-15 | contents against positions: what either of two cuts holds is what their join holds with the rows closed between their meet and their join, and what both hold is what their meet and their join both hold; for a row that is never closed the contents of the join are the union of the contents and the contents of the meet their intersection; the control: one key written twice, where the union holds two rows and the join one (exact: finite lists; on the code, in classes whose paths land once the contents of the join of two cuts are the union of their contents and those of the meet their intersection, on any log the union is the join's contents with the rows gone between the meet and the join, and after one edit the union holds both versions and the join one, the control; the tool gives the two meanings two names and two types) | a lattice homomorphism from cuts to sets of rows, exactly on the rows never closed | `core/stores/cuts.py::Versions.__or__`; `core/stores/cuts.py::Versions.__and__`; `core/stores/cuts.py::Cut.join`; `core/stores/cuts.py::Cut.meet` | Claim | `tests/property/test_cut_algebra.py::test_on_a_class_with_no_closes_the_join_holds_the_union`, `tests/property/test_cut_algebra.py::test_the_union_is_the_join_with_the_rows_closed_between`, `tests/property/test_cut_algebra.py::test_after_one_edit_the_union_holds_both_versions_and_the_join_one`, `tests/unit/test_cut_tool.py::test_the_two_meanings_of_union_differ_by_name_and_type` | `SnapshotAlgebra.lean::Gen.aliveAt_and_eq_inf_sup`, `SnapshotAlgebra.lean::Gen.aliveAt_or_eq_sup`, `SnapshotAlgebra.lean::Gen.aliveAt_sup_of_open`, `SnapshotAlgebra.lean::Gen.aliveAt_inf_of_open`, `SnapshotAlgebra.lean::Held.has_union_cut`, `SnapshotAlgebra.lean::Held.has_inter_cut`; the control: `SnapshotAlgebra.lean::Witness.union_ne_join` | +| SNP-16 | the grant commutes with every set: read on the chains a grant shows, a set is the grant's restriction of the set read on the whole store; under a grant it reads only the chains the grant names and its cuts' positions on them, so two stores that agree there give one answer; a narrower grant's set is the restriction of a wider grant's; it names no chain the grant does not name; and the events between two cuts commute with a grant of whole chains; the control: a row's test applied before the generations are computed moves the positions (exact: finite lists; on the code, every statement of one class's sets and differences names only its chains, and they are unchanged by writes to another class and by positions named on another class's chains; the tool refuses a chain its grant does not read in the words it uses for one that does not exist) | noninterference: restriction as a homomorphism that acts chain by chain | `core/stores/cuts.py::Evaluation`; `core/stores/cuts.py::Evaluation.cut`; `core/stores/cuts.py::Evaluation.named` | Claim | `tests/property/test_cut_algebra.py::test_one_class_reads_only_its_chains`, `tests/property/test_cut_algebra.py::test_a_cut_past_the_head_or_of_an_unread_chain_is_refused`, `tests/unit/test_cut_tool.py::test_a_chain_the_grant_does_not_read_is_refused_as_one_that_does_not_exist` | `SnapshotAlgebra.lean::restrict_narrow`, `SnapshotAlgebra.lean::Held.across_restrict`, `SnapshotAlgebra.lean::Held.across_congr`, `SnapshotAlgebra.lean::Held.across_narrow`, `SnapshotAlgebra.lean::Held.across_of_not`, `SnapshotAlgebra.lean::restrict_readBetween`; the control: `SnapshotAlgebra.lean::Witness.filter_before_gens` | +| SNP-17 | erasure and retire on sets: the closing stamps are a function of the keys alone, so a hole that keeps its key moves no position and no stamp; no row of a chain with holes carries an erased value, and an erasure takes its own rows out of every set and changes no other; a retire is a removal in the signed difference that spans it: the version's row is gone and no row of its key that came carries a version (exact: finite lists; on the code, after a purge no set and no difference at any cut holds a row of the purged digest, every other row is the row it was, and every count falls by the rows purged as its holes rise by them; a retired version is held by every cut from its landing to the retire and removed in every difference from such a cut to one at the retire or after it while the path stays retired) | erasure dominance carried from reads to sets of rows | `core/stores/cuts.py::VERSION`; `core/stores/cuts.py::Versions.tally`; `core/stores/cuts.py::Delta.sorted` | Claim | `tests/property/test_cut_algebra.py::test_a_purge_takes_its_rows_out_of_every_set_and_a_retire_is_a_removal`, `tests/unit/test_cut_tool.py::test_the_note_says_the_head_the_horizon_the_holes_and_what_waits_for_sn4` | `SnapshotAlgebra.lean::gens_map`, `SnapshotAlgebra.lean::removed_of_retire`, `SnapshotAlgebra.lean::not_erased_of_mem_gens_holes`, `SnapshotAlgebra.lean::Held.rows_gens_holes` | diff --git a/docs/design-notes/dn-temporal-snapshot.md b/docs/design-notes/dn-temporal-snapshot.md index dc1dac9d..fa02f7b5 100644 --- a/docs/design-notes/dn-temporal-snapshot.md +++ b/docs/design-notes/dn-temporal-snapshot.md @@ -3,9 +3,9 @@ type: design-note id: dn-temporal-snapshot track: query-language status: draft # provenance description, never a gate; the merge is ratification -implementation: partial # SN-1 built (the landing log, core/stores/landings.py; SNP-1 to SNP-5 in docs/LAWS.md); SN-2 to SN-8 design +implementation: partial # SN-1 built (the landing log, core/stores/landings.py; SNP-1 to SNP-5 in docs/LAWS.md); SN-1b built (the cut and its algebra, core/stores/cuts.py, and the cut tool, agents/ambassador/cut_tool.py; SNP-11 to SNP-17 in docs/LAWS.md); SN-2 to SN-8 design created: 2026-11-10 -updated: 2026-11-11 +updated: 2026-11-14 links: - papers/2026-11-10-temporal-snapshot/paper.tex # the article: the same theorems, with proof sketches and the references - docs/design-notes/global-event-clock.md # N, its generators, the cut as a certified frontier (§2.4) @@ -18,9 +18,14 @@ links: - docs/design-notes/dn-graph-dynamics.md # GD-4: velocity over a window of cuts, which waits on the snapshot - docs/design-notes/dn-mathematical-foundations.md # the ladder; design theorems before code - formal/Palace/Snapshot.lean # the theorems (Snapshot/Defs.lean the model; PalaceTest/Snapshot.lean the attacks) + - formal/Palace/SnapshotAlgebra.lean # the algebra of cuts, SNP-11 to SNP-17 (SnapshotAlgebra/Defs.lean the model; PalaceTest/SnapshotAlgebra.lean the attacks) - core/stores/landings.py # SN-1 as built: the landing log, in the catalog's file - docs/experiments/landing-log-2026-11-11.md # SN-1 measured on a copy of the corpus instance's catalog - papers/2026-11-11-landing-log/paper.tex # the article of SN-1 + - core/stores/cuts.py # SN-1b as built: the cut, the contents of a cut and the algebra + - agents/ambassador/cut_tool.py # SN-1b as built: the cut tool's handler (§7.5) + - docs/experiments/cut-algebra-2026-11-13.md # SN-1b measured on a copy of the corpus instance's catalog + - papers/2026-11-13-cut-algebra/paper.tex # the article of the algebra of cuts and of SN-1b supersedes: null superseded_by: null warrant: null @@ -60,6 +65,26 @@ warrant: null > the tombstones of a path none of whose versions keeps its content (§6.1); the first open writes > the genesis for a reader too, which is open for the owner (§12, SN-1); and every head costs > what building the answer costs, which meets SNF-6 (§4.2, §11). +> +> On 2026-11-12 and 2026-11-13 the note was amended for the cut as a lazy object and its algebra +> (§4.4, with §5.7, §6.5, §7.4 to §7.6, SNP-11 to SNP-17 in §10 and the stage SN-1b in §12). The +> owner decided the shape of the read of every head at a cut on 2026-11-11 and 2026-11-12, and §13 +> records those decisions as decided (D15 to D23) and, apart from them, what this amendment +> proposes, each as a proposal with its recommendation (D24 to D36). The amendment was written +> before its code: `core/stores/landings.py` and the code it cites were read at `8d4dff3d`, the +> seven laws are proved in `formal/Palace/SnapshotAlgebra.lean`, and the figures it adds to §11 are +> of probes on synthetic fixtures. One rule the owner gave for every change, that a new form takes +> the place of the old with nothing kept beside it, is applied to the stages of §12, and each +> revision it makes is listed in §13 (D29). Stage SN-1b was built on 2026-11-13, the second part of +> the same pull request: `core/stores/cuts.py`, the cut tool, their property tests and their +> figures on a copy of the corpus instance's catalog (§11, +> `docs/experiments/cut-algebra-2026-11-13.md`). Where the build departed from §4.4 or §7.5, §12 +> says so under SN-1b. The review of that build corrected four claims of the amendment, each +> marked where it stands: a cut can split a change of class, which no reference of §3.5 joins +> (§3.5, §7.5); through the stamps of the rows it keeps, a grant's test of rows inside a chain +> shows where rows it hides lie (§6.5); three of its citations claimed more than their theorems +> state (§4.4, §10); and the tool reads the heads, and a chain's horizon, before its outermost +> operator (§4.4, §7.5). ## 1. Purpose and scope @@ -78,6 +103,12 @@ checkpoint is a cut and whose input is the delta between two cuts; the velocity over a window of cuts (dn-graph-dynamics GD-4, which waits on the snapshot); and the utility field as of a cut (dn-utility-field, open question 1). +Since 2026-11-12 the requirement has a second half. A cut is not only an index a sentence is +read at: it is a value that stands for the palace's graph at its positions, evaluated lazily; +operators take one cut with another, a difference, a union and an intersection among them, and +operations apply to one cut or to a family of cuts (the owner's decisions, §13 D15 to D17). §4.4 +is the design of that value and of its algebra. + ### 1.2 Decisions 1. **A cut is one position per chain, about a dozen positions for an instance, not one per @@ -123,8 +154,20 @@ as of a cut (dn-utility-field, open question 1). the horizon is not served. `[THEOREM: SNP-10]` 9. **Retention is counted in positions and drops derived rows before ledgers (§9).** `[INFERENCE, falsifier SNF-9]` -10. **The build is eight stages, each a pull request with its tests and its rollback; the first - is the landing log (§12).** `[INFERENCE, falsifier SNF-11]` +10. **The build is nine stages, each a pull request with its tests; the first is the landing log + (§12).** What a stage changes it changes outright, with no switch back to the old form, so a + stage's rollback is reverting its pull request (the owner's rule of 2026-11-11 and 2026-11-12 + for every change, D20; its application to the stages is D29). `[INFERENCE, falsifier SNF-11]` +11. **A cut is a lazy value with an algebra (§4.4).** It is addressed by its frontier, and holding + it reads no store. On positions the cuts are a lattice, and the meet and the join of two cuts + are cuts. On contents a cut holds the versions alive at it, each a row + of the log that lives on one interval of positions, so a union, an intersection, a + difference and what a whole family of cuts holds are predicates on a row's position and its + closing stamp, combined without a read and run as one statement. The signed difference of + two cuts is two range reads whose cost grows with what changed between them. Every operator + commutes with the grant and holds no erased row. `[THEOREM: SNP-11 to SNP-17; the owner's + decisions of 2026-11-11 and 2026-11-12 for the object and its operators, D15 to D23; this + note's proposals for the rest, D24 to D36]` ### 1.3 Out of scope @@ -168,13 +211,29 @@ to SNP-10 are design theorems: no code relies on them yet, so they have no row a §12 says when each enters. Some of what §6 and §7 require holds by the construction of the model and not by a theorem about the code: §10 says which, law by law. +Proved for the algebra of cuts, in `formal/Palace/SnapshotAlgebra.lean` over +`formal/Palace/SnapshotAlgebra/Defs.lean`: SNP-11 to SNP-17 as §10 states them, 110 theorems, six +of them the controls; attacked in `formal/PalaceTest/SnapshotAlgebra.lean` (seeds 529 to 566: +twenty-one attacks, twenty surviving all 500 instances and one, whose guard holds in 295 of +them, surviving those, and seventeen negative controls, each refuted). The seven laws are what +stage SN-1b builds on, so they entered the ledger with the design: seven rows of family XVI, +and the 80 declarations §10 lists for them restated in `formal/Spec/SnapshotAlgebra.lean` and +judged by the comparator. SN-1b's code and tests landed with them: each row names its anchor in +`core/stores/cuts.py` and its property tests as its falsifier (§12). + Measured, on synthetic fixtures (§11): the landing log's size and the cost of its reads; what a kept version costs in the lexical index; what a purge leaves behind today; that the causal store depends on the order of two jobs; that the events of a transcript's prefix are not always the prefix of its events, and what re-deriving a session costs; what `as of` accepts and when; that a position taken from a store's row numbering is given again after a delete. And, at SN-1, the log as built, on a copy of the corpus instance's catalog: its migration, its bytes, its writes and its -reads (§11, as built). +reads (§11, as built). And for the algebra of cuts, before its code and on synthetic fixtures +again: the interval reads against a fold of the log, their plans and what they cost, every head +read as columns, and where updating a quantity of a graph over the difference of two cuts costs +less than computing it again (§11, the algebra). And at SN-1b, the algebra as built, on a copy of +the corpus instance's catalog: every head counted and as columns against SN-1's rows, the signed +difference over spans from one position to every position, and a family of ten cuts (§11, as +built at SN-1b). Open, stated where it bites: the attestation ledger's own content hashes under an erasure (decision D9); the cadence of recorded cuts (§3.3); a repository history that is not one line @@ -539,19 +598,20 @@ tombstone stamp on each row, and `read_at(g)` as exactly this predicate ### 3.3 The cut and its record -A cut is a position for every chain of §3.1: for an instance, about a dozen integers. -`[DERIVED]` The read at a cut is the prefix of every chain (`readAt`), and everything else in this -note is a function of that. A cut is worth recording when it is consistent (§3.5) and certified -in the event clock's sense. GC-N3 names three certificates +A cut is a position for every chain of §3.1: for an instance, about a dozen integers. `[DERIVED]` +The read at a cut is the prefix of every chain (`readAt`), and everything else in this note is a +function of that. The positions are the whole of a cut: it is a value, with an order, a meet and a +join, and it reads nothing until an operator needs it (§4.4). A cut is worth recording when it is +consistent (§3.5) and certified in the event clock's sense. GC-N3 names three certificates (`docs/design-notes/global-event-clock.md:175-186`): the commit, which certifies the strata the repository backs; trough quiescence, an empty queue with no queued and no running job -(`core/temporal/spine.py:197-206`), which certifies that no causality of the core is in flight; -and the empty handoff, which certifies that nothing is in flight between the edge and the core. -A cut across strata composes the three, and the spine refuses a cut whose certificate it cannot -source (`spine.py:275-281`, `:1064-1084`). As the spine sources it, the handoff certificate is -the emptiness of the two directories of the one sensing handoff it is given (`spine.py:218`, -`:283-286`, `:1090-1103`); §1.3 says what that leaves unlooked at, and why a cut does not need -it. `[ESTABLISHED]` +(`core/temporal/spine.py:197-206`), which certifies that no causality of the core is in flight; and +the empty handoff, which certifies that nothing is in flight between the edge and the core. A cut +across strata composes the three, and the spine refuses a cut whose certificate it cannot source +(`spine.py:275-281`, `:1064-1084`). As the spine sources it, the handoff certificate is the +emptiness of the two directories of the one sensing handoff it is given (`spine.py:218`, `:283-286`, +`:1090-1103`); §1.3 says what that leaves unlooked at, and why a cut does not need it. +`[ESTABLISHED]` So a cut is recorded at a trough and at no other moment. Two things ask for one: the trough itself, when the queue and the handoff are empty and the frontier moved since the last record; @@ -692,6 +752,20 @@ A causal edge reads from the turn that witnessed it and, when it ends at a commi commit (`causal_edges.py:58-60`, `integrator.py:134-137`); it is recomputed at a cut (§5.5), so it is a filter of a read and no row of a chain. +**A change of class, which neither list holds (added 2026-11-13).** A `record` that gives a path +another class writes two rows in one transaction: a `leave` that closes the path in the chain of +its old class, then its `store` in a chain of the new one (`core/stores/landings.py:446-457`, +§3.2). The `store` follows the `leave`, and no reference above says so; the review of SN-1b found +the pair missing from the list. So a frontier can split it. One that holds the `store` and not the +`leave` holds the path in both chains, and one that holds the `leave` and not the `store` holds +it in neither: a state the catalog never had, either way. Were the `store` a resolved reference +of the `leave`, the first frontier would be inconsistent, and the resolver would lower the new +chain under the `store`; the second would stay consistent, as a message sent and not yet received +leaves a cut of a distributed computation consistent, and would still hold the path in no class. +Which the pair becomes, and where its bound is recorded, is open (Open questions); until it is +decided, such a frontier is read as asked and the tool says so (§7.5). `[ESTABLISHED: read off +the writer; DERIVED for the two frontiers, checked by tests/property/test_cut_algebra.py]` + A cut is **consistent** when every source of an event inside it is inside it (`Consistent`): no fact whose sources lie after the cut, every cross-chain reference closed. `[THEOREM: SNP-8]` @@ -935,8 +1009,44 @@ size of the answer and not the part of the log walked is the cost, and the read alone passes a tenth of a second near 27,000 heads: a chain of 30,002 events takes 0.11 s. That meets SNF-6's first condition. Kept heads at a recorded cut shorten the walk and leave the building, so they do not answer it. Before SN-4 builds the universe's nodes on this read, either -the threshold moves or the read changes so that it builds less than a row a head, and which is -open (SN-c). `[MEASURED §11; the decision open]` +the threshold moves or the read changes so that it builds less than a row a head, and which +was open (SN-c). `[MEASURED §11]` + +The shape half of that question is decided, and the read changes. The owner decided on +2026-11-11 and 2026-11-12 that a cut is a lazy object, read only when an operation needs it +(§13, D15), so the read of every head is no list of rows: it is the contents of a cut (§4.4), +named by a predicate and read as a count, as columns or as a difference from another cut. The +contents replace `heads_at`, and no eager list is kept beside them (D20, D29). What that buys, +on a synthetic chain of 150,002 rows with 100,000 heads: the count walks the prefix and builds +nothing, 19 ms, 0.13 µs an event; three columns of every head, the position, the path's key and +the digest, come back as three buffers in 49 ms, 0.49 µs a head, against 381 ms for a row a +head. And on one of 200,002 rows with 100,000 heads, a difference from another cut costs what +changed between the two: over a thousand positions 0.6 ms for the rows come and 2.0 ms for the +rows gone, against 150 to 170 ms for two reads and a set difference. `[MEASURED §11, at a load +average that was not recorded; the corpus figures below, which carry theirs, supersede them]` + +The size half is not decided: the owner did not rule on the threshold. This note keeps SNF-6's +bar, a tenth of a second, as a recommendation (§13, D30), and keeps the rule a rule by size. The +size is what the bar and the measured cost give, so the figure of 250,000 events stands only +until SN-1b measures the contents on the corpus's catalog. By arithmetic from the fixture's +0.49 µs a head, three columns of every head pass the bar near 200,000 heads, and the count +passes it near 750,000 events. So a chain of 250,000 events all of which are heads would read +its columns in 0.12 s, a fifth over the bar, and the corpus chain, with 400,274 heads, is +expected over the bar for its columns and under it for its count. A reader that needs every +head of such a chain reads them once and then walks the differences, which is the journal of +§5.1 under another name, or reads a kept head; which of the two SN-4 takes is SN-c's size half, +parked as before. `[DERIVED from the fixture, whose load average was not recorded; INFERENCE for +the bar, falsifier SNF-6]` + +As built at SN-1b, on a copy of the corpus instance's catalog (§11): every head of the corpus +chain, 400,274, counted in 66 ms, 0.17 µs an event walked, and read as three columns in 219 to +224 ms, against 1.74 to 1.79 s for SN-1's rows. Beyond the walk a head costs 0.39 µs as three +columns and 4.2 µs as a row. So the count passes the bar up to about 600,000 events, and three +columns pass it near 180,000 heads on a chain whose events are its heads, and fewer where many +rows are closed, since the walk is over events. That is the size the rule by size takes from +here, in place of the 250,000 events the fixture gave (D30): a chain whose every head, read as +columns, passes the bar is over it, and the corpus chain is. The owner has not ruled on the bar, +so the size stays a recommendation. `[MEASURED §11; INFERENCE for the bar, falsifier SNF-6]` ### 4.3 What the reads cost in bytes @@ -949,6 +1059,233 @@ integer, the row's key and a 32-byte hash. A recorded cut is about 2.7 kilobytes (§3.3). None of it is content: the log holds paths, digests and titles, which the catalog holds already. +### 4.4 The cut as a lazy object, and its algebra + +Added on 2026-11-12. The owner decided on 2026-11-11 and 2026-11-12 what the object is (§13, +D15 to D23): the palace's graph at a cut, evaluated lazily; operators that take one cut with +another, and operations of any kind on one cut or on a set of cuts; the two meanings of a union +and an intersection, of positions and of contents, both kept; and each node held at a cut in the +version alive there. This section is the design that carries those decisions out over +the landing log. What it adds to them is this note's proposal, recorded as such in §13 (D24 to +D36). Its laws are SNP-11 to SNP-17 (§10), proved in `formal/Palace/SnapshotAlgebra.lean`; stage +SN-1b builds it (§12); what a cut's graph is beyond its versions, the edges and the mathematics +on them, is §5.7 and stage SN-4. + +**The objects.** Each is a value that names something and reads nothing. The table says what +each holds before anything is read and what reading it costs; the costs are of the probes of +§11, on synthetic chains, at a load average that was not recorded, and SN-1b's figures on the +corpus's catalog, which carry theirs, are in §11. `[MEASURED §11 for the costs]` + +| object | what it is | what it holds, unread | what reading it costs | +|---|---|---|---| +| a cut | a frontier: one position a chain (§3.3). Before SN-2 the chains it names are the landing chains; SN-2 adds the others to the same value | the positions, a few integers. It is immutable and hashable, and equal cuts are one key | nothing of what it holds: its contents and its events are read, not the cut. A position named under a chain's head is checked against the chain's horizon, a walk of the chain made once an evaluation (§7.5) | +| the events between two cuts | the difference on positions: on each chain, the events after the first cut's position and up to the second's (`readBetween`) | the two cuts | a range of the log's primary key: 0.6 ms a thousand events | +| the contents of a cut, under a grant | the versions the cut holds on the chains the grant names: the `store` rows alive at it that no purge emptied | the cut, the chains, and a predicate on a row's position and its closing stamp | a count walks the prefix and builds nothing, 0.13 µs an event; the rows come back as columns, 0.49 µs a head for three columns | +| a set of versions | the contents of a cut, or the union, the intersection or the difference of two sets | an expression: the cuts it names and how they are combined | one statement, whose predicate is the expression | +| the signed difference of two cuts | two sets: the versions the first holds and the second does not, and the converse. Read, they sort by path into removed, added and replaced | the two cuts | two range reads, of the events between and of the rows closed between: 0.6 ms and 2.0 ms for a thousand of each | +| a family of cuts | a list of cuts | the cuts | by operation, below | +| a number, a series, a table | a count, a measure at each cut of a family, the sizes of the pairwise differences | nothing: it is a result | it is no operand of a set operator, and its type says so | + +A version is one landing: a `store` row of the log, named by its chain and its position. That +is this note's reading of the owner's decision that an edit gives a node a new version while it +stays the same node (D23), and it is proposed as such (D31). A path that returns to +bytes it held before lands a new version, as it appends a new row to the log and, in the place +that keeps version chains, a new version there (§2.3, item 2). The digest, the title, the +identity and the version number are columns of the version. What the version is made of is the +node design's, a separate track, and nothing here assumes its shape (§5.7). + +**The operators and their types.** A cut, a set and a signed difference that an operator returns +are operands of the next, so those results compose. `[THEOREM: SNP-11, SNP-13, SNP-14 for the +closure]` The other results are answers and no operand: the events between two cuts are counted +or listed, and a truth value, an order, a number, a series, a table and rows are typed as what +they are, and no operator takes one. + +| operator | takes | returns | +|---|---|---| +| the order, equality | two cuts | a truth value; with `order`, which of equal, before, after and unordered | +| the join and the meet | two cuts | a cut | +| the bottom; the head | nothing; the store | a cut | +| between | two cuts | the events between them | +| the contents | a cut | a set of versions | +| union, intersection, difference, symmetric difference | two sets | a set | +| the signed difference | two cuts | a pair of sets, the rows gone and the rows come | +| a difference applied; two differences composed | a set and a difference; two differences through a cut between | a set; a difference | +| what every cut holds; what some cut holds | a family | a set | +| the count | a set | a number | +| in how many | a set and a family | the rows of the set, each with the number of the family's cuts that hold it | +| a measure at each cut; the sizes of the pairwise differences | a family | a series; a table | +| the rows | a set | columns | + +**The interface every operator is built on.** Four forms (proposed, D25): *apply*, a function of +one cut's read (`view`); *combine*, a function of two cuts' reads (`combine`); *map*, a function +at each cut of a family (`series`); and *fold*, an accumulation over the cuts of a family +(`foldOver`). Each is a derived view of the prefixes, so each is append invariant on cuts inside +the store, and the same on every store that verifies a certificate of its cuts +(`appendInvariant_view`, `combine_grow`, `series_grow`, `foldOver_grow`, with `Verifies.view_eq`). +`[THEOREM: SNP-1, SNP-9, SNP-14]` The operations this section names are instances and not the +list: the events between two cuts are a combine, the second read past the length of the first +(`readBetween_eq_combine`); the contents of a cut are an apply, since a set whose cuts lie at or +under a cut reads the prefix at that cut and nothing after it (`Held.rows_gens_take`); the +velocity of a value over a window (§7.4) is a combine; a measure over a family is a map. An +operation that is none of the named ones is written against the same four, which is how any +operation on one cut or on a set of cuts is admitted (D17). + +**On positions: the lattice.** `[THEOREM: SNP-11, on CLK-2]` + +- *The statement.* The cuts inside a store are closed under the pointwise meet and join, with + the empty cut at the bottom and the head at the top (`cutsIn`, `bot_mem_cutsIn`, + `head_mem_cutsIn`), and the meet distributes over the join (`readAt_inf_sup`). The head is the + one cut that moves: it rises as the store grows and no cut leaves (`cutsIn_mono`). The read at + the join is, chain by chain, the later of the two reads, and the read at the meet the earlier + (`readAt_sup`, `readAt_inf`): the join is everything that had happened by either cut and the + meet everything that had happened by both, as sets of events (CLK-2's `frontierCut_sup` and + `frontierCut_inf`). The difference is the events the second cut holds and the first does not: + the read between the two, which is the read between their meet and the second, or between the + first and their join (`readBetween_inf_left`, `readBetween_sup_right`); the symmetric + difference is the read between their meet and their join, on each chain one of the two + differences (`readBetween_inf_sup`). +- *Closure.* The result of a meet or a join is a cut, so it is an operand of every operator. It + can also be read: the cuts every position of which its chain serves are closed under both, + whatever the chains serve (`servedCuts`), the consistent cuts are closed under both by CLK-2 + (`Consistent.inf`, `Consistent.sup`), and so the meet and the join of two cuts read as asked + are read as asked (`resolvesIn_sup`, `resolvesIn_inf`). The difference of two cuts is no cut: + it is a range of events, held as the pair. +- *On the log.* Nothing is run: a meet and a join are a minimum and a maximum a chain. The + events between are the rows with `a < seq ≤ b` on each chain (§4.1). +- *Against §7.4.* `changed between` is the identity projection of this difference, the + identities the events between two cuts name, and it stays as that. + +**On contents: a version lives on an interval.** `[THEOREM: SNP-12]` A row of the log is alive +from its position up to, and not at, its closing stamp, the position of its path's next event +(`Gen.aliveAt_iff`, `exists_next_of_mem_gens`). So a row alive at two cuts is alive at every cut +between them (`Gen.aliveAt_of_between`), a cut holds one row a path at most +(`eq_of_key_eq_of_mem_contentAt`), and what a cut holds is each path's state at the cut, once +(`map_val_filter_key_contentAt`): the read of every head is the read of every path. Contiguity is +a law of rows and not of values. A path that returns to a digest it held holds it at two cuts and +not between them (`Witness.value_not_contiguous`), which is why §5.2 could put no stamp on a +version's derived rows, and why the element here is the landing and not the digest. The four +reads the intervals give, on one chain with `a ≤ b`, each checked against a fold of the log over +900 random catalogs (§11): + +| what | over the intervals | the statement it runs as | what it walks | +|---|---|---|---| +| what `b` holds and `a` does not | stored after `a`, alive at `b` (`Gen.aliveAt_and_not`) | `seq > :a AND seq <= :b AND (closed_at IS NULL OR closed_at > :b)` | the events between, on the primary key | +| what `a` holds and `b` does not | alive at `a`, closed at or under `b` (`Gen.aliveAt_and_not'`) | `seq <= :a AND closed_at > :a AND closed_at <= :b` | the rows closed between, on `landings_closed` | +| what both hold | stored at or under `a`, not closed at or under `b` (`Gen.aliveAt_and`) | `seq <= :a AND (closed_at IS NULL OR closed_at > :b)` | the prefix at `a` | +| alive at every cut of a set | alive at its least and at its greatest position (`Gen.forall_aliveAt_iff`) | the row above, with the least and the greatest | the prefix at the least | + +Each statement carries the chain and the version's own test, `kind = 'store' AND salt IS NOT +NULL`, which no cut enters. The first two cost what changed and not what is held. The last two +do not: what two cuts both hold is as large as the state, so reading it walks the prefix as the +contents of a cut do. What the interval gives there is that it is one statement of two +positions whatever the size of the family, and that a reader which holds the count at `a` +needs no walk for its count: what `a` holds is what both hold with the rows gone, so the +count is that count less the count of the rows gone, one range read. `[MEASURED §11 for the +plans and the costs; DERIVED for the count]` + +**The sets a cut's contents generate.** `[THEOREM: SNP-14]` A set of versions is an expression: +the contents of a cut, or the union, the intersection or the difference of two sets (`Held`). + +- *The statement.* A set read is the set operation on the reads (`Held.mem_rows_union`, + `Held.mem_rows_inter`, `Held.mem_rows_diff`), with the laws of sets: both operations commute, + associate and absorb, each distributes over the other, and the symmetric difference is the + union less the intersection (`Held.has_inter_union`, `Held.has_diff_diff`, `Held.has_symm`). +- *Combining reads nothing.* Whether a row is in a set is a function of the row's position and + its closing stamp alone (`Held.has_eq_of_interval`). So an expression of any depth is one + predicate on two columns, and it runs as one statement. +- *There is no complement.* A set lies inside the contents of the cuts it names + (`Held.exists_atom_of_has`). That is what makes every set append invariant + (`Held.rows_gens_append`), free of holes and inside the grant (§6.5). The control is the + complement, the rows a cut does not hold, which grows with every landing + (`Witness.complement_grows`); it is not offered (D35). +- *A row's own test commutes with every set* (`Held.rows_filter`): the version's test, a + class, an event filter of a grant. A test applied to the chain before its closing stamps are + computed does not: it moves the positions (`Witness.filter_before_gens`). +- *Cost.* A count is one statement that returns a number. The rows are read as columns, one + buffer a column, and a column no operator asks for is not read (D24). + +**The signed difference.** `[THEOREM: SNP-13]` The difference of two cuts on contents is signed: +the rows gone, which the first holds and the second does not, and the rows come (`Held.gone`, +`Held.come`). Exchanging the cuts exchanges the sides (`Held.gone_swap`). + +- *Applied.* What the second cut holds is what the first holds, less the rows gone, with the + rows come (`Held.has_cut_eq_apply`): a reader that holds one cut's contents reaches another's + at the cost of what changed. +- *Composed.* Through a cut `b` that lies between `a` and `c` on every chain, in either + direction, the rows come from `a` to `c` are those come from `a` to `b` that did not go from + `b` to `c`, with those come from `b` to `c`, and the rows gone likewise (`Held.has_come_trans`, + `Held.has_gone_trans`); a row that came and went on the way is on neither side + (`Held.has_trans_of_transient`). Through a cut outside the two the composition fails + (`Witness.delta_through_outside`): it rests on contiguity. +- *Counted.* A sum over the rows at the second cut is the sum at the first, less the sum over + the rows gone, with the sum over the rows come, between any two cuts (`Held.sum_rows_delta`); + the count is the case of the measure one (`Held.length_rows_delta`). A row gone from a first + cut to a third is gone in one of the two steps through any cut (`Held.has_gone_triangle`), so + the sizes of the differences obey the triangle inequality; the library states the rows, and + the sizes follow. `[DERIVED for the sizes]` +- *Sorted.* Read, the rows sort by the path's key within a chain: a path with a row on each side is + **replaced**, its head having moved to another version; a path with a row gone only is + **removed**; with a row come only, **added**. Each row gone is removed or the first of a replaced + pair, and not both (`mem_gone_iff`, `not_replacedOf_of_removedOf`); each row come is added or the + second of a pair (`mem_come_iff`), and that it is not both is attacked (seed 547) and tested, not + proved. A side holds one row a path, since a cut does. The pairing is within a chain: a path that + changes class leaves one chain and lands in another (§3.2), so it is removed in the first and + added in the second, and a rename is a removal at the old path and an addition at the new one, + both rows carrying the one identity (D32). +- *On the log.* The two range reads of the table above, and the pairing in the reader over the + rows read. The cost grows with what changed: on the fixture 0.6 µs an event between for the + rows come and 2.0 µs a row closed between for the rows gone, against two reads of the contents + and a set difference, 150 to 170 ms at 100,000 heads whatever changed. When the two cuts span + the whole chain the range reads walk everything, 235 ms there, about one and a half times the + two reads. `[MEASURED §11, the load not recorded; SN-1b's corpus figures are in §11]` +- *Against §7.4.* Every row of the signed difference belongs to a path that an event between + the two cuts names (`key_mem_of_mem_delta`), so the region of §7.4 is sound for the signed + difference as it is for the state: outside it nothing is gone and nothing has come. The region + holds more. A path landed and retired between the two cuts is named by the events and holds a + version at neither cut (`Witness.changed_not_delta`); by the argument of the theorem, a path + the events name is in the signed difference exactly when it holds a version at one of the two + cuts. And the region says only that an identity has an event, where the difference says which + version left and which arrived: a path that returned to the bytes it had is a member of both, + and the difference carries the two digests, which are equal, so a use can set it aside. + +**Contents against positions.** `[THEOREM: SNP-15]` The owner decided that union and intersection +are kept in both meanings (D22). They are two operators each, and they differ. What either of two +cuts holds is what their join holds, with the rows closed between their meet and their join +(`Held.has_union_cut`). What both hold is what their meet and their join both hold +(`Held.has_inter_cut`): on each chain the two cuts in their order, which reads as the rows the meet +holds less those closed by the join, one range read. `[DERIVED for the range read]` So the union on +contents holds both versions of a note edited between two cuts, and the cut at the joined positions +holds the later one alone (`Witness.union_ne_join`). The two meanings agree exactly on the rows +that are never closed (`Gen.aliveAt_sup_of_open`, `Gen.aliveAt_inf_of_open`): in a class where +every path lands once and nothing is edited, renamed, retired or reclassified, the contents of the +join are the union of the contents. The types tell them apart: a join and a meet return a cut, a +union and an intersection a set of versions (D26). + +**A family of cuts.** Each operation is built on the four forms. `[THEOREM: SNP-12, SNP-13, +SNP-14; DERIVED where said]` + +| operation | over the intervals | on the log | cost | +|---|---|---|---| +| what persisted through all | what the family's meet and its join both hold: on each chain, the least and the greatest of its positions (`Held.has_all_eq_kept`) | the third statement above, once a chain | the prefix at the meet, whatever the size of the family | +| what existed in any | the union of the contents (`Held.has_any`). It lies inside the rows alive at some position between the meet and the join, `seq <= :hi AND (closed_at IS NULL OR closed_at > :lo)`, and is less by the rows stored and closed between two cuts of the family (`Gen.exists_aliveAt_iff` for the range) | the disjunction of the family's predicates | the prefix at the join | +| in how many | the number of the family's cuts in the row's interval (`countIn_pos_iff`, `countIn_eq_length_iff`) | read with the row, from its position and its stamp; how many rows every cut holds is the count of the set and what persisted through the family | with the rows it is asked of, and a count | +| a measure at each cut | a map; for a measure that is a sum over the rows, the first cut's value and then each next value from the last by the signed difference (`Held.sum_rows_delta`) | one read of the first cut and two range reads a step | the first cut's prefix, then what changed | +| the sizes of the pairwise differences | a table `D` with `D[i][j]` the count of what cut `i` holds and cut `j` does not. `D[i][j] − D[j][i]` is the difference of the two counts (`Held.length_rows_delta`), and `D[i][k] ≤ D[i][j] + D[j][k]`, since a row gone from `i` to `k` is gone from `i` to `j` or from `j` to `k` (`Held.has_gone_triangle`) | one read of the rows alive at some position of the family's range, each counted into the table by the run of cuts its interval covers | that range once, and the square of the family for the table | + +A family need not be ordered. The signed difference between two cuts neither of which is under +the other is taken chain by chain, each chain in its own direction, and the count walks it all +the same; what an ordered family buys is that the walk's cost is the span from its first cut to +its last and not the sum of the steps back and forth. `[DERIVED]` + +**The default operand.** An operation that names no cut uses the current cut, as the owner +decided (D19). How the default binds is this note's proposal (D27): the head is read once, when +the evaluation starts, and every part of the answer reads that one cut. The answer names the +positions it read, chain by chain (§7.1), so the same question asked again with those positions +is the same answer whatever has landed since (`readAt_grow`, `Held.rows_gens_append`). The stack +is a comparison for the default operand and no more: there is no stack of cuts, no push or pop, +and no state kept between two calls. `[THEOREM: SNP-1, SNP-14 for the reproducibility; +INFERENCE for the binding, falsifier SNF-19]` + ## 5. Derived data as a function of a cut ### 5.1 The rule and the four forms @@ -1165,6 +1502,136 @@ node, and the answer's note says how many curated rows have no landing and were repair is to route that script through the writer's `store`, as every other source is; it is parked (SN-i) because it changes a writer and not a reader. `[INFERENCE]` +### 5.7 The graph at a cut + +Added on 2026-11-12 with §4.4. A cut stands for the palace's graph as of it (D15). §4.4 gives its +nodes: the versions the cut holds, one a path. This section says what the rest of the graph is at +a cut, which of it follows from the difference of two cuts and which is computed again, and the +interface an operator reads the graph through. Stage SN-4 builds it; nothing here is built by +SN-1b, whose contents are the nodes and no edge (§12). + +**A node and its version.** A node persists across its versions: an edit lands a new version of +the same node (D23), and the cut holds, for each node, the version alive at it. +What a version is made of is the node design's, a separate track, and this note does not record +it. The interface assumes three things about a node and no more. It hands an operator the node's +version at the cut as its parts, with no one vector standing for the version. An operation on a +node is taken from one definition, the same in every instance, and a use chooses which operations +it applies and never how one is computed (D21). And nothing here assumes a version has one vector +or one size of part. The universe as built does: it averages a node's rows into one vector +(`core/sentence/universe.py:204-207`) and compares those (`universe.py:930-937`). That is the +present's code, and SN-4 is built on what the node design gives in its place. `[ESTABLISHED for +the code, read at 8d4dff3d; INFERENCE for the interface, D25]` + +**Which species follow from the node difference.** The signed difference of two cuts (§4.4) +names the nodes removed, added and replaced. An edge species follows from it when the edges that +differ between the two cuts can be found from those nodes without reading the rest. Species by +species: `[DERIVED, each from the rule of §7.2; INFERENCE for the condition on S, falsifier +SNF-23]` + +| species | follows from | the condition | what is read over a difference | +|---|---|---|---| +| `S`, similarity | the node difference | the comparison of two nodes is a function of their two versions and of constants: no statistic of the stratum, no rank among the other nodes. The derivation's identity is the present's at both cuts (D5), so it does not enter | the comparisons of each node of the difference against the stratum at the later cut: as many rows of the comparison as the difference has nodes, in place of all of them. An edge between two nodes neither of which is in the difference is the same at both cuts | +| the relations a note declares | the node difference, with the titles | an authored edge is a function of its source's version and of the title its property names, resolved among the cut's heads (§5.4) | the properties of the nodes of the difference, parsed again; and the edges whose property names a title that a row of the difference carries, on either side, since the resolution of that title may have moved | +| `D`, supersession | the events between the two cuts, not the signed difference | the moves of an identity are its consecutive versions. The signed difference holds the first and the last of a path replaced more than once, and the versions between are rows the events between name | the `store` rows of the identities the difference names, in the range (§4.1). At the node grain the species is empty today (§7.2) | +| `F`, citation | the difference on `repo` and on `att`, not the node difference | a reading belongs to a commit and to the projection that wrote it (§5.1) | nothing, where the two cuts name one commit and hold the same projections of it; otherwise the paths whose blob differs between the two commits, with their readings at each (§4.1) | +| `C`, causal witness | the difference on `chat` and on `repo`, not the node difference | an edge is inside a cut when its turn and its commit are (§7.2) | the edges whose turn lies between the two cuts, and those whose turn lies under the first and whose commit lies between: a pair read at the later cut was read at the earlier or has a member in the difference (`pair_readAt`) | +| an interpreted relation edge | the difference on its `interp` chain, with the node difference | a kept generation is served when it was written at or under the cut and its two endpoint digests are heads there (§5.4) | the generations written or replaced between the two cuts, and the kept edges an endpoint of which is in the node difference | +| an assumed edge | nothing | it is applied to the universe of the cut read and not stored (§7.2) | nothing | + +So the node difference decides two species, `S` and the relations a note declares, and for the +others it is one of the differences read. Before SN-2 a cut names the landing chains alone, so the +node difference is the only one there is; the cut gains `chat`, `att`, `repo` and the `interp` +chains at SN-2 (§12), and the difference on each is the events between two positions of it, which +is §4.4's difference on positions with no change. + +A pending node has no edge of `S` at either cut (§7.2), and a node that was pending at one cut +and derived at the other is not in the node difference, since its version did not change. Pending +is a fact of the present's derivation and not of the cut (§5.2, §9.3), so it is the same at both +cuts of one evaluation and cancels. `[DERIVED]` + +**What is updated over a difference, and what is computed again.** A quantity of a cut's graph +is one of three kinds. `[THEOREM: SNP-13 for the first; MEASURED §11 for the break-even points, +on synthetic graphs; INFERENCE for the rule, falsifier SNF-24]` + +- *A sum over rows or over edges.* A count, the size of a stratum, the lexical statistics of a + mask (the unit count, the mean length and each term's document frequency, §5.3), a degree and a + volume. The value at the later cut is the value at the earlier, less the sum over what is gone, + with the sum over what has come (`Held.sum_rows_delta`), exactly and between any two cuts. Its + cost is the difference's. A degree is a sum over a node's edges, so a node outside the + difference can change its degree, by the edges it has to nodes inside it: the degrees follow the + edge difference and not the node difference. +- *A quantity with a cheaper update than its computation, up to a size of the difference.* Three + were measured, each against computing it again at the later cut, on nearest-neighbour graphs of + 2,000 and of 20,000 nodes with 9,300 and 92,300 edges (§11): + - *A solve*, as an effective resistance, a diffusion or a resolvent takes. The earlier cut's + factor with a low-rank correction, one rank an edge changed, against a new factor. The + correction is one solve on the earlier factor an edge changed, and a factor costs 50 to 60 + solves at both sizes, so the two meet near a hundred edges: at 30 edges the correction took a + third to a quarter of the new factor's time, at 100 it took 0.9 to 1.4 times it, and at 300 + it took 0.9 to 3.4 times it. Under about a hundred changed edges the factor is corrected, + and over it a new one is made. + - *The bottom eigenpairs*, as a spectrum, a spectral partition or the modes of a heat kernel + take. An iteration started from the earlier cut's eigenvectors against one started from + nothing, and each with the earlier cut's factor as its preconditioner. At 20,000 nodes the + start from the earlier vectors took 0.2 to 0.7 s where the start from nothing took 1.2 to + 2.1 s, for an edit of a tenth of a percent and of one percent of the edges; at ten percent + it took 0.45 to 0.55 s against 0.6 to 1.6 s, and for edits that join far parts of the graph + the two were then close, 550 ms against 588. With the earlier factor as preconditioner the + same start took 64 to 167 ms up to one percent and 143 to 310 ms at ten, under every other + form measured, a shift-and-invert iteration that factors the later cut's own matrix + included (230 to 272 ms where its factor stayed sparse, and 1.4 s and more where it did + not). So the eigenvectors and the factor are carried from cut to cut, and the start from + them pays at every edit measured, least at ten percent. + - *The components*, for edges added. The earlier cut's components with one union an edge + added, against the components computed again. Computing them again took 0.36 ms at 20,000 + nodes and 4 ms at 200,000, and the unions took a copy of the earlier labels, 0.25 ms and + 2.6 ms, and 0.2 to 0.5 µs an edge: the unions were ahead by a factor of at most one and a + half, up to a few hundred edges at the smaller size and a few thousand at the larger, and + behind past that. The components are computed again. An edge removed has no update in this + form at all. +- *A quantity computed again at each cut.* A rank and a `top`, which depend on every candidate; + the causal fiber (§5.5); the comparisons of the nodes of the difference, which are new work + and not an update; and each quantity of the second kind once the difference passes its + break-even point. + +**A family of ordered cuts.** A measure over a family is a map (§4.4), and for a family in the +order of the cuts it is walked: the graph of the first cut is read whole, and each next cut is +reached from the last by the signed difference between the two, which gives the nodes changed +(`Held.has_cut_eq_apply`), then the edges changed by the table above, then each quantity by its +kind. What is carried from one cut to the next is the node set, the edges, and for the second +kind the factor and the eigenvectors. The steps compose: the difference from the first cut to +the third is the two steps' differences composed, since the second cut lies between them +(`Held.has_come_trans`, `Held.has_gone_trans`), so a walk that skips a cut and a walk that +stops at it reach the same graph. A family that is not a chain is walked in any order that +visits every cut, at the cost of the steps' sizes summed; sorting it along one chain's positions +keeps that sum near the span. `[THEOREM: SNP-13 for the composition; DERIVED for the walk]` + +The break-even points are of one fixture and one machine, with compiled factorizations against +an update written over them, and they are counted in edges changed, not in nodes: a node of the +difference changes as many edges as it has. They are the default SN-4 builds on and measures +again on an instance's own graph (SNF-24). + +**The interface a cut's graph gives an operator.** SN-4 implements it under the universe; it is +specified here so that the algebra's four forms (§4.4) have one thing to read. A graph is +obtained from a cut and a grant, and obtaining it reads nothing. `[INFERENCE: the interface is +this note's proposal, D25; falsifier SNF-18]` + +| member | what it gives | what is read, and when | +|---|---|---| +| the cut | the cut read, chain by chain on the chains the grant names (§7.1) | nothing | +| the nodes, of some classes or of all the grant reads | a set of versions (§4.4), one a node: an operand of every set operator, with its count and its columns | as §4.4: a count walks the prefix, columns are read as buffers, a difference from another cut's nodes costs what changed | +| a node's version | the version alive at the cut, as its parts, as the node design defines them: each part with what names it and, where it is derived, its vector. A part that is pending says so | on the call: the version's rows in the stores that hold them, by the digest the log names (§5.2, §5.3) | +| the edges of a species, among some nodes or all | columns: the source, the target, the weight, and the sign for a signed relation | on the read, by the species' rule at a cut (§7.2) | +| a sparse matrix of a species | the matrix in compressed rows with the index of its nodes, weights as the species defines them | on the call; built from the edge columns | +| a neighbourhood of a node | the nodes and the edges within a number of steps along a species | on the call, by a seek where the species' store has one (`F`, `C`, the relations) and by the node's own comparisons for `S`; the species is not loaded whole | +| the difference from another cut's graph | the signed difference of the nodes, sorted (§4.4), and for each species the edges gone and the edges come | the two range reads of the nodes, then the table above, species by species | + +Four rules hold for every member. A member reads under the grant the graph was obtained with, +and the grant is the asker's now (§6.3, §6.5). No member returns a hole or an edge that ends at +one (§6.5). Every result carries the cut read, so it can be asked again (§7.1). And a member +returns a node's parts, or columns over them, and never one vector a node: an operator that +needs a comparison of two nodes calls the node design's operation on their parts. + ## 6. Erasure and scope Two things are parameters of a read and no function of the cut, because they are the present's: @@ -1461,6 +1928,84 @@ name the head withholds. And the filter is then applied after the read, which is owner's at every cut (`snapshot_narrow`). The alternative, the list taken at the cut's tree, is decision D11. +### 6.5 The algebra under a grant and an erasure + +Added on 2026-11-12 with §4.4. The grant and the erasure are parameters of every operator of +the algebra as they are of a read, and neither is a function of a cut. + +**Every operator commutes with the grant.** `[THEOREM: SNP-16, with SNP-6]` + +- A set read on the chains a grant shows is the grant's restriction of the set read on the + whole store (`Held.across_restrict`). It reads only the chains the grant names and its cuts' + positions on them, so two stores that agree there give one answer, whatever the other chains + hold and wherever the cuts stand on them (`Held.across_congr`). It names no chain the grant + does not name (`Held.across_of_not`), and a narrower grant's set is the restriction of a wider + grant's (`Held.across_narrow`, on `restrict_narrow`). +- The difference on positions commutes with a grant of whole chains (`restrict_readBetween`), and + the meet and the join are taken chain by chain, so their positions on the grant's chains are a + function of the operands' positions there. +- So a signed difference read under a grant names only the chains the grant names, and so does + every count, every series and every table made from it. A path that changes class leaves one + chain and lands in another (§3.2): an asker whose grant names the first and not the second is + shown the removal and not the addition, which is what a read of its own class shows it at the + head. +- A test of a row that a grant applies inside a chain is applied after the set is read, with which + it commutes (`Held.rows_filter`). Applied to the chain before its closing stamps are computed it + moves the positions and the stamps (`Witness.filter_before_gens`), the same failure as an event + filter applied before the cut (§6.3). Applied after, it leaves the stamps computed over every row + of the chain, and a row's stamp is the position of its path's next event + (`exists_next_of_mem_gens`). So a row the test shows names, by its stamp, the position of the row + that closed it, a row of the same path that the test may hide: whether a version is in the set at + a cut then shows whether the hidden row after it is of its path, where the read at the cut under + the same test (`snapshot`) shows only the rows the test keeps (added 2026-11-13). `[DERIVED from + the stamp's definition]` What must be hidden is hidden by chain, in position as in number: a + count of the events between two positions of a chain counts every event of it + (`Witness.position_channel`), and a stamp names an event of the chain whatever the test. + +For a grant that names whole chains, no operator opens a channel the read at a cut did not have, +since each is a function of reads the grant already restricts (`Held.across_congr`). A test of rows +inside a chain is not such a grant, as the last item says. SN-1b's grants name whole classes, and +its one test of rows, the version's own, hides nothing from the asker: the events between two cuts +list every row of the chains it reads. One thing a cut's name shows is not content and is said +here: a landing chain's id is given in the order the chains were opened, over every class, so an +asker shown the id of one of its chains can bound how many chains were opened before it. That is a +count of classes and merges of the instance, not of any class's landings. `[DERIVED]` The tool +names a cut on the chains the asker's grant names and on no other (§7.5), and a cut given to it +that names another chain is refused in the words it uses for a chain that does not exist. + +**A hole is in no set.** `[THEOREM: SNP-17, with SNP-7]` A version is a `store` row that keeps +its content, and a row a purge emptied is not one: the version's own test leaves it out of every +cut's contents (`Held.rows_gens_holes`, `not_erased_of_mem_gens_holes`), so it is in no union, +no intersection, no difference and no side of a signed difference, and it counts in no count. The +hole keeps its key and its position, and the closing stamps are a function of the keys alone +(`gens_map`), so an erasure moves no position and no stamp: it takes its own rows out of every +set and changes no other row of any set. A row before a hole stays closed by it, so the version +before a purged one does not come back as the path's head (§6.1). The control is the erasure +that deletes its rows, after which a set holds rows from after its cuts (seed 565). + +What a purge changes in the algebra is what it changes in a read (§6.2). A purged version was in +the contents of the cuts where it was alive and is in none afterwards. A path whose earlier +version is purged and whose later one is kept was replaced between two cuts before the purge and +is added between them after it. The sets and the differences at past cuts are what they are on +a store that never held the purged content, and append invariance is stated for a fixed erasure +(`Held.rows_gens_append`). + +**Counting the holes.** An answer can say how many rows of the range it read are holes, or say +nothing of them. The count tells an asker that purges happened among its own classes' landings +and how many, which the events between two positions already show it, since a hole is returned +as a hole with its position (§12, SN-1). It makes a count that fell between two askings +explicable. This note recommends that the answer's note carry the count, and the choice is the +owner's (D33). `[INFERENCE]` + +**A retire is a removal.** `[THEOREM: SNP-17]` A retire is the shallow form (§6.2): its row is a +tombstone and no version, it closes the version before it, and nothing is emptied. So between a +cut that holds the item and a cut at or after the retire, the version is among the rows gone, +and no row of its path that came carries a version (`removed_of_retire`): the item is removed in +every signed difference that spans the retire. The cuts before the retire hold the version as +they did, and a union or an intersection that names one of them holds it. A rename is a `move` +at the old path and a `store` at the new one: a removal and an addition, the two rows carrying +one identity, so a use that follows identities pairs them (D32). + ## 7. The sentence surface ### 7.1 The cut asked and the cut read @@ -1562,7 +2107,7 @@ The mode of a clause follows from its scope (`core/query.py:273-281`). | species | at a cut | |---|---| -| `S`, similarity | recomputed from the vectors of the versions alive at the cut, within a stratum, as today (`core/sentence/universe.py:733-739`); no edge at a pending node | +| `S`, similarity | recomputed from the versions alive at the cut, within a stratum. Today the comparison is of one averaged vector a node (`core/sentence/universe.py:204-207`, `:930-937`, read at `8d4dff3d`); §5.7 says what the interface assumes in its place and which edges follow from the difference of two cuts. No edge at a pending node | | `F`, citation | the edges of the reading at the commit; a reading is whole, so nothing is inferred between commits | | `D`, supersession | consecutive versions of the chain's prefix; at the node grain it is empty today and stays so (`universe.py:810`) | | `C`, causal witness | an edge whose witness turn is inside the cut on `chat` and whose commit, if it ends at one, is inside the cut on `repo` | @@ -1632,6 +2177,181 @@ reports its two universes (`execute.py:1045-1063`), is the `velocity of` that dn designs as GD-4. This note supplies the two readings it needs and does not add a second way to write it. +**The region and the two differences (added 2026-11-12).** §4.4 gives two differences of two +cuts, and the region is a projection of the first. + +- The difference on positions is the events between the two cuts. `changed between` is its + identity projection: the identities those events name. It stays as it is, a region, sound for + what did not change. +- The difference on contents is signed and is of versions: the rows gone and the rows come, + sorted into removed, added and replaced. Every path in it is in the region + (`key_mem_of_mem_delta`), and the region holds more: a path landed and retired between the two + cuts has an event and holds a version at neither (`Witness.changed_not_delta`). The region + answers whether an identity was touched, and the signed difference what it held before and + after. `[THEOREM: SNP-13]` + +GD-4's `velocity of` is neither: it is a function of two readings, the value of an identity at +the versions alive at the two cuts, which in §4.4's interface is a combine. The algebra gives it +three things. The two readings come from one pair of range reads: for an identity that was +replaced, the signed difference carries the version at each cut, which is the pair the +displacement is taken between. An identity outside the region has one state at both cuts +(`stateAt_eq_of_not_written`), so its velocity is zero and is not computed: the velocity's +support lies inside the region. And DYN-1's additivity over adjacent windows is the composition +of the differences through a cut between the two (`Held.has_come_trans`, `Held.has_gone_trans`), +which is why it needs the middle cut between the outer ones. A velocity over a window of more +than two cuts is a map over a family (§4.4), walked as §5.7 says, and the velocity of a flow or a +potential is a quantity of the graph at each cut, read through §5.7's interface. + +What a value is stays GD-4's and the node design's. This note supplies the versions and no +vector: a version is its parts (§5.7), and a displacement of an embedding is defined where the +node design defines a difference of two versions. An identity added or removed between the cuts +has a version at one cut only, and what its velocity is, if anything, is GD-4's to say. +`[DERIVED]` + +So there remain one region and one way to write a velocity. The signed difference is reached +through the tool (§7.5), and where the sentence surface takes it later is §7.6. + +### 7.5 The tool + +Added on 2026-11-12. The engine and its tool are built before the grammar takes the algebra +(D18). The tool is one tool of the palace's MCP server, `cut`, whose handler is a module of its +own (`agents/ambassador/cut_tool.py`) over the engine (`core/stores/cuts.py`); SN-1b builds both +and registers the tool for the Ambassador (§12). The server opens the catalog's file to only read +for each call (`read_only`), so a call takes no lock a writer waits on and writes nothing. +Everything about its surface is this note's proposal (D26, D27, D28, D34, D36). `[INFERENCE, +falsifiers SNF-19, SNF-20]` + +**What it delivers.** The cut as a value, the contents of a cut and the algebra over them, on +the landing log. It is not yet the graph: the edges and the graph mathematics at a cut arrive +with SN-4, through the interface of §5.7. Every answer of the tool says so in its note. + +**The arguments.** + +| argument | what it is | default | +|---|---|---| +| `op` | the operator, by one of the names below | none: it is required | +| `a`, `b` | the operands: each a cut's name, or a call of the tool written as an object with its own `op`, whose result is the operand | the head, bound once (below) | +| `cuts` | a family: a list of operands, for the operators over a family | none | +| `over` | the provenance classes whose chains are read | every class the asker's grant reads | +| `list` | whether the rows of a set or of a difference are returned beside its counts | false: counts only | +| `limit` | the most rows returned when `list` is set | 50, and the answer says when it stopped there | + +An operand that is a call is how a result is an operand again: the union of two differences is +`union` with a `difference` in `a` and another in `b`. The whole call composes to one +expression. Before its outermost operator reads, a call reads the heads, when it starts, and the +horizon of a chain a position is named on (below); a set of any depth is then one statement +(§4.4). A call's sets name at most 256 cuts, counted each time their statement names one, so that +a short call cannot ask for a statement of any size; a call over the bound is refused before a +statement is written. + +**How a cut is named.** By one of four forms, and an answer prints every cut it read in the +third, so that a cut is copied from an answer into a question. + +- `head`: the head, read when the evaluation starts. +- `bottom`: the empty cut. +- positions: `land.@`, one a chain, separated by spaces, as `land.3@412 land.5@97`. + A chain the name leaves out stands at 0, its empty prefix. +- from SN-2 on, the names of §3.4: a recorded cut's id, a commit, a date. They resolve to a + frontier as they do for `as of`, and the chains SN-2 adds are named in the same form with + their own prefixes. + +A cut is read as §7.1 says. A position past a chain's head is refused, and the refusal names the +head. A position under a chain's horizon is not served (§8): the chain is read at its empty +prefix and the answer says so. No index finds a chain's horizon row, so a position named under a +chain's head walks the chain back to it; an evaluation walks no row twice, so a call walks a +chain once, and a position at the head not at all. Before SN-2 no reference of §3.5 lowers a +landing chain, so the cut read is the cut asked with each chain at the greatest position it +serves. That does not make every frontier of landing chains a state the catalog had, as this +paragraph said until 2026-11-13: a change of class writes a `leave` in one chain and the `store` +in another, which no reference joins (§3.5), and a cut over two chains that is neither the head +nor the bottom can hold one of the two rows without the other, and so the path in both classes or +in neither. Such a cut is read as asked, and the note says so (below). + +**The default.** An operand left out is the head, and so is an operand of a family when the +family is given none. The head is read once, when the evaluation starts, and every operand that +is the head, wherever it stands in the expression, is that one cut (D19, D27). The answer names +it by its positions. + +**The operators, by name.** Both meanings of union and intersection are exposed, under different +names, and their results differ in type (D22, D26). + +| name | operands | returns | §4.4 | +|---|---|---|---| +| `head`, `bottom` | none | a cut | the head; the bottom | +| `join`, `meet` | `a`, `b` | a cut: the union and the intersection on positions | the lattice | +| `order` | `a`, `b` | one of `equal`, `before`, `after`, `unordered` | the order | +| `between` | `a`, `b` | the events after `a` and up to `b`: their count, and listed, each event's position, kind and names | the difference on positions | +| `held` | `a` | a set: the versions the cut holds | the contents | +| `union`, `intersection`, `difference`, `symmetric_difference` | `a`, `b`, each a cut or a set | a set: the operation on contents | the sets | +| `delta` | `a`, `b` | a signed difference: the counts removed, added and replaced, and listed, the rows of each | the signed difference | +| `apply` | `a` a set, `b` a signed difference | a set | applied | +| `compose` | `a`, `b` two signed differences that share a cut between their outer ones | a signed difference; refused when the shared cut is not between | composed | +| `persisted`, `existed` | `cuts` | a set: what every cut of the family holds; what some cut holds | a family | +| `count` | `a` a cut or a set | a number | the count | +| `in_how_many` | `cuts`, and `a` a set | rows: the set's first `limit` rows, each with the number of the family's cuts that hold it, the set's count, and how many of its rows every cut holds | a family | +| `measure` | `cuts`, and `of`, the measure's name | a series, one value a cut. At SN-1b the one measure is `count`; SN-4 adds the measures of a graph | a family | +| `pairwise` | `cuts` | a table: for each ordered pair, the count of what the first holds and the second does not | a family | + +A cut given where a set is expected is the set it holds. A set, a signed difference or a number +given where a cut is expected is refused, and the refusal names the type that was given and the +one the operator takes: a `join` of two sets is the mistake the two names exist to catch (SNF-20). + +**The answer.** One object: + +- `op` and `type`: what was asked, and whether the result is a cut, events, a set, a signed + difference, a number, rows, a series, a table or an order. +- `cuts`: every cut the evaluation read, in the order the expression names them, each by its + positions on the chains the grant names, and once beside each cut asked for it where the two + differ, so a cut read for two names that differ is listed beside each. +- the result: for a cut, its positions; for a set, its `count`; for a signed difference, + `removed`, `added` and `replaced`; for the others, the number, the series or the table. +- `rows`, when `list` is set: for each row its chain, its position, its path, its identity, its + digest, its title and its version number; for a replaced path, the two rows. `truncated` says + whether `limit` cut the list. +- `note`: sentences, in this order where each applies. That no cut was named and the head was read, + with its positions. Each chain read below the position asked, and why (§7.1). That a cut that is + neither the head nor the bottom can split a change of class, when the answer reads what cuts hold + on two chains or more at such a cut: the tool cannot tell whether one is split without reading + every change of class in the range (§3.5). How many rows of the ranges read are holes (D33). That + the result is of the versions the landing log holds, and that edges and graph mathematics at a + cut arrive with SN-4. + +The same call with the cuts of `cuts` in place of its defaults returns the same result whatever +has landed since, under the same grant and the same erasure (§4.4, the default operand). + +**What a guest may call.** Not decided: it is the owner's (D34). The tool is registered in the +Ambassador's table. The guest's table (`GUEST_TOOLS` in `agents/ambassador/mcp.py`) is +not changed by SN-1b, so a guest has no `cut` tool until the owner rules. What this note +recommends, and what the ruling weighs, is in D34. + +### 7.6 The grammar, later + +Added on 2026-11-12. Nothing of the grammar is built with the algebra (D18). This section says +where the sentence surface takes it, so that the tool's names and the grammar's words are one +vocabulary when stage SN-8 builds them (§12). `[INFERENCE, falsifier SNF-14]` + +- **A cut is already a word of the grammar.** `as of ""` names one, and stays the index of + the reading (§2.1). The names the tool takes are the names `as of` takes (§3.4), with the + positions form added to both. +- **A region from two cuts.** `changed between "" and ""` stays, with `changed since` + (§7.4). The signed difference gives three regions that refine it, each a filter of the same + range read: the identities removed, added and replaced between the two cuts. A sentence form + for them, as adjectives of `changed` or as three words beside it, is SN-8's to choose and is + not chosen here. Whatever form it takes, each is a region, so it masks a field and meets a + region with no new rule (§7.4). +- **A region from a family.** What persisted through every cut of a family and what existed in + some cut are regions as well, and a form for them belongs with the same stage. +- **Two readings.** `velocity of` is GD-4's, over a window of cuts (§7.4). This note adds no + second form for a function of two readings. +- **What stays out of a sentence.** A sentence has one cut (§2.1) and its answer is a region or + a field over one universe. The join and the meet of two cuts are names of cuts and can be + written wherever a cut's name can, once the grammar admits an expression there. A set of + versions that mixes cuts, as a union on contents does, is no universe: it can hold two + versions of one node. So the union and the intersection on contents enter a sentence only as + regions of identities, and the sets of versions themselves stay the tool's. +- **The default.** A sentence with no `as of` reads the head, which is the default operand of + the tool (D19): the two surfaces agree on what a missing cut means. + ## 8. The exactness boundary History is exact from the first retained generation and from no earlier. Each chain has a @@ -1822,11 +2542,13 @@ then exact. Two more things follow. ## 10. The laws -Each law is stated so that it becomes a property test when its stage is built, and is proved -now. The Lean names are in `formal/Palace/Snapshot.lean`, the attacks and controls in -`formal/PalaceTest/Snapshot.lean`, by seed. `[THEOREM]` throughout. Each law also says what in -it is a theorem and what holds because the model was built that way, since the second kind -passes to the code only as an obligation of the stage that transcribes it. +Each law is stated so that it becomes a property test when its stage is built, and is proved now. +The Lean names are in `formal/Palace/Snapshot.lean`, the attacks and controls in +`formal/PalaceTest/Snapshot.lean`, by seed; for SNP-11 to SNP-17, the algebra of cuts, they are in +`formal/Palace/SnapshotAlgebra.lean` and `formal/PalaceTest/SnapshotAlgebra.lean`. `[THEOREM]` +throughout. Each law also says what in it is a theorem and what holds because the model was built +that way, since the second kind passes to the code only as an obligation of the stage that +transcribes it. - **SNP-1 append invariance.** A read at a cut inside the store, a read between two such cuts and every derived view are unchanged by any growth of the store (`readAt_grow`, `readAt_of_extends`, @@ -2007,6 +2729,125 @@ passes to the code only as an obligation of the stage that transcribes it. on the chains that could not serve and on the chain of records; at SN-7: every read at a cut from the horizon on is the same before and after a retention pass. +- **SNP-11 the lattice of cuts.** The cuts inside a store are closed under the pointwise meet + and join, with the empty cut at the bottom and the head at the top, and no cut leaves as the + store grows (`bot_mem_cutsIn`, `head_mem_cutsIn`, `cutsIn_mono`, on `cutsIn`); the read at the + empty cut is empty (`readAt_bot`). The read at the join is, chain by chain, the later of the + two reads and the read at the meet the earlier, and the meet distributes over the join + (`readAt_sup`, `readAt_inf`, `readAt_inf_sup`). The difference of two cuts on positions is the + events between them, read from their meet or to their join; the symmetric difference is the + events between their meet and their join; and the difference is a function of the two reads + (`readBetween_inf_left`, `readBetween_sup_right`, `readBetween_inf_sup`, + `readBetween_eq_combine`). The meet and the join of two cuts that are consistent and served + are read as asked (`resolvesIn_sup`, `resolvesIn_inf`, on `servedCuts`): the consistency is + CLK-2's, cited and not claimed here, as in SNP-8. By construction: a cut is a function from + chains to positions, so the lattice is the pointwise one and there is nothing to choose. + Controls: the read at the join taken for the read at the meet (530); the difference taken for + symmetric (532); the join of a cut read as asked with a frontier that is not, taken for + consistent (535). Attacks 529, 531, 533, 534. The test, at SN-1b: on random cuts of random + logs, the join and the meet are cuts inside the head, the order is the pointwise one, the + lattice laws hold as equalities of values, and the events between two cuts are the reference + fold's rows in the range, from the meet and to the join. +- **SNP-12 a row lives on an interval.** A row of a chain kept by generation is alive from its + position up to, and not at, its closing stamp (`Gen.aliveAt_iff`), so a row alive at two cuts + is alive at every cut between them (`Gen.aliveAt_of_between`). The range reads: what the later + of two cuts holds and the earlier does not, what the earlier holds and the later does not, and + what both hold (`Gen.aliveAt_and_not`, `Gen.aliveAt_and_not'`, `Gen.aliveAt_and`); a row is + alive at every cut of a family exactly when it is alive at the least and at the greatest, and + at some position of a range exactly when it was stored by the range's end and not closed by + its start (`Gen.forall_aliveAt_iff`, `Gen.exists_aliveAt_iff`). On the generations of a chain: + a row records the chain's event at its position, its stamp is the position of its key's next + event, every row is alive at one cut at least, and a cut holds each key's state once + (`getElem?_of_mem_gens`, `exists_next_of_mem_gens`, `proper_of_mem_gens`, + `map_val_filter_key_contentAt`, `eq_of_key_eq_of_mem_contentAt`). Controls: a value has no + interval (`Witness.value_not_contiguous`, 537); the rows come taken for every row stored + between the two cuts (539); what some cut of a family holds taken for what the range between + its least and its greatest holds (541). Attacks 536, 538, 540, 542. The test, at SN-1b: each + of the four statements of §4.4 against the reference fold at every pair of positions of a + random log; a row alive at two positions alive at every position between; and one row a path + in the contents of every cut. +- **SNP-13 the signed difference.** Each side of the signed difference is one range read between + two cuts in order (`Held.has_come`, `Held.has_gone`). Applied to what the first cut holds it + gives what the second holds (`Held.has_cut_eq_apply`). Differences compose through a cut between + the two, a row that came and went on the way being on neither side (`Held.has_come_trans`, + `Held.has_gone_trans`, `Held.has_trans_of_transient`), and a row gone from a first cut to a third + is gone in one of the two steps through any cut (`Held.has_gone_triangle`), from which their + sizes obey the triangle inequality. A sum over the rows at the second cut is the sum at the first + less the rows gone, with the rows come, and so is the count (`Held.sum_rows_delta`, + `Held.length_rows_delta`). The rows sort by key into removed, added and replaced: each row gone + is removed or the first of a replaced pair and not both, and each row come is added or the second + of a pair (`mem_gone_iff`, `not_replacedOf_of_removedOf`, `mem_come_iff`); that a row come is not + both is attacked (547) and tested, not proved. Every row of the difference belongs to a key the + events between the two cuts name (`key_mem_of_mem_delta`). By construction: the pairing is by key + within one chain; a path's identity, a rename and a change of class are the code's (D32). + Controls: a composition through a cut outside the two (`Witness.delta_through_outside`, 544); the + count that forgets the rows gone (546); the events between two cuts taken for the signed + difference (`Witness.changed_not_delta`, 549). Attacks 543, 545, 547, 548. The test, at SN-1b: + the two sides against the set difference of the reference fold's contents at the two cuts, in + both orders and for cuts neither of which is under the other; the contents of the second cut from + those of the first and the difference; composition through every cut between, and its failure + through one outside as the control; the count at each cut of a family walked by the differences + against the count read; the three classes disjoint and covering, with one row a path a side; and + every path of the difference among the paths `read_between` names. +- **SNP-14 closure.** A set of rows is an expression over the contents of cuts under union, + intersection and difference, and a set read is the set operation on the reads, so every set + they give is an operand again (`Held.mem_rows_union`, `Held.mem_rows_inter`, + `Held.mem_rows_diff`, with `Held.has_symm`, `Held.has_inter_union` and `Held.has_diff_diff` + among the laws of sets). Whether a row is in a set is a function of its position and its + closing stamp alone (`Held.has_eq_of_interval`); a set lies inside the contents of the cuts + it names (`Held.exists_atom_of_has`); a row's own test commutes with it (`Held.rows_filter`). + A set whose cuts lie inside the chain is unchanged by any growth of the chain, and a set + whose cuts lie at or under a cut reads the prefix at that cut (`Held.rows_gens_append`, + `Held.rows_gens_take`). What both of two cuts hold, what every cut of a family holds, which is + what its least and its greatest both hold, what some cut holds, and in how many cuts a row is + alive (`Held.has_kept`, `Held.has_all`, `Held.has_all_eq_kept`, `Held.has_any`, + `countIn_pos_iff`, `countIn_eq_length_iff`). A function of two reads, a measure at each cut + and a fold over a family are append invariant (`combine_grow`, `series_grow`, + `foldOver_grow`). By construction: a set is read chain by chain, and the statement it runs as + is not in the model. Controls: the complement, which grows with the store + (`Witness.complement_grows`); the operations taken on the values the cuts hold and not on the + rows (552); a set that names a cut past the head (554); the closing stamps taken for part of + what a set held (555); a row's test applied before the generations are computed (558). + Attacks 551, 553, 556, 557. The test, at SN-1b: expressions drawn at random, of any depth, + each read lazily against the same operations on the reference fold's sets of rows; results + of each operator given to every other as operands; a set composed without a statement being + run, and read by one; the count without the rows; every set unchanged after further writes, + up to the holes a later purge leaves; and the family operations against the fold. +- **SNP-15 contents against positions.** What either of two cuts holds is what their join holds + with the rows closed between their meet and their join, and what both hold is what their meet + and their join both hold (`Gen.aliveAt_or_eq_sup`, `Gen.aliveAt_and_eq_inf_sup`, + `Held.has_union_cut`, `Held.has_inter_cut`). For a row that is never closed the contents of + the join are the union of the contents and the contents of the meet their intersection + (`Gen.aliveAt_sup_of_open`, `Gen.aliveAt_inf_of_open`). Control: one key written twice, where + the union holds two rows and the join one (`Witness.union_ne_join`, 560). Attacks 559, 561. + The test, at SN-1b: on a class each of whose paths lands once and is never written again, the + contents of the join equal the union of the contents and those of the meet the intersection, + for every pair of cuts; and after one edit between two cuts the union holds both versions of + the path and the contents of the join one, as the control. +- **SNP-16 the grant commutes with every set.** A set read on the chains a grant shows is the + grant's restriction of the set read on the whole store; it reads only those chains and its + cuts' positions on them; a narrower grant's set is the restriction of a wider one's; it names + no chain the grant does not name; and the events between two cuts commute with a grant of + whole chains (`Held.across_restrict`, `Held.across_congr`, `Held.across_narrow`, + `Held.across_of_not`, `restrict_narrow`, `restrict_readBetween`). By construction, as in + SNP-6: the grant is an argument of the reader. Controls: a row's test applied to the chain + before its generations are computed (`Witness.filter_before_gens`); a set read without the + grant's restriction, which reads the other chain (563). Attack 562. The test, at SN-1b: the + contents, the sets and the differences of one class are unchanged by writes to another class + and by the positions a cut names on another class's chains, and their statements name only + the class's chains. +- **SNP-17 erasure and retire on sets.** The closing stamps are a function of the keys alone, so + a hole that keeps its key moves no position and no stamp (`gens_map`); no row of a chain with + holes carries an erased value, and an erasure takes its own rows out of every set and changes + no other (`not_erased_of_mem_gens_holes`, `Held.rows_gens_holes`); a retire is a removal in + the signed difference that spans it (`removed_of_retire`). Controls: the erasure that deletes + its rows (565); a hole taken for a version (566). Attacks 550, whose guard holds in 295 of + its 500 instances, and 564. The test, at SN-1b: after a purge, no set and no side of a + difference at any cut holds a row of the purged digest, every other row of every set is the + row it was, and the counts fall by the rows purged; a retired path is removed in every + difference from a cut that holds it to a cut at or after its retire, and held by every cut + before. + What the model leaves out, said plainly. A chain is a list and a store a family of lists: one writer is assumed, and nothing is said of two. Events are opaque, and so is the stores' SQL. The set of chain keys is fixed: a relabel is not in the model, which is why a chain has an id that a relabel @@ -2026,6 +2867,20 @@ argued there, not proved. The filtered read is a derived view, not a prefix. A r with merges is covered by CLK-2's down-sets and not by the chain model (§3.1). The resolver, the descent and its alternation with the floor, is attacked, not proved. +What the model of the algebra leaves out. A set is read on one chain, and across a store chain +by chain (`Held.across`): a class with several chains is the union of its chains' reads, as in +SN-1. The statements of §4.4 are not in the model: that each runs as the predicate it is given +was checked by a probe against a fold of the log (§11), and is SN-1b's property test. A version +is modelled as a row whose value is present, a tombstone or a hole as one whose value is absent; +the kinds of the log, the identity a row carries, a rename and a change of class are the code's, +and so is the pairing of a removal with an addition by identity (D32). The default operand is +not in the model: that the head is read once an evaluation is a property of the code, tested at +SN-1b. The node as its parts, the edges of §5.7 and the updates of a quantity over a difference +are not in the library: the first is the node design's, the second is argued in §5.7 from the +rules of §7.2, and the third is measured (§11) and rests on identities of linear algebra this +note does not prove. And the tool is not in the model: its types are the model's, its names and +its answer are §7.5's. + ## 11. Measurements Every figure measured for the design, before SN-1 was built, is from a synthetic fixture: a @@ -2103,12 +2958,82 @@ from the log alone passes a tenth of a second near 27,000 heads, a chain of 30,0 0.11 s. That is SNF-6's first condition, met at SN-1, and kept heads do not remove it: a kept head at a recorded cut shortens the walk, not the building of the answer (§4.2). +**Measured for the algebra of cuts, before its code (added 2026-11-12).** Four probes, none in the +repository: SN-1b commits the harness of what it builds and measures it again on a copy of the +corpus instance's catalog (§12). The fixtures are synthetic and are built by the probes in +temporary files or in memory. The same machine with other work running, the load average near 3 +during the fourth probe. It was not recorded for the second and the third, whose times §4.2 and +§4.4 use and mark so, and the first times nothing; SN-1b's figures on the corpus's catalog, below, +carry their load. Python 3.15.2, SQLite 3.54.1, NumPy 2.5.4, SciPy 1.18.1; the log's tables and +indexes as `core/stores/landings.py` creates them, with the landing-log secret a test value from +the environment. `[MEASURED]` + +| probe | fixture | result | +|---|---|---| +| the interval reads against a fold | 900 catalogs, 300 for each of three seeds, written through `VaultCatalog` by random sequences of its writes: records, retires, renames, relabels, changes of class and purges, so the logs have holes and classes of several chains; at every pair of positions of every chain, the statements of §4.4 against a fold of the chain's prefix written in the probe | about 344,000 comparisons, none failing: the contents of a cut, the rows come, the rows gone and the rows both hold; what every cut of a family holds, and what some cut holds inside the range read; the count at the second cut from the count at the first and the two sides; composition through a middle cut; one row a path on each side; every path of the difference among the paths of the events between | +| the plans and the cost of the reads | one chain of one class in a temporary file: 100,000 paths, half of them recorded twice more, 200,002 rows, 100,000 heads; each read five times | the planner takes the primary key for the contents of a cut and for the rows come, and `landings_closed` for the rows gone, unprompted. The contents at the head as tuples 90 ms (88 to 91), and counted 25 ms, 0.125 µs an event. The signed difference ending at the head: over 1 position 0.004 ms a side; over 1,000 positions the rows come 0.60 ms and the rows gone 2.0 ms, 1,000 rows each; over 100,000 positions 58 ms and 189 ms, 74,895 rows each; over every position 88 ms and 147 ms. Two reads of the contents and a set difference: 150 to 170 ms whatever the span | +| every head as columns | the same tables: 100,000 paths, half recorded once more, 150,002 rows, 100,000 heads; each read five times | `heads_at`, a row in Python a head: 381 ms (373 to 408), 3.81 µs a head. Three columns as tuples 87 ms. The count 19 ms, 0.13 µs an event. One column as one buffer: the positions 23 to 28 ms, the digests 22 ms, the paths' keys 32 ms. The three columns in one statement, each aggregated to one buffer and read as an array, 49 ms (49 to 51), 0.49 µs a head; the columns equal to the rows | +| a quantity updated over a difference | graphs in memory: points drawn uniformly in the unit square, each joined to its 8 nearest, made symmetric, unit weights; 2,000 nodes with 9,285 edges and 20,000 with about 92,300. An edit adds edges between nodes not yet joined: between random pairs, or between a node and one of its ninth to sixteenth nearest. For the components, the same graph with nine tenths of its edges dropped, at 20,000 and at 200,000 nodes. Medians of three to five runs | below | + +The fourth probe, by quantity. `[MEASURED]` + +| quantity | computed again at the later cut | updated from the earlier cut | where the two meet | +|---|---|---|---| +| one solve of the Laplacian with one node grounded | a sparse factor and a solve: 4.5 to 4.8 ms at 2,000 nodes and 71 to 77 ms at 20,000, a factor costing 50 to 60 solves; with random edges added the factor fills, and takes 18 ms at 2,000 nodes with 300 added and 613 ms at 20,000 with 1,000 added | the earlier factor with a correction of one rank an edge added: at 20,000 nodes 2.5 ms for 1 edge, 9 ms for 10, 22 to 23 ms for 30, 90 to 93 ms for 100, 255 to 263 ms for 300, 1.0 to 1.1 s for 1,000; the two solutions agree to 12 digits | near 100 edges at both sizes: the correction is 3.2 to 3.9 times faster at 30 and 0.7 to 1.1 times as fast at 100 | +| the four bottom eigenpairs of the normalized Laplacian, to a residual of 10⁻⁶, by a block iteration | from a random start, at 20,000 nodes: 1.2 to 2.1 s for an edit of 0.1 and of 1 percent of the edges and 0.6 to 1.6 s at 10 percent. By shift and invert, which factors the later cut's own matrix: 230 to 272 ms, and 1.4 s at 1 percent and 164 s at 10 percent of random edges, where that factor fills | from the earlier eigenvectors: 198 and 362 ms for edits among near neighbours and 720 and 693 ms for random ones, at 0.1 and 1 percent; 446 and 550 ms at 10 percent. With the earlier cut's shifted factor as the preconditioner as well: 64, 94 and 143 ms for edits among near neighbours and 143, 167 and 310 ms for random ones, at 0.1, 1 and 10 percent. The eigenvalues agree to 9 digits | the start from the earlier vectors alone meets the random start at 10 percent of random edits (550 ms against 588); with the earlier factor it is ahead of every form measured, at every edit measured | +| the components, edges added | 0.36 ms at 20,000 nodes and 4.0 ms at 200,000 | the earlier labels copied, 0.25 ms and 2.6 ms, and one union an edge added, 0.2 to 0.5 µs: 0.27 ms and 2.6 ms for 100 edges, 0.53 ms and 3.1 ms for 1,000, 4.2 ms and 7.2 ms for 10,000 | between 100 and 1,000 edges at 20,000 nodes and between 1,000 and 10,000 at 200,000; under that the unions are ahead by 1.2 to 1.5 times | + +Three notes on these figures. The factorizations use the fill-reducing ordering that was fastest +on the fixture among those the library offers, and a first run under another ordering took 2.7 s +for the factor at 20,000 nodes where this one takes 71 ms: a break-even point moves with the +ordering, and the figures above are with the faster one on both sides. At 2,000 nodes the same +shapes hold at a tenth of the times or less. And the unions are written in Python over compiled +components, which is the comparison an instance would run and not one of two algorithms on equal +terms. By arithmetic from the third probe, not measured: three columns of the corpus chain's +400,274 heads would take about 0.2 s and its count about 52 ms (§4.2). + +Not measured for the algebra: anything on an instance's own log, which is SN-1b's; the pairwise +table and the count of the cuts that hold a row; a set of more than two cuts read as one +statement; any quantity of a real graph at two cuts, which is SN-4's. + +**Measured at SN-1b, on a copy of the corpus instance's catalog (added 2026-11-13).** The algebra +as built, by its committed harness (`eval/cut_algebra_bench.py`, at `4e94b442`, the engine at +`b210db03`), on two copy-on-write clones of the corpus instance's catalog, migrated in place: the +genesis of 400,274 `observed` rows, then a history of 200,000 writes through `record` and +`tombstone` (100,000 new versions of held paths, 50,000 retires, 50,000 new paths, shuffled), so +the chain ends at position 600,276 with 400,274 heads. The record is +`docs/experiments/cut-algebra-2026-11-13.md`, every figure in its JSON. The same machine, macOS +27.0.1, Python 3.15.2, SQLite 3.54.1, NumPy 2.5.4, the load average between 2.3 and 4.0. Medians +over five repetitions, the two runs given as a range. `[MEASURED]` + +| probe | result | +|---|---| +| every head at the genesis's head, 400,274 | SN-1's rows (`heads_at`, called before the contents replaced it) 1.74 to 1.79 s, 4.3 to 4.5 µs a head; counted 66 ms, 0.17 µs an event; three columns 219 to 224 ms, 0.55 to 0.56 µs a head; eight columns 433 to 437 ms; the columns equal to the rows | +| every head after the history, over 600,276 events | the rows 1.82 to 1.86 s; counted 90 to 95 ms, 0.15 to 0.16 µs an event; three columns 236 to 241 ms | +| the signed difference ending at the head, over 1, 1,000, 100,000 and 200,000 positions | its counts 0.02, 2.5, 279 to 305 and 560 to 604 ms; its two sides as columns 0.02 and 0.02, 0.4 and 1.9 to 2.0, 42 and 218 to 238, 83 to 90 and 448 to 463 ms, the rows come then the rows gone; read and sorted 0.08, 2.7 to 2.9, 318 to 362 and 657 to 682 ms. Two reads of every head and a set difference: 3.6 to 3.8 s at every span. Each side equal to the set difference | +| the same from the bottom, every position | counts 144 to 147 ms; the rows come as columns 238 to 260 ms; the baseline 1.8 to 1.9 s | +| a family of ten cuts from the horizon to the head | the count at each walked by the differences 435 to 487 ms, against 790 to 834 ms for ten counts, equal; what persisted through all 64 ms; what existed in any 99 ms; the pairwise sizes 315 to 319 ms, equal to the hundred differences' sizes | +| the plans | what a cut holds on the primary key, `seq? AND seq? AND closed_at@`, a chain left out standing at its empty + prefix (§7.5). The alternatives: a tool an operator, some twenty entries of the server's + table, none of which can take another's result as an operand; or a chain left out standing + at its head, after which a name means another cut each time the store grows. + ## Parked decisions | id | decision | default recorded | re-entry condition | |---|---|---|---| | SN-a | the cadence of recorded cuts | a trough that moved, the owner's command | a date that resolves to a cut farther from it than a declared tolerance | | SN-b | the citation readings as rows valid over a range of commits | append-only rows a commit, stamped with their projection | the store's size on an instance | -| SN-c | the heads kept at some recorded cuts | none for a chain under 250,000 events; kept, from SN-4, for a chain over it (§4.2) | `heads_at` past a tenth of a second on a chain under the threshold, or under it by a wide margin on one over; met at SN-1, 0.11 s on a chain of 30,002 events, the cost the building of the answer (§4.2, §11), so this re-enters before SN-4 | +| SN-c | the heads kept at some recorded cuts | the shape is decided (D15): the read of every head is the contents of a cut, with no list of rows. The size is not: none kept for a chain whose contents read as columns under a tenth of a second, about 180,000 heads as SN-1b measured them (§11); over it, from SN-4, the contents read once and walked over the differences, or heads kept at a recorded cut (§4.2, D30) | the owner's ruling on D30 | | SN-d | a second embedder identity's vectors kept beside the first | none: the present's identity | dn-two-phase-ingestion's open question 4 | | SN-e | lexical statistics stored per class and per recorded cut | computed from the mask | a lexical query at a past cut over its budget | | SN-f | `repo` as a graph of commits, and a chain a repository | the line of the branch the sensor reads, one repository | an instance whose history has merges or that reads several repositories | @@ -2461,8 +3697,14 @@ give, and what each alternative costs is the answers it changes, which the entry over. Then the threshold moves; on the fixture the read from the log alone passes a tenth of a second between 100,000 and 500,000 events (§4.2). Met at SN-1: as built every head costs 3.5 to 3.9 µs a head returned, and a chain of 30,002 events reads them in 0.11 s (§4.2, §11). Since - kept heads leave that cost, moving the threshold alone does not answer it; the read's shape is - open with SN-c. + kept heads leave that cost, moving the threshold alone does not answer it; the read's shape was + open with SN-c. The shape was decided on 2026-11-11 and 2026-11-12 (D15): the read is the + contents of a cut (§4.4), which replace `heads_at`. The bar stays a tenth of a second, as a + recommendation (D30), and from SN-1b on it is tested on the contents: their columns, or their + count, past the bar on a chain under the size §4.2 gives, or kept heads costing more than the + read they save on one over. At SN-1b the corpus chain's 400,274 heads counted in 66 ms and read + as three columns in 0.22 s, over the bar on a chain over the size the measurement sets + (§4.2, §11), so the falsifier is not met. - **SNF-7 (the mask is too slow for the lexical statistics):** a lexical query at a past cut over its budget at the instance's size. Then SN-e; the rule that the statistics are the mask's does not change. @@ -2503,6 +3745,37 @@ give, and what each alternative costs is the answers it changes, which the entry history at the head holds the retired note's versions. Then the exception of §6.2 for a note that declares its identity is reopened with the owner (D3); the retire stays unsealed. +- **SNF-18 (the four forms are not enough):** an operation on one cut or on a set of cuts that + cannot be written as an apply, a combine, a map or a fold over the reads and the interface of + §5.7 without reading a store around them. Then the interface gains the member it lacked, and + D25 is reopened if the member is no function of the cut's read. +- **SNF-19 (the default is not one cut):** an answer two parts of which read different heads, or + an answer that differs when asked again with the positions it named, the grant and the + erasure unchanged. Then the binding is not once an evaluation, and SN-1b does not land until + it is. +- **SNF-20 (the two meanings are taken for one):** callers that take the contents of a `join` + where they meant a `union`, seen as a `join` followed by `held` or `count` and then the same + cuts asked again under `union`, or refusals by type that recur. Then the names change, to + D26's alternatives; both meanings stay. +- **SNF-21 (the element or the pairing is not what is asked):** uses that set aside, every time, + the paths replaced by an equal digest, or that pair every removal with an addition by + identity. Then the pairing by identity, or the comparison of digests, becomes an operation of + the engine on top of the signed difference; D31 and D32 stand for the laws. +- **SNF-22 (an operator opens a channel):** a result under a grant that changes with writes to + a class the grant does not name or with the positions named on that class's chains, or that + names such a chain. Then the operator is not a function of the reads the grant restricts, and + it does not land. A grant that tests rows inside a chain is outside this falsifier: §6.5 says + what the stamps of the rows it shows tell of the rows it hides. +- **SNF-23 (a species does not follow the node difference):** the node design's comparison of + two nodes uses a statistic of the stratum or a rank among the other nodes; or, at SN-4, the + edges of `S` at a later cut reached by the differences are not the edges computed there. Then + `S` is computed again at each cut, or the update carries the statistic; the table of §5.7 + changes and the algebra does not. +- **SNF-24 (walking the differences costs more):** on an instance's own graph, a quantity + updated over a difference under its break-even point of §5.7 takes longer than computing it + again, or its break-even point is far from §11's. Then the points are set from the instance's + measurement, and a quantity whose update never pays is computed again at each cut. + ## Open questions Each with the default the stages build on until it is decided. @@ -2518,6 +3791,15 @@ Each with the default the stages build on until it is decided. can be. - The `cuts` chain under a reset: the records name chains by id, and a reset makes new chains. Default: the records are in the catalog's file and go with it. +- A change of class writes a `leave` in one chain and the `store` in another, and no reference + of §3.5 joins the two, so a frontier can hold one without the other (§3.5). Open: whether the + `store` becomes a resolved reference of the `leave`, which needs the old chain's position + recorded on the `store`, as `att_head` records a landing's bound, and a fourth bound for SN-2's + descent to read, so that the resolver lowers a frontier holding the `store` without the + `leave`; and what an answer says of a frontier holding the `leave` without the `store`, which + no reference makes inconsistent and which shows the path in no class. Default: such a frontier + is read as asked, and the tool's note says that a cut that is neither the head nor the bottom + can split a change of class (§7.5). ## Cross-references @@ -2530,7 +3812,13 @@ Each with the default the stages build on until it is decided. `CollisionFree`, `Certificate`, `certify`, `Verifies`, and `sinceRetire`, `historyAt`, `holes`, `shown`, `landingsAt`, `retiresOf`, `lives`); `formal/Palace/Snapshot.lean` (the declarations §10 names, by law, and the twenty `Witness` controls); `formal/PalaceTest/Snapshot.lean` (seeds -430 to 528); the families cited: +430 to 528); for the algebra of cuts, `formal/Palace/SnapshotAlgebra/Defs.lean` (`Gen.event`, +`Gen.Proper`, `contentAt`, `Held` with `has`, `atoms`, `rows`, `across`, `symm`, `gone`, `come`, +`kept`, `all` and `any`, `countIn`, `Gen.isVersion`, `versionsAt`, `removedOf`, `addedOf`, +`replacedOf`, `cutsIn`, `servedCuts`, `combine`, `series`, `foldOver`), +`formal/Palace/SnapshotAlgebra.lean` (the declarations §10 names for SNP-11 to SNP-17, and six +`Witness` controls), `formal/PalaceTest/SnapshotAlgebra.lean` (seeds 529 to 566) and +`formal/Spec/SnapshotAlgebra.lean` (the 80 statements the comparator judges); the families cited: `Palace/Clock.lean` (CLK-2: `IsCut`, `frontierCut`, `isCut_iff_not_crossed`, `IsCut.inter`, `IsCut.union`, `IsCut.frontier_inf`, `IsCut.frontier_sup`), `Palace/Ingress.lean` (ING-7), `Palace/Script.lean` (ING-17), `Palace/Derived.lean` (ING-19 to ING-21), `Palace/Plane.lean` @@ -2555,12 +3843,27 @@ Each with the default the stages build on until it is decided. `ops/heartbeat.py`, `ops/ledger.py`, `ops/effect_ledger.py`, `ops/lifecycle/launcher.py`, `ops/lifecycle/runs.py`; `eval/harness/store.py`, `eval/predictions/ledger.py`. +**Code of the algebra of cuts as built (SN-1b):** `core/stores/cuts.py` (`Cut`, `Evaluation`, +`Versions`, `Events`, `Delta`, `Columns`, `read_only`), `core/stores/catalog.py` +(`VaultCatalog.cuts`), `agents/ambassador/cut_tool.py` and its registration in +`agents/ambassador/mcp.py`, `tests/property/test_cut_algebra.py`, `tests/unit/test_cut_tool.py`, +`eval/cut_algebra_bench.py`. + +**Code read for the algebra of cuts (at `8d4dff3d`, before SN-1b changed some of it):** +`core/stores/landings.py` (the tables, the indexes, and `heads_at`, then at `:603-615`, which +SN-1b removed), +`core/stores/catalog.py` (`:410-444`, the reads), `core/sentence/universe.py` (`:204-207`, +`:930-937`), `core/kernel/clearance.py` (`classes_of`), `core/query.py` (`GUEST`), +`agents/ambassador/mcp.py` (`TOOLS`, `GUEST_TOOLS`, `Server.handle`), +`tests/property/test_landing_log.py`, `eval/landing_log_bench.py`. + **Design:** global-event-clock §2.2 to §2.4 (the generators, Law C4, the certified frontier, GC-N3's three certificates); limits-of-the-algebra L7; dn-query-sentence-algebra §2.3, §2.7, §2.9; dn-ingress D1, D3, D5 (ING-7, the one writer); dn-ingress-language (ING-13 to ING-17); dn-two-phase-ingestion D1, D2 (ING-19 to ING-21); vector-membership-store A3.5, A3.7 (noninterference, the purge); -dn-utility-field §3.1, §4 (UTL-2, UTL-4) and its first open question; dn-graph-dynamics §6, §7.1 -(GD-4, the state at a cut); dn-decision-integrators (the integrators' layer); +dn-utility-field §3.1, §4 (UTL-2, UTL-4) and its first open question; dn-graph-dynamics §2.2, +§6, §7.1 (DYN-1, GD-4, the state at a cut); dn-guest-principal (the guest's grant and its +table); dn-decision-integrators (the integrators' layer); dn-mathematical-foundations §2.4 (design theorems and the ledger); `papers/2026-11-10-temporal-snapshot/paper.tex`. diff --git a/docs/experiments/cut-algebra-2026-11-13.json b/docs/experiments/cut-algebra-2026-11-13.json new file mode 100644 index 00000000..de8cef42 --- /dev/null +++ b/docs/experiments/cut-algebra-2026-11-13.json @@ -0,0 +1,1095 @@ +{ + "harness": "eval/cut_algebra_bench.py", + "harness_commit": "4e94b442", + "code_commit": "b210db03", + "baseline": "SN-1's heads_at, a Landing a head, called at the harness commit", + "machine": "Apple M2 Pro, 12 cores, 32 GB, macOS 27.0.1", + "runs": [ + { + "catalog_copy": "catalog.sqlite", + "load_start": [ + 2.60302734375, + 2.43212890625, + 2.43359375 + ], + "python": "3.15.2", + "sqlite": "3.54.1", + "numpy": "2.5.4", + "machine": "arm64", + "history": 200000, + "repeat": 5, + "batch": 10000, + "seed": 13, + "migration_s": 7.44883320806548, + "chain": 1, + "class": "observed", + "genesis": { + "position": 400276, + "heads": 400274, + "heads_at_rows": { + "median_ms": 1786.4847080782056, + "low_ms": 1759.1289579868317, + "high_ms": 1950.2384581137449, + "runs": 5, + "us_a_head": 4.463154509356604, + "under_the_bar": false + }, + "count": { + "median_ms": 66.54283311218023, + "low_ms": 66.06354098767042, + "high_ms": 66.69954187236726, + "runs": 5, + "us_a_head": 0.1662432061842144, + "under_the_bar": true + }, + "count_value": 400274, + "three_columns": { + "median_ms": 224.37670780345798, + "low_ms": 218.98995898663998, + "high_ms": 228.946290910244, + "runs": 5, + "us_a_head": 0.5605577874242593, + "under_the_bar": false + }, + "listing_columns": { + "median_ms": 432.50191607512534, + "low_ms": 423.2540000230074, + "high_ms": 456.901540979743, + "runs": 5, + "us_a_head": 1.0805146376610155, + "under_the_bar": false + }, + "columns_equal_rows": true + }, + "load_before_history": [ + 2.890625, + 2.52197265625, + 2.4658203125 + ], + "history_written": { + "new_versions": 100000, + "retires": 50000, + "new_paths": 50000 + }, + "history_s": 24.93899775017053, + "after_history": { + "position": 600276, + "heads": 400274, + "heads_at_rows": { + "median_ms": 1818.9401670824736, + "low_ms": 1760.1945418864489, + "high_ms": 1968.9878330100328, + "runs": 5, + "us_a_head": 4.54423761493995, + "under_the_bar": false + }, + "count": { + "median_ms": 89.78445804677904, + "low_ms": 89.45195795968175, + "high_ms": 91.10591607168317, + "runs": 5, + "us_a_head": 0.2243074944832266, + "under_the_bar": true + }, + "count_value": 400274, + "three_columns": { + "median_ms": 240.52354111336172, + "low_ms": 238.2343749050051, + "high_ms": 258.70395894162357, + "runs": 5, + "us_a_head": 0.6008972381752542, + "under_the_bar": false + }, + "listing_columns": { + "median_ms": 441.6287501808256, + "low_ms": 433.0394589342177, + "high_ms": 461.46362484432757, + "runs": 5, + "us_a_head": 1.103316103920878, + "under_the_bar": false + }, + "columns_equal_rows": true + }, + "deltas": [ + { + "from": 600275, + "to": 600276, + "events_between": 1, + "removed": 1, + "added": 0, + "replaced": 0, + "holes": 0, + "counts": { + "median_ms": 0.017083948478102684, + "low_ms": 0.015916069969534874, + "high_ms": 0.027708010748028755, + "runs": 5 + }, + "sizes": { + "median_ms": 0.011124880984425545, + "low_ms": 0.010458054021000862, + "high_ms": 0.05837506614625454, + "runs": 5 + }, + "come_columns": { + "median_ms": 0.01645786687731743, + "low_ms": 0.014249933883547783, + "high_ms": 0.08941697888076305, + "runs": 5 + }, + "gone_columns": { + "median_ms": 0.018916092813014984, + "low_ms": 0.01791701652109623, + "high_ms": 0.05679205060005188, + "runs": 5 + }, + "sorted": { + "median_ms": 0.08370797149837017, + "low_ms": 0.07745809853076935, + "high_ms": 0.18229195848107338, + "runs": 5 + }, + "two_heads_at_and_a_set_difference": { + "median_ms": 3727.5576249230653, + "low_ms": 3656.3079999759793, + "high_ms": 3781.5605411306024, + "runs": 5 + }, + "equal_to_the_baseline": true + }, + { + "from": 599276, + "to": 600276, + "events_between": 1000, + "removed": 248, + "added": 224, + "replaced": 528, + "holes": 0, + "counts": { + "median_ms": 2.455167006701231, + "low_ms": 2.3747498635202646, + "high_ms": 2.8732498176395893, + "runs": 5 + }, + "sizes": { + "median_ms": 1.618832815438509, + "low_ms": 1.6112499870359898, + "high_ms": 1.6752080991864204, + "runs": 5 + }, + "come_columns": { + "median_ms": 0.373166985809803, + "low_ms": 0.3684579860419035, + "high_ms": 0.4666249733418226, + "runs": 5 + }, + "gone_columns": { + "median_ms": 1.8711669836193323, + "low_ms": 1.842208905145526, + "high_ms": 1.9715831149369478, + "runs": 5 + }, + "sorted": { + "median_ms": 2.7379579842090607, + "low_ms": 2.723541809245944, + "high_ms": 2.7882501017302275, + "runs": 5 + }, + "two_heads_at_and_a_set_difference": { + "median_ms": 3741.943374974653, + "low_ms": 3696.0534169338644, + "high_ms": 3782.730499980971, + "runs": 5 + }, + "equal_to_the_baseline": true + }, + { + "from": 500276, + "to": 600276, + "events_between": 100000, + "removed": 24995, + "added": 25010, + "replaced": 49995, + "holes": 0, + "counts": { + "median_ms": 305.1412079948932, + "low_ms": 295.25108402594924, + "high_ms": 324.72920790314674, + "runs": 5 + }, + "sizes": { + "median_ms": 200.5719169974327, + "low_ms": 199.77475004270673, + "high_ms": 230.3748750127852, + "runs": 5 + }, + "come_columns": { + "median_ms": 42.745749931782484, + "low_ms": 41.90279194153845, + "high_ms": 50.592083018273115, + "runs": 5 + }, + "gone_columns": { + "median_ms": 237.75179195217788, + "low_ms": 232.64820803888142, + "high_ms": 252.7281658258289, + "runs": 5 + }, + "sorted": { + "median_ms": 361.8501250166446, + "low_ms": 344.41562509164214, + "high_ms": 374.2012910079211, + "runs": 5 + }, + "two_heads_at_and_a_set_difference": { + "median_ms": 3786.5932499989867, + "low_ms": 3694.097541971132, + "high_ms": 3870.0775001198053, + "runs": 5 + }, + "equal_to_the_baseline": true + }, + { + "from": 400276, + "to": 600276, + "events_between": 200000, + "removed": 50000, + "added": 50000, + "replaced": 100000, + "holes": 0, + "counts": { + "median_ms": 604.0303749032319, + "low_ms": 589.3915831111372, + "high_ms": 612.1919590514153, + "runs": 5 + }, + "sizes": { + "median_ms": 411.692958092317, + "low_ms": 390.57666598819196, + "high_ms": 418.9133329782635, + "runs": 5 + }, + "come_columns": { + "median_ms": 89.66729114763439, + "low_ms": 87.6938751898706, + "high_ms": 91.59979200921953, + "runs": 5 + }, + "gone_columns": { + "median_ms": 463.32320803776383, + "low_ms": 453.72474985197186, + "high_ms": 499.7913329862058, + "runs": 5 + }, + "sorted": { + "median_ms": 682.4499999638647, + "low_ms": 666.7612500023097, + "high_ms": 710.1297080516815, + "runs": 5 + }, + "two_heads_at_and_a_set_difference": { + "median_ms": 3811.7812499403954, + "low_ms": 3742.0870000496507, + "high_ms": 3879.806167213246, + "runs": 5 + }, + "equal_to_the_baseline": true + }, + { + "from": 0, + "to": 600276, + "events_between": 600276, + "removed": 0, + "added": 400274, + "replaced": 0, + "holes": 0, + "counts": { + "median_ms": 147.26729202084243, + "low_ms": 145.9038748871535, + "high_ms": 154.47312500327826, + "runs": 5 + }, + "sizes": { + "median_ms": 105.26966606266797, + "low_ms": 104.62475009262562, + "high_ms": 109.0328749269247, + "runs": 5 + }, + "come_columns": { + "median_ms": 259.78579209186137, + "low_ms": 249.77808282710612, + "high_ms": 265.4809579253197, + "runs": 5 + }, + "gone_columns": { + "median_ms": 0.007207971066236496, + "low_ms": 0.006250105798244476, + "high_ms": 0.034125056117773056, + "runs": 5 + }, + "sorted": { + "median_ms": 447.73220806382596, + "low_ms": 429.8904170282185, + "high_ms": 541.7154999449849, + "runs": 5 + }, + "two_heads_at_and_a_set_difference": { + "median_ms": 1879.1241250000894, + "low_ms": 1869.466541800648, + "high_ms": 1988.8032909948379, + "runs": 5 + }, + "equal_to_the_baseline": true + } + ], + "family": { + "positions": [ + 400276, + 422498, + 444720, + 466942, + 489164, + 511387, + 533609, + 555831, + 578053, + 600276 + ], + "counts": [ + 400274, + 400253, + 400089, + 400320, + 400192, + 400196, + 400093, + 400189, + 400126, + 400274 + ], + "walked": { + "median_ms": 486.69337504543364, + "low_ms": 462.9527919460088, + "high_ms": 507.86666688509285, + "runs": 5 + }, + "ten_counts": { + "median_ms": 833.9648330584168, + "low_ms": 809.180665994063, + "high_ms": 837.5831670127809, + "runs": 5 + }, + "walked_equals_counted": true, + "persisted": { + "median_ms": 64.05925005674362, + "low_ms": 63.68287489749491, + "high_ms": 68.79070797003806, + "runs": 5, + "count": 250274 + }, + "existed": { + "median_ms": 98.54433289729059, + "low_ms": 98.40629203245044, + "high_ms": 102.91941603645682, + "runs": 5, + "count": 550274 + }, + "pairwise": { + "median_ms": 318.7847079243511, + "low_ms": 313.70508298277855, + "high_ms": 330.7187920436263, + "runs": 5, + "sizes": [ + [ + 0, + 16679, + 33435, + 49942, + 66717, + 83377, + 100070, + 116698, + 133361, + 150000 + ], + [ + 16658, + 0, + 16756, + 33263, + 50038, + 66698, + 83391, + 100019, + 116682, + 133321 + ], + [ + 33250, + 16592, + 0, + 16507, + 33282, + 49942, + 66635, + 83263, + 99926, + 116565 + ], + [ + 49988, + 33330, + 16738, + 0, + 16775, + 33435, + 50128, + 66756, + 83419, + 100058 + ], + [ + 66635, + 49977, + 33385, + 16647, + 0, + 16660, + 33353, + 49981, + 66644, + 83283 + ], + [ + 83299, + 66641, + 50049, + 33311, + 16664, + 0, + 16693, + 33321, + 49984, + 66623 + ], + [ + 99889, + 83231, + 66639, + 49901, + 33254, + 16590, + 0, + 16628, + 33291, + 49930 + ], + [ + 116613, + 99955, + 83363, + 66625, + 49978, + 33314, + 16724, + 0, + 16663, + 33302 + ], + [ + 133213, + 116555, + 99963, + 83225, + 66578, + 49914, + 33324, + 16600, + 0, + 16639 + ], + [ + 150000, + 133342, + 116750, + 100012, + 83365, + 66701, + 50111, + 33387, + 16787, + 0 + ] + ] + }, + "pairwise_equal_to_the_differences": true, + "persisted_horizon_to_head": { + "median_ms": 66.48391718044877, + "low_ms": 63.7301669921726, + "high_ms": 72.51195795834064, + "runs": 5, + "count": 250274 + } + }, + "plans": { + "held": [ + "CO-ROUTINE (subquery-1) | SEARCH landings USING PRIMARY KEY (chain=? AND seq? AND seq? AND closed_at? AND seq? AND closed_at? AND +seq? AND +closed_at [beta b] | reach F from [depth n] [back|forward] | relate | trace | walk from [to ] via | witness \"\" | read \"\" [chunk n] (the full text; read before quoting). Connectives and, or, minus, then; adjectives within , over ; top k, atleast t, far, not; assume [+w] in (a hypothetical: the answer is a Hyp, never a fact). A is a quoted path or title. Papers: over curated. Example: top 5 (near \"sleep\" and diffuse S from \"health.md\"), the five best of the product; top k takes its field with the field's adjectives, so top 5 near \"x\" within ranks within it. The plan rides with the answer; a refusal names the word that would fix it; trace: true shows the work: the parse, every rewrite with its law, the support's census, each clause's arithmetic, the ranking.", + "description": "Read the palace by a sentence of the query algebra, not keywords. Verbs: near \"text\" | diffuse S from [beta b] | reach F from [depth n] [back|forward] | relate | trace | walk from [to ] via | witness \"\" | read \"\" [chunk n] (the full text; read before quoting). Connectives and, or, minus, then; adjectives within , over ; top k, atleast t, far, not; assume [+w] in (a hypothetical: the answer is a Hyp, never a fact). A is a quoted path or title. Papers: over curated. Example: top 5 (near \"sleep\" and diffuse S from \"health.md\"), the five best of the product; top k takes its field with the field's adjectives, so top 5 near \"x\" within ranks within it. The plan rides with the answer; a refusal names the word that would fix it; trace: true shows the work: the parse, every rewrite with its law, the support's census, each clause's arithmetic, the ranking.", "inputSchema": { "type": "object", "properties": { diff --git a/eval/cut_algebra_bench.py b/eval/cut_algebra_bench.py new file mode 100644 index 00000000..feae3755 --- /dev/null +++ b/eval/cut_algebra_bench.py @@ -0,0 +1,298 @@ +"""The algebra of cuts, measured (dn-temporal-snapshot §4.4, §11; stage SN-1b). + + uv run python -m eval.cut_algebra_bench --catalog COPY [--history 200000] [--repeat 5] + [--batch 10000] [--seed 13] [--out PATH] + +COPY is a copy of an instance's catalog file, never a live one: a copy-on-write clone of the file +with its `-wal` and `-shm` beside it (`cp -c`), which the harness migrates in place and then +writes a history into. It refuses the catalog the configuration names. The landing log's secret is +a random one made for the run and dropped with it, as SN-1's harness makes it +(`eval/landing_log_bench.py`, whose timing helpers this one uses). + +The measurements, on the copy's largest chain: + +1. **Every head.** At the head of the genesis, before any history: the read SN-1's `heads_at` + made, a row in Python a head, which the contents replaced (the harness keeps its statement as + the baseline), against the contents of the cut (`core/stores/cuts.py`): counted, which builds + no row, and read as columns, the three a head is named by (its position, its path's key, its + digest) and the eight a listing reads. The bar is SNF-6's tenth of a second. +2. **A history.** `--history` catalog writes after the genesis, landed through `record` and + `tombstone` in batches of `--batch`, in a shuffled order: a new version of a held path for half + of them, a retire of another held path for a quarter, a new path for the rest. Each appends one + row, so the history is that many positions. +3. **The signed difference.** From the head less 1, 1,000, 100,000 and the whole history, and from + the bottom, to the head: its counts (one statement), its sizes, its two sides read as columns, + and its rows sorted into removed, added and replaced; against two reads of every head as SN-1 + made them and a set difference of their rows. The two give the same rows. +4. **A family.** Ten cuts spread evenly over the history: the count at each, walked by the + differences against ten counts; what persisted through all, what existed in any, and the + sizes of the pairwise differences; and what persisted from the horizon to the head. +5. **The plans.** The statements of what a cut holds, the rows come and the rows gone, as SQLite + plans them on the copy. + +Timings are wall time on whatever else the machine is doing, medians with their ranges over +`--repeat` runs; the load average is recorded at the start, before the history and at the end, +with the versions of Python, SQLite and NumPy. +""" + +from __future__ import annotations + +import argparse +import functools +import hashlib +import json +import os +import platform +import random +import sqlite3 +import sys +import time +from collections.abc import Callable +from pathlib import Path +from typing import Any + +import numpy as np + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # repo root on path + +from core.kernel.provenance import Provenance # noqa: E402 +from core.stores.catalog import VaultCatalog # noqa: E402 +from core.stores.cuts import Cut, Evaluation, Text # noqa: E402 +from core.stores.landings import Landing # noqa: E402 +from eval.landing_log_bench import _checkpoint, _timed # noqa: E402 + +BAR_S = 0.1 # SNF-6: every head read in a tenth of a second +THREE = ("path_key", "digest") # with `seq`, which every read carries: what names a head +LISTING = ("path_key", "source_path", "doc_id", "digest", "title", "version") + + +def _ms(t: dict[str, float]) -> dict[str, float]: + return {"median_ms": t["median_us"] / 1e3, "low_ms": t["low_us"] / 1e3, + "high_ms": t["high_us"] / 1e3, "runs": t["runs"]} + + +# Every head as SN-1 read it, before the contents of a cut replaced the read: the statement of the +# removed `LandingLog.heads_at` (`core/stores/landings.py` at `8d4dff3d`), a chain at a time. +_ROWS_A_HEAD = ( + "SELECT chain, seq, kind, path_key, source_path, doc_id, version, digest, title, att_head, " + "horizon, salt, commitment, hash, closed_at, at FROM landings WHERE chain = ? AND seq <= ? " + "AND kind = 'store' AND (closed_at IS NULL OR closed_at > ?) ORDER BY seq") + + +def _rows_a_head(cat: VaultCatalog, cls: str, cut: dict[int, int]) -> list[Landing]: + """Every head of a class at a cut as SN-1's `heads_at` built it, a `Landing` in Python a row, + a hole included: the baseline the contents are measured against, kept in the harness.""" + out: list[Landing] = [] + for chain in cat.chains(cls): + pos = cut.get(chain, 0) + out.extend(Landing(*r) for r in cat._conn.execute(_ROWS_A_HEAD, [chain, pos, pos])) + return out + + +def _seqs(rows: list[Landing]) -> set[tuple[int, int]]: + """The versions among SN-1's rows, by their positions: a hole is no version.""" + return {(r.chain, r.seq) for r in rows if not r.hole} + + +def _pairs(cols: Any) -> set[tuple[int, int]]: + return set(zip(cols.ints("chain").tolist(), cols.ints("seq").tolist(), strict=True)) + + +def _plan(conn: sqlite3.Connection, run: Callable[[], object]) -> list[str]: + """How SQLite plans the statements `run` makes, one line a statement.""" + seen: list[str] = [] + conn.set_trace_callback(seen.append) + try: + run() + finally: + conn.set_trace_callback(None) + return [" | ".join(str(tuple(r)[-1]) for r in conn.execute("EXPLAIN QUERY PLAN " + q)) + for q in seen] + + +def every_head(cat: VaultCatalog, ev: Evaluation, chain: int, cls: str, + repeat: int) -> dict[str, Any]: + """Every head at the evaluation's head: SN-1's rows against the contents' count and columns.""" + head = ev.head + out: dict[str, Any] = {"position": head.at(chain)} + rows = _rows_a_head(cat, cls, head.as_dict()) + held = ev.held(head) + out["heads"] = len(rows) + out["heads_at_rows"] = {**_ms(_timed(functools.partial(_rows_a_head, cat, cls, + head.as_dict()), repeat))} + out["count"] = _ms(_timed(held.count, repeat)) + out["count_value"] = held.count() + out["three_columns"] = _ms(_timed(functools.partial(held.columns, *THREE), repeat)) + out["listing_columns"] = _ms(_timed(functools.partial(held.columns, *LISTING), repeat)) + cols = held.columns(*THREE) + keys, digests = cols["path_key"], cols["digest"] + assert isinstance(digests, Text) and not isinstance(keys, Text) + versions = [r for r in rows if not r.hole] + out["columns_equal_rows"] = ( + _pairs(cols) == _seqs(rows) + and [bytes(k.tobytes()) for k in keys] == [bytes(r.path_key or b"") for r in versions] + and [digests[i] for i in range(len(cols))] == [r.digest for r in versions]) + n = max(1, out["heads"]) + for name in ("heads_at_rows", "count", "three_columns", "listing_columns"): + out[name]["us_a_head"] = out[name]["median_ms"] * 1e3 / n + out[name]["under_the_bar"] = out[name]["median_ms"] / 1e3 <= BAR_S + return out + + +def write_history(cat: VaultCatalog, cls: str, n: int, batch: int, + rng: random.Random) -> dict[str, int]: + """`n` writes after the genesis, each appending one row: a new version of a held path for + half, a retire of another held path for a quarter, a new path for the rest, shuffled.""" + held = [str(r[0]) for r in cat._conn.execute( + "SELECT source_path FROM vault_files WHERE provenance = ? AND active = 1 " + "ORDER BY source_path", [cls])] + n_new_version, n_retire = n // 2, n // 4 + n_new_path = n - n_new_version - n_retire + chosen = rng.sample(held, n_new_version + n_retire) + titles = {str(p): str(t) for p, t in cat._conn.execute( + "SELECT source_path, title FROM vault_files WHERE provenance = ?", [cls])} + work: list[tuple[str, str]] = ( + [("version", p) for p in chosen[:n_new_version]] + + [("retire", p) for p in chosen[n_new_version:]] + + [("new", f"bench/history/{i:07}.md") for i in range(n_new_path)]) + rng.shuffle(work) + provenance = Provenance(cls) + for start in range(0, len(work), batch): + with cat.deferred(): + for i, (what, path) in enumerate(work[start:start + batch], start): + digest = hashlib.sha256(f"history {i} {path}".encode()).hexdigest() + if what == "retire": + cat.tombstone(path) + else: + cat.record(path, digest, titles.get(path, f"history {i}"), + provenance=provenance) + return {"new_versions": n_new_version, "retires": n_retire, "new_paths": n_new_path} + + +def deltas(cat: VaultCatalog, ev: Evaluation, chain: int, cls: str, spans: list[int], + repeat: int) -> list[dict[str, Any]]: + """The signed difference ending at the head, over each span, against two reads of every head + and a set difference.""" + head = ev.head.at(chain) + out = [] + for span in spans: + a, b = Cut.of({chain: max(0, head - span)}), ev.head + d = ev.delta(a, b) + entry: dict[str, Any] = {"from": a.at(chain), "to": head, + "events_between": ev.between(a, b).count()} + counts = d.counts() + entry["removed"], entry["added"], entry["replaced"] = (counts.removed, counts.added, + counts.replaced) + entry["holes"] = counts.holes + entry["counts"] = _ms(_timed(d.counts, repeat)) + entry["sizes"] = _ms(_timed(d.sizes, repeat)) + entry["come_columns"] = _ms(_timed(functools.partial(d.come.columns, *THREE), repeat)) + entry["gone_columns"] = _ms(_timed(functools.partial(d.gone.columns, *THREE), repeat)) + entry["sorted"] = _ms(_timed(functools.partial(d.sorted, *THREE), repeat)) + + def baseline(a: Cut = a, b: Cut = b) -> tuple[set[tuple[int, int]], + set[tuple[int, int]]]: + ra, rb = _seqs(_rows_a_head(cat, cls, a.as_dict())), _seqs( + _rows_a_head(cat, cls, b.as_dict())) + return ra - rb, rb - ra + + entry["two_heads_at_and_a_set_difference"] = _ms(_timed(baseline, repeat)) + gone, come = baseline() + entry["equal_to_the_baseline"] = (_pairs(d.gone.columns()) == gone + and _pairs(d.come.columns()) == come) + out.append(entry) + return out + + +def family(ev: Evaluation, chain: int, start: int, repeat: int) -> dict[str, Any]: + """Ten cuts spread evenly from `start` to the head.""" + head = ev.head.at(chain) + fam = [Cut.of({chain: start + (head - start) * i // 9}) for i in range(10)] + out: dict[str, Any] = {"positions": [c.at(chain) for c in fam]} + walked = ev.count_series(fam) + out["counts"] = list(walked.values) + out["walked"] = _ms(_timed(functools.partial(ev.count_series, fam), repeat)) + out["ten_counts"] = _ms(_timed(lambda: [ev.held(c).count() for c in fam], repeat)) + out["walked_equals_counted"] = list(walked.values) == [ev.held(c).count() for c in fam] + persisted, existed = ev.persisted(fam), ev.existed(fam) + out["persisted"] = {**_ms(_timed(persisted.count, repeat)), "count": persisted.count()} + out["existed"] = {**_ms(_timed(existed.count, repeat)), "count": existed.count()} + table = ev.pairwise(fam) + out["pairwise"] = {**_ms(_timed(functools.partial(ev.pairwise, fam), repeat)), + "sizes": [list(row) for row in table.sizes]} + out["pairwise_equal_to_the_differences"] = all( + table.sizes[i][j] == ev.delta(fam[i], fam[j]).sizes()[0] + for i in range(10) for j in range(10)) + span = [fam[0], ev.head] + kept = ev.persisted(span) + out["persisted_horizon_to_head"] = {**_ms(_timed(kept.count, repeat)), + "count": kept.count()} + return out + + +def measure(db: Path, history: int, repeat: int, batch: int, seed: int) -> dict[str, Any]: + from core.kernel.config import get_config + + if db.resolve() == Path(get_config().paths.vault_catalog).resolve(): + raise SystemExit("refusing the configured instance's own catalog: give a copy") + rng = random.Random(seed) + out: dict[str, Any] = {"catalog_copy": db.name, "load_start": os.getloadavg(), + "python": platform.python_version(), + "sqlite": sqlite3.sqlite_version, "numpy": np.__version__, + "machine": platform.machine(), "history": history, + "repeat": repeat, "batch": batch, "seed": seed} + t0 = time.perf_counter() + cat = VaultCatalog(db, key=os.urandom(32)) + out["migration_s"] = time.perf_counter() - t0 + chains = {int(c): str(k) for c, k in cat._conn.execute( + "SELECT chain, class FROM landing_chains ORDER BY chain")} + big = max(chains, key=cat.head) + cls = chains[big] + out["chain"], out["class"] = big, cls + try: + ev = cat.cuts([cls]) + horizon = ev.head.at(big) + out["genesis"] = every_head(cat, ev, big, cls, repeat) + out["load_before_history"] = os.getloadavg() + t0 = time.perf_counter() + out["history_written"] = write_history(cat, cls, history, batch, rng) + out["history_s"] = time.perf_counter() - t0 + _checkpoint(cat._conn) + ev = cat.cuts([cls]) + out["after_history"] = every_head(cat, ev, big, cls, repeat) + head = ev.head.at(big) + spans = [1, 1_000, 100_000, head - horizon, head] + out["deltas"] = deltas(cat, ev, big, cls, spans, repeat) + out["family"] = family(ev, big, horizon, repeat) + mid = Cut.of({big: head - 1_000}) + out["plans"] = { + "held": _plan(cat._conn, ev.held().count), + "come": _plan(cat._conn, ev.delta(mid).come.count), + "gone": _plan(cat._conn, ev.delta(mid).gone.count), + } + out["load_end"] = os.getloadavg() + finally: + cat.close() + return out + + +def main(argv: list[str] | None = None) -> int: + ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + ap.add_argument("--catalog", type=Path, required=True, + help="a copy of a catalog file, migrated and written in place") + ap.add_argument("--history", type=int, default=200_000) + ap.add_argument("--repeat", type=int, default=5) + ap.add_argument("--batch", type=int, default=10_000) + ap.add_argument("--seed", type=int, default=13) + ap.add_argument("--out", type=Path) + args = ap.parse_args(argv) + out = measure(args.catalog, args.history, args.repeat, args.batch, args.seed) + text = json.dumps(out, indent=2, default=str) + if args.out: + args.out.write_text(text + "\n", encoding="utf-8") + print(text) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/eval/landing_log_bench.py b/eval/landing_log_bench.py index fa6036ed..d4e6e858 100644 --- a/eval/landing_log_bench.py +++ b/eval/landing_log_bench.py @@ -25,14 +25,15 @@ alone. The first against the third is what SN-1 adds to a key's write, and the first against the second what the log's rows add. 4. **The reads.** `state_at` and `history_at` of one path, the paths drawn from the catalog; - `heads_at` at a tenth of the chain, at its middle and at its head, and the same predicate - counted in SQL, the walk without the rows built; `read_at` and + every head at a tenth of the chain, at its middle and at its head, as the contents of the cut + (`core/stores/cuts.py`, which replaced SN-1's `heads_at`): counted, the walk without a row + built, and read as three columns (the position, the path's key, the digest); `read_at` and `read_between` of a thousand positions; `head`; and the keyed hash of a path alone. Medians with their ranges over `--repeat` (a whole-class read over five). 5. **Every head of a smaller chain.** With `--fresh`, for each size a new catalog beside the copy with that many paths of one class, landed through `record` in batches, its paths and titles of - the corpus's lengths: `heads_at` at its head and the walk counted in SQL, five times each, so - the cost a head returned can be read apart from the walk. The file is removed after. + the corpus's lengths: the contents at its head counted and read as three columns, five times + each, so the cost a head returned can be read apart from the walk. The file is removed after. Timings are wall time on whatever else the machine is doing, so the load average is recorded at the start and the end, and before each fresh chain, with the versions of Python and SQLite. @@ -60,6 +61,7 @@ from core.kernel.provenance import Provenance # noqa: E402 from core.stores.catalog import VaultCatalog, _utcnow # noqa: E402 +from core.stores.cuts import Cut # noqa: E402 # The key's write as `record` made it before SN-1 (`core/stores/catalog.py` at `f969904e`): this # upsert alone, in the batch's transaction, with no read of the row before it and no log. @@ -70,6 +72,7 @@ " digest=excluded.digest, title=excluded.title," " provenance=excluded.provenance, active=1, updated_at=excluded.updated_at") ARMS = ("with", "without", "before") # record as built; its log rows off; the write before SN-1 +_THREE = ("path_key", "digest") # with the position, which every read of rows carries def _files(db: Path) -> dict[str, int]: @@ -104,10 +107,6 @@ def _timed(fn: Callable[[], Any], n: int) -> dict[str, float]: "runs": n} -def _count(conn: sqlite3.Connection, sql: str, args: list[int]) -> int: - return int(conn.execute(sql, args).fetchone()[0]) - - def _fold(cat: VaultCatalog) -> dict[str, tuple[str, str, str, bool, str]]: """The catalog the log gives: each path's last event in the chain where it is not a `leave`, an active row for a `store`, a tombstoned one with its last `store`'s digest and title for a @@ -174,8 +173,9 @@ def _batch(cat: VaultCatalog, records: list[tuple[str, str, str, Provenance]], def _fresh_heads(where: Path, n: int, key: bytes, batch: int) -> dict[str, Any]: """A new catalog of `n` paths of one class, landed through `record` in batches, its paths and - titles about the corpus's lengths (28.6 and 63.8 characters): every head at its head, and the - walk counted in SQL, five times each. The file is removed after.""" + titles about the corpus's lengths (28.6 and 63.8 characters): every head at its head, the + contents of the cut counted and read as three columns, five times each. The file is removed + after.""" db = where / f"fresh-{n}.sqlite" for suffix in ("", "-wal", "-shm"): Path(f"{db}{suffix}").unlink(missing_ok=True) @@ -189,15 +189,13 @@ def _fresh_heads(where: Path, n: int, key: bytes, batch: int) -> dict[str, Any]: f"{'t' * 56} {i:07}", provenance=Provenance.OBSERVED) (chain,) = cat.chains(Provenance.OBSERVED) head = cat.head(chain) - cut = {chain: head} + held = cat.cuts([Provenance.OBSERVED]).held() out["chain_rows"] = head - out["heads_at"] = {**_timed(functools.partial(cat.heads_at, Provenance.OBSERVED, cut), 5), - "rows": len(cat.heads_at(Provenance.OBSERVED, cut))} - out["heads_walk"] = _timed(functools.partial( - _count, cat._conn, "SELECT count(*) FROM landings WHERE chain = ? AND seq <= ? AND " - "kind = 'store' AND (closed_at IS NULL OR closed_at > ?)", [chain, head, head]), 5) - past = out["heads_at"]["median_us"] - out["heads_walk"]["median_us"] - out["us_a_head_past_the_walk"] = past / out["heads_at"]["rows"] + out["heads_columns"] = {**_timed(functools.partial(held.columns, *_THREE), 5), + "rows": held.count()} + out["heads_count"] = _timed(held.count, 5) + past = out["heads_columns"]["median_us"] - out["heads_count"]["median_us"] + out["us_a_head_past_the_walk"] = past / max(1, out["heads_columns"]["rows"]) finally: cat.close() for suffix in ("", "-wal", "-shm"): @@ -280,15 +278,13 @@ def measure(db: Path, batch: int, rounds: int, repeat: int, seed: int, repeat) reads["read_at_1000"] = _timed(lambda: cat.read_at(big, 1000), repeat) reads["head"] = _timed(lambda: cat.head(big), repeat) - walk = ("SELECT count(*) FROM landings WHERE chain = ? AND seq <= ? AND kind = 'store' " - "AND (closed_at IS NULL OR closed_at > ?)") - for name, c in (("heads_at_tenth", head // 10), ("heads_at_mid", mid), ("heads_at_head", head)): - cut = {big: c} - reads[name] = {**_timed(functools.partial(cat.heads_at, cls, cut), 5), - "rows": len(cat.heads_at(cls, cut))} - # the same predicate counted in SQL: the walk alone, without building the rows - reads[name.replace("heads_at", "heads_walk")] = _timed( - functools.partial(_count, cat._conn, walk, [big, c, c]), 5) + ev = cat.cuts([cls]) + for name, c in (("tenth", head // 10), ("mid", mid), ("head", head)): + contents = ev.held(Cut.of({big: c})) + # every head as the contents of the cut: counted, the walk without a row built, and read + # as three columns, one buffer a column + reads[f"heads_count_{name}"] = {**_timed(contents.count, 5), "rows": contents.count()} + reads[f"heads_columns_{name}"] = _timed(functools.partial(contents.columns, *_THREE), 5) out["reads"] = reads # the write overhead: new paths, then new versions of held paths, by each arm in turn diff --git a/formal/Palace.lean b/formal/Palace.lean index a1a28363..3af0833c 100644 --- a/formal/Palace.lean +++ b/formal/Palace.lean @@ -67,6 +67,8 @@ public import Palace.SigmaStar public import Palace.SigmaStar.Defs public import Palace.Snapshot public import Palace.Snapshot.Defs +public import Palace.SnapshotAlgebra +public import Palace.SnapshotAlgebra.Defs public import Palace.Spectral public import Palace.Spectral.Defs public import Palace.Superconnection diff --git a/formal/Palace/SnapshotAlgebra.lean b/formal/Palace/SnapshotAlgebra.lean new file mode 100644 index 00000000..add8f3df --- /dev/null +++ b/formal/Palace/SnapshotAlgebra.lean @@ -0,0 +1,1252 @@ +module + +public import Palace.SnapshotAlgebra.Defs +public import Palace.Snapshot + +/-! +# The algebra of cuts + +The laws of dn-temporal-snapshot §4.4, on the model of `Palace/SnapshotAlgebra/Defs.lean`: a cut +as a value that stands for what the store held as of it, the operators on its positions, and the +operators on its contents, the rows of the generational store (`gens`) alive at it. SNP-11 to +SNP-17 are the ledger's (`docs/LAWS.md`, XVI): each declaration a row cites carries its law in +bold and is stated in `formal/Spec/SnapshotAlgebra.lean`. + +* SNP-11, the lattice of cuts: the cuts inside a store are a distributive lattice under the + pointwise meet and join, with the empty cut at the bottom and the head at the top, and no cut + leaves it as the store grows (`cutsIn`, `bot_mem_cutsIn`, `head_mem_cutsIn`, `cutsIn_mono`, + `readAt_inf_sup`). The read at the join is, chain by chain, the later of the two reads, and at + the meet the earlier (`readAt_sup`, `readAt_inf`). The difference of two cuts on positions is + the events between them, read from their meet or to their join, and the symmetric difference + the events between their meet and their join (`readBetween_inf_left`, `readBetween_sup_right`, + `readBetween_inf_sup`); it is a function of the two reads (`readBetween_eq_combine`). The meet + and the join of two cuts that are read as asked are read as asked, the consistency by CLK-2 + (`resolvesIn_sup`, `resolvesIn_inf`). +* SNP-12, a row lives on an interval: a row is alive from its position up to its closing stamp + (`Gen.aliveAt_iff`), so a row alive at two cuts is alive at every cut between them + (`Gen.aliveAt_of_between`). What the later of two cuts holds and the earlier does not, what + the earlier holds and the later does not and what both hold are each one range of positions + and stamps (`Gen.aliveAt_and_not`, `Gen.aliveAt_and_not'`, `Gen.aliveAt_and`); a row is alive + at every cut of a family exactly when it is alive at the least and at the greatest + (`Gen.forall_aliveAt_iff`), and at some cut of a range exactly when it was stored by its end + and not closed by its start (`Gen.exists_aliveAt_iff`). On the generations of a chain a row + records the chain's event at its position, its stamp is the position of its key's next event, + and a cut holds each key's state once (`getElem?_of_mem_gens`, `exists_next_of_mem_gens`, + `proper_of_mem_gens`, `map_val_filter_key_contentAt`, `eq_of_key_eq_of_mem_contentAt`). The + control is a value, which has no interval (`Witness.value_not_contiguous`). +* SNP-13, the signed difference: its two sides are range reads (`Held.has_come`, + `Held.has_gone`); applied to what the first cut holds it gives what the second holds + (`Held.has_cut_eq_apply`); differences compose along cuts in order, a row that came and went + on the way cancelling, and a row gone across two steps is gone in one of them + (`Held.has_come_trans`, `Held.has_gone_trans`, `Held.has_trans_of_transient`, + `Held.has_gone_triangle`); a sum over the rows, a count among them, walks the difference + (`Held.sum_rows_delta`, `Held.length_rows_delta`); its rows sort by key into removed, added + and replaced (`mem_gone_iff`, `not_replacedOf_of_removedOf`, `mem_come_iff`); and every row + of it belongs to a key the events between the two cuts name (`key_mem_of_mem_delta`). The + controls: a composition through a cut outside the two, and a key the events name that the + difference does not hold (`Witness.delta_through_outside`, `Witness.changed_not_delta`). +* SNP-14, closure: a set of rows is an expression over the contents of cuts, closed under + union, intersection and difference, and a set read is the set operation on the reads + (`Held.mem_rows_union`, `Held.mem_rows_inter`, `Held.mem_rows_diff`, `Held.has_symm`, + `Held.has_inter_union`, `Held.has_diff_diff`). Whether a row is in a set is a function of its + position and its stamp (`Held.has_eq_of_interval`); a set lies inside the contents of the cuts + it names (`Held.exists_atom_of_has`); a row's own test commutes with it (`Held.rows_filter`); + and it is append invariant, a derived view of the read at its cuts (`Held.rows_gens_append`, + `Held.rows_gens_take`). What every cut of a family holds is what its least and greatest cuts + both hold, one range read (`Held.has_all`, `Held.has_all_eq_kept`, `Held.has_kept`), what + some cut holds and in how many are read off the same intervals (`Held.has_any`, + `countIn_pos_iff`, `countIn_eq_length_iff`), and a function of two reads, a measure at each + cut and a fold over a family are append invariant (`combine_grow`, `series_grow`, + `foldOver_grow`). The control is the complement, which grows with the store + (`Witness.complement_grows`). +* SNP-15, contents against positions: what either of two cuts holds is what their join holds + with the rows closed between their meet and their join, and what both hold is what their meet + and their join both hold (`Gen.aliveAt_or_eq_sup`, `Gen.aliveAt_and_eq_inf_sup`, + `Held.has_union_cut`, `Held.has_inter_cut`); for a row that is never closed the two meanings + agree (`Gen.aliveAt_sup_of_open`, `Gen.aliveAt_inf_of_open`). The control is one key written + twice (`Witness.union_ne_join`). +* SNP-16, the grant: every set commutes with the grant's restriction, reads only the chains + the grant names and the cuts' positions on them, is under a narrower grant the restriction of + a wider grant's, and names no other chain (`Held.across_restrict`, `Held.across_congr`, + `restrict_narrow`, `Held.across_narrow`, `Held.across_of_not`); the events between two cuts + commute with a grant of whole chains (`restrict_readBetween`). The control is a row's test + applied before the generations are computed (`Witness.filter_before_gens`). +* SNP-17, erasure and retire: the closing stamps are a function of the keys alone, so a hole + that keeps its key moves no position and no stamp (`gens_map`); no row of a chain with holes + carries an erased value, and an erasure takes its own rows out of every set and changes no + other (`not_erased_of_mem_gens_holes`, `Held.rows_gens_holes`); a retire is a removal in the + signed difference that spans it (`removed_of_retire`). +-/ + +@[expose] public section + +namespace Palace.Snapshot + +/-! ### A row lives on an interval -/ + +section Interval + +variable {κ β : Type*} + +/-- **SNP-12** A row is alive at a cut from its position up to, and not at, its closing stamp. -/ +theorem Gen.aliveAt_iff {r : Gen κ β} {c : ℕ} : + r.aliveAt c = true ↔ r.born ≤ c ∧ ∀ d, r.died = some d → c < d := by + unfold Gen.aliveAt + cases r.died with + | none => simp + | some d => simp + +/-- A row is not alive at a cut before its position, and from its closing stamp on. -/ +theorem Gen.aliveAt_eq_false_iff {r : Gen κ β} {c : ℕ} : + r.aliveAt c = false ↔ c < r.born ∨ ∃ d, r.died = some d ∧ d ≤ c := by + unfold Gen.aliveAt + cases r.died with + | none => simp + | some d => simp; omega + +/-- **SNP-12** Contiguity: a row alive at two cuts is alive at every cut between them. A row lives +on one interval of its chain's positions. -/ +theorem Gen.aliveAt_of_between {r : Gen κ β} {a b c : ℕ} (ha : r.aliveAt a = true) + (hb : r.aliveAt b = true) (hac : a ≤ c) (hcb : c ≤ b) : r.aliveAt c = true := by + rw [Gen.aliveAt_iff] at ha hb ⊢ + exact ⟨ha.1.trans hac, fun d hd ↦ lt_of_le_of_lt hcb (hb.2 d hd)⟩ + +/-- **SNP-12** What the later of two cuts holds and the earlier does not: the rows stored after the +earlier cut and alive at the later one. -/ +theorem Gen.aliveAt_and_not {r : Gen κ β} {a b : ℕ} (h : a ≤ b) : + (r.aliveAt b && !r.aliveAt a) = (decide (a < r.born) && r.aliveAt b) := by + unfold Gen.aliveAt + rw [Bool.eq_iff_iff] + cases r.died <;> simp <;> omega + +/-- **SNP-12** What the earlier of two cuts holds and the later does not: the rows alive at the +earlier cut whose closing stamp is at or under the later one. -/ +theorem Gen.aliveAt_and_not' {r : Gen κ β} {a b : ℕ} (h : a ≤ b) : + (r.aliveAt a && !r.aliveAt b) = (r.aliveAt a && r.died.any fun d ↦ decide (d ≤ b)) := by + unfold Gen.aliveAt + rw [Bool.eq_iff_iff] + cases r.died <;> simp <;> omega + +/-- **SNP-12** What two cuts both hold: the rows stored at or under the earlier cut whose closing +stamp is absent or past the later one. -/ +theorem Gen.aliveAt_and {r : Gen κ β} {a b : ℕ} (h : a ≤ b) : + (r.aliveAt a && r.aliveAt b) + = (decide (r.born ≤ a) && r.died.all fun d ↦ decide (b < d)) := by + unfold Gen.aliveAt + rw [Bool.eq_iff_iff] + cases r.died <;> simp <;> omega + +/-- **SNP-12** A row is alive at every cut of a family exactly when it is alive at the family's +least cut and at its greatest. -/ +theorem Gen.forall_aliveAt_iff {r : Gen κ β} {F : List ℕ} {lo hi : ℕ} (hlo : lo ∈ F) + (hhi : hi ∈ F) (hF : ∀ c ∈ F, lo ≤ c ∧ c ≤ hi) : + (∀ c ∈ F, r.aliveAt c = true) ↔ r.aliveAt lo = true ∧ r.aliveAt hi = true := + ⟨fun h ↦ ⟨h lo hlo, h hi hhi⟩, + fun h c hc ↦ Gen.aliveAt_of_between h.1 h.2 (hF c hc).1 (hF c hc).2⟩ + +/-- **SNP-12** A well-formed row is alive at some cut of a range of positions exactly when it was +stored at or under the range's end and not closed at or under its start. -/ +theorem Gen.exists_aliveAt_iff {r : Gen κ β} (hr : r.Proper) {lo hi : ℕ} (h : lo ≤ hi) : + (∃ c, lo ≤ c ∧ c ≤ hi ∧ r.aliveAt c = true) + ↔ r.born ≤ hi ∧ ∀ d, r.died = some d → lo < d := by + constructor + · rintro ⟨c, hlo, hhi, hc⟩ + rw [Gen.aliveAt_iff] at hc + exact ⟨hc.1.trans hhi, fun d hd ↦ lt_of_le_of_lt hlo (hc.2 d hd)⟩ + · rintro ⟨hb, hd⟩ + refine ⟨max r.born lo, le_max_right _ _, max_le hb h, ?_⟩ + rw [Gen.aliveAt_iff] + exact ⟨le_max_left _ _, fun d hdd ↦ max_lt (hr d hdd) (hd d hdd)⟩ + +/-- **SNP-15** What two cuts both hold is what their meet and their join both hold. -/ +theorem Gen.aliveAt_and_eq_inf_sup (r : Gen κ β) (a b : ℕ) : + (r.aliveAt a && r.aliveAt b) = (r.aliveAt (a ⊓ b) && r.aliveAt (a ⊔ b)) := by + rcases le_total a b with h | h + · rw [inf_of_le_left h, sup_of_le_right h] + · rw [inf_of_le_right h, sup_of_le_left h, Bool.and_comm] + +/-- **SNP-15** What either of two cuts holds is what their join holds and what was closed between +their meet and their join. -/ +theorem Gen.aliveAt_or_eq_sup (r : Gen κ β) (a b : ℕ) : + (r.aliveAt a || r.aliveAt b) + = (r.aliveAt (a ⊔ b) || (r.aliveAt (a ⊓ b) && !r.aliveAt (a ⊔ b))) := by + rcases le_total a b with h | h + · rw [inf_of_le_left h, sup_of_le_right h] + cases r.aliveAt a <;> cases r.aliveAt b <;> rfl + · rw [inf_of_le_right h, sup_of_le_left h] + cases r.aliveAt a <;> cases r.aliveAt b <;> rfl + +/-- **SNP-15** A row that is never closed is alive at the join of two cuts exactly when it is alive +at one of them. -/ +theorem Gen.aliveAt_sup_of_open {r : Gen κ β} (hr : r.died = none) (a b : ℕ) : + r.aliveAt (a ⊔ b) = (r.aliveAt a || r.aliveAt b) := by + rcases le_total a b with h | h + · rw [sup_of_le_right h] + unfold Gen.aliveAt + rw [Bool.eq_iff_iff, hr] + simp + omega + · rw [sup_of_le_left h] + unfold Gen.aliveAt + rw [Bool.eq_iff_iff, hr] + simp + omega + +/-- **SNP-15** And at their meet exactly when it is alive at both. -/ +theorem Gen.aliveAt_inf_of_open {r : Gen κ β} (hr : r.died = none) (a b : ℕ) : + r.aliveAt (a ⊓ b) = (r.aliveAt a && r.aliveAt b) := by + rcases le_total a b with h | h + · rw [inf_of_le_left h] + unfold Gen.aliveAt + rw [Bool.eq_iff_iff, hr] + simp + omega + · rw [inf_of_le_right h] + unfold Gen.aliveAt + rw [Bool.eq_iff_iff, hr] + simp + omega + +end Interval + +/-! ### Sets of rows, named and not read -/ + +section Expressions + +variable {κ β γ : Type*} {pos : γ → ℕ} + +namespace Held + +theorem rows_cut (c : γ) (rs : List (Gen κ β)) : (cut c).rows pos rs = contentAt rs (pos c) := + rfl + +/-- A set read on a chain is a sublist of the chain's rows. -/ +theorem rows_sublist (e : Held γ) (rs : List (Gen κ β)) : (e.rows pos rs).Sublist rs := + List.filter_sublist + +/-- **SNP-14** The union read is the union of the reads. -/ +theorem mem_rows_union {p q : Held γ} {rs : List (Gen κ β)} {r : Gen κ β} : + r ∈ (p.union q).rows pos rs ↔ r ∈ p.rows pos rs ∨ r ∈ q.rows pos rs := by + simp only [rows, has, List.mem_filter, Bool.or_eq_true, and_or_left] + +/-- **SNP-14** The intersection read is the intersection of the reads. -/ +theorem mem_rows_inter {p q : Held γ} {rs : List (Gen κ β)} {r : Gen κ β} : + r ∈ (p.inter q).rows pos rs ↔ r ∈ p.rows pos rs ∧ r ∈ q.rows pos rs := by + simp only [rows, has, List.mem_filter, Bool.and_eq_true] + tauto + +/-- **SNP-14** The difference read is the difference of the reads. -/ +theorem mem_rows_diff {p q : Held γ} {rs : List (Gen κ β)} {r : Gen κ β} : + r ∈ (p.diff q).rows pos rs ↔ r ∈ p.rows pos rs ∧ r ∉ q.rows pos rs := by + simp only [rows, has, List.mem_filter, Bool.and_eq_true, Bool.not_eq_true', not_and, + Bool.not_eq_true] + tauto + +/-- **SNP-14** What exactly one of two sets holds is what either holds and not both. -/ +theorem has_symm (p q : Held γ) (r : Gen κ β) : + (symm p q).has pos r = ((p.union q).diff (p.inter q)).has pos r := by + simp only [symm, has] + cases p.has pos r <;> cases q.has pos r <;> rfl + +theorem has_union_comm (p q : Held γ) (r : Gen κ β) : + (p.union q).has pos r = (q.union p).has pos r := + Bool.or_comm _ _ + +theorem has_inter_comm (p q : Held γ) (r : Gen κ β) : + (p.inter q).has pos r = (q.inter p).has pos r := + Bool.and_comm _ _ + +theorem has_union_assoc (p q t : Held γ) (r : Gen κ β) : + ((p.union q).union t).has pos r = (p.union (q.union t)).has pos r := + Bool.or_assoc _ _ _ + +theorem has_inter_assoc (p q t : Held γ) (r : Gen κ β) : + ((p.inter q).inter t).has pos r = (p.inter (q.inter t)).has pos r := + Bool.and_assoc _ _ _ + +theorem has_union_self (p : Held γ) (r : Gen κ β) : (p.union p).has pos r = p.has pos r := + Bool.or_self _ + +theorem has_inter_self (p : Held γ) (r : Gen κ β) : (p.inter p).has pos r = p.has pos r := + Bool.and_self _ + +/-- Absorption: a set united with its intersection with another is itself. -/ +theorem has_union_inter_self (p q : Held γ) (r : Gen κ β) : + (p.union (p.inter q)).has pos r = p.has pos r := by + simp only [has] + cases p.has pos r <;> cases q.has pos r <;> rfl + +/-- Absorption: a set intersected with its union with another is itself. -/ +theorem has_inter_union_self (p q : Held γ) (r : Gen κ β) : + (p.inter (p.union q)).has pos r = p.has pos r := by + simp only [has] + cases p.has pos r <;> cases q.has pos r <;> rfl + +/-- **SNP-14** Intersection distributes over union. -/ +theorem has_inter_union (p q t : Held γ) (r : Gen κ β) : + (p.inter (q.union t)).has pos r = ((p.inter q).union (p.inter t)).has pos r := by + simp only [has] + cases p.has pos r <;> cases q.has pos r <;> cases t.has pos r <;> rfl + +/-- Union distributes over intersection. -/ +theorem has_union_inter (p q t : Held γ) (r : Gen κ β) : + (p.union (q.inter t)).has pos r = ((p.union q).inter (p.union t)).has pos r := by + simp only [has] + cases p.has pos r <;> cases q.has pos r <;> cases t.has pos r <;> rfl + +/-- A set less itself holds nothing. -/ +theorem has_diff_self (p : Held γ) (r : Gen κ β) : (p.diff p).has pos r = false := + Bool.and_not_self _ + +/-- **SNP-14** A set less what it holds and another does not is what both hold. -/ +theorem has_diff_diff (p q : Held γ) (r : Gen κ β) : + (p.diff (p.diff q)).has pos r = (p.inter q).has pos r := by + simp only [has] + cases p.has pos r <;> cases q.has pos r <;> rfl + +/-- A difference distributes over the union it is taken from. -/ +theorem has_union_diff (p q t : Held γ) (r : Gen κ β) : + ((p.union q).diff t).has pos r = ((p.diff t).union (q.diff t)).has pos r := by + simp only [has] + cases p.has pos r <;> cases q.has pos r <;> cases t.has pos r <;> rfl + +/-- A set reads of the cuts it names only their positions: two readings of the positions that +agree on its cuts give one set. -/ +theorem has_congr {pos' : γ → ℕ} {e : Held γ} (h : ∀ c ∈ e.atoms, pos c = pos' c) + (r : Gen κ β) : e.has pos r = e.has pos' r := by + induction e with + | cut c => simp only [has, h c (by simp [atoms])] + | union p q ihp ihq => + simp only [has, ihp fun c hc ↦ h c (by simp [atoms, hc]), + ihq fun c hc ↦ h c (by simp [atoms, hc])] + | inter p q ihp ihq => + simp only [has, ihp fun c hc ↦ h c (by simp [atoms, hc]), + ihq fun c hc ↦ h c (by simp [atoms, hc])] + | diff p q ihp ihq => + simp only [has, ihp fun c hc ↦ h c (by simp [atoms, hc]), + ihq fun c hc ↦ h c (by simp [atoms, hc])] + +/-- **SNP-14** Whether a row is in a set is a function of the row's position and its closing stamp: +two rows with one interval, whatever their keys and values, are in the same sets. Combining sets +reads no row. -/ +theorem has_eq_of_interval {κ' β' : Type*} (e : Held γ) {r : Gen κ β} {r' : Gen κ' β'} + (hb : r.born = r'.born) (hd : r.died = r'.died) : e.has pos r = e.has pos r' := by + induction e with + | cut c => simp only [has, Gen.aliveAt, hb, hd] + | union p q ihp ihq => simp only [has, ihp, ihq] + | inter p q ihp ihq => simp only [has, ihp, ihq] + | diff p q ihp ihq => simp only [has, ihp, ihq] + +/-- **SNP-14** A set lies inside the contents of the cuts it names: a row in it is alive at one of +them. There is no complement. -/ +theorem exists_atom_of_has {e : Held γ} {r : Gen κ β} (h : e.has pos r = true) : + ∃ c ∈ e.atoms, r.aliveAt (pos c) = true := by + induction e with + | cut c => exact ⟨c, by simp [atoms], h⟩ + | union p q ihp ihq => + rcases Bool.or_eq_true_iff.1 h with h | h + · obtain ⟨c, hc, ha⟩ := ihp h + exact ⟨c, by simp [atoms, hc], ha⟩ + · obtain ⟨c, hc, ha⟩ := ihq h + exact ⟨c, by simp [atoms, hc], ha⟩ + | inter p q ihp _ => + obtain ⟨c, hc, ha⟩ := ihp (Bool.and_eq_true_iff.1 h).1 + exact ⟨c, by simp [atoms, hc], ha⟩ + | diff p q ihp _ => + obtain ⟨c, hc, ha⟩ := ihp (Bool.and_eq_true_iff.1 h).1 + exact ⟨c, by simp [atoms, hc], ha⟩ + +/-- A closing stamp written past every cut a set names changes nothing in the set: a row that +was open, and is closed later at a position past those cuts, is in the set exactly when it +was. -/ +theorem has_of_closed_later {e : Held γ} {r r' : Gen κ β} (hb : r'.born = r.born) + (hd : r'.died = r.died ∨ (r.died = none ∧ ∃ d, r'.died = some d ∧ ∀ c ∈ e.atoms, pos c < d)) : + e.has pos r' = e.has pos r := by + induction e with + | cut c => + rcases hd with hd | ⟨hn, d, hd, hlt⟩ + · simp only [has, Gen.aliveAt, hb, hd] + · have hc : pos c < d := hlt c (by simp [atoms]) + simp [has, Gen.aliveAt, hb, hd, hn, hc] + | union p q ihp ihq => + simp only [has, ihp (hd.imp_right fun ⟨hn, d, h1, h2⟩ ↦ ⟨hn, d, h1, fun c hc ↦ + h2 c (by simp [atoms, hc])⟩), ihq (hd.imp_right fun ⟨hn, d, h1, h2⟩ ↦ ⟨hn, d, h1, + fun c hc ↦ h2 c (by simp [atoms, hc])⟩)] + | inter p q ihp ihq => + simp only [has, ihp (hd.imp_right fun ⟨hn, d, h1, h2⟩ ↦ ⟨hn, d, h1, fun c hc ↦ + h2 c (by simp [atoms, hc])⟩), ihq (hd.imp_right fun ⟨hn, d, h1, h2⟩ ↦ ⟨hn, d, h1, + fun c hc ↦ h2 c (by simp [atoms, hc])⟩)] + | diff p q ihp ihq => + simp only [has, ihp (hd.imp_right fun ⟨hn, d, h1, h2⟩ ↦ ⟨hn, d, h1, fun c hc ↦ + h2 c (by simp [atoms, hc])⟩), ihq (hd.imp_right fun ⟨hn, d, h1, h2⟩ ↦ ⟨hn, d, h1, + fun c hc ↦ h2 c (by simp [atoms, hc])⟩)] + +/-- **SNP-14** A row's own test, one that does not depend on a cut, commutes with every set: the +rows of a set that pass the test are the set read on the rows that pass it. -/ +theorem rows_filter (e : Held γ) (p : Gen κ β → Bool) (rs : List (Gen κ β)) : + (e.rows pos rs).filter p = e.rows pos (rs.filter p) := by + simp only [rows, List.filter_filter] + exact List.filter_congr fun r _ ↦ Bool.and_comm _ _ + +end Held + +end Expressions + +/-! ### The signed difference of two cuts, and a family of cuts -/ + +section Delta + +variable {κ β γ : Type*} {pos : γ → ℕ} + +namespace Held + +/-- The two sides of a signed difference exchange when the two cuts do. -/ +theorem gone_swap (a b : γ) : gone b a = come a b := rfl + +/-- A cut differs from itself by nothing. -/ +theorem has_gone_self (a : γ) (r : Gen κ β) : (gone a a).has pos r = false := + Bool.and_not_self _ + +/-- **SNP-13** What the later cut holds and the earlier does not, as one range read: the rows stored +after the earlier cut and alive at the later one. -/ +theorem has_come {a b : γ} (h : pos a ≤ pos b) (r : Gen κ β) : + (come a b).has pos r = (decide (pos a < r.born) && r.aliveAt (pos b)) := + Gen.aliveAt_and_not h + +/-- **SNP-13** What the earlier cut holds and the later does not, as one range read: the rows alive +at the earlier cut whose closing stamp is at or under the later one. -/ +theorem has_gone {a b : γ} (h : pos a ≤ pos b) (r : Gen κ β) : + (gone a b).has pos r = (r.aliveAt (pos a) && r.died.any fun d ↦ decide (d ≤ pos b)) := + Gen.aliveAt_and_not' h + +/-- **SNP-14** What both cuts hold, as one range read: the rows stored at or under the earlier cut +and not closed at or under the later one. -/ +theorem has_kept {a b : γ} (h : pos a ≤ pos b) (r : Gen κ β) : + (kept a b).has pos r + = (decide (r.born ≤ pos a) && r.died.all fun d ↦ decide (pos b < d)) := + Gen.aliveAt_and h + +/-- **SNP-13** The signed difference applied: what the second cut holds is what the first holds, +less the rows gone, with the rows come. The result of a difference is an operand again. -/ +theorem has_cut_eq_apply (a b : γ) (r : Gen κ β) : + (cut b).has pos r = (((cut a).diff (gone a b)).union (come a b)).has pos r := by + simp only [gone, come, has] + cases r.aliveAt (pos a) <;> cases r.aliveAt (pos b) <;> rfl + +/-- **SNP-13** Signed differences compose along cuts in order: the rows come from `a` to `c` are the +rows come from `a` to `b` that did not go from `b` to `c`, with the rows come from `b` to `c`. It +holds when `b` lies between `a` and `c` on the chain, in either direction. -/ +theorem has_come_trans {a b c : γ} + (h : (pos a ≤ pos b ∧ pos b ≤ pos c) ∨ (pos c ≤ pos b ∧ pos b ≤ pos a)) (r : Gen κ β) : + (come a c).has pos r = (((come a b).diff (gone b c)).union (come b c)).has pos r := by + have hB : r.aliveAt (pos a) = true → r.aliveAt (pos c) = true → r.aliveAt (pos b) = true := by + intro ha hc + rcases h with h | h + · exact Gen.aliveAt_of_between ha hc h.1 h.2 + · exact Gen.aliveAt_of_between hc ha h.1 h.2 + revert hB + simp only [gone, come, has] + generalize r.aliveAt (pos a) = A + generalize r.aliveAt (pos b) = B + generalize r.aliveAt (pos c) = C + intro hB + cases A <;> cases B <;> cases C <;> + first | rfl | exact absurd (hB rfl rfl) Bool.false_ne_true + +/-- **SNP-13** And the rows gone from `a` to `c` are the rows gone from `a` to `b`, with the rows +gone from `b` to `c` that had not come from `a` to `b`. -/ +theorem has_gone_trans {a b c : γ} + (h : (pos a ≤ pos b ∧ pos b ≤ pos c) ∨ (pos c ≤ pos b ∧ pos b ≤ pos a)) (r : Gen κ β) : + (gone a c).has pos r = ((gone a b).union ((gone b c).diff (come a b))).has pos r := by + have hB : r.aliveAt (pos a) = true → r.aliveAt (pos c) = true → r.aliveAt (pos b) = true := by + intro ha hc + rcases h with h | h + · exact Gen.aliveAt_of_between ha hc h.1 h.2 + · exact Gen.aliveAt_of_between hc ha h.1 h.2 + revert hB + simp only [gone, come, has] + generalize r.aliveAt (pos a) = A + generalize r.aliveAt (pos b) = B + generalize r.aliveAt (pos c) = C + intro hB + cases A <;> cases B <;> cases C <;> + first | rfl | exact absurd (hB rfl rfl) Bool.false_ne_true + +/-- **SNP-13** A row that came between `a` and `b` and went between `b` and `c` is on neither side +of the difference from `a` to `c`: what a composition cancels. -/ +theorem has_trans_of_transient {a b c : γ} {r : Gen κ β} (h1 : (come a b).has pos r = true) + (h2 : (gone b c).has pos r = true) : + (come a c).has pos r = false ∧ (gone a c).has pos r = false := by + revert h1 h2 + simp only [gone, come, has] + cases r.aliveAt (pos a) <;> cases r.aliveAt (pos b) <;> cases r.aliveAt (pos c) <;> simp + +/-- **SNP-13** A row gone from `a` to `c` is gone from `a` to `b` or from `b` to `c`, whatever `b`: +the inclusion the triangle inequality of the differences' sizes follows from. -/ +theorem has_gone_triangle (a b c : γ) {r : Gen κ β} (h : (gone a c).has pos r = true) : + (gone a b).has pos r = true ∨ (gone b c).has pos r = true := by + revert h + simp only [gone, has] + cases r.aliveAt (pos a) <;> cases r.aliveAt (pos b) <;> cases r.aliveAt (pos c) <;> simp + +theorem has_foldl_inter (F : List γ) (e : Held γ) (r : Gen κ β) : + (F.foldl (fun e d ↦ inter e (cut d)) e).has pos r = true + ↔ e.has pos r = true ∧ ∀ d ∈ F, r.aliveAt (pos d) = true := by + induction F generalizing e with + | nil => simp + | cons d F ih => + rw [List.foldl_cons, ih] + simp only [has, Bool.and_eq_true, List.forall_mem_cons, and_assoc] + +theorem has_foldl_union (F : List γ) (e : Held γ) (r : Gen κ β) : + (F.foldl (fun e d ↦ union e (cut d)) e).has pos r = true + ↔ e.has pos r = true ∨ ∃ d ∈ F, r.aliveAt (pos d) = true := by + induction F generalizing e with + | nil => simp + | cons d F ih => + rw [List.foldl_cons, ih] + simp only [has, Bool.or_eq_true, List.exists_mem_cons_iff, or_assoc] + +/-- **SNP-14** What every cut of a family holds: the rows alive at each of them. -/ +theorem has_all {c : γ} {F : List γ} {r : Gen κ β} : + (all c F).has pos r = true ↔ ∀ d ∈ c :: F, r.aliveAt (pos d) = true := by + rw [all, has_foldl_inter, List.forall_mem_cons] + rfl + +/-- **SNP-14** What some cut of a family holds: the rows alive at one of them. -/ +theorem has_any {c : γ} {F : List γ} {r : Gen κ β} : + (any c F).has pos r = true ↔ ∃ d ∈ c :: F, r.aliveAt (pos d) = true := by + rw [any, has_foldl_union, List.exists_mem_cons_iff] + rfl + +/-- **SNP-14** What every cut of a family holds is what its least and its greatest cut both hold: +two positions, whatever the size of the family. -/ +theorem has_all_eq_kept {c lo hi : γ} {F : List γ} (hlo : lo ∈ c :: F) (hhi : hi ∈ c :: F) + (hF : ∀ d ∈ c :: F, pos lo ≤ pos d ∧ pos d ≤ pos hi) (r : Gen κ β) : + (all c F).has pos r = (kept lo hi).has pos r := by + rw [Bool.eq_iff_iff, has_all] + simp only [kept, has, Bool.and_eq_true] + exact ⟨fun h ↦ ⟨h lo hlo, h hi hhi⟩, + fun h d hd ↦ Gen.aliveAt_of_between h.1 h.2 (hF d hd).1 (hF d hd).2⟩ + +theorem sum_map_filter_or {M : Type*} [AddCommMonoid M] (w : Gen κ β → M) + (p q : Gen κ β → Bool) (rs : List (Gen κ β)) : + ((rs.filter fun r ↦ p r || q r).map w).sum + = ((rs.filter p).map w).sum + ((rs.filter fun r ↦ q r && !p r).map w).sum := by + induction rs with + | nil => simp + | cons r rs ih => + cases hp : p r <;> cases hq : q r <;> + simp [hp, hq, ih, add_assoc, add_left_comm] + +/-- **SNP-13** A measure that is a sum over the rows walks the signed difference: the sum over what +the second cut holds, with the sum over the rows gone, is the sum over what the first holds, with +the sum over the rows come. A count is the case of the measure one. -/ +theorem sum_rows_delta {M : Type*} [AddCommMonoid M] (w : Gen κ β → M) (a b : γ) + (rs : List (Gen κ β)) : + (((cut b).rows pos rs).map w).sum + (((gone a b).rows pos rs).map w).sum + = (((cut a).rows pos rs).map w).sum + (((come a b).rows pos rs).map w).sum := by + have h1 := sum_map_filter_or w (fun r ↦ r.aliveAt (pos b)) (fun r ↦ r.aliveAt (pos a)) rs + have h2 := sum_map_filter_or w (fun r ↦ r.aliveAt (pos a)) (fun r ↦ r.aliveAt (pos b)) rs + have h3 : (rs.filter fun r ↦ r.aliveAt (pos b) || r.aliveAt (pos a)) + = rs.filter fun r ↦ r.aliveAt (pos a) || r.aliveAt (pos b) := + List.filter_congr fun r _ ↦ Bool.or_comm _ _ + rw [h3] at h1 + exact h1.symm.trans h2 + +/-- **SNP-13** The count walks the signed difference: no set is read to count the next cut's rows +from the last cut's. -/ +theorem length_rows_delta (a b : γ) (rs : List (Gen κ β)) : + ((cut b).rows pos rs).length + ((gone a b).rows pos rs).length + = ((cut a).rows pos rs).length + ((come a b).rows pos rs).length := by + simpa using sum_rows_delta (pos := pos) (fun _ ↦ (1 : ℕ)) a b rs + +end Held + +/-- **SNP-14** A row is alive at some cut of a family exactly when it is counted in one at least. -/ +theorem countIn_pos_iff {F : List ℕ} {r : Gen κ β} : + 0 < countIn F r ↔ ∃ c ∈ F, r.aliveAt c = true := + List.countP_pos_iff + +/-- **SNP-14** A row is alive at every cut of a family exactly when it is counted in each. -/ +theorem countIn_eq_length_iff {F : List ℕ} {r : Gen κ β} : + countIn F r = F.length ↔ ∀ c ∈ F, r.aliveAt c = true := + List.countP_eq_length + +end Delta + +/-! ### The rows removed, added and replaced -/ + +section Classes + +variable {κ β : Type*} [DecidableEq κ] + +/-- A replaced pair is a row of the first side and a row of its key on the second. -/ +theorem mem_replacedOf {g c : List (Gen κ β)} {r r' : Gen κ β} (h : (r, r') ∈ replacedOf g c) : + r ∈ g ∧ r' ∈ c ∧ r'.key = r.key := by + obtain ⟨a, ha, hab⟩ := List.mem_filterMap.1 h + obtain ⟨b, hb, hpair⟩ := Option.map_eq_some_iff.1 hab + obtain ⟨rfl, rfl⟩ := Prod.mk.inj hpair + exact ⟨ha, List.mem_of_find?_eq_some hb, by simpa using List.find?_some hb⟩ + +/-- **SNP-13** The first side of a signed difference is sorted in two: each of its rows is removed +or is the first of a replaced pair. -/ +theorem mem_gone_iff {g c : List (Gen κ β)} {r : Gen κ β} : + r ∈ g ↔ r ∈ removedOf g c ∨ ∃ r', (r, r') ∈ replacedOf g c := by + constructor + · intro hr + cases hf : c.find? fun r' ↦ decide (r'.key = r.key) with + | none => + refine Or.inl (List.mem_filter.2 ⟨hr, ?_⟩) + rw [Bool.not_eq_true', Bool.eq_false_iff] + intro hany + obtain ⟨r', hr', hk⟩ := List.any_eq_true.1 hany + exact absurd hk (by simpa using List.find?_eq_none.1 hf r' hr') + | some r' => exact Or.inr ⟨r', List.mem_filterMap.2 ⟨r, hr, by rw [hf]; rfl⟩⟩ + · rintro (h | ⟨r', h⟩) + · exact (List.mem_filter.1 h).1 + · exact (mem_replacedOf h).1 + +/-- **SNP-13** And not in both: a removed row is the first of no replaced pair. -/ +theorem not_replacedOf_of_removedOf {g c : List (Gen κ β)} {r r' : Gen κ β} + (h : r ∈ removedOf g c) : (r, r') ∉ replacedOf g c := by + intro hp + obtain ⟨-, hr', hk⟩ := mem_replacedOf hp + have hnone := (List.mem_filter.1 h).2 + rw [Bool.not_eq_true', Bool.eq_false_iff] at hnone + exact hnone (List.any_eq_true.2 ⟨r', hr', by simpa using hk⟩) + +/-- **SNP-13** The second side is sorted in two as well, when it holds one row a key at most, as the +contents of a cut do: each of its rows is added or is the second of a replaced pair. -/ +theorem mem_come_iff {g c : List (Gen κ β)} + (hc : ∀ x ∈ c, ∀ y ∈ c, x.key = y.key → x = y) {r' : Gen κ β} : + r' ∈ c ↔ r' ∈ addedOf g c ∨ ∃ r, (r, r') ∈ replacedOf g c := by + constructor + · intro hr' + by_cases hany : (g.any fun r ↦ decide (r.key = r'.key)) = true + · obtain ⟨r, hr, hk⟩ := List.any_eq_true.1 hany + have hk' : r.key = r'.key := by simpa using hk + cases hf : c.find? fun y ↦ decide (y.key = r.key) with + | none => exact absurd hk'.symm (by simpa using List.find?_eq_none.1 hf r' hr') + | some y => + have hy : y.key = r.key := by simpa using List.find?_some hf + have hyr : y = r' := hc y (List.mem_of_find?_eq_some hf) r' hr' (hy.trans hk') + exact Or.inr ⟨r, List.mem_filterMap.2 ⟨r, hr, by rw [hf, hyr]; rfl⟩⟩ + · exact Or.inl (List.mem_filter.2 ⟨hr', by simpa using hany⟩) + · rintro (h | ⟨r, h⟩) + · exact (List.mem_filter.1 h).1 + · exact (mem_replacedOf h).2.1 + +end Classes + +/-! ### On the generations of a chain -/ + +section Generations + +variable {κ β : Type*} [DecidableEq κ] + +theorem event_closeAt (x : κ) (p : ℕ) (r : Gen κ β) : (closeAt x p r).event = r.event := by + unfold closeAt + split_ifs <;> rfl + +theorem born_closeAt (x : κ) (p : ℕ) (r : Gen κ β) : (closeAt x p r).born = r.born := by + unfold closeAt + split_ifs <;> rfl + +/-- A row's position is a position of its chain. -/ +theorem born_of_mem_gens {l : List (κ × β)} {r : Gen κ β} (hr : r ∈ gens l) : + 1 ≤ r.born ∧ r.born ≤ l.length := by + induction l using List.reverseRecOn generalizing r with + | nil => simp [gens_nil] at hr + | append_singleton l e ih => + rw [gens_append_singleton] at hr + rw [List.length_append, List.length_singleton] + rcases List.mem_append.1 hr with hr | hr + · obtain ⟨r', hr', rfl⟩ := List.mem_map.1 hr + rw [born_closeAt] + have := ih hr' + omega + · rw [List.mem_singleton.1 hr] + exact ⟨Nat.le_add_left _ _, le_rfl⟩ + +/-- **SNP-12** A row records the chain's event at its position: the rows of the generations are the +events of the chain, each with the stamp of its key's next event. -/ +theorem getElem?_of_mem_gens {l : List (κ × β)} {r : Gen κ β} (hr : r ∈ gens l) : + l[r.born - 1]? = some (r.key, r.val) := by + induction l using List.reverseRecOn generalizing r with + | nil => simp [gens_nil] at hr + | append_singleton l e ih => + rw [gens_append_singleton] at hr + rcases List.mem_append.1 hr with hr | hr + · obtain ⟨r', hr', rfl⟩ := List.mem_map.1 hr + have hb := born_of_mem_gens hr' + rw [born_closeAt, closeAt_key, closeAt_val, List.getElem?_append_left (by omega)] + exact ih hr' + · rw [List.mem_singleton.1 hr] + simp + +/-- **SNP-12** The closing stamp of a row is the position of its key's next event, which lies past +the row's own. -/ +theorem exists_next_of_mem_gens {l : List (κ × β)} {r : Gen κ β} (hr : r ∈ gens l) {d : ℕ} + (hd : r.died = some d) : r.born < d ∧ ∃ r' ∈ gens l, r'.key = r.key ∧ r'.born = d := by + induction l using List.reverseRecOn generalizing r with + | nil => simp [gens_nil] at hr + | append_singleton l e ih => + rw [gens_append_singleton] at hr ⊢ + rcases List.mem_append.1 hr with hr | hr + · obtain ⟨r', hr', rfl⟩ := List.mem_map.1 hr + have hb := born_of_mem_gens hr' + by_cases hc : r'.key = e.1 ∧ r'.died = none + · have hd' : l.length + 1 = d := by + simpa [closeAt, hc] using hd + subst hd' + refine ⟨by rw [born_closeAt]; omega, ⟨e.1, e.2, l.length + 1, none⟩, + List.mem_append_right _ (List.mem_singleton_self _), ?_, rfl⟩ + rw [closeAt_key] + exact hc.1.symm + · have hsame : closeAt e.1 (l.length + 1) r' = r' := by + simp only [closeAt, hc, ↓reduceIte] + rw [hsame] at hd ⊢ + obtain ⟨hlt, r'', hr'', hk, hbn⟩ := ih hr' hd + exact ⟨hlt, closeAt e.1 (l.length + 1) r'', + List.mem_append_left _ (List.mem_map_of_mem hr''), by rw [closeAt_key, hk], + by rw [born_closeAt, hbn]⟩ + · rw [List.mem_singleton.1 hr] at hd + simp at hd + +/-- **SNP-12** A row of the generations is well formed: it is alive at its own position. -/ +theorem proper_of_mem_gens {l : List (κ × β)} {r : Gen κ β} (hr : r ∈ gens l) : r.Proper := + fun _ hd ↦ (exists_next_of_mem_gens hr hd).1 + +/-- **SNP-17** The closing stamps are a function of the keys alone: a chain with its values +rewritten, key by key, has the generations of the chain with their values rewritten. An erasure that +keeps the key of a hole moves no position and no stamp. -/ +theorem gens_map {β' : Type*} (f : κ × β → β') (l : List (κ × β)) : + gens (l.map fun e ↦ (e.1, f e)) + = (gens l).map fun r ↦ ⟨r.key, f (r.key, r.val), r.born, r.died⟩ := by + induction l using List.reverseRecOn with + | nil => rfl + | append_singleton l e ih => + rw [List.map_append, List.map_singleton, gens_append_singleton, gens_append_singleton, ih, + List.length_map] + simp only [landGen, List.map_append, List.map_map, List.map_singleton] + congr 1 + refine List.map_congr_left fun r _ ↦ ?_ + simp only [Function.comp_apply, closeAt] + split_ifs <;> rfl + +theorem filter_key_contentAt (rs : List (Gen κ β)) (c : ℕ) (x : κ) : + (contentAt rs c).filter (fun r ↦ decide (r.key = x)) = rs.filter (selects c x) := by + unfold contentAt + rw [List.filter_filter] + rfl + +/-- **SNP-12** What a cut holds is each key's state at the cut, once: the rows of a key alive at a +cut are the one row of its state there, or none. Every head at once is the read of every key. -/ +theorem map_val_filter_key_contentAt (l : List (κ × β)) (c : ℕ) (x : κ) : + ((contentAt (gens l) c).filter fun r ↦ decide (r.key = x)).map Gen.val + = (stateAt l c x).toList := by + rw [filter_key_contentAt, ← genRead_gens] + have hlen := length_filter_selects_le_one l c x + unfold genRead + rw [← List.head?_filter] + rcases hf : (gens l).filter (selects c x) with _ | ⟨r, _ | ⟨r', t⟩⟩ + · rfl + · rfl + · rw [hf] at hlen + simp at hlen + +/-- **SNP-12** A cut holds one row a key at most: two rows of one key alive at one cut are one row. +-/ +theorem eq_of_key_eq_of_mem_contentAt {l : List (κ × β)} {c : ℕ} {r r' : Gen κ β} + (hr : r ∈ contentAt (gens l) c) (hr' : r' ∈ contentAt (gens l) c) (hk : r.key = r'.key) : + r = r' := by + have hlen := length_filter_selects_le_one l c r'.key + have h1 : r ∈ (gens l).filter (selects c r'.key) := by + rw [← filter_key_contentAt] + exact List.mem_filter.2 ⟨hr, by simpa using hk⟩ + have h2 : r' ∈ (gens l).filter (selects c r'.key) := by + rw [← filter_key_contentAt] + exact List.mem_filter.2 ⟨hr', by simp⟩ + rcases hf : (gens l).filter (selects c r'.key) with _ | ⟨a, _ | ⟨b, t⟩⟩ + · rw [hf] at h1 + exact absurd h1 List.not_mem_nil + · rw [hf] at h1 h2 + rw [List.mem_singleton.1 h1, List.mem_singleton.1 h2] + · rw [hf] at hlen + simp at hlen + +theorem gens_append_exists (l t : List (κ × β)) : + ∃ (g : Gen κ β → Gen κ β) (new : List (Gen κ β)), + gens (l ++ t) = (gens l).map g ++ new ∧ + (∀ r, (g r).event = r.event ∧ + ((g r).died = r.died ∨ (r.died = none ∧ ∃ d, (g r).died = some d ∧ l.length < d))) ∧ + ∀ r ∈ new, l.length < r.born := by + induction t using List.reverseRecOn with + | nil => exact ⟨id, [], by simp, fun r ↦ ⟨rfl, Or.inl rfl⟩, by simp⟩ + | append_singleton t e ih => + obtain ⟨g, new, hg, hprop, hnew⟩ := ih + refine ⟨closeAt e.1 ((l ++ t).length + 1) ∘ g, + new.map (closeAt e.1 ((l ++ t).length + 1)) ++ [⟨e.1, e.2, (l ++ t).length + 1, none⟩], + ?_, fun r ↦ ⟨?_, ?_⟩, ?_⟩ + · rw [← List.append_assoc, gens_append_singleton, hg] + simp [landGen, List.map_append, List.map_map] + · rw [Function.comp_apply, event_closeAt, (hprop r).1] + · rw [Function.comp_apply] + by_cases hc : (g r).key = e.1 ∧ (g r).died = none + · rcases (hprop r).2 with h | ⟨-, d, hd, -⟩ + · refine Or.inr ⟨h ▸ hc.2, (l ++ t).length + 1, by simp [closeAt, hc], ?_⟩ + rw [List.length_append] + omega + · rw [hd] at hc + exact absurd hc.2 (by simp) + · have hsame : closeAt e.1 ((l ++ t).length + 1) (g r) = g r := by + simp only [closeAt, hc, ↓reduceIte] + rw [hsame] + exact (hprop r).2 + · intro r hr + rcases List.mem_append.1 hr with hr | hr + · obtain ⟨r', hr', rfl⟩ := List.mem_map.1 hr + rw [born_closeAt] + exact hnew r' hr' + · rw [List.mem_singleton.1 hr, List.length_append] + exact Nat.lt_succ_of_le (Nat.le_add_right _ _) + +/-- **SNP-14** Append invariance for every set: a set whose cuts lie inside the chain holds, after +any growth of the chain, the events it held. The growth writes closing stamps into rows the set +holds, each past the old head, so the events are compared and not the stamps. -/ +theorem Held.rows_gens_append {γ : Type*} {pos : γ → ℕ} {e : Held γ} {l : List (κ × β)} + (t : List (κ × β)) (h : ∀ c ∈ e.atoms, pos c ≤ l.length) : + (e.rows pos (gens (l ++ t))).map Gen.event = (e.rows pos (gens l)).map Gen.event := by + obtain ⟨g, new, hg, hprop, hnew⟩ := gens_append_exists l t + have hnone : new.filter (e.has pos) = [] := by + rw [List.filter_eq_nil_iff] + intro r hr hhas + obtain ⟨c, hc, ha⟩ := Held.exists_atom_of_has hhas + have h1 := (Gen.aliveAt_iff.1 ha).1 + have h2 := hnew r hr + have h3 := h c hc + omega + have hsame : (e.has pos ∘ g) = e.has pos := funext fun r ↦ + Held.has_of_closed_later (congrArg (fun x ↦ x.2.2) (hprop r).1) + ((hprop r).2.imp_right fun ⟨hn, d, hd, hlt⟩ ↦ + ⟨hn, d, hd, fun c hc ↦ lt_of_le_of_lt (h c hc) hlt⟩) + unfold Held.rows + rw [hg, List.filter_append, hnone, List.append_nil, List.filter_map, hsame, List.map_map] + exact List.map_congr_left fun r _ ↦ (hprop r).1 + +/-- **SNP-14** So a set whose cuts lie at or under a cut inside the chain reads the prefix at that +cut and nothing after it: what a cut holds is a derived view of its read. -/ +theorem Held.rows_gens_take {γ : Type*} {pos : γ → ℕ} {e : Held γ} {l : List (κ × β)} {c : ℕ} + (hc : c ≤ l.length) (h : ∀ a ∈ e.atoms, pos a ≤ c) : + (e.rows pos (gens l)).map Gen.event = (e.rows pos (gens (l.take c))).map Gen.event := by + have hlen : (l.take c).length = c := by rw [List.length_take, Nat.min_eq_left hc] + have := Held.rows_gens_append (e := e) (pos := pos) (l := l.take c) (l.drop c) + fun a ha ↦ by rw [hlen]; exact h a ha + rwa [List.take_append_drop] at this + +theorem mem_drop_take_of_mem_gens {l : List (κ × β)} {r : Gen κ β} (hr : r ∈ gens l) {a b : ℕ} + (ha : a < r.born) (hb : r.born ≤ b) : (r.key, r.val) ∈ (l.take b).drop a := by + have hget := getElem?_of_mem_gens hr + have hpos := born_of_mem_gens hr + refine List.mem_of_getElem? (i := r.born - 1 - a) ?_ + rw [List.getElem?_drop, List.getElem?_take_of_lt (by omega), + show a + (r.born - 1 - a) = r.born - 1 by omega] + exact hget + +/-- **SNP-13** The signed difference is sound for what did not change: every row on either side of +it belongs to a key that an event between the two cuts names. A key the events between do not name +holds at both cuts the row it held. -/ +theorem key_mem_of_mem_delta {l : List (κ × β)} {a b : ℕ} (h : a ≤ b) {r : Gen κ β} + (hr : r ∈ gens l) + (hd : (Held.gone a b).has id r = true ∨ (Held.come a b).has id r = true) : + r.key ∈ ((l.take b).drop a).map Prod.fst := by + rcases hd with hd | hd + · have hab : r.aliveAt a = true ∧ r.aliveAt b = false := by + simpa [Held.gone, Held.has] using hd + have hal := Gen.aliveAt_iff.1 hab.1 + rcases Gen.aliveAt_eq_false_iff.1 hab.2 with hlt | ⟨d, hdd, hle⟩ + · omega + · obtain ⟨-, r', hr', hk, hbn⟩ := exists_next_of_mem_gens hr hdd + have hmem := mem_drop_take_of_mem_gens hr' (a := a) (b := b) + (by rw [hbn]; exact hal.2 d hdd) (by rw [hbn]; exact hle) + exact List.mem_map.2 ⟨_, hmem, hk⟩ + · have hab : r.aliveAt b = true ∧ r.aliveAt a = false := by + simpa [Held.come, Held.has] using hd + have hbl := Gen.aliveAt_iff.1 hab.1 + rcases Gen.aliveAt_eq_false_iff.1 hab.2 with hlt | ⟨d, hdd, hle⟩ + · exact List.mem_map.2 ⟨_, mem_drop_take_of_mem_gens hr hlt hbl.1, rfl⟩ + · have := hbl.2 d hdd + omega + +/-- **SNP-17** A retire is a removal: when a key holds a version at one cut and its last event at +another is a retire, the row of the version is gone between the two, and no row of the key that came +carries a version. -/ +theorem removed_of_retire {l : List (κ × Option β)} {a b : ℕ} {x : κ} {v : β} + (ha : stateAt l a x = some (some v)) (hb : stateAt l b x = some none) : + (∃ r ∈ gens l, r.key = x ∧ r.val = some v ∧ (Held.gone a b).has id r = true) ∧ + ∀ r ∈ gens l, r.key = x → (Held.come a b).has id r = true → r.val = none := by + have h1 := map_val_filter_key_contentAt l a x + have h2 := map_val_filter_key_contentAt l b x + rw [ha] at h1 + rw [hb] at h2 + obtain ⟨ra, hra, hva⟩ := List.map_eq_singleton_iff.1 h1 + obtain ⟨rb, hrb, hvb⟩ := List.map_eq_singleton_iff.1 h2 + have hmema : ra ∈ (contentAt (gens l) a).filter fun r ↦ decide (r.key = x) := by + rw [hra] + exact List.mem_singleton_self _ + obtain ⟨hca, hka⟩ := List.mem_filter.1 hmema + have hkey : ra.key = x := by simpa using hka + have honly : ∀ r ∈ gens l, r.key = x → r.aliveAt b = true → r.val = none := by + intro r hr hk hal + have : r ∈ (contentAt (gens l) b).filter fun r ↦ decide (r.key = x) := + List.mem_filter.2 ⟨List.mem_filter.2 ⟨hr, hal⟩, by simpa using hk⟩ + rw [hrb, List.mem_singleton] at this + rw [this, hvb] + refine ⟨⟨ra, (List.mem_filter.1 hca).1, hkey, hva, ?_⟩, fun r hr hk hcome ↦ ?_⟩ + · have hala : ra.aliveAt a = true := (List.mem_filter.1 hca).2 + have hnb : ra.aliveAt b = false := by + rw [Bool.eq_false_iff] + intro hal + have := honly ra (List.mem_filter.1 hca).1 hkey hal + rw [hva] at this + exact absurd this (by simp) + simp [Held.gone, Held.has, hala, hnb] + · have hal : r.aliveAt b = true := by + simp only [Held.come, Held.has, id, Bool.and_eq_true] at hcome + exact hcome.1 + exact honly r hr hk hal + +/-- **SNP-17** No row of a chain with holes carries an erased value, so no set of its versions holds +one. -/ +theorem not_erased_of_mem_gens_holes {E : κ × β → Bool} {l : List (κ × β)} + {r : Gen κ (Option β)} {v : β} (hr : r ∈ gens (holes E l)) (hv : r.val = some v) : + E (r.key, v) = false := by + have hg := gens_map (fun e ↦ if E e then none else some e.2) l + change gens (holes E l) = _ at hg + rw [hg] at hr + obtain ⟨r', -, rfl⟩ := List.mem_map.1 hr + by_cases hE : E (r'.key, r'.val) = true + · simp [hE] at hv + · have hval : r'.val = v := by simpa [hE] using hv + rw [← hval] + simpa using hE + +/-- **SNP-17** An erasure takes its own rows out of every set and changes no other: the versions a +set holds on the chain with holes are the rows it holds on the chain, less the erased ones, each at +the position it had. -/ +theorem Held.rows_gens_holes {γ : Type*} {pos : γ → ℕ} (e : Held γ) (E : κ × β → Bool) + (l : List (κ × β)) : + ((e.rows pos (gens (holes E l))).filter Gen.isVersion).map Gen.event + = ((e.rows pos (gens l)).filter fun r ↦ !E (r.key, r.val)).map + fun r ↦ (r.key, some r.val, r.born) := by + have hg := gens_map (fun e ↦ if E e then none else some e.2) l + change gens (holes E l) = _ at hg + unfold Held.rows + rw [hg, List.filter_map, List.filter_map, List.map_map, List.filter_filter] + have h1 : ∀ r : Gen κ β, r ∈ gens l → + ((Gen.isVersion ∘ fun r : Gen κ β ↦ + (⟨r.key, if E (r.key, r.val) then none else some r.val, r.born, r.died⟩ : + Gen κ (Option β))) r + && (e.has pos ∘ fun r : Gen κ β ↦ + (⟨r.key, if E (r.key, r.val) then none else some r.val, r.born, r.died⟩ : + Gen κ (Option β))) r) + = (!E (r.key, r.val) && e.has pos r) := by + intro r _ + have hi : e.has pos (⟨r.key, if E (r.key, r.val) then none else some r.val, r.born, + r.died⟩ : Gen κ (Option β)) = e.has pos r := + Held.has_eq_of_interval e rfl rfl + simp only [Function.comp_apply, hi, Gen.isVersion] + cases E (r.key, r.val) <;> rfl + rw [List.filter_congr h1, List.filter_filter] + refine List.map_congr_left fun r hr ↦ ?_ + have hE : E (r.key, r.val) = false := by + have := (List.mem_filter.1 hr).2 + simp only [Bool.and_eq_true, Bool.not_eq_true'] at this + exact this.1 + simp [Gen.event, hE] + +end Generations + +/-! ### On a store: the grant and the positions -/ + +section Store + +variable {K α β κ γ : Type*} + +/-- **SNP-16** A narrower grant's restriction of a family of chains is its restriction of a wider +grant's. -/ +theorem restrict_narrow {G G' : K → Prop} [DecidablePred G] [DecidablePred G'] + {p p' : α → Bool} (hG : ∀ k, G k → G' k) (hp : ∀ a, p a = true → p' a = true) + (t : Store K α) : restrict G p t = restrict G p (restrict G' p' t) := by + funext k + by_cases h : G k + · have h' := hG k h + simp only [restrict, h, h', ↓reduceIte, List.filter_filter] + refine List.filter_congr fun a _ ↦ ?_ + cases hpa : p a + · rfl + · simp [hp a hpa] + · simp [restrict, h] + +/-- **SNP-16** Every set commutes with the grant: read on the chains the grant shows, it is the +grant's restriction of the set read on the whole store. The grant may be applied before the +operators or after them. -/ +theorem Held.across_restrict (G : K → Prop) [DecidablePred G] (p : Gen κ β → Bool) + (pos : γ → Cut K) (e : Held γ) (R : K → List (Gen κ β)) : + e.across pos (restrict G p R) = restrict G p (e.across pos R) := by + funext k + by_cases h : G k + · simp only [Held.across, restrict, h, ↓reduceIte, List.filter_filter] + exact List.filter_congr fun r _ ↦ Bool.and_comm _ _ + · simp [Held.across, restrict, h] + +/-- **SNP-16** Noninterference for every set: under a grant a set reads only the chains the grant +names, and of its cuts only their positions on them. Two stores that agree on those chains, at cuts +that agree on them, give one answer. -/ +theorem Held.across_congr (G : K → Prop) [DecidablePred G] (p : Gen κ β → Bool) + {pos pos' : γ → Cut K} {e : Held γ} {R R' : K → List (Gen κ β)} + (hR : ∀ k, G k → R k = R' k) (hpos : ∀ c ∈ e.atoms, ∀ k, G k → pos c k = pos' c k) : + restrict G p (e.across pos R) = restrict G p (e.across pos' R') := by + funext k + by_cases h : G k + · simp only [restrict, Held.across, h, ↓reduceIte, hR k h] + congr 1 + exact List.filter_congr fun r _ ↦ Held.has_congr (fun c hc ↦ hpos c hc k h) r + · simp [restrict, h] + +/-- **SNP-16** A narrower grant's set is the restriction of a wider grant's. -/ +theorem Held.across_narrow {G G' : K → Prop} [DecidablePred G] [DecidablePred G'] + {p p' : Gen κ β → Bool} (hG : ∀ k, G k → G' k) (hp : ∀ a, p a = true → p' a = true) + (pos : γ → Cut K) (e : Held γ) (R : K → List (Gen κ β)) : + restrict G p (e.across pos R) = restrict G p (restrict G' p' (e.across pos R)) := + restrict_narrow hG hp _ + +/-- **SNP-16** Under a grant a set names no chain the grant does not name. -/ +theorem Held.across_of_not (G : K → Prop) [DecidablePred G] (p : Gen κ β → Bool) + (pos : γ → Cut K) (e : Held γ) (R : K → List (Gen κ β)) {k : K} (h : ¬G k) : + restrict G p (e.across pos R) k = [] := by + simp [restrict, h] + +/-- **SNP-16** The events between two cuts under a grant that names whole chains: restricting to the +chains commutes with the read between, as it does with the read at a cut. -/ +theorem restrict_readBetween (G : K → Prop) [DecidablePred G] (s : Store K α) (a b : Cut K) : + restrict G (fun _ ↦ true) (readBetween s a b) + = readBetween (restrict G (fun _ ↦ true) s) a b := by + funext k + by_cases h : G k <;> simp [restrict, readBetween, h] + +/-- **SNP-15** Contents against positions, on a store: what either of two cuts holds is what their +join holds, with the rows closed between their meet and their join. -/ +theorem Held.has_union_cut (a b : Cut K) (k : K) (r : Gen κ β) : + ((Held.cut a).union (Held.cut b)).has (fun c ↦ c k) r + = ((Held.cut (a ⊔ b)).union (Held.gone (a ⊓ b) (a ⊔ b))).has (fun c ↦ c k) r := + Gen.aliveAt_or_eq_sup r (a k) (b k) + +/-- **SNP-15** And what both hold is what their meet and their join both hold, the two cuts taken +chain by chain in their order. -/ +theorem Held.has_inter_cut (a b : Cut K) (k : K) (r : Gen κ β) : + ((Held.cut a).inter (Held.cut b)).has (fun c ↦ c k) r + = (Held.kept (a ⊓ b) (a ⊔ b)).has (fun c ↦ c k) r := + Gen.aliveAt_and_eq_inf_sup r (a k) (b k) + +/-- **SNP-11** The meet and the join of two cuts that are read as asked are read as asked: the cuts +that are consistent and served are closed under both, the consistency by CLK-2. -/ +theorem resolvesIn_sup {R : K → ℕ → K → ℕ → Prop} {S : K → Set ℕ} {a b : Cut K} + (ha : Consistent R a) (hb : Consistent R b) (hSa : a ∈ servedCuts S) + (hSb : b ∈ servedCuts S) : ResolvesIn R S (a ⊔ b) (a ⊔ b) := + resolvesIn_self (ha.sup hb) ((servedCuts S).supClosed hSa hSb) + +/-- **SNP-11** The same for the meet. -/ +theorem resolvesIn_inf {R : K → ℕ → K → ℕ → Prop} {S : K → Set ℕ} {a b : Cut K} + (ha : Consistent R a) (hb : Consistent R b) (hSa : a ∈ servedCuts S) + (hSb : b ∈ servedCuts S) : ResolvesIn R S (a ⊓ b) (a ⊓ b) := + resolvesIn_self (ha.inf hb) ((servedCuts S).infClosed hSa hSb) + +/-- **SNP-11** The read at the join of two cuts is, chain by chain, the read at the later of the +two. -/ +theorem readAt_sup (s : Store K α) (a b : Cut K) (k : K) : + readAt s (a ⊔ b) k = if a k ≤ b k then readAt s b k else readAt s a k := by + by_cases h : a k ≤ b k + · simp only [h, ↓reduceIte] + change (s k).take (a k ⊔ b k) = (s k).take (b k) + rw [sup_of_le_right h] + · simp only [h, ↓reduceIte] + change (s k).take (a k ⊔ b k) = (s k).take (a k) + rw [sup_of_le_left (not_le.1 h).le] + +/-- **SNP-11** The read at the meet of two cuts is, chain by chain, the read at the earlier of the +two. -/ +theorem readAt_inf (s : Store K α) (a b : Cut K) (k : K) : + readAt s (a ⊓ b) k = if a k ≤ b k then readAt s a k else readAt s b k := by + by_cases h : a k ≤ b k + · simp only [h, ↓reduceIte] + change (s k).take (a k ⊓ b k) = (s k).take (a k) + rw [inf_of_le_left h] + · simp only [h, ↓reduceIte] + change (s k).take (a k ⊓ b k) = (s k).take (b k) + rw [inf_of_le_right (not_le.1 h).le] + +/-- **SNP-11** The read at the empty cut is empty. -/ +theorem readAt_bot (s : Store K α) : readAt s ⊥ = fun _ ↦ [] := by + funext k + simp [readAt] + +/-- **SNP-11** The meet distributes over the join, and so do the reads: the cuts are a distributive +lattice. -/ +theorem readAt_inf_sup (s : Store K α) (a b c : Cut K) : + readAt s (a ⊓ (b ⊔ c)) = readAt s (a ⊓ b ⊔ a ⊓ c) := + congrArg (readAt s) (inf_sup_left a b c) + +theorem readBetween_of_le (s : Store K α) {a b : Cut K} {k : K} (h : b k ≤ a k) : + readBetween s a b k = [] := by + refine List.drop_of_length_le ?_ + rw [List.length_take] + exact (Nat.min_le_left _ _).trans h + +/-- **SNP-11** The difference of two cuts on positions, the events the second holds and the first +does not, is the read between their meet and the second. -/ +theorem readBetween_inf_left (s : Store K α) (a b : Cut K) : + readBetween s (a ⊓ b) b = readBetween s a b := by + funext k + rcases le_total (a k) (b k) with h | h + · change ((s k).take (b k)).drop (a k ⊓ b k) = ((s k).take (b k)).drop (a k) + rw [inf_of_le_left h] + · rw [readBetween_of_le s h] + refine List.drop_of_length_le ?_ + change ((s k).take (b k)).length ≤ a k ⊓ b k + rw [inf_of_le_right h, List.length_take] + exact Nat.min_le_left _ _ + +/-- **SNP-11** And the read between the first and their join. -/ +theorem readBetween_sup_right (s : Store K α) (a b : Cut K) : + readBetween s a (a ⊔ b) = readBetween s a b := by + funext k + rcases le_total (a k) (b k) with h | h + · change ((s k).take (a k ⊔ b k)).drop (a k) = ((s k).take (b k)).drop (a k) + rw [sup_of_le_right h] + · rw [readBetween_of_le s h] + refine List.drop_of_length_le ?_ + change ((s k).take (a k ⊔ b k)).length ≤ a k + rw [sup_of_le_left h, List.length_take] + exact Nat.min_le_left _ _ + +/-- **SNP-11** The symmetric difference of two cuts on positions, the events exactly one of them +holds, is the read between their meet and their join: on each chain, one of the two differences. -/ +theorem readBetween_inf_sup (s : Store K α) (a b : Cut K) (k : K) : + readBetween s (a ⊓ b) (a ⊔ b) k = readBetween s a b k ++ readBetween s b a k := by + rcases le_total (a k) (b k) with h | h + · rw [readBetween_of_le s h, List.append_nil] + change ((s k).take (a k ⊔ b k)).drop (a k ⊓ b k) = ((s k).take (b k)).drop (a k) + rw [sup_of_le_right h, inf_of_le_left h] + · rw [readBetween_of_le s h, List.nil_append] + change ((s k).take (a k ⊔ b k)).drop (a k ⊓ b k) = ((s k).take (a k)).drop (b k) + rw [sup_of_le_left h, inf_of_le_right h] + +theorem mem_cutsIn {s : Store K α} {c : Cut K} : c ∈ cutsIn s ↔ c ≤ head s := Iff.rfl + +/-- **SNP-11** The empty cut is inside every store: the bottom. -/ +theorem bot_mem_cutsIn (s : Store K α) : (⊥ : Cut K) ∈ cutsIn s := + show (⊥ : Cut K) ≤ head s from bot_le + +/-- **SNP-11** The head is inside the store, and every cut inside the store lies under it: the top. +-/ +theorem head_mem_cutsIn (s : Store K α) : head s ∈ cutsIn s := le_refl (head s) + +/-- **SNP-11** The head moves and no cut leaves: the cuts inside a store are inside every extension +of it. -/ +theorem cutsIn_mono {s s' : Store K α} (h : Extends s s') : cutsIn s ≤ cutsIn s' := + fun _ hc ↦ le_trans hc h.head_le + +/-- **SNP-14** A function of two cuts' reads is append invariant. -/ +theorem combine_grow (f : Store K α → Store K α → β) {s : Store K α} (t : Store K α) + {a b : Cut K} (ha : a ≤ head s) (hb : b ≤ head s) : + combine f (grow s t) a b = combine f s a b := by + unfold combine + rw [readAt_grow t ha, readAt_grow t hb] + +/-- **SNP-14** A measure at each cut of a family is append invariant. -/ +theorem series_grow (D : Store K α → β) {s : Store K α} (t : Store K α) {F : List (Cut K)} + (hF : ∀ c ∈ F, c ≤ head s) : series D (grow s t) F = series D s F := + List.map_congr_left fun c hc ↦ appendInvariant_view D s t c (hF c hc) + +/-- **SNP-14** A fold over a family of cuts is append invariant. -/ +theorem foldOver_grow (g : β → Store K α → β) (init : β) {s : Store K α} (t : Store K α) + {F : List (Cut K)} (hF : ∀ c ∈ F, c ≤ head s) : + foldOver g init (grow s t) F = foldOver g init s F := by + unfold foldOver + induction F generalizing init with + | nil => rfl + | cons c F ih => + rw [List.foldl_cons, List.foldl_cons, readAt_grow t (hF c List.mem_cons_self), + ih _ fun d hd ↦ hF d (List.mem_cons_of_mem _ hd)] + +/-- **SNP-11** The difference of two cuts on positions is a function of their two reads: the events +of the second read past the length of the first. -/ +theorem readBetween_eq_combine (s : Store K α) (a b : Cut K) : + readBetween s a b = combine (fun x y k ↦ (y k).drop (x k).length) s a b := by + funext k + change ((s k).take (b k)).drop (a k) = ((s k).take (b k)).drop ((s k).take (a k)).length + rw [List.length_take] + rcases le_total (a k) (s k).length with h | h + · rw [Nat.min_eq_left h] + · rw [Nat.min_eq_right h, List.drop_of_length_le ((List.length_take_le' _ _).trans h), + List.drop_of_length_le (List.length_take_le' _ _)] + +end Store + +namespace Witness + +/-- **SNP-15** The control for the two meanings of union: on contents it does not follow the join of +the positions. One key written twice: the union of what the two cuts hold has both rows, and the +join of the two cuts holds the later one alone. -/ +theorem union_ne_join : + ∃ (l : List (Unit × ℕ)) (a b : ℕ), + (((Held.cut a).union (Held.cut b)).rows id (gens l)).map Gen.val = [0, 1] ∧ + ((Held.cut (a ⊔ b)).rows id (gens l)).map Gen.val = [1] := + ⟨[((), 0), ((), 1)], 1, 2, by decide, by decide⟩ + +/-- **SNP-12** The control for contiguity: it is a law of rows, and a value has none. A key that +returns to a value it held before holds it at two cuts and not between them. -/ +theorem value_not_contiguous : + ∃ l : List (Unit × ℕ), + stateAt l 1 () = some 0 ∧ stateAt l 3 () = some 0 ∧ stateAt l 2 () = some 1 := + ⟨[((), 0), ((), 1), ((), 0)], by decide, by decide, by decide⟩ + +/-- **SNP-13** The control for the composition of signed differences: through a cut that does not +lie between the two it fails. A row alive at `a` and `c` and not at `b` is come from `b` to `c` and +is on neither side from `a` to `c`. -/ +theorem delta_through_outside : + ∃ (r : Gen Unit Unit) (a b c : ℕ), + (Held.come a c).has id r = false ∧ + (((Held.come a b).diff (Held.gone b c)).union (Held.come b c)).has id r = true := + ⟨⟨(), (), 1, none⟩, 1, 0, 1, by decide, by decide⟩ + +/-- **SNP-16** The control for the row's own test: applied to the chain before its generations are +computed, it moves the positions, and a cut then holds an event from after it. -/ +theorem filter_before_gens : + ∃ (l : List (ℕ × ℕ)) (p : ℕ × ℕ → Bool) (c : ℕ), + (contentAt (gens (l.filter p)) c).map Gen.val = [8] ∧ + ((contentAt (gens l) c).filter fun r ↦ p (r.key, r.val)).map Gen.val = [] := + ⟨[(0, 7), (1, 8)], fun e ↦ e.1 != 0, 1, by decide, by decide⟩ + +/-- **SNP-13** The control for the signed difference against the events between two cuts: a key +landed and retired between them is named by the events and is on neither side of the difference. -/ +theorem changed_not_delta : + ∃ (l : List (Unit × Option ℕ)) (a b : ℕ), + () ∈ ((l.take b).drop a).map Prod.fst ∧ + ((Held.gone a b).rows id ((gens l).filter Gen.isVersion)).length = 0 ∧ + ((Held.come a b).rows id ((gens l).filter Gen.isVersion)).length = 0 := + ⟨[((), some 0), ((), none)], 0, 2, by decide, by decide, by decide⟩ + +/-- **SNP-14** The control for the missing complement: the rows a cut does not hold are not append +invariant, since every later row is among them. -/ +theorem complement_grows : + ∃ (l t : List (Unit × ℕ)) (c : ℕ), c ≤ l.length ∧ + ((gens (l ++ t)).filter fun r ↦ !r.aliveAt c).length + ≠ ((gens l).filter fun r ↦ !r.aliveAt c).length := + ⟨[], [((), 0)], 0, by decide, by decide⟩ + +end Witness + +end Palace.Snapshot diff --git a/formal/Palace/SnapshotAlgebra/Defs.lean b/formal/Palace/SnapshotAlgebra/Defs.lean new file mode 100644 index 00000000..d73ed0d9 --- /dev/null +++ b/formal/Palace/SnapshotAlgebra/Defs.lean @@ -0,0 +1,184 @@ +module + +public import Palace.Snapshot.Defs +public import Mathlib.Order.Sublattice + +/-! +# The algebra of cuts: the model + +dn-temporal-snapshot §4.4, on the model of `Palace/Snapshot/Defs.lean`. A cut is a value, one +position a chain, and it stands for what the store held as of it; nothing is read until an +operation needs it. Two kinds of operation act on cuts. + +**On positions.** The cuts inside a store are a lattice under the pointwise meet and join, with +the empty cut at the bottom and the head at the top (`cutsIn`); the result of a meet or a join is +a cut again, and the difference of two cuts is the events between them (`readBetween`, from the +model of the reads). + +**On contents.** A chain of keyed writes kept by generation (`gens`) has one row a write, alive +from the cut that contains it up to the cut that contains its key's next write. What a cut holds +is the rows alive at it (`contentAt`). A set of rows is named and not read: `Held` is an +expression over the contents of cuts, closed under union, intersection and difference, and it has +no complement, so every set it names lies inside the contents of the cuts it names. Whether a row +is in the set is a function of the row's position and its closing stamp alone (`Held.has`); the +rows are read when the set is materialized (`Held.rows`), chain by chain for a store +(`Held.across`). The signed difference of two cuts is two such sets, what the first holds and the +second does not and the converse (`Held.gone`, `Held.come`), sorted by key into the rows removed, +added and replaced (`removedOf`, `addedOf`, `replacedOf`). A family of cuts gives what every cut +of it holds, what some cut holds and in how many a row is alive (`Held.all`, `Held.any`, +`countIn`). + +A row that carries no version, the tombstone of a retire or the hole an erasure leaves, is a row +whose value is `none`: it closes the row before it and is in no cut's versions (`versionsAt`). + +An operator reads a cut through one interface: a function of one cut's read (`view`, in the model +of the reads), of two (`combine`), a measure at each cut of a family (`series`) and a fold over +one (`foldOver`). +-/ + +@[expose] public section + +namespace Palace.Snapshot + +/-! ### What a cut holds -/ + +section Held + +variable {κ β γ : Type*} + +/-- The event a row records: its key, its value and its position. The closing stamp is left out: +it is the one field written after the row, and it is a function of the rows. -/ +def Gen.event (r : Gen κ β) : κ × β × ℕ := (r.key, r.val, r.born) + +/-- A row is well formed when its closing stamp, if it has one, lies past its position: it is +alive at one cut at least. -/ +def Gen.Proper (r : Gen κ β) : Prop := ∀ d, r.died = some d → r.born < d + +/-- What a cut holds on one chain: the rows alive at it, every key at once. -/ +def contentAt (rs : List (Gen κ β)) (c : ℕ) : List (Gen κ β) := rs.filter fun r ↦ r.aliveAt c + +/-- A set of rows, named and not read: the contents of a cut, or the union, the intersection or +the difference of two such sets. There is no complement: a set lies inside the contents of the +cuts it names. `γ` is what names a cut, a position on one chain or a cut of a store. -/ +inductive Held (γ : Type*) where + /-- What the cut holds. -/ + | cut (c : γ) : Held γ + /-- What either set holds. -/ + | union (p q : Held γ) : Held γ + /-- What both sets hold. -/ + | inter (p q : Held γ) : Held γ + /-- What the first set holds and the second does not. -/ + | diff (p q : Held γ) : Held γ + +namespace Held + +/-- Whether a row is in the set, on the chain where the cut named `c` stands at `pos c`. It +reads the row's position and its closing stamp and nothing else. -/ +def has (pos : γ → ℕ) : Held γ → Gen κ β → Bool + | cut c, r => r.aliveAt (pos c) + | union p q, r => p.has pos r || q.has pos r + | inter p q, r => p.has pos r && q.has pos r + | diff p q, r => p.has pos r && !q.has pos r + +/-- The cuts a set names. -/ +def atoms : Held γ → List γ + | cut c => [c] + | union p q => p.atoms ++ q.atoms + | inter p q => p.atoms ++ q.atoms + | diff p q => p.atoms ++ q.atoms + +/-- The set read on one chain: the rows of the chain that are in it. -/ +def rows (pos : γ → ℕ) (e : Held γ) (rs : List (Gen κ β)) : List (Gen κ β) := + rs.filter (e.has pos) + +/-- The set read on a store, chain by chain, each chain at the cuts' positions on it. -/ +def across {K : Type*} (pos : γ → Cut K) (e : Held γ) (R : K → List (Gen κ β)) : + Store K (Gen κ β) := + fun k ↦ (R k).filter (e.has fun c ↦ pos c k) + +/-- What exactly one of two sets holds. -/ +def symm (p q : Held γ) : Held γ := union (diff p q) (diff q p) + +/-- The rows the cut `a` holds and the cut `b` does not: one side of the signed difference. -/ +def gone (a b : γ) : Held γ := diff (cut a) (cut b) + +/-- The rows the cut `b` holds and the cut `a` does not: the other side. -/ +def come (a b : γ) : Held γ := diff (cut b) (cut a) + +/-- The rows both cuts hold. -/ +def kept (a b : γ) : Held γ := inter (cut a) (cut b) + +/-- What every cut of a family holds, the family given as one cut and the rest. -/ +def all (c : γ) (F : List γ) : Held γ := F.foldl (fun e d ↦ inter e (cut d)) (cut c) + +/-- What some cut of a family holds. -/ +def any (c : γ) (F : List γ) : Held γ := F.foldl (fun e d ↦ union e (cut d)) (cut c) + +end Held + +/-- In how many cuts of a family a row is alive. -/ +def countIn (F : List ℕ) (r : Gen κ β) : ℕ := F.countP fun c ↦ r.aliveAt c + +/-- A row that carries a version: a landing, and no tombstone and no hole. -/ +def Gen.isVersion (r : Gen κ (Option β)) : Bool := r.val.isSome + +/-- The versions a cut holds on a chain of landings, tombstones and holes: the rows alive at the +cut that carry one. -/ +def versionsAt (rs : List (Gen κ (Option β))) (c : ℕ) : List (Gen κ (Option β)) := + (contentAt rs c).filter Gen.isVersion + +/-- The rows of the first side of a signed difference whose key has no row on the second: the +keys removed. -/ +def removedOf [DecidableEq κ] (gone come : List (Gen κ β)) : List (Gen κ β) := + gone.filter fun r ↦ !come.any fun r' ↦ decide (r'.key = r.key) + +/-- The rows of the second side whose key has no row on the first: the keys added. -/ +def addedOf [DecidableEq κ] (gone come : List (Gen κ β)) : List (Gen κ β) := + come.filter fun r' ↦ !gone.any fun r ↦ decide (r.key = r'.key) + +/-- The pairs of a row of the first side and the row of its key on the second: the keys whose +row was replaced by another. -/ +def replacedOf [DecidableEq κ] (gone come : List (Gen κ β)) : List (Gen κ β × Gen κ β) := + gone.filterMap fun r ↦ (come.find? fun r' ↦ decide (r'.key = r.key)).map fun r' ↦ (r, r') + +end Held + +/-! ### The positions, and the interface an operator reads through -/ + +section Interface + +variable {K α β : Type*} + +/-- The cuts inside a store, as a sublattice of the cuts: closed under the pointwise meet and +join, with the empty cut at the bottom and the head at the top. -/ +def cutsIn (s : Store K α) : Sublattice (Cut K) where + carrier := {c | c ≤ head s} + supClosed' := fun a ha b hb ↦ show a ⊔ b ≤ head s from sup_le ha hb + infClosed' := fun a ha b _ ↦ show a ⊓ b ≤ head s from le_trans inf_le_left ha + +/-- The cuts every position of which its chain serves, as a sublattice of the cuts, whatever the +chains serve: on one chain the meet and the join of two positions are each one of the two. -/ +def servedCuts (S : K → Set ℕ) : Sublattice (Cut K) where + carrier := {c | ∀ k, c k ∈ S k} + supClosed' := fun a ha b hb k ↦ show a k ⊔ b k ∈ S k from + (le_total (a k) (b k)).elim (fun h ↦ (sup_of_le_right h).symm ▸ hb k) + fun h ↦ (sup_of_le_left h).symm ▸ ha k + infClosed' := fun a ha b hb k ↦ show a k ⊓ b k ∈ S k from + (le_total (a k) (b k)).elim (fun h ↦ (inf_of_le_left h).symm ▸ ha k) + fun h ↦ (inf_of_le_right h).symm ▸ hb k + +/-- A function of two cuts' reads: the form a difference, a velocity and every comparison of two +cuts take. -/ +def combine (f : Store K α → Store K α → β) (s : Store K α) (a b : Cut K) : β := + f (readAt s a) (readAt s b) + +/-- A measure at each cut of a family: a derived view, cut by cut. -/ +def series (D : Store K α → β) (s : Store K α) (F : List (Cut K)) : List β := F.map (view D s) + +/-- A fold over the cuts of a family, each read in its turn. -/ +def foldOver (g : β → Store K α → β) (init : β) (s : Store K α) (F : List (Cut K)) : β := + F.foldl (fun acc c ↦ g acc (readAt s c)) init + +end Interface + +end Palace.Snapshot diff --git a/formal/PalaceTest.lean b/formal/PalaceTest.lean index b16be187..ec0e8b66 100644 --- a/formal/PalaceTest.lean +++ b/formal/PalaceTest.lean @@ -31,6 +31,7 @@ public import PalaceTest.Script public import PalaceTest.Sentence public import PalaceTest.SigmaStar public import PalaceTest.Snapshot +public import PalaceTest.SnapshotAlgebra public import PalaceTest.Spectral public import PalaceTest.Superconnection public import PalaceTest.Utility diff --git a/formal/PalaceTest/SnapshotAlgebra.lean b/formal/PalaceTest/SnapshotAlgebra.lean new file mode 100644 index 00000000..b62a5fe4 --- /dev/null +++ b/formal/PalaceTest/SnapshotAlgebra.lean @@ -0,0 +1,428 @@ +module + +public import Palace.SnapshotAlgebra +public import PalaceTest.Attack +public import PalaceTest.Snapshot +public meta import Palace.SnapshotAlgebra +public meta import PalaceTest.Attack +public meta import PalaceTest.Snapshot + +/-! +# Attacks on `Palace.SnapshotAlgebra` + +The Plausible attacks and negative controls for the algebra of cuts, on the model's own +definitions and with the helpers of `PalaceTest/Snapshot.lean`: stores of two chains, cuts from +two naturals, keyed chains as lists of (key, value) over three keys, chains of landings and +retires from codes, grants from two bits and row tests and erasures from three. A set of rows is +built from a program, each step pushing what a cut holds or combining the two sets on top of the +stack, so the attacks draw sets of any shape. Beside the model the attacks carry an oracle the +library does not define: the set an expression names computed by list operations on what its +cuts hold, row by row, against which the lazy membership is tested. The controls are the +readings a build must not take: the read at the join taken for the read at the meet, a +difference taken for symmetric, a value taken to live on an interval as a row does, the rows +come taken for every row stored between two cuts, what some cut of a family holds taken for +what a range of positions holds, a composition through a cut outside the two, a count that +forgets the rows gone, the events between two cuts taken for the signed difference, sets +computed on values and not on rows, a set at cuts past the head taken for append invariant, the +closing stamps taken for part of what a cut held, a row's test applied before the generations +are computed, the two meanings of union taken for one, a set read without the grant's +restriction, an erasure that deletes rows, and a hole taken for a version. They run when this +module builds (`lake test`). +-/ + +@[expose] public section + +namespace Palace.Snapshot.Attack + +/-- A row as a tuple, its closing stamp included. -/ +def rowT (r : Gen (Fin 3) (Fin 3)) : Fin 3 × Fin 3 × ℕ × Option ℕ := (r.key, r.val, r.born, r.died) + +/-- One step of a program on a stack of sets: push what a cut holds, or combine the two sets on +top. -/ +def stepSet {γ : Type} (op : Fin 4) (c : γ) (stack : List (Held γ)) : List (Held γ) := + match op.val, stack with + | 1, q :: p :: rest => Held.union p q :: rest + | 2, q :: p :: rest => Held.inter p q :: rest + | 3, q :: p :: rest => Held.diff p q :: rest + | _, stack => Held.cut c :: stack + +/-- A set of rows from a program over the cuts of one chain: the top of the stack after at most +twelve steps. -/ +def build (prog : List (Fin 4 × Fin 32)) : Held ℕ := + ((prog.take 12).foldl (fun stack i ↦ stepSet i.1 i.2.val stack) []).headD (Held.cut 0) + +/-- The same with every cut at or under a position. -/ +def buildAt (n : ℕ) (prog : List (Fin 4 × Fin 32)) : Held ℕ := + ((prog.take 12).foldl (fun stack i ↦ stepSet i.1 (min i.2.val n) stack) []).headD (Held.cut 0) + +/-- A set of rows from a program over the cuts of a store of two chains. -/ +def build2 (prog : List (Fin 4 × Fin 32 × Fin 32)) : Held (ℕ × ℕ) := + ((prog.take 12).foldl (fun stack i ↦ stepSet i.1 (i.2.1.val, i.2.2.val) stack) []).headD + (Held.cut (0, 0)) + +/-- The oracle: the positions of the rows an expression names, by list operations on what its +cuts hold. -/ +def bornsOf (rs : List (Gen (Fin 3) (Fin 3))) : Held ℕ → List ℕ + | .cut c => (contentAt rs c).map Gen.born + | .union p q => (bornsOf rs p ++ bornsOf rs q).eraseDups + | .inter p q => (bornsOf rs p).filter fun n ↦ (bornsOf rs q).contains n + | .diff p q => (bornsOf rs p).filter fun n ↦ !(bornsOf rs q).contains n + +/-- The same operations on the (key, value) pairs the cuts hold and not on the rows. -/ +def valsOf (rs : List (Gen (Fin 3) (Fin 3))) : Held ℕ → List (Fin 3 × Fin 3) + | .cut c => (contentAt rs c).map fun r ↦ (r.key, r.val) + | .union p q => (valsOf rs p ++ valsOf rs q).eraseDups + | .inter p q => (valsOf rs p).filter fun n ↦ (valsOf rs q).contains n + | .diff p q => (valsOf rs p).filter fun n ↦ !(valsOf rs q).contains n + +/-- A chain of at most twenty-four keyed writes. -/ +def ch (l : List (Fin 3 × Fin 3)) : List (Fin 3 × Fin 3) := l.take 24 + +/-- A chain in which no key is written twice: the key is the position. -/ +def once (vals : List (Fin 3)) : List (ℕ × Fin 3) := (vals.take 24).zipIdx.map fun x ↦ (x.2, x.1) + +/-- A chain of at most twenty-four landings and retires. -/ +def chv (l : List (Fin 9)) : List (Fin 3 × Option (Fin 2)) := (l.take 24).map ev + +/-- The generations of two chains, as a store of rows. -/ +def rows2 (a b : List (Fin 3 × Fin 3)) : Fin 2 → List (Gen (Fin 3) (Fin 3)) := + fun k ↦ if k = 0 then gens (ch a) else gens (ch b) + +/-- Two stores of rows agree, stamps included. -/ +def sameRows (s t : Store (Fin 2) (Gen (Fin 3) (Fin 3))) : Bool := + (List.finRange 2).all fun k ↦ (s k).map rowT == (t k).map rowT + +/-- A family of at most six positions. -/ +def fam (F : List (Fin 28)) : List ℕ := (F.take 6).map fun c ↦ c.val + +/-- The least of a family of positions. -/ +def least (c : ℕ) (F : List ℕ) : ℕ := F.foldl min c + +/-- The greatest of a family of positions. -/ +def greatest (c : ℕ) (F : List ℕ) : ℕ := F.foldl max c + +/- SNP-11: the read at the join of two cuts is, chain by chain, the later of the two reads, and +the read at their meet the earlier. -/ +#eval survives (∀ (a b : List (Fin 3)) (m n i j : ℕ), + (List.finRange 2).all (fun k ↦ + (readAt (st a b) (cu m n ⊔ cu i j) k + == if cu m n k ≤ cu i j k then readAt (st a b) (cu i j) k else readAt (st a b) (cu m n) k) + && readAt (st a b) (cu m n ⊓ cu i j) k + == if cu m n k ≤ cu i j k then readAt (st a b) (cu m n) k else readAt (st a b) (cu i j) k) + = true) 529 + +/- Control: the read at the join is not the read at the meet. -/ +#eval refuted (∀ (a b : List (Fin 3)) (m n i j : ℕ), + same (readAt (st a b) (cu m n ⊔ cu i j)) (readAt (st a b) (cu m n ⊓ cu i j)) = true) 530 + +/- SNP-11: the difference of two cuts on positions is the read between them from their meet and +to their join, and the symmetric difference is, on each chain, one of the two differences. -/ +#eval survives (∀ (a b : List (Fin 3)) (m n i j : ℕ), + (same (readBetween (st a b) (cu m n ⊓ cu i j) (cu i j)) (readBetween (st a b) (cu m n) (cu i j)) + && same (readBetween (st a b) (cu m n) (cu m n ⊔ cu i j)) + (readBetween (st a b) (cu m n) (cu i j)) + && (List.finRange 2).all fun k ↦ + readBetween (st a b) (cu m n ⊓ cu i j) (cu m n ⊔ cu i j) k + == readBetween (st a b) (cu m n) (cu i j) k ++ readBetween (st a b) (cu i j) (cu m n) k) + = true) 531 + +/- Control: the difference of two cuts is not symmetric. -/ +#eval refuted (∀ (a b : List (Fin 3)) (m n i j : ℕ), + same (readBetween (st a b) (cu m n) (cu i j)) (readBetween (st a b) (cu i j) (cu m n)) + = true) 532 + +/- SNP-11: the meet distributes over the join and absorbs it, on the reads; and the difference +is a function of the two reads. -/ +#eval survives (∀ (a b : List (Fin 3)) (m n i j u v : ℕ), + (same (readAt (st a b) (cu m n ⊓ (cu i j ⊔ cu u v))) + (readAt (st a b) (cu m n ⊓ cu i j ⊔ cu m n ⊓ cu u v)) + && same (readAt (st a b) (cu m n ⊔ cu m n ⊓ cu i j)) (readAt (st a b) (cu m n)) + && same (readBetween (st a b) (cu m n) (cu i j)) + (combine (fun x y k ↦ (y k).drop (x k).length) (st a b) (cu m n) (cu i j))) = true) 533 + +/- SNP-11: the join and the meet of two cuts read as asked are consistent and served, so they +are read as asked. The cuts are the greatest consistent served cuts under two frontiers. -/ +#eval survives (∀ (es : List Edge) (m : Fin 1024) (x y u v : Fin 6), + (cons es (at2 (bestIn es (sv m) x.val y.val) ⊔ at2 (bestIn es (sv m) u.val v.val)) + && cons es (at2 (bestIn es (sv m) x.val y.val) ⊓ at2 (bestIn es (sv m) u.val v.val)) + && (List.finRange 2).all fun k ↦ + sv m k ((at2 (bestIn es (sv m) x.val y.val) ⊔ at2 (bestIn es (sv m) u.val v.val)) k) + && sv m k ((at2 (bestIn es (sv m) x.val y.val) ⊓ at2 (bestIn es (sv m) u.val v.val)) k)) + = true) 534 + +/- Control: the join of a cut read as asked with a frontier is not always consistent. -/ +#eval refuted (∀ (es : List Edge) (m : Fin 1024) (x y u v : Fin 6), + cons es (at2 (bestIn es (sv m) x.val y.val) ⊔ cu u.val v.val) = true) 535 + +/- SNP-12: a row alive at two cuts is alive at every cut between them. -/ +#eval survives (∀ (l : List (Fin 3 × Fin 3)) (a : Fin 12) (d e : Fin 8), + (gens (ch l)).all (fun r ↦ + !(r.aliveAt a.val && r.aliveAt (a.val + d.val + e.val)) || r.aliveAt (a.val + d.val)) + = true) 536 + +/- Control: a value has no interval. A key that holds one value at two cuts does not always hold +it between them. -/ +#eval refuted (∀ (l : List (Fin 3 × Fin 3)) (a : Fin 12) (d e : Fin 8) (x : Fin 3), + (stateAt (ch l) a.val x != stateAt (ch l) (a.val + d.val + e.val) x + || stateAt (ch l) (a.val + d.val) x == stateAt (ch l) a.val x) = true) 537 + +/- SNP-12: the three range reads. What the later cut holds and the earlier does not is the rows +stored after the earlier and alive at the later; what the earlier holds and the later does not, +the rows alive at the earlier and closed at or under the later; what both hold, the rows stored +at or under the earlier and not closed at or under the later. -/ +#eval survives (∀ (l : List (Fin 3 × Fin 3)) (a d : Fin 14), + (gens (ch l)).all (fun r ↦ + ((r.aliveAt (a.val + d.val) && !r.aliveAt a.val) + == (decide (a.val < r.born) && r.aliveAt (a.val + d.val))) + && ((r.aliveAt a.val && !r.aliveAt (a.val + d.val)) + == (r.aliveAt a.val && r.died.any fun x ↦ decide (x ≤ a.val + d.val))) + && (r.aliveAt a.val && r.aliveAt (a.val + d.val)) + == (decide (r.born ≤ a.val) && r.died.all fun x ↦ decide (a.val + d.val < x))) + = true) 538 + +/- Control: the rows the later cut holds and the earlier does not are not every row stored +between the two: some were closed before the later cut. -/ +#eval refuted (∀ (l : List (Fin 3 × Fin 3)) (a d : Fin 14), + (gens (ch l)).all (fun r ↦ + (r.aliveAt (a.val + d.val) && !r.aliveAt a.val) + == (decide (a.val < r.born) && decide (r.born ≤ a.val + d.val))) = true) 539 + +/- SNP-12: a row is alive at every cut of a family exactly when it is alive at the least and at +the greatest, and at some position of a range exactly when it was stored by the end of the range +and not closed by its start. -/ +#eval survives (∀ (l : List (Fin 3 × Fin 3)) (c : Fin 28) (F : List (Fin 28)), + (gens (ch l)).all (fun r ↦ + ((c.val :: fam F).all (fun d ↦ r.aliveAt d) + == (r.aliveAt (least c.val (fam F)) && r.aliveAt (greatest c.val (fam F)))) + && (List.range (greatest c.val (fam F) + 1)).any + (fun d ↦ decide (least c.val (fam F) ≤ d) && r.aliveAt d) + == (decide (r.born ≤ greatest c.val (fam F)) + && r.died.all fun x ↦ decide (least c.val (fam F) < x))) = true) 540 + +/- Control: what some cut of a family holds is not what the range between its least and its +greatest cut holds: a row stored and closed between two cuts of the family is alive at none. -/ +#eval refuted (∀ (l : List (Fin 3 × Fin 3)) (c : Fin 28) (F : List (Fin 28)), + (gens (ch l)).all (fun r ↦ + (c.val :: fam F).any (fun d ↦ r.aliveAt d) + == (decide (r.born ≤ greatest c.val (fam F)) + && r.died.all fun x ↦ decide (least c.val (fam F) < x))) = true) 541 + +/- SNP-12: what a cut holds is each key's state at the cut, once; and a row records the chain's +event at its position, with its closing stamp past it. -/ +#eval survives (∀ (l : List (Fin 3 × Fin 3)) (c : Fin 28) (x : Fin 3), + (((contentAt (gens (ch l)) c.val).filter fun r ↦ r.key == x).map Gen.val + == (stateAt (ch l) c.val x).toList + && (gens (ch l)).all fun r ↦ + (ch l)[r.born - 1]? == some (r.key, r.val) && r.died.all fun d ↦ decide (r.born < d)) + = true) 542 + +/- SNP-13: the signed difference applied gives the later contents, and differences compose +along cuts in order. -/ +#eval survives (∀ (l : List (Fin 3 × Fin 3)) (a : Fin 12) (d e : Fin 8), + (gens (ch l)).all (fun r ↦ + ((Held.cut (a.val + d.val)).has id r + == (((Held.cut a.val).diff (Held.gone a.val (a.val + d.val))).union + (Held.come a.val (a.val + d.val))).has id r) + && ((Held.come a.val (a.val + d.val + e.val)).has id r + == (((Held.come a.val (a.val + d.val)).diff + (Held.gone (a.val + d.val) (a.val + d.val + e.val))).union + (Held.come (a.val + d.val) (a.val + d.val + e.val))).has id r) + && (Held.gone a.val (a.val + d.val + e.val)).has id r + == ((Held.gone a.val (a.val + d.val)).union + ((Held.gone (a.val + d.val) (a.val + d.val + e.val)).diff + (Held.come a.val (a.val + d.val)))).has id r) = true) 543 + +/- Control: through a cut that does not lie between the two, differences do not compose. -/ +#eval refuted (∀ (l : List (Fin 3 × Fin 3)) (a b c : Fin 28), + (gens (ch l)).all (fun r ↦ + (Held.come a.val c.val).has id r + == (((Held.come a.val b.val).diff (Held.gone b.val c.val)).union + (Held.come b.val c.val)).has id r) = true) 544 + +/- SNP-13: the count walks the signed difference, between any two cuts, and the sizes of the +differences obey the triangle inequality. -/ +#eval survives (∀ (l : List (Fin 3 × Fin 3)) (a b c : Fin 28), + (((Held.cut b.val).rows id (gens (ch l))).length + + ((Held.gone a.val b.val).rows id (gens (ch l))).length + == ((Held.cut a.val).rows id (gens (ch l))).length + + ((Held.come a.val b.val).rows id (gens (ch l))).length + && decide (((Held.gone a.val c.val).rows id (gens (ch l))).length + ≤ ((Held.gone a.val b.val).rows id (gens (ch l))).length + + ((Held.gone b.val c.val).rows id (gens (ch l))).length)) = true) 545 + +/- Control: the count of the later cut is not the count of the earlier with the rows come: the +rows gone are subtracted. -/ +#eval refuted (∀ (l : List (Fin 3 × Fin 3)) (a d : Fin 14), + (((Held.cut (a.val + d.val)).rows id (gens (ch l))).length + == ((Held.cut a.val).rows id (gens (ch l))).length + + ((Held.come a.val (a.val + d.val)).rows id (gens (ch l))).length) = true) 546 + +/- SNP-13: the rows of a signed difference sort by key: each row gone is removed or the first of +a replaced pair and not both, each row come is added or the second of one, and the two rows of a +pair share their key. -/ +#eval survives (∀ (l : List (Fin 3 × Fin 3)) (a b : Fin 28), + (((Held.gone a.val b.val).rows id (gens (ch l))).all (fun r ↦ + ((removedOf ((Held.gone a.val b.val).rows id (gens (ch l))) + ((Held.come a.val b.val).rows id (gens (ch l)))).any fun x ↦ x.born == r.born) + != (replacedOf ((Held.gone a.val b.val).rows id (gens (ch l))) + ((Held.come a.val b.val).rows id (gens (ch l)))).any fun x ↦ x.1.born == r.born) + && ((Held.come a.val b.val).rows id (gens (ch l))).all (fun r ↦ + ((addedOf ((Held.gone a.val b.val).rows id (gens (ch l))) + ((Held.come a.val b.val).rows id (gens (ch l)))).any fun x ↦ x.born == r.born) + != (replacedOf ((Held.gone a.val b.val).rows id (gens (ch l))) + ((Held.come a.val b.val).rows id (gens (ch l)))).any fun x ↦ x.2.born == r.born) + && (replacedOf ((Held.gone a.val b.val).rows id (gens (ch l))) + ((Held.come a.val b.val).rows id (gens (ch l)))).all fun x ↦ x.1.key == x.2.key) + = true) 547 + +/- SNP-13: every row of the signed difference belongs to a key the events between the two cuts +name. -/ +#eval survives (∀ (l : List (Fin 3 × Fin 3)) (a d : Fin 14), + ((Held.gone a.val (a.val + d.val)).rows id (gens (ch l)) + ++ (Held.come a.val (a.val + d.val)).rows id (gens (ch l))).all + (fun r ↦ ((((ch l).take (a.val + d.val)).drop a.val).map Prod.fst).contains r.key) + = true) 548 + +/- Control: the events between two cuts are not the signed difference. On a chain of landings +and retires a key the events name does not always have a version on either side. -/ +#eval refuted (∀ (l : List (Fin 9)) (a d : Fin 14), + (((chv l).take (a.val + d.val)).drop a.val).all (fun e ↦ + ((Held.gone a.val (a.val + d.val)).rows id ((gens (chv l)).filter Gen.isVersion) + ++ (Held.come a.val (a.val + d.val)).rows id ((gens (chv l)).filter Gen.isVersion)).any + fun r ↦ r.key == e.1) = true) 549 + +/- SNP-17: a retire is a removal. When a key holds a version at one cut and its last event at +another is a retire, the version's row is gone between the two and no row of the key that came +carries a version. -/ +#eval survives (∀ (l : List (Fin 9)) (a b : Fin 28) (x : Fin 3), + ((stateAt (chv l) a.val x).join.isSome && stateAt (chv l) b.val x == some none) = true → + (((Held.gone a.val b.val).rows id (gens (chv l))).any + (fun r ↦ r.key == x && r.val == (stateAt (chv l) a.val x).join) + && ((Held.come a.val b.val).rows id (gens (chv l))).all + fun r ↦ r.key != x || r.val.isNone) = true) 550 + +/- SNP-14: a set read lazily is the set computed by list operations on what its cuts hold. -/ +#eval survives (∀ (l : List (Fin 3 × Fin 3)) (prog : List (Fin 4 × Fin 32)), + (gens (ch l)).all (fun r ↦ + (build prog).has id r == (bornsOf (gens (ch l)) (build prog)).contains r.born) = true) 551 + +/- Control: the same operations on the values the cuts hold are another thing: a key that +returns to a value has two rows and one value. -/ +#eval refuted (∀ (l : List (Fin 3 × Fin 3)) (prog : List (Fin 4 × Fin 32)), + (gens (ch l)).all (fun r ↦ + (build prog).has id r == (valsOf (gens (ch l)) (build prog)).contains (r.key, r.val)) + = true) 552 + +/- SNP-14: a set whose cuts lie inside the chain holds, after any growth of the chain, the +events it held. -/ +#eval survives (∀ (l t : List (Fin 3 × Fin 3)) (prog : List (Fin 4 × Fin 32)), + (((buildAt (ch l).length prog).rows id (gens (ch l ++ ch t))).map Gen.event + == ((buildAt (ch l).length prog).rows id (gens (ch l))).map Gen.event) = true) 553 + +/- Control: a set that names a cut past the head changes when the chain grows. -/ +#eval refuted (∀ (l t : List (Fin 3 × Fin 3)) (prog : List (Fin 4 × Fin 32)), + (((build prog).rows id (gens (ch l ++ ch t))).map Gen.event + == ((build prog).rows id (gens (ch l))).map Gen.event) = true) 554 + +/- Control: the closing stamps are not part of what a set held: growth writes them. -/ +#eval refuted (∀ (l t : List (Fin 3 × Fin 3)) (prog : List (Fin 4 × Fin 32)), + (((buildAt (ch l).length prog).rows id (gens (ch l ++ ch t))).map rowT + == ((buildAt (ch l).length prog).rows id (gens (ch l))).map rowT) = true) 555 + +/- SNP-14: a set whose cuts lie at or under a cut reads the prefix at that cut; a row's own +test commutes with it; every row in it is alive at a cut it names. -/ +#eval survives (∀ (l : List (Fin 3 × Fin 3)) (c : Fin 28) (e : Fin 8) + (prog : List (Fin 4 × Fin 32)), + (((buildAt (min c.val (ch l).length) prog).rows id (gens (ch l))).map Gen.event + == ((buildAt (min c.val (ch l).length) prog).rows id + (gens ((ch l).take (min c.val (ch l).length)))).map Gen.event + && (((build prog).rows id (gens (ch l))).filter fun r ↦ pf e r.val).map rowT + == ((build prog).rows id ((gens (ch l)).filter fun r ↦ pf e r.val)).map rowT + && ((build prog).rows id (gens (ch l))).all fun r ↦ + (build prog).atoms.any fun a ↦ r.aliveAt a) = true) 556 + +/- SNP-14: what every cut of a family holds, what some cut holds, and in how many cuts a row is +alive. -/ +#eval survives (∀ (l : List (Fin 3 × Fin 3)) (c : Fin 28) (F : List (Fin 28)), + (gens (ch l)).all (fun r ↦ + ((Held.all c.val (fam F)).has id r == (c.val :: fam F).all fun d ↦ r.aliveAt d) + && ((Held.any c.val (fam F)).has id r == (c.val :: fam F).any fun d ↦ r.aliveAt d) + && ((Held.all c.val (fam F)).has id r + == (Held.kept (least c.val (fam F)) (greatest c.val (fam F))).has id r) + && decide (0 < countIn (c.val :: fam F) r) == (Held.any c.val (fam F)).has id r + && decide (countIn (c.val :: fam F) r = (fam F).length + 1) + == (Held.all c.val (fam F)).has id r) = true) 557 + +/- Control: a row's test applied to the chain before its generations are computed is not the +test applied to what a cut holds: the positions move. -/ +#eval refuted (∀ (l : List (Fin 3 × Fin 3)) (c : Fin 28) (e : Fin 8), + ((contentAt (gens ((ch l).filter fun w ↦ pf e w.2)) c.val).map (fun r ↦ (r.key, r.val)) + == ((contentAt (gens (ch l)) c.val).filter fun r ↦ pf e r.val).map fun r ↦ (r.key, r.val)) + = true) 558 + +/- SNP-15: on a chain in which no row is ever closed the contents follow the positions: the join +holds what either cut holds and the meet what both hold. -/ +#eval survives (∀ (vals : List (Fin 3)) (a b : Fin 28), + (gens (once vals)).all (fun r ↦ + (r.aliveAt (a.val ⊔ b.val) == (r.aliveAt a.val || r.aliveAt b.val)) + && r.aliveAt (a.val ⊓ b.val) == (r.aliveAt a.val && r.aliveAt b.val)) = true) 559 + +/- Control: on a chain where keys are written again they do not: what either cut holds is more +than what the join holds. -/ +#eval refuted (∀ (l : List (Fin 3 × Fin 3)) (a b : Fin 28), + (gens (ch l)).all (fun r ↦ + r.aliveAt (a.val ⊔ b.val) == (r.aliveAt a.val || r.aliveAt b.val)) = true) 560 + +/- SNP-15: on any chain, what either cut holds is what the join holds with the rows closed +between the meet and the join, and what both hold is what the meet and the join both hold. -/ +#eval survives (∀ (l : List (Fin 3 × Fin 3)) (a b : Fin 28), + (gens (ch l)).all (fun r ↦ + ((r.aliveAt a.val || r.aliveAt b.val) + == (r.aliveAt (a.val ⊔ b.val) + || (r.aliveAt (a.val ⊓ b.val) && !r.aliveAt (a.val ⊔ b.val)))) + && (r.aliveAt a.val && r.aliveAt b.val) + == (r.aliveAt (a.val ⊓ b.val) && r.aliveAt (a.val ⊔ b.val))) = true) 561 + +/- SNP-16: every set commutes with the grant's restriction, and under a grant that names one +chain it reads that chain and the cuts' positions on it and nothing else. -/ +#eval survives (∀ (a b b' : List (Fin 3 × Fin 3)) (g : Fin 4) (c : Fin 8) (n : ℕ) + (prog : List (Fin 4 × Fin 32 × Fin 32)), + (sameRows + ((build2 prog).across (fun x ↦ cu x.1 x.2) + (restrict (fun k ↦ gr g k = true) (fun r ↦ pf c r.val) (rows2 a b))) + (restrict (fun k ↦ gr g k = true) (fun r ↦ pf c r.val) + ((build2 prog).across (fun x ↦ cu x.1 x.2) (rows2 a b))) + && sameRows + (restrict (fun k ↦ k = 0) (fun r ↦ pf c r.val) + ((build2 prog).across (fun x ↦ cu x.1 x.2) (rows2 a b))) + (restrict (fun k ↦ k = 0) (fun r ↦ pf c r.val) + ((build2 prog).across (fun x ↦ cu x.1 (x.2 + n)) (rows2 a b')))) = true) 562 + +/- Control: without the grant's restriction a set reads the other chain. -/ +#eval refuted (∀ (a b b' : List (Fin 3 × Fin 3)) (prog : List (Fin 4 × Fin 32 × Fin 32)), + sameRows ((build2 prog).across (fun x ↦ cu x.1 x.2) (rows2 a b)) + ((build2 prog).across (fun x ↦ cu x.1 x.2) (rows2 a b')) = true) 563 + +/- SNP-17: an erasure takes its own rows out of every set and changes no other. The versions a +set holds on the chain with holes carry no erased value, and they are the rows it holds on the +chain, less the erased ones, at the positions they had. -/ +#eval survives (∀ (l : List (Fin 3 × Fin 3)) (e : Fin 8) (prog : List (Fin 4 × Fin 32)), + ((((build prog).rows id (gens (holes (ek e) (ch l)))).filter Gen.isVersion).map Gen.event + == (((build prog).rows id (gens (ch l))).filter fun r ↦ !pf e r.val).map + (fun r ↦ (r.key, some r.val, r.born)) + && (((build prog).rows id (gens (holes (ek e) (ch l)))).filter Gen.isVersion).all + fun r ↦ r.val.all fun v ↦ !pf e v) = true) 564 + +/- Control: an erasure that deletes the rows moves the later ones up, and a set then holds +another thing. -/ +#eval refuted (∀ (l : List (Fin 3 × Fin 3)) (e : Fin 8) (prog : List (Fin 4 × Fin 32)), + (((build prog).rows id (gens ((ch l).filter fun w ↦ !ek e w))).map Gen.event + == (((build prog).rows id (gens (ch l))).filter fun r ↦ !pf e r.val).map Gen.event) + = true) 565 + +/- Control: a hole is no version. The rows alive at a cut of a chain with holes are not all +versions. -/ +#eval refuted (∀ (l : List (Fin 3 × Fin 3)) (e : Fin 8) (c : Fin 28), + (contentAt (gens (holes (ek e) (ch l))) c.val).all (fun r ↦ r.isVersion) = true) 566 + +end Palace.Snapshot.Attack diff --git a/formal/README.md b/formal/README.md index 7e94c4dd..88074e7f 100644 --- a/formal/README.md +++ b/formal/README.md @@ -380,13 +380,46 @@ Roundoff and FloatModel, so it has no statements of its own): (`resolution_reads_unnamed`), and served positions that shrink (`served_set_shrinks`). Design theorems (Palace and PalaceTest, no Spec rows): `as of` reads the citation graph at a commit and every other store as it is now. +- `SnapshotAlgebra`: the algebra of cuts (dn-temporal-snapshot §4.4), on the model of `Snapshot` + and proved before its code, which is stage SN-1b's. A cut is a value, one position a chain, + that stands for what the store held as of it and is read only when an operation needs it. Two + kinds of operation act on it. On positions the cuts inside a store are a sublattice of the + cuts (`cutsIn`), with the empty cut and the head as its bounds, and the difference of two cuts + is the events between them. On contents a chain of keyed writes kept by generation has one row + a write, alive on one interval of positions; what a cut holds is the rows alive at it + (`contentAt`), and a set of rows is an expression over the contents of cuts under union, + intersection and difference, with no complement (`Held`), whose membership reads a row's + position and its closing stamp and nothing else (`Held.has`). The signed difference of two + cuts is two such sets (`Held.gone`, `Held.come`), sorted by key into the rows removed, added + and replaced; a family of cuts gives what every cut holds, what some cut holds and in how + many a row is alive (`Held.all`, `Held.any`, `countIn`); and an operator reads through four + forms, a function of one read, of two, a measure at each cut of a family and a fold over one + (`view`, `combine`, `series`, `foldOver`). SNP-11 the lattice of cuts, the reads at the meet + and the join, and the difference on positions from the meet and to the join; SNP-12 a row is + alive from its position up to its closing stamp, so a row alive at two cuts is alive between + them, with the range reads that follow and one row a key at a cut; SNP-13 the signed + difference applied, composed through a cut between the two, counted and sorted, and every row + of it under a key the events between name; SNP-14 closure: a set read is the set operation on + the reads, lies inside the contents of the cuts it names, commutes with a row's own test and + is append invariant, as the four forms are; SNP-15 the union on contents is the join's + contents with the rows closed between the meet and the join, and the two agree on the rows + never closed; SNP-16 every set commutes with the grant's restriction and reads only the + chains the grant names; SNP-17 an erasure takes its own rows out of every set and changes no + other, and a retire is a removal in the signed difference that spans it. The seven laws are + rows of family XVI (`Spec/SnapshotAlgebra.lean`, 80 statements), whose code is SN-1b's + (`core/stores/cuts.py`, checked by `tests/property/test_cut_algebra.py`). The six controls as theorems, in `Witness`: a value has no interval + (`value_not_contiguous`), the union on contents is not the contents of the join + (`union_ne_join`), a complement grows with the store (`complement_grows`), differences do + not compose through a cut outside the two (`delta_through_outside`), the events between two + cuts name a key the signed difference does not hold (`changed_not_delta`), and a row's test + applied before the generations are computed moves the positions (`filter_before_gens`). - `Bridges`: theorems that join two families, so that what one proves serves the other: BRG-1 the Laplacian as `∂₁ ∂₁ᵀ`, BRG-2 Euler and Poincaré on the flag complex, BRG-3 Thomson's principle on edge flows, BRG-4 the clock's cuts and scope's closed strata as lower sets, BRG-5 delegation's noninterference through the plane, and BRG-6 Forman's curvature as the Weitzenböck term of `L₁`. - `comparator.json`: what `lake comparator` judges: `Spec` against `Palace`, the cited theorems - (380 theorems), and the three standard axioms. + (460 theorems), and the three standard axioms. - `Compare.lean`: the comparator's comparison step, run in-process where its sandbox is unavailable (macOS has no `bwrap`); CI runs the comparator itself. It is weaker than the comparator: it compares the statements' types and the definitions' values, not constructors, recursor rules or @@ -396,7 +429,8 @@ Roundoff and FloatModel, so it has no statements of its own): exported, every module contributes, and only the unsafe compiler helpers are left out, and `check.sh` holds its count to the audit's, since a checker accepts an empty export. - `PalaceTest/`: the attacks, one module per ledger family's `Palace` module (of the design - theorems, Magnetic, NegativeType, Superconnection, Dynamics, Scale and Snapshot have them), as + theorems, Magnetic, NegativeType, Superconnection, Dynamics, Scale and Snapshot have them, and + SnapshotAlgebra has its own module), as Mathlib keeps its tests in `MathlibTest`. `lake test` builds them, which runs every attack and negative control. `PalaceTest/Attack.lean` holds `survives` and `refuted`, which run Plausible with a fixed seed and count the instances that passed their guards. @@ -514,6 +548,13 @@ Roundoff and FloatModel, so it has no statements of its own): | SNP-3 | the read at `a` and the read between `a` and `b` compose to the read at `b`, so a fold continued over the delta is the fold of the prefix; a key the delta does not write keeps its state | proved; attacks survived 500 each (seeds 436, 438, 439, 447, 475, 476); the controls refuted | | SNP-4 | a cut at or past the head reads the store, so every reading at the head is the present's | proved; the attack survived 500 (seed 440); the control refuted | | SNP-5 | a reader is append invariant exactly when it reads only the prefixes, exactly when it is a derived view; the generational read is the recomputed state and the last write, with at most one generation alive | proved; attacks survived 500 each (seeds 441, 442, 443); the controls refuted, the store rewritten in place also as a theorem | +| SNP-11 | the cuts inside a store are a lattice under the pointwise meet and join, bounded by the empty cut and the head; the read at the join is the later read and at the meet the earlier; the difference on positions is the events between, from the meet and to the join | proved; attacks survived 500 each (seeds 529, 531, 533, 534); the controls refuted (530, 532, 535) | +| SNP-12 | a row is alive from its position up to its closing stamp, so a row alive at two cuts is alive between them; the range reads for what the later cut holds and the earlier does not, the converse, and what both hold; a family's cuts all hold a row exactly when the least and the greatest do | proved; attacks survived 500 each (seeds 536, 538, 540, 542); the controls refuted (537, 539, 541), a value with no interval also as a theorem | +| SNP-13 | the signed difference of two cuts applied gives the later contents, composes through a cut between the two, walks a count, sorts by key into removed, added and replaced, and holds only keys the events between name | proved; attacks survived 500 each (seeds 543, 545, 547, 548); the controls refuted (544, 546, 549), two of them also as theorems | +| SNP-14 | a set of rows read lazily is the set operation on the reads; it lies inside the contents of its cuts, commutes with a row's own test and is append invariant, as a function of two reads, a series and a fold over a family are | proved; attacks survived 500 each (seeds 551, 553, 556, 557); the controls refuted (552, 554, 555, 558), the complement as a theorem | +| SNP-15 | what either cut holds is what the join holds with the rows closed between the meet and the join; on rows never closed the contents follow the positions | proved; attacks survived 500 each (seeds 559, 561); the control refuted (560), also as a theorem | +| SNP-16 | every set commutes with the grant's restriction, reads only the chains the grant names and names no other | proved; the attack survived 500 (seed 562); the control refuted (563); a test applied before the generations as a theorem | +| SNP-17 | an erasure takes its own rows out of every set and changes no other; a retire is a removal in the signed difference that spans it | proved; attacks survived 500 (seed 564) and 295 with 205 discarded by the guard (seed 550); the controls refuted (565, 566) | The binarized forms (0/1 adjacency) reduce to Mathlib's `SimpleGraph.posSemidef_lapMatrix` and `card_connectedComponent_eq_finrank_ker_toLin'_lapMatrix` in one line each. @@ -973,6 +1014,39 @@ served (5). The rows whose own sources lie inside the cut taken for a closed set prefix taken for the filtered read (15); a chain that follows a lowered chain read as asked (38). +The algebra of cuts is attacked in a module of its own (`PalaceTest/SnapshotAlgebra.lean`, seeds +529 to 566), on the same helpers. A set of rows is built from a program, each step pushing what +a cut holds or combining the two sets on top of a stack, so the attacks draw sets of any shape, +and beside the model the module carries an oracle the library does not define: the set an +expression names computed by list operations on what its cuts hold, against which the lazy +membership is tested. Twenty-one attacks survived, twenty of them all 500 instances: the reads +at the join and the meet, the difference on positions from the meet and to the join, the +lattice laws on the reads, and the join and the meet of two cuts read as asked; a row alive +between two cuts at which it is alive, the three range reads, the family read from its least +and its greatest position, and one row a key at a cut; the signed difference applied and +composed, the count walked and the triangle inequality, the rows sorted into three classes, and +every row under a key the events between name; a set read lazily against the oracle, the same +after growth, read from the prefix at a cut above its cuts, and the family operations; the +contents following the positions on a chain with no closes, and the union as the join's +contents with the rows closed between; a set under a grant against the restriction of the set +on the whole store, on stores that differ off the grant's chains; and an erasure taking its own +rows out of every set. The attack on a retire as a removal (550) is guarded by a key that holds +a version at one cut and whose last event at the other is a retire, and survived the 295 +instances that passed the guard. + +Its seventeen controls, each refuted, with the instances it took. The read at the join taken +for the read at the meet (5); the difference taken for symmetric (10); the join of a cut read +as asked with any frontier taken for consistent (11). A value taken to live on an interval +(61); the rows come taken for every row stored between the two cuts (25); what some cut of a +family holds taken for what the range between its least and its greatest holds (23). A +composition through a cut outside the two (6); the count that forgets the rows gone (21); the +events between two cuts taken for the signed difference (14). The set operations taken on +values and not on rows (19); a set at a cut past the head taken for append invariant (5); the +closing stamps taken for part of what a set held (18); a row's test applied before the +generations are computed (25). The contents of the join taken for the union of the contents +(31). A set read without the grant's restriction (10). An erasure that deletes its rows (21); a +hole taken for a version (7). + ## Build The toolchain is pinned in `lean-toolchain` (elan resolves it); Mathlib is pinned in @@ -1001,7 +1075,7 @@ another module, and without it 68 proofs in seven files fail. One instance is wr to importers (`Palace/Scope.lean`). The kernel re-check. `Export.lean` writes every `Palace` declaration and everything it uses, from -`Init` up (55,608 declarations on the run this commit was built with), and `check.sh` replays that export from nothing through Lean's +`Init` up (56,530 declarations on the run this commit was built with), and `check.sh` replays that export from nothing through Lean's kernel and the five independent checkers bundled with Lean: `leanchecker-paranoid`, `lean4lean` (a kernel written in Lean), `nanoda` (one written in Rust), and `con-leche`, whose acceptance carries a machine-checked theorem that the environment holds no proof of `False`, with `con-ron`, its port. @@ -1012,7 +1086,7 @@ nothing safe can mention them, and nanoda refuses them. `lake comparator` builds and exports both sides in a `bwrap` sandbox, so it runs where `bwrap` does, which is Linux: CI runs it with `--paranoid`, and the same five checkers replay what the -306 statements reach. Elsewhere `check.sh` runs `Compare.lean`, the comparator's +460 statements reach. Elsewhere `check.sh` runs `Compare.lean`, the comparator's comparison step over the two environments the build left; planted, a weakened statement in the library and a changed one in `Spec/` each fail it. diff --git a/formal/Spec.lean b/formal/Spec.lean index 6c45fa55..38c18b99 100644 --- a/formal/Spec.lean +++ b/formal/Spec.lean @@ -25,5 +25,6 @@ public import Spec.Script public import Spec.Sentence public import Spec.SigmaStar public import Spec.Snapshot +public import Spec.SnapshotAlgebra public import Spec.Spectral public import Spec.Utility diff --git a/formal/Spec/SnapshotAlgebra.lean b/formal/Spec/SnapshotAlgebra.lean new file mode 100644 index 00000000..40ebceae --- /dev/null +++ b/formal/Spec/SnapshotAlgebra.lean @@ -0,0 +1,611 @@ +module + +public import Palace.SnapshotAlgebra.Defs +public import Mathlib.Data.List.Induction +public import Mathlib.Data.List.ReduceOption +public import Mathlib.Order.Lattice +public import Mathlib.Order.Lattice.Nat +public import Mathlib.Order.Sublattice + +/-! +# The algebra of cuts: the statements + +SNP-11 to SNP-17 (`docs/LAWS.md`, XVI): the lattice of cuts, a row's interval, the signed +difference of two cuts, the closure of the sets of rows a cut's contents generate, contents +against positions, the grant, and erasure and retire, over the model of +`Palace/SnapshotAlgebra/Defs.lean` and `Palace/Snapshot/Defs.lean`: a cut as one position a +chain, the cuts inside a store as a lattice, the rows of a chain of keyed writes kept by +generation and alive at a cut, a set of rows as an expression over the contents of cuts with +union, intersection and difference and no complement, the two sides of a signed difference and +their rows sorted by key, a family of cuts, and the interface an operator reads a cut through. +The controls that are theorems are among the statements; the other controls are refuted attacks +in `PalaceTest/SnapshotAlgebra.lean`. What they leave out: the stores' SQL and the statements a +set compiles to, the class a chain holds, the kinds of the landing log's rows beyond a row that +carries a version and one that does not, and the graph a cut stands for beyond its rows, which +stage SN-4 of dn-temporal-snapshot builds. + +These are the laws of `Palace/SnapshotAlgebra.lean` as the ledger cites them, each with its +proof left as `sorry`. `lake comparator` checks that the `Palace` library proves each one +exactly as stated here, from the standard axioms alone. +-/ + +@[expose] public section + +namespace Palace.Snapshot + +/-! ### A row lives on an interval -/ + +section Interval + +variable {κ β : Type*} + +/-- **SNP-12** A row is alive at a cut from its position up to, and not at, its closing stamp. -/ +theorem Gen.aliveAt_iff {r : Gen κ β} {c : ℕ} : + r.aliveAt c = true ↔ r.born ≤ c ∧ ∀ d, r.died = some d → c < d := + sorry + +/-- **SNP-12** Contiguity: a row alive at two cuts is alive at every cut between them. A row lives +on one interval of its chain's positions. -/ +theorem Gen.aliveAt_of_between {r : Gen κ β} {a b c : ℕ} (ha : r.aliveAt a = true) + (hb : r.aliveAt b = true) (hac : a ≤ c) (hcb : c ≤ b) : r.aliveAt c = true := + sorry + +/-- **SNP-12** What the later of two cuts holds and the earlier does not: the rows stored after the +earlier cut and alive at the later one. -/ +theorem Gen.aliveAt_and_not {r : Gen κ β} {a b : ℕ} (h : a ≤ b) : + (r.aliveAt b && !r.aliveAt a) = (decide (a < r.born) && r.aliveAt b) := + sorry + +/-- **SNP-12** What the earlier of two cuts holds and the later does not: the rows alive at the +earlier cut whose closing stamp is at or under the later one. -/ +theorem Gen.aliveAt_and_not' {r : Gen κ β} {a b : ℕ} (h : a ≤ b) : + (r.aliveAt a && !r.aliveAt b) = (r.aliveAt a && r.died.any fun d ↦ decide (d ≤ b)) := + sorry + +/-- **SNP-12** What two cuts both hold: the rows stored at or under the earlier cut whose closing +stamp is absent or past the later one. -/ +theorem Gen.aliveAt_and {r : Gen κ β} {a b : ℕ} (h : a ≤ b) : + (r.aliveAt a && r.aliveAt b) + = (decide (r.born ≤ a) && r.died.all fun d ↦ decide (b < d)) := + sorry + +/-- **SNP-12** A row is alive at every cut of a family exactly when it is alive at the family's +least cut and at its greatest. -/ +theorem Gen.forall_aliveAt_iff {r : Gen κ β} {F : List ℕ} {lo hi : ℕ} (hlo : lo ∈ F) + (hhi : hi ∈ F) (hF : ∀ c ∈ F, lo ≤ c ∧ c ≤ hi) : + (∀ c ∈ F, r.aliveAt c = true) ↔ r.aliveAt lo = true ∧ r.aliveAt hi = true := + sorry + +/-- **SNP-12** A well-formed row is alive at some cut of a range of positions exactly when it was +stored at or under the range's end and not closed at or under its start. -/ +theorem Gen.exists_aliveAt_iff {r : Gen κ β} (hr : r.Proper) {lo hi : ℕ} (h : lo ≤ hi) : + (∃ c, lo ≤ c ∧ c ≤ hi ∧ r.aliveAt c = true) + ↔ r.born ≤ hi ∧ ∀ d, r.died = some d → lo < d := + sorry + +/-- **SNP-15** What two cuts both hold is what their meet and their join both hold. -/ +theorem Gen.aliveAt_and_eq_inf_sup (r : Gen κ β) (a b : ℕ) : + (r.aliveAt a && r.aliveAt b) = (r.aliveAt (a ⊓ b) && r.aliveAt (a ⊔ b)) := + sorry + +/-- **SNP-15** What either of two cuts holds is what their join holds and what was closed between +their meet and their join. -/ +theorem Gen.aliveAt_or_eq_sup (r : Gen κ β) (a b : ℕ) : + (r.aliveAt a || r.aliveAt b) + = (r.aliveAt (a ⊔ b) || (r.aliveAt (a ⊓ b) && !r.aliveAt (a ⊔ b))) := + sorry + +/-- **SNP-15** A row that is never closed is alive at the join of two cuts exactly when it is alive +at one of them. -/ +theorem Gen.aliveAt_sup_of_open {r : Gen κ β} (hr : r.died = none) (a b : ℕ) : + r.aliveAt (a ⊔ b) = (r.aliveAt a || r.aliveAt b) := + sorry + +/-- **SNP-15** And at their meet exactly when it is alive at both. -/ +theorem Gen.aliveAt_inf_of_open {r : Gen κ β} (hr : r.died = none) (a b : ℕ) : + r.aliveAt (a ⊓ b) = (r.aliveAt a && r.aliveAt b) := + sorry + +end Interval + +/-! ### Sets of rows, named and not read -/ + +section Expressions + +variable {κ β γ : Type*} {pos : γ → ℕ} + +namespace Held + +/-- **SNP-14** The union read is the union of the reads. -/ +theorem mem_rows_union {p q : Held γ} {rs : List (Gen κ β)} {r : Gen κ β} : + r ∈ (p.union q).rows pos rs ↔ r ∈ p.rows pos rs ∨ r ∈ q.rows pos rs := + sorry + +/-- **SNP-14** The intersection read is the intersection of the reads. -/ +theorem mem_rows_inter {p q : Held γ} {rs : List (Gen κ β)} {r : Gen κ β} : + r ∈ (p.inter q).rows pos rs ↔ r ∈ p.rows pos rs ∧ r ∈ q.rows pos rs := + sorry + +/-- **SNP-14** The difference read is the difference of the reads. -/ +theorem mem_rows_diff {p q : Held γ} {rs : List (Gen κ β)} {r : Gen κ β} : + r ∈ (p.diff q).rows pos rs ↔ r ∈ p.rows pos rs ∧ r ∉ q.rows pos rs := + sorry + +/-- **SNP-14** What exactly one of two sets holds is what either holds and not both. -/ +theorem has_symm (p q : Held γ) (r : Gen κ β) : + (symm p q).has pos r = ((p.union q).diff (p.inter q)).has pos r := + sorry + +/-- **SNP-14** Intersection distributes over union. -/ +theorem has_inter_union (p q t : Held γ) (r : Gen κ β) : + (p.inter (q.union t)).has pos r = ((p.inter q).union (p.inter t)).has pos r := + sorry + +/-- **SNP-14** A set less what it holds and another does not is what both hold. -/ +theorem has_diff_diff (p q : Held γ) (r : Gen κ β) : + (p.diff (p.diff q)).has pos r = (p.inter q).has pos r := + sorry + +/-- **SNP-14** Whether a row is in a set is a function of the row's position and its closing stamp: +two rows with one interval, whatever their keys and values, are in the same sets. Combining sets +reads no row. -/ +theorem has_eq_of_interval {κ' β' : Type*} (e : Held γ) {r : Gen κ β} {r' : Gen κ' β'} + (hb : r.born = r'.born) (hd : r.died = r'.died) : e.has pos r = e.has pos r' := + sorry + +/-- **SNP-14** A set lies inside the contents of the cuts it names: a row in it is alive at one of +them. There is no complement. -/ +theorem exists_atom_of_has {e : Held γ} {r : Gen κ β} (h : e.has pos r = true) : + ∃ c ∈ e.atoms, r.aliveAt (pos c) = true := + sorry + +/-- **SNP-14** A row's own test, one that does not depend on a cut, commutes with every set: the +rows of a set that pass the test are the set read on the rows that pass it. -/ +theorem rows_filter (e : Held γ) (p : Gen κ β → Bool) (rs : List (Gen κ β)) : + (e.rows pos rs).filter p = e.rows pos (rs.filter p) := + sorry + +end Held + +end Expressions + +/-! ### The signed difference of two cuts, and a family of cuts -/ + +section Delta + +variable {κ β γ : Type*} {pos : γ → ℕ} + +namespace Held + +/-- **SNP-13** What the later cut holds and the earlier does not, as one range read: the rows stored +after the earlier cut and alive at the later one. -/ +theorem has_come {a b : γ} (h : pos a ≤ pos b) (r : Gen κ β) : + (come a b).has pos r = (decide (pos a < r.born) && r.aliveAt (pos b)) := + sorry + +/-- **SNP-13** What the earlier cut holds and the later does not, as one range read: the rows alive +at the earlier cut whose closing stamp is at or under the later one. -/ +theorem has_gone {a b : γ} (h : pos a ≤ pos b) (r : Gen κ β) : + (gone a b).has pos r = (r.aliveAt (pos a) && r.died.any fun d ↦ decide (d ≤ pos b)) := + sorry + +/-- **SNP-14** What both cuts hold, as one range read: the rows stored at or under the earlier cut +and not closed at or under the later one. -/ +theorem has_kept {a b : γ} (h : pos a ≤ pos b) (r : Gen κ β) : + (kept a b).has pos r + = (decide (r.born ≤ pos a) && r.died.all fun d ↦ decide (pos b < d)) := + sorry + +/-- **SNP-13** The signed difference applied: what the second cut holds is what the first holds, +less the rows gone, with the rows come. The result of a difference is an operand again. -/ +theorem has_cut_eq_apply (a b : γ) (r : Gen κ β) : + (cut b).has pos r = (((cut a).diff (gone a b)).union (come a b)).has pos r := + sorry + +/-- **SNP-13** Signed differences compose along cuts in order: the rows come from `a` to `c` are the +rows come from `a` to `b` that did not go from `b` to `c`, with the rows come from `b` to `c`. It +holds when `b` lies between `a` and `c` on the chain, in either direction. -/ +theorem has_come_trans {a b c : γ} + (h : (pos a ≤ pos b ∧ pos b ≤ pos c) ∨ (pos c ≤ pos b ∧ pos b ≤ pos a)) (r : Gen κ β) : + (come a c).has pos r = (((come a b).diff (gone b c)).union (come b c)).has pos r := + sorry + +/-- **SNP-13** And the rows gone from `a` to `c` are the rows gone from `a` to `b`, with the rows +gone from `b` to `c` that had not come from `a` to `b`. -/ +theorem has_gone_trans {a b c : γ} + (h : (pos a ≤ pos b ∧ pos b ≤ pos c) ∨ (pos c ≤ pos b ∧ pos b ≤ pos a)) (r : Gen κ β) : + (gone a c).has pos r = ((gone a b).union ((gone b c).diff (come a b))).has pos r := + sorry + +/-- **SNP-13** A row that came between `a` and `b` and went between `b` and `c` is on neither side +of the difference from `a` to `c`: what a composition cancels. -/ +theorem has_trans_of_transient {a b c : γ} {r : Gen κ β} (h1 : (come a b).has pos r = true) + (h2 : (gone b c).has pos r = true) : + (come a c).has pos r = false ∧ (gone a c).has pos r = false := + sorry + +/-- **SNP-13** A row gone from `a` to `c` is gone from `a` to `b` or from `b` to `c`, whatever `b`: +the inclusion the triangle inequality of the differences' sizes follows from. -/ +theorem has_gone_triangle (a b c : γ) {r : Gen κ β} (h : (gone a c).has pos r = true) : + (gone a b).has pos r = true ∨ (gone b c).has pos r = true := + sorry + +/-- **SNP-14** What every cut of a family holds: the rows alive at each of them. -/ +theorem has_all {c : γ} {F : List γ} {r : Gen κ β} : + (all c F).has pos r = true ↔ ∀ d ∈ c :: F, r.aliveAt (pos d) = true := + sorry + +/-- **SNP-14** What some cut of a family holds: the rows alive at one of them. -/ +theorem has_any {c : γ} {F : List γ} {r : Gen κ β} : + (any c F).has pos r = true ↔ ∃ d ∈ c :: F, r.aliveAt (pos d) = true := + sorry + +/-- **SNP-14** What every cut of a family holds is what its least and its greatest cut both hold: +two positions, whatever the size of the family. -/ +theorem has_all_eq_kept {c lo hi : γ} {F : List γ} (hlo : lo ∈ c :: F) (hhi : hi ∈ c :: F) + (hF : ∀ d ∈ c :: F, pos lo ≤ pos d ∧ pos d ≤ pos hi) (r : Gen κ β) : + (all c F).has pos r = (kept lo hi).has pos r := + sorry + +/-- **SNP-13** A measure that is a sum over the rows walks the signed difference: the sum over what +the second cut holds, with the sum over the rows gone, is the sum over what the first holds, with +the sum over the rows come. A count is the case of the measure one. -/ +theorem sum_rows_delta {M : Type*} [AddCommMonoid M] (w : Gen κ β → M) (a b : γ) + (rs : List (Gen κ β)) : + (((cut b).rows pos rs).map w).sum + (((gone a b).rows pos rs).map w).sum + = (((cut a).rows pos rs).map w).sum + (((come a b).rows pos rs).map w).sum := + sorry + +/-- **SNP-13** The count walks the signed difference: no set is read to count the next cut's rows +from the last cut's. -/ +theorem length_rows_delta (a b : γ) (rs : List (Gen κ β)) : + ((cut b).rows pos rs).length + ((gone a b).rows pos rs).length + = ((cut a).rows pos rs).length + ((come a b).rows pos rs).length := + sorry + +end Held + +/-- **SNP-14** A row is alive at some cut of a family exactly when it is counted in one at least. -/ +theorem countIn_pos_iff {F : List ℕ} {r : Gen κ β} : + 0 < countIn F r ↔ ∃ c ∈ F, r.aliveAt c = true := + sorry + +/-- **SNP-14** A row is alive at every cut of a family exactly when it is counted in each. -/ +theorem countIn_eq_length_iff {F : List ℕ} {r : Gen κ β} : + countIn F r = F.length ↔ ∀ c ∈ F, r.aliveAt c = true := + sorry + +end Delta + +/-! ### The rows removed, added and replaced -/ + +section Classes + +variable {κ β : Type*} [DecidableEq κ] + +/-- **SNP-13** The first side of a signed difference is sorted in two: each of its rows is removed +or is the first of a replaced pair. -/ +theorem mem_gone_iff {g c : List (Gen κ β)} {r : Gen κ β} : + r ∈ g ↔ r ∈ removedOf g c ∨ ∃ r', (r, r') ∈ replacedOf g c := + sorry + +/-- **SNP-13** And not in both: a removed row is the first of no replaced pair. -/ +theorem not_replacedOf_of_removedOf {g c : List (Gen κ β)} {r r' : Gen κ β} + (h : r ∈ removedOf g c) : (r, r') ∉ replacedOf g c := + sorry + +/-- **SNP-13** The second side is sorted in two as well, when it holds one row a key at most, as the +contents of a cut do: each of its rows is added or is the second of a replaced pair. -/ +theorem mem_come_iff {g c : List (Gen κ β)} + (hc : ∀ x ∈ c, ∀ y ∈ c, x.key = y.key → x = y) {r' : Gen κ β} : + r' ∈ c ↔ r' ∈ addedOf g c ∨ ∃ r, (r, r') ∈ replacedOf g c := + sorry + +end Classes + +/-! ### On the generations of a chain -/ + +section Generations + +variable {κ β : Type*} [DecidableEq κ] + +/-- **SNP-12** A row records the chain's event at its position: the rows of the generations are the +events of the chain, each with the stamp of its key's next event. -/ +theorem getElem?_of_mem_gens {l : List (κ × β)} {r : Gen κ β} (hr : r ∈ gens l) : + l[r.born - 1]? = some (r.key, r.val) := + sorry + +/-- **SNP-12** The closing stamp of a row is the position of its key's next event, which lies past +the row's own. -/ +theorem exists_next_of_mem_gens {l : List (κ × β)} {r : Gen κ β} (hr : r ∈ gens l) {d : ℕ} + (hd : r.died = some d) : r.born < d ∧ ∃ r' ∈ gens l, r'.key = r.key ∧ r'.born = d := + sorry + +/-- **SNP-12** A row of the generations is well formed: it is alive at its own position. -/ +theorem proper_of_mem_gens {l : List (κ × β)} {r : Gen κ β} (hr : r ∈ gens l) : r.Proper := + sorry + +/-- **SNP-17** The closing stamps are a function of the keys alone: a chain with its values +rewritten, key by key, has the generations of the chain with their values rewritten. An erasure that +keeps the key of a hole moves no position and no stamp. -/ +theorem gens_map {β' : Type*} (f : κ × β → β') (l : List (κ × β)) : + gens (l.map fun e ↦ (e.1, f e)) + = (gens l).map fun r ↦ ⟨r.key, f (r.key, r.val), r.born, r.died⟩ := + sorry + +/-- **SNP-12** What a cut holds is each key's state at the cut, once: the rows of a key alive at a +cut are the one row of its state there, or none. Every head at once is the read of every key. -/ +theorem map_val_filter_key_contentAt (l : List (κ × β)) (c : ℕ) (x : κ) : + ((contentAt (gens l) c).filter fun r ↦ decide (r.key = x)).map Gen.val + = (stateAt l c x).toList := + sorry + +/-- **SNP-12** A cut holds one row a key at most: two rows of one key alive at one cut are one row. +-/ +theorem eq_of_key_eq_of_mem_contentAt {l : List (κ × β)} {c : ℕ} {r r' : Gen κ β} + (hr : r ∈ contentAt (gens l) c) (hr' : r' ∈ contentAt (gens l) c) (hk : r.key = r'.key) : + r = r' := + sorry + +/-- **SNP-14** Append invariance for every set: a set whose cuts lie inside the chain holds, after +any growth of the chain, the events it held. The growth writes closing stamps into rows the set +holds, each past the old head, so the events are compared and not the stamps. -/ +theorem Held.rows_gens_append {γ : Type*} {pos : γ → ℕ} {e : Held γ} {l : List (κ × β)} + (t : List (κ × β)) (h : ∀ c ∈ e.atoms, pos c ≤ l.length) : + (e.rows pos (gens (l ++ t))).map Gen.event = (e.rows pos (gens l)).map Gen.event := + sorry + +/-- **SNP-14** So a set whose cuts lie at or under a cut inside the chain reads the prefix at that +cut and nothing after it: what a cut holds is a derived view of its read. -/ +theorem Held.rows_gens_take {γ : Type*} {pos : γ → ℕ} {e : Held γ} {l : List (κ × β)} {c : ℕ} + (hc : c ≤ l.length) (h : ∀ a ∈ e.atoms, pos a ≤ c) : + (e.rows pos (gens l)).map Gen.event = (e.rows pos (gens (l.take c))).map Gen.event := + sorry + +/-- **SNP-13** The signed difference is sound for what did not change: every row on either side of +it belongs to a key that an event between the two cuts names. A key the events between do not name +holds at both cuts the row it held. -/ +theorem key_mem_of_mem_delta {l : List (κ × β)} {a b : ℕ} (h : a ≤ b) {r : Gen κ β} + (hr : r ∈ gens l) + (hd : (Held.gone a b).has id r = true ∨ (Held.come a b).has id r = true) : + r.key ∈ ((l.take b).drop a).map Prod.fst := + sorry + +/-- **SNP-17** A retire is a removal: when a key holds a version at one cut and its last event at +another is a retire, the row of the version is gone between the two, and no row of the key that came +carries a version. -/ +theorem removed_of_retire {l : List (κ × Option β)} {a b : ℕ} {x : κ} {v : β} + (ha : stateAt l a x = some (some v)) (hb : stateAt l b x = some none) : + (∃ r ∈ gens l, r.key = x ∧ r.val = some v ∧ (Held.gone a b).has id r = true) ∧ + ∀ r ∈ gens l, r.key = x → (Held.come a b).has id r = true → r.val = none := + sorry + +/-- **SNP-17** No row of a chain with holes carries an erased value, so no set of its versions holds +one. -/ +theorem not_erased_of_mem_gens_holes {E : κ × β → Bool} {l : List (κ × β)} + {r : Gen κ (Option β)} {v : β} (hr : r ∈ gens (holes E l)) (hv : r.val = some v) : + E (r.key, v) = false := + sorry + +/-- **SNP-17** An erasure takes its own rows out of every set and changes no other: the versions a +set holds on the chain with holes are the rows it holds on the chain, less the erased ones, each at +the position it had. -/ +theorem Held.rows_gens_holes {γ : Type*} {pos : γ → ℕ} (e : Held γ) (E : κ × β → Bool) + (l : List (κ × β)) : + ((e.rows pos (gens (holes E l))).filter Gen.isVersion).map Gen.event + = ((e.rows pos (gens l)).filter fun r ↦ !E (r.key, r.val)).map + fun r ↦ (r.key, some r.val, r.born) := + sorry + +end Generations + +/-! ### On a store: the grant and the positions -/ + +section Store + +variable {K α β κ γ : Type*} + +/-- **SNP-16** A narrower grant's restriction of a family of chains is its restriction of a wider +grant's. -/ +theorem restrict_narrow {G G' : K → Prop} [DecidablePred G] [DecidablePred G'] + {p p' : α → Bool} (hG : ∀ k, G k → G' k) (hp : ∀ a, p a = true → p' a = true) + (t : Store K α) : restrict G p t = restrict G p (restrict G' p' t) := + sorry + +/-- **SNP-16** Every set commutes with the grant: read on the chains the grant shows, it is the +grant's restriction of the set read on the whole store. The grant may be applied before the +operators or after them. -/ +theorem Held.across_restrict (G : K → Prop) [DecidablePred G] (p : Gen κ β → Bool) + (pos : γ → Cut K) (e : Held γ) (R : K → List (Gen κ β)) : + e.across pos (restrict G p R) = restrict G p (e.across pos R) := + sorry + +/-- **SNP-16** Noninterference for every set: under a grant a set reads only the chains the grant +names, and of its cuts only their positions on them. Two stores that agree on those chains, at cuts +that agree on them, give one answer. -/ +theorem Held.across_congr (G : K → Prop) [DecidablePred G] (p : Gen κ β → Bool) + {pos pos' : γ → Cut K} {e : Held γ} {R R' : K → List (Gen κ β)} + (hR : ∀ k, G k → R k = R' k) (hpos : ∀ c ∈ e.atoms, ∀ k, G k → pos c k = pos' c k) : + restrict G p (e.across pos R) = restrict G p (e.across pos' R') := + sorry + +/-- **SNP-16** A narrower grant's set is the restriction of a wider grant's. -/ +theorem Held.across_narrow {G G' : K → Prop} [DecidablePred G] [DecidablePred G'] + {p p' : Gen κ β → Bool} (hG : ∀ k, G k → G' k) (hp : ∀ a, p a = true → p' a = true) + (pos : γ → Cut K) (e : Held γ) (R : K → List (Gen κ β)) : + restrict G p (e.across pos R) = restrict G p (restrict G' p' (e.across pos R)) := + sorry + +/-- **SNP-16** Under a grant a set names no chain the grant does not name. -/ +theorem Held.across_of_not (G : K → Prop) [DecidablePred G] (p : Gen κ β → Bool) + (pos : γ → Cut K) (e : Held γ) (R : K → List (Gen κ β)) {k : K} (h : ¬G k) : + restrict G p (e.across pos R) k = [] := + sorry + +/-- **SNP-16** The events between two cuts under a grant that names whole chains: restricting to the +chains commutes with the read between, as it does with the read at a cut. -/ +theorem restrict_readBetween (G : K → Prop) [DecidablePred G] (s : Store K α) (a b : Cut K) : + restrict G (fun _ ↦ true) (readBetween s a b) + = readBetween (restrict G (fun _ ↦ true) s) a b := + sorry + +/-- **SNP-15** Contents against positions, on a store: what either of two cuts holds is what their +join holds, with the rows closed between their meet and their join. -/ +theorem Held.has_union_cut (a b : Cut K) (k : K) (r : Gen κ β) : + ((Held.cut a).union (Held.cut b)).has (fun c ↦ c k) r + = ((Held.cut (a ⊔ b)).union (Held.gone (a ⊓ b) (a ⊔ b))).has (fun c ↦ c k) r := + sorry + +/-- **SNP-15** And what both hold is what their meet and their join both hold, the two cuts taken +chain by chain in their order. -/ +theorem Held.has_inter_cut (a b : Cut K) (k : K) (r : Gen κ β) : + ((Held.cut a).inter (Held.cut b)).has (fun c ↦ c k) r + = (Held.kept (a ⊓ b) (a ⊔ b)).has (fun c ↦ c k) r := + sorry + +/-- **SNP-11** The meet and the join of two cuts that are read as asked are read as asked: the cuts +that are consistent and served are closed under both, the consistency by CLK-2. -/ +theorem resolvesIn_sup {R : K → ℕ → K → ℕ → Prop} {S : K → Set ℕ} {a b : Cut K} + (ha : Consistent R a) (hb : Consistent R b) (hSa : a ∈ servedCuts S) + (hSb : b ∈ servedCuts S) : ResolvesIn R S (a ⊔ b) (a ⊔ b) := + sorry + +/-- **SNP-11** The same for the meet. -/ +theorem resolvesIn_inf {R : K → ℕ → K → ℕ → Prop} {S : K → Set ℕ} {a b : Cut K} + (ha : Consistent R a) (hb : Consistent R b) (hSa : a ∈ servedCuts S) + (hSb : b ∈ servedCuts S) : ResolvesIn R S (a ⊓ b) (a ⊓ b) := + sorry + +/-- **SNP-11** The read at the join of two cuts is, chain by chain, the read at the later of the +two. -/ +theorem readAt_sup (s : Store K α) (a b : Cut K) (k : K) : + readAt s (a ⊔ b) k = if a k ≤ b k then readAt s b k else readAt s a k := + sorry + +/-- **SNP-11** The read at the meet of two cuts is, chain by chain, the read at the earlier of the +two. -/ +theorem readAt_inf (s : Store K α) (a b : Cut K) (k : K) : + readAt s (a ⊓ b) k = if a k ≤ b k then readAt s a k else readAt s b k := + sorry + +/-- **SNP-11** The read at the empty cut is empty. -/ +theorem readAt_bot (s : Store K α) : readAt s ⊥ = fun _ ↦ [] := + sorry + +/-- **SNP-11** The meet distributes over the join, and so do the reads: the cuts are a distributive +lattice. -/ +theorem readAt_inf_sup (s : Store K α) (a b c : Cut K) : + readAt s (a ⊓ (b ⊔ c)) = readAt s (a ⊓ b ⊔ a ⊓ c) := + sorry + +/-- **SNP-11** The difference of two cuts on positions, the events the second holds and the first +does not, is the read between their meet and the second. -/ +theorem readBetween_inf_left (s : Store K α) (a b : Cut K) : + readBetween s (a ⊓ b) b = readBetween s a b := + sorry + +/-- **SNP-11** And the read between the first and their join. -/ +theorem readBetween_sup_right (s : Store K α) (a b : Cut K) : + readBetween s a (a ⊔ b) = readBetween s a b := + sorry + +/-- **SNP-11** The symmetric difference of two cuts on positions, the events exactly one of them +holds, is the read between their meet and their join: on each chain, one of the two differences. -/ +theorem readBetween_inf_sup (s : Store K α) (a b : Cut K) (k : K) : + readBetween s (a ⊓ b) (a ⊔ b) k = readBetween s a b k ++ readBetween s b a k := + sorry + +/-- **SNP-11** The empty cut is inside every store: the bottom. -/ +theorem bot_mem_cutsIn (s : Store K α) : (⊥ : Cut K) ∈ cutsIn s := + sorry + +/-- **SNP-11** The head is inside the store, and every cut inside the store lies under it: the top. +-/ +theorem head_mem_cutsIn (s : Store K α) : head s ∈ cutsIn s := + sorry + +/-- **SNP-11** The head moves and no cut leaves: the cuts inside a store are inside every extension +of it. -/ +theorem cutsIn_mono {s s' : Store K α} (h : Extends s s') : cutsIn s ≤ cutsIn s' := + sorry + +/-- **SNP-14** A function of two cuts' reads is append invariant. -/ +theorem combine_grow (f : Store K α → Store K α → β) {s : Store K α} (t : Store K α) + {a b : Cut K} (ha : a ≤ head s) (hb : b ≤ head s) : + combine f (grow s t) a b = combine f s a b := + sorry + +/-- **SNP-14** A measure at each cut of a family is append invariant. -/ +theorem series_grow (D : Store K α → β) {s : Store K α} (t : Store K α) {F : List (Cut K)} + (hF : ∀ c ∈ F, c ≤ head s) : series D (grow s t) F = series D s F := + sorry + +/-- **SNP-14** A fold over a family of cuts is append invariant. -/ +theorem foldOver_grow (g : β → Store K α → β) (init : β) {s : Store K α} (t : Store K α) + {F : List (Cut K)} (hF : ∀ c ∈ F, c ≤ head s) : + foldOver g init (grow s t) F = foldOver g init s F := + sorry + +/-- **SNP-11** The difference of two cuts on positions is a function of their two reads: the events +of the second read past the length of the first. -/ +theorem readBetween_eq_combine (s : Store K α) (a b : Cut K) : + readBetween s a b = combine (fun x y k ↦ (y k).drop (x k).length) s a b := + sorry + +end Store + +namespace Witness + +/-- **SNP-15** The control for the two meanings of union: on contents it does not follow the join of +the positions. One key written twice: the union of what the two cuts hold has both rows, and the +join of the two cuts holds the later one alone. -/ +theorem union_ne_join : + ∃ (l : List (Unit × ℕ)) (a b : ℕ), + (((Held.cut a).union (Held.cut b)).rows id (gens l)).map Gen.val = [0, 1] ∧ + ((Held.cut (a ⊔ b)).rows id (gens l)).map Gen.val = [1] := + sorry + +/-- **SNP-12** The control for contiguity: it is a law of rows, and a value has none. A key that +returns to a value it held before holds it at two cuts and not between them. -/ +theorem value_not_contiguous : + ∃ l : List (Unit × ℕ), + stateAt l 1 () = some 0 ∧ stateAt l 3 () = some 0 ∧ stateAt l 2 () = some 1 := + sorry + +/-- **SNP-13** The control for the composition of signed differences: through a cut that does not +lie between the two it fails. A row alive at `a` and `c` and not at `b` is come from `b` to `c` and +is on neither side from `a` to `c`. -/ +theorem delta_through_outside : + ∃ (r : Gen Unit Unit) (a b c : ℕ), + (Held.come a c).has id r = false ∧ + (((Held.come a b).diff (Held.gone b c)).union (Held.come b c)).has id r = true := + sorry + +/-- **SNP-16** The control for the row's own test: applied to the chain before its generations are +computed, it moves the positions, and a cut then holds an event from after it. -/ +theorem filter_before_gens : + ∃ (l : List (ℕ × ℕ)) (p : ℕ × ℕ → Bool) (c : ℕ), + (contentAt (gens (l.filter p)) c).map Gen.val = [8] ∧ + ((contentAt (gens l) c).filter fun r ↦ p (r.key, r.val)).map Gen.val = [] := + sorry + +/-- **SNP-13** The control for the signed difference against the events between two cuts: a key +landed and retired between them is named by the events and is on neither side of the difference. -/ +theorem changed_not_delta : + ∃ (l : List (Unit × Option ℕ)) (a b : ℕ), + () ∈ ((l.take b).drop a).map Prod.fst ∧ + ((Held.gone a b).rows id ((gens l).filter Gen.isVersion)).length = 0 ∧ + ((Held.come a b).rows id ((gens l).filter Gen.isVersion)).length = 0 := + sorry + +/-- **SNP-14** The control for the missing complement: the rows a cut does not hold are not append +invariant, since every later row is among them. -/ +theorem complement_grows : + ∃ (l t : List (Unit × ℕ)) (c : ℕ), c ≤ l.length ∧ + ((gens (l ++ t)).filter fun r ↦ !r.aliveAt c).length + ≠ ((gens l).filter fun r ↦ !r.aliveAt c).length := + sorry + +end Witness + +end Palace.Snapshot diff --git a/formal/comparator.json b/formal/comparator.json index bb76128d..2a0c8e16 100644 --- a/formal/comparator.json +++ b/formal/comparator.json @@ -271,38 +271,118 @@ "Palace.SigmaStar.sigmaStar_eq_none_iff", "Palace.SigmaStar.sigmaStar_symm", "Palace.SigmaStar.sigmaStar_ultra", + "Palace.Snapshot.Gen.aliveAt_and", + "Palace.Snapshot.Gen.aliveAt_and_eq_inf_sup", + "Palace.Snapshot.Gen.aliveAt_and_not", + "Palace.Snapshot.Gen.aliveAt_and_not'", + "Palace.Snapshot.Gen.aliveAt_iff", + "Palace.Snapshot.Gen.aliveAt_inf_of_open", + "Palace.Snapshot.Gen.aliveAt_of_between", + "Palace.Snapshot.Gen.aliveAt_or_eq_sup", + "Palace.Snapshot.Gen.aliveAt_sup_of_open", + "Palace.Snapshot.Gen.exists_aliveAt_iff", + "Palace.Snapshot.Gen.forall_aliveAt_iff", + "Palace.Snapshot.Held.across_congr", + "Palace.Snapshot.Held.across_narrow", + "Palace.Snapshot.Held.across_of_not", + "Palace.Snapshot.Held.across_restrict", + "Palace.Snapshot.Held.exists_atom_of_has", + "Palace.Snapshot.Held.has_all", + "Palace.Snapshot.Held.has_all_eq_kept", + "Palace.Snapshot.Held.has_any", + "Palace.Snapshot.Held.has_come", + "Palace.Snapshot.Held.has_come_trans", + "Palace.Snapshot.Held.has_cut_eq_apply", + "Palace.Snapshot.Held.has_diff_diff", + "Palace.Snapshot.Held.has_eq_of_interval", + "Palace.Snapshot.Held.has_gone", + "Palace.Snapshot.Held.has_gone_trans", + "Palace.Snapshot.Held.has_gone_triangle", + "Palace.Snapshot.Held.has_inter_cut", + "Palace.Snapshot.Held.has_inter_union", + "Palace.Snapshot.Held.has_kept", + "Palace.Snapshot.Held.has_symm", + "Palace.Snapshot.Held.has_trans_of_transient", + "Palace.Snapshot.Held.has_union_cut", + "Palace.Snapshot.Held.length_rows_delta", + "Palace.Snapshot.Held.mem_rows_diff", + "Palace.Snapshot.Held.mem_rows_inter", + "Palace.Snapshot.Held.mem_rows_union", + "Palace.Snapshot.Held.rows_filter", + "Palace.Snapshot.Held.rows_gens_append", + "Palace.Snapshot.Held.rows_gens_holes", + "Palace.Snapshot.Held.rows_gens_take", + "Palace.Snapshot.Held.sum_rows_delta", "Palace.Snapshot.Kept.mono", + "Palace.Snapshot.Witness.changed_not_delta", + "Palace.Snapshot.Witness.complement_grows", + "Palace.Snapshot.Witness.delta_through_outside", + "Palace.Snapshot.Witness.filter_before_gens", "Palace.Snapshot.Witness.present_not_appendInvariant", "Palace.Snapshot.Witness.seal_empties_history", "Palace.Snapshot.Witness.stateOf_forgets", + "Palace.Snapshot.Witness.union_ne_join", + "Palace.Snapshot.Witness.value_not_contiguous", "Palace.Snapshot.appendInvariant_iff_exists_view", "Palace.Snapshot.appendInvariant_iff_prefixOnly", "Palace.Snapshot.appendInvariant_view", + "Palace.Snapshot.bot_mem_cutsIn", + "Palace.Snapshot.combine_grow", + "Palace.Snapshot.countIn_eq_length_iff", + "Palace.Snapshot.countIn_pos_iff", + "Palace.Snapshot.cutsIn_mono", + "Palace.Snapshot.eq_of_key_eq_of_mem_contentAt", + "Palace.Snapshot.exists_next_of_mem_gens", "Palace.Snapshot.foldAt_readBetween", + "Palace.Snapshot.foldOver_grow", "Palace.Snapshot.genRead_gens", "Palace.Snapshot.genRead_gens_append", "Palace.Snapshot.genRead_gens_length", + "Palace.Snapshot.gens_map", + "Palace.Snapshot.getElem?_of_mem_gens", + "Palace.Snapshot.head_mem_cutsIn", "Palace.Snapshot.head_readAt", "Palace.Snapshot.historyAt_length", "Palace.Snapshot.kept_grown_iff", + "Palace.Snapshot.key_mem_of_mem_delta", "Palace.Snapshot.landingsAt_append", "Palace.Snapshot.landingsAt_length", "Palace.Snapshot.landingsAt_lives_append", "Palace.Snapshot.landingsAt_mono", "Palace.Snapshot.length_filter_selects_le_one", + "Palace.Snapshot.map_val_filter_key_contentAt", + "Palace.Snapshot.mem_come_iff", + "Palace.Snapshot.mem_gone_iff", "Palace.Snapshot.mem_readAt_iff", "Palace.Snapshot.mem_readAt_of_le", + "Palace.Snapshot.not_erased_of_mem_gens_holes", + "Palace.Snapshot.not_replacedOf_of_removedOf", "Palace.Snapshot.pair_readAt", "Palace.Snapshot.prefixOnly_view", + "Palace.Snapshot.proper_of_mem_gens", "Palace.Snapshot.readAt_append_readBetween", + "Palace.Snapshot.readAt_bot", "Palace.Snapshot.readAt_grow", "Palace.Snapshot.readAt_head", + "Palace.Snapshot.readAt_inf", + "Palace.Snapshot.readAt_inf_sup", "Palace.Snapshot.readAt_mono", "Palace.Snapshot.readAt_of_extends", "Palace.Snapshot.readAt_of_head_le", "Palace.Snapshot.readAt_readAt", + "Palace.Snapshot.readAt_sup", "Palace.Snapshot.readBetween_append", + "Palace.Snapshot.readBetween_eq_combine", "Palace.Snapshot.readBetween_grow", + "Palace.Snapshot.readBetween_inf_left", + "Palace.Snapshot.readBetween_inf_sup", + "Palace.Snapshot.readBetween_sup_right", + "Palace.Snapshot.removed_of_retire", + "Palace.Snapshot.resolvesIn_inf", + "Palace.Snapshot.resolvesIn_sup", + "Palace.Snapshot.restrict_narrow", + "Palace.Snapshot.restrict_readBetween", + "Palace.Snapshot.series_grow", "Palace.Snapshot.servedAt_length", "Palace.Snapshot.servedNow_length", "Palace.Snapshot.shown_grow", diff --git a/papers/2026-11-13-cut-algebra/paper.tex b/papers/2026-11-13-cut-algebra/paper.tex new file mode 100644 index 00000000..86dbe7aa --- /dev/null +++ b/papers/2026-11-13-cut-algebra/paper.tex @@ -0,0 +1,471 @@ +\documentclass[11pt]{article} +\usepackage[T1]{fontenc} +\usepackage{lmodern} +\usepackage{microtype} +\usepackage[margin=1in]{geometry} +\usepackage{amsmath,amssymb,amsthm,mathtools} +\usepackage{algorithm} +\usepackage{algpseudocode} +\usepackage{booktabs} +\usepackage{tabularx} +\usepackage[numbers,sort&compress]{natbib} +\usepackage[hidelinks]{hyperref} +\usepackage[capitalise,noabbrev]{cleveref} +\setlength{\emergencystretch}{3em} + +\theoremstyle{plain} +\newtheorem{theorem}{Theorem}[section] +\theoremstyle{definition} +\newtheorem{definition}[theorem]{Definition} + +\newcommand{\lean}[1]{\path{#1}} +\newcommand{\N}{\mathbb{N}} +\newcommand{\alive}{\mathrm{alive}} +\newcommand{\gone}{\mathrm{gone}} +\newcommand{\come}{\mathrm{come}} +\newcommand{\held}{\mathrm{held}} +\newcommand{\born}{\mathrm{born}} +\newcommand{\died}{\mathrm{died}} + +\title{The Algebra of Cuts:\\ +Positions, Contents and Their Differences over an Append-Only Log} +\author{Alberto Serrano-Calva} +\date{November 13, 2026} + +\begin{document} +\maketitle + +\begin{abstract} +A personal knowledge store records every change to its catalog in an append-only log, one chain a +provenance class, so a cut, one position a chain, names the store as of a moment. Its first read +of every version a cut holds built a row in Python a head, 1.7 to 1.8~s for the 400{,}274 heads +of a corpus chain whose walk in SQL takes 66~ms. This paper treats the cut as a lazy value with an +algebra instead. On positions, cuts form a distributive lattice, as the consistent cuts of a +distributed computation do, and the difference of two cuts is the events between them. On +contents, a version is one row of the log, alive on one half-open interval of positions, so the +union, the intersection and the difference of what cuts hold are predicates on a row's position +and its closing stamp: they compose without a read and run as one statement, and the signed +difference of two cuts is two range reads whose cost grows with what changed. The union on +contents is not the union on positions: it holds both versions of an edited note, and the two +agree exactly on rows that are never closed. Seven laws are proved in Lean~4, 110 theorems with +six controls among them, and a property test checks the code against a fold of the log. On a +copy of the corpus catalog, every head counts in 66~ms and reads as three columns in 0.22~s, and +the signed difference over a thousand positions is counted in 2.5~ms and read and sorted in 2.7 +to 2.9~ms, against 3.6 to 3.8~s for two full reads and a set difference. +\end{abstract} + +\section{Introduction} + +The system is a personal knowledge store \cite{serranocalva2026palace}: notes, dialogue, papers and +code land through one writer into a dozen stores, and a sentence of a query algebra reads them. +Its catalog maps each source path to the content it holds now and is rewritten in place. A +landing log, built as the first stage of a design for reading the store as of a past cut, keeps +the catalog's past: every write appends a row to a hash-chained chain of its provenance class, in +the transaction of the catalog's own row, and a row stores the position of its path's next event +when that event lands, its closing stamp. A cut is one position a chain, about a dozen integers +for an instance. + +That stage's read of every version a cut holds returned a list of row objects: 3.5 to 3.9~$\mu$s a +head beyond the walk, so the read passed a tenth of a second near 27{,}000 heads. Before a later +stage builds the store's graph at a cut on this read, its shape had to change. The design takes +five requirements as given. The value a cut names is the store's graph at its positions, evaluated +lazily, so that holding a cut reads nothing. Operators take one cut with another, a difference, a +union and an intersection among them, and operations of any kind apply to one cut or to a family of +cuts. Each of the two set operations has two forms, one of positions and one of contents, and both +are kept. An operation given no cut works on the current one, the way a stack operation takes the +value on top. And editing a node gives it a new version while it stays the same node, so that a cut +holds each node in the version alive there. + +The contributions: +\begin{enumerate} +\item A design (\cref{sec:design}): the cut as an immutable frontier; operators typed so that every + result that is a cut, a set or a difference is an operand again; four forms every operation is + written on; and a default that binds the head once an evaluation. +\item The interval structure (\cref{sec:laws}): a version alive on one half-open interval makes + every set operation a predicate on two columns, both differences of two cuts range reads, and + the composition of differences exact through a cut between the two. +\item Seven laws, SNP-11 to SNP-17, proved in Lean~4 over a model of the log, with controls that + show where each fails, and attacked by randomized instances. +\item A build over SQLite (\cref{sec:build}): statements bounded by the intervals so that the + planner walks what changed, columns read as one buffer each, and a tool of the store's protocol + for agents. +\item Measurements on a copy of a 400{,}274-item catalog (\cref{sec:eval}). +\end{enumerate} + +\section{Background and related work} + +\paragraph{Cuts.} A cut of a distributed computation is a set of events closed under the order of +each process; Chandy and Lamport recorded consistent global states with markers +\cite{chandy1985snapshots}, and Mattern showed that the consistent cuts form a lattice under union +and intersection, with vector time as its coordinates \cite{mattern1989virtual}. Down-sets of a +partial order form a distributive lattice \cite{davey2002lattices}. Each chain here is one append +order, so a cut is a down-set of a disjoint union of chains, the lattice is the product of the +chains' positions, and every frontier of chains that read no other chain is consistent. The log's +chains read no other chain but for a change of class, which writes a row in each of two chains in +one transaction (\cref{sec:limits}). + +\paragraph{Temporal data.} Transaction-time databases keep each version of a record with the +interval of time it was current, and a survey compares the access methods for such data +\cite{salzberg1999access}; SQL:2011 stores a system-time period on each row of a versioned table +\cite{kulkarni2012sql2011}. The relational interval tree answers interval intersection queries +with the indexes a relational system already has \cite{kriegel2000intervals}, and a timeline index +serves temporal aggregation, joins and time travel in a column store \cite{kaufmann2013timeline}. +The landing log is a transaction-time table whose period ends at the closing stamp. Allen's +thirteen relations classify how two intervals stand \cite{allen1983intervals}; a cut asks only +whether a point lies in an interval, and that is what keeps every operator a range read. + +\paragraph{Graphs over time.} DeltaGraph retrieves past snapshots of a graph from a hierarchy of +stored deltas \cite{khurana2013deltagraph}, a temporal graph algebra gives operators on evolving +graphs under point semantics \cite{moffitt2017tga}, and temporal networks are studied for the +structure of contacts in time \cite{holme2012temporal}. The cut here is a frontier over several +chains read under a grant, and its graph is a later stage; the quantities that stage updates over +a difference rest on standard tools: a low-rank correction of a factor \cite{woodbury1950inverting}, +eigensolvers started from earlier vectors \cite{knyazev2001lobpcg}, and union-find for added edges +\cite{tarjan1975union}. + +\paragraph{Tools.} The laws are proved in Lean~4 \cite{moura2021lean4} with mathlib +\cite{mathlib2020}; the code is tested with Hypothesis \cite{maciver2019hypothesis}. + +\section{The model and the laws}\label{sec:laws} + +\begin{definition}[Stores, cuts, reads] +A store is a family of lists indexed by chain keys $K$, and a cut is a function $c : K \to \N$. +The read at $c$ takes the first $c(k)$ events of each chain, the head is the cut of the lengths, +and the cuts inside a store are those at or under the head. The events between cuts $a$ and $b$ +are, on each chain, those after position $a(k)$ and up to $b(k)$. +\end{definition} + +\begin{definition}[Generations] +On a chain of keyed writes each write is a row $r$ with a key, a value, its position $\born(r)$, +and its closing stamp $\died(r)$, the position of the key's next write, or none. The row is +alive at $c$ when $\born(r) \le c$ and $\died(r)$ is none or above $c$. A tombstone and a purged +row carry no value: they close the row before them and are no version. +\end{definition} + +\begin{definition}[Sets of rows] +A set is an expression: $\held(c)$, or the union, the intersection or the difference of two +sets. A row is in $\held(c)$ when it is alive at $c$, and in a combination by the Boolean +operation on the operands. The signed difference of two cuts is +$\gone(a,b) = \held(a) \setminus \held(b)$ and $\come(a,b) = \held(b) \setminus \held(a)$. +\end{definition} + +The definitions are \lean{Gen}, \lean{Held} and \lean{Held.has} in +\lean{formal/Palace/SnapshotAlgebra/Defs.lean}, over the model of the reads in +\lean{formal/Palace/Snapshot/Defs.lean}. There is no complement, deliberately: every set lies +inside the contents of the cuts it names (\lean{Held.exists_atom_of_has}), and the complement, the +rows a cut does not hold, grows with every landing (\lean{Witness.complement_grows}). + +\begin{theorem}[SNP-11, the lattice of cuts] +The cuts inside a store are closed under the pointwise meet and join, with the empty cut at the +bottom and the head at the top, and no cut leaves as the store grows. The read at $a \sqcup b$ +is, chain by chain, the later of the two reads and at $a \sqcap b$ the earlier; the events +between $a$ and $b$ are those between $a \sqcap b$ and $b$, and those between $a$ and +$a \sqcup b$. (\lean{cutsIn}, \lean{readAt_sup}, \lean{readAt_inf}, \lean{readBetween_inf_left}, +\lean{readBetween_sup_right}.) +\end{theorem} + +\begin{theorem}[SNP-12, a row lives on an interval] +A row alive at two cuts is alive at every cut between them. For $a \le b$ on a chain, +\begin{align*} +r \in \come(a,b) &\iff a < \born(r) \le b \text{ and } \died(r) \notin [\born(r), b],\\ +r \in \gone(a,b) &\iff \born(r) \le a < \died(r) \le b,\\ +r \in \held(a) \cap \held(b) &\iff \born(r) \le a \text{ and } \died(r) \notin [\born(r), b], +\end{align*} +and a row is alive at every cut of a family exactly when it is alive at the least and the +greatest. On the generations of a chain a cut holds one row a key. (\lean{Gen.aliveAt_of_between}, +\lean{Gen.aliveAt_and_not}, \lean{Gen.aliveAt_and_not'}, \lean{Gen.aliveAt_and}, +\lean{Gen.forall_aliveAt_iff}, \lean{eq_of_key_eq_of_mem_contentAt}.) +\end{theorem} + +The first two are what make a difference cheap: the rows come are a range of positions, read on +the primary key, and the rows gone a range of closing stamps, read on an index of them. Both cost +what changed, not what is held. The control is a value rather than a row: a path that returns to +bytes it held holds them at two cuts and not between (\lean{Witness.value_not_contiguous}), which +is why the element of a cut's contents is a row of the log and not a digest. + +\begin{theorem}[SNP-13, the signed difference] +$\held(b) = (\held(a) \setminus \gone(a,b)) \cup \come(a,b)$. When $b$ lies between $a$ and $c$ on +every chain, in either direction, +\begin{align*} +\come(a,c) &= (\come(a,b) \setminus \gone(b,c)) \cup \come(b,c),\\ +\gone(a,c) &= \gone(a,b) \cup (\gone(b,c) \setminus \come(a,b)), +\end{align*} +and a row that came and went on the way is on neither side. A sum over the rows at $b$ is the +sum at $a$ less the rows gone, with the rows come. Sorted by key, each row gone is removed or the +first of a replaced pair and not both, each row come is added or the second of one, and every key +of the difference is one the events between name. (\lean{Held.has_cut_eq_apply}, +\lean{Held.has_come_trans}, \lean{Held.has_gone_trans}, \lean{Held.sum_rows_delta}, +\lean{mem_gone_iff}, \lean{not_replacedOf_of_removedOf}, \lean{mem_come_iff}, +\lean{key_mem_of_mem_delta}.) +\end{theorem} + +Through a cut outside the two the composition fails (\lean{Witness.delta_through_outside}). The +region of identities the events between two cuts name holds more than the difference: a path +landed and retired between them is named by the events and holds a version at neither cut +(\lean{Witness.changed_not_delta}). + +\begin{theorem}[SNP-14, closure] +Whether a row is in a set is a function of its position and its closing stamp alone; a set read +is the set operation on the reads; a row's own test commutes with every set; a set whose cuts +lie inside the chain is unchanged by its growth; and what every cut of a family holds is what +its least and its greatest both hold. A function of two reads, a measure at each cut of a family +and a fold over one are unchanged by growth. (\lean{Held.has_eq_of_interval}, +\lean{Held.mem_rows_union}, \lean{Held.rows_filter}, \lean{Held.rows_gens_append}, +\lean{Held.has_all_eq_kept}, \lean{combine_grow}, \lean{series_grow}, \lean{foldOver_grow}.) +\end{theorem} + +\begin{theorem}[SNP-15, contents against positions] +What either of two cuts holds is what their join holds with the rows gone between their meet and +their join; what both hold is what their meet and their join both hold. For a row never closed, +the join's contents are the union of the contents and the meet's their intersection. +(\lean{Held.has_union_cut}, \lean{Held.has_inter_cut}, \lean{Gen.aliveAt_sup_of_open}, +\lean{Gen.aliveAt_inf_of_open}.) +\end{theorem} + +The control is one key written twice between two cuts: the union on contents holds two rows and +the contents of the join one (\lean{Witness.union_ne_join}). So the two meanings are two +operators, and the types tell them apart. + +\begin{theorem}[SNP-16 and SNP-17, the grant and the erasure] +A set read on the chains a grant shows is the grant's restriction of the set read on the whole +store, reads only those chains and its cuts' positions on them, and names no other. The closing +stamps are a function of the keys alone, so a purged row that keeps its key moves no position and +no stamp; it leaves every set and changes no other row of any set. A retire is a removal in every +signed difference that spans it. (\lean{Held.across_restrict}, \lean{Held.across_congr}, +\lean{gens_map}, \lean{Held.rows_gens_holes}, \lean{removed_of_retire}.) +\end{theorem} + +Each proof is a case analysis on the Boolean values of aliveness at the cuts involved, or an +induction on the list of rows; the composition laws use contiguity to exclude the one case, +alive at $a$ and $c$ and not at $b$, that a cut between rules out. The library proves the seven +laws in 110 theorems, six of them the controls, with no axiom beyond the standard three; 80 of +the declarations are restated with their proofs left out and judged identical by a comparator, +and every proof is replayed by six independent kernel checkers. Seeds 529 to 566 attack the +statements with 500 random instances each: twenty-one attacks survive, one of them on the 295 +instances its guard admits, and seventeen negative controls are refuted. + +\section{The design}\label{sec:design} + +\Cref{tab:objects} gives the objects and what each holds before anything is read. A cut is its +positions, compared and hashed as a value, so two equal cuts are one key. Every other object holds +cuts and how they are combined, and reading is a separate act: a count, columns, or the sorted +rows of a difference. + +\begin{table}[t] +\centering\small +\begin{tabularx}{\linewidth}{@{}lXX@{}} +\toprule +object & holds, unread & read as \\ +\midrule +a cut & one position a chain & nothing: it is the value \\ +events between two cuts & the two cuts & a count; rows of every kind \\ +a set of versions & an expression over cuts & a count; columns \\ +a signed difference & two sets, gone and come & counts of removed, added, replaced; sorted rows \\ +a family & a list of cuts & by operation \\ +a number, a series, a table & nothing: a result & itself; no operand of a set operator \\ +\bottomrule +\end{tabularx} +\caption{The objects of the algebra. Join and meet take two cuts and return a cut; union, +intersection, difference and symmetric difference take two sets and return a set, a cut given +there being the set it holds.}\label{tab:objects} +\end{table} + +\paragraph{The interface.} Every operation is written against four forms: \emph{apply}, a +function of one cut's read; \emph{combine}, a function of two; \emph{map}, a function at each +cut of a family; and \emph{fold}, an accumulation over a family. A read hands an operator the cut, +the versions it holds and the events up to it, all unread. The named operations are instances: +what a cut holds is an apply, the events between and the signed difference are combines, what +persisted through a family is a fold that carries the family's meet and join, and the count at +each cut walked by the differences is a fold that carries the last read and its count. Each form +is a function of the prefixes, so by SNP-14 each is unchanged by growth, and any operation that +is none of the named ones is admitted by writing it against the same four. + +\paragraph{The default.} An operation that names no cut reads the head, and the head is read once, +when the evaluation starts: every part of one answer reads one cut, and the answer names its +positions. Asked again with those positions, the question gives the same answer whatever has +landed since, up to what a later purge erased. The stack the requirement compares the default to +is a comparison only; no stack of cuts and no state is kept between two evaluations. + +\paragraph{Scope and erasure.} The grant names chains, so every statement names the chains of the +grant's classes and no other; a cut naming another chain is refused in the words used for a chain +that does not exist. A purged version is a row without its salt, which the version's own test +leaves out of every set; the answer counts such rows in the ranges it read. + +\section{The build}\label{sec:build} + +The engine is one module over the log's tables in the catalog's SQLite file. An evaluation reads +the chains of the asker's classes and their heads in one statement; cuts are restricted to those +chains, and a position past a chain's head is refused. + +\paragraph{From an expression to a statement.} For each chain the expression compiles to two +things (\cref{alg:compile}): the predicate, a Boolean combination of +\texttt{seq <= c AND (closed\_at IS NULL OR closed\_at > c)} for each cut's position $c$; and the +bounds the intervals imply, a range of positions and a range of closing stamps that every row of +the set lies in. The bounds add nothing to the predicate's meaning, but they are ranges an index +can take: for $\come(a,b)$ the positions $(a, b]$, on the primary key; for $\gone(a,b)$ the closing +stamps $(a, b]$, on the index of closing stamps. A chain whose bounds are empty is skipped, so a +difference between two cuts that agree on a chain reads nothing there. A set of any depth is then +one statement, and combining two sets runs none. + +\begin{algorithm}[t] +\caption{The bounds of a set on one chain: positions in $(\ell, h]$, closing stamps in $(d, u]$, +$u = \top$ for an open row.}\label{alg:compile} +\begin{algorithmic}[1] +\Function{Bounds}{$e$} + \If{$e = \held(c)$} \Return $(0, c, c, \top)$ if $c > 0$, else empty \EndIf + \State $P \gets \Call{Bounds}{e.p}$ + \If{$e$ is a union} \Return the hull of $P$ and \Call{Bounds}{$e.q$} \EndIf + \If{$e$ is an intersection} \Return the meet of $P$ and \Call{Bounds}{$e.q$}, or empty \EndIf + \For{each cut $c > 0$ that $e.q$ is, or is a union of}\Comment{$e = e.p \setminus e.q$} + \If{$d_P \ge c$} $\ell_P \gets \max(\ell_P, c)$\Comment{alive past $c$, not at it: stored after it}\EndIf + \If{$h_P \le c$} $u_P \gets \min(u_P, c)$\Comment{stored by $c$, not alive at it: closed by it}\EndIf + \EndFor + \State \Return $P$, or empty if a range is empty +\EndFunction +\end{algorithmic} +\end{algorithm} + +\paragraph{Columns.} A count is one statement of two aggregates, the versions and the holes, and +builds no row. Rows are read as columns: each column is aggregated in SQL into one string and +decoded into one buffer, an integer column into an array of 64-bit integers, the path's key into +an array of 32-byte values, and text into one run of bytes with an array of offsets, decoded a +value at a time when a listing asks for it. Reading rows makes fewer than one Python object a +row. + +\paragraph{The signed difference.} Its counts are one statement: the two sides, materialized, +joined on the chain and the path's key, so a path replaced is counted once and removed and added +are the rest. Read, both sides are sorted in one sort of their 40-byte keys, the chain and the +path's key; since a cut holds one row a path on a chain, a key on both sides is two neighbours, +the row gone first. Composition takes the formulas of SNP-13 and is refused unless the shared cut +lies between the outer two on every chain. + +\paragraph{Families.} What persisted reads two positions a chain whatever the family's size. The +pairwise table reads once what some cut of the family holds, as positions and closing stamps, +builds the matrix $M$ with $M_{ri} = 1$ when cut $i$ holds row $r$, and returns +$M^{\top}(1 - M)$, whose entry $(i,j)$ counts what $i$ holds and $j$ does not. + +\paragraph{The tool.} One tool of the store's protocol for agents, \texttt{cut}, takes an operator +and its operands: each a cut's name (\texttt{head}, \texttt{bottom}, or positions written +\texttt{land.@}) or a call written as an object, whose result is the operand. So a +call is one expression: it reads the heads when it starts, a chain's horizon once for a position +named under the chain's head, and then what its outermost operator needs. The server opens the +catalog's file to only read, and a call's sets name at most 256 cuts, counted each time their +statement names one. A set given where a cut is expected is refused by its type, and the refusal +names what was given and what is taken. A +position under a chain's horizon, inside the block that opens a chain and is not history, is read +at the chain's empty prefix, and the answer's note says so. Every answer names the cuts it read +by their positions and says that it is of versions only: edges and graph mathematics at a cut +arrive with a later stage. + +The read the contents replace is removed with nothing kept beside it; the measurements keep its +statement as their baseline. The tests check every law against a plain fold of the log kept in +the test code, over Hypothesis's random sequences of catalog writes: records, retires, renames, +relabels, re-keys, changes of class and purges, at every position and every pair of positions of +each chain and at random frontiers over several chains, ordered and not. + +\section{Evaluation}\label{sec:eval} + +The deterministic tier of the repository's tests passes at 3{,}757 tests with the algebra's 36. +The measurements are of the code as built, on two copy-on-write clones of a corpus instance's +catalog: 400{,}274 items of one class, so one chain whose genesis ends at position 400{,}276, then +200{,}000 writes after it (100{,}000 new versions of held paths, 50{,}000 retires, 50{,}000 new +paths, shuffled), the chain ending at 600{,}276 with 400{,}274 heads. One machine, an Apple M2 +Pro with 32~GB, Python 3.15.2, SQLite 3.54.1 and NumPy 2.5.4, with other work running at a load +average between 2.3 and 4.0. The figures are medians of five repetitions, the two runs given as a +range (\cref{tab:heads,tab:delta}). + +\begin{table}[t] +\centering\small +\begin{tabular}{@{}lrr@{}} +\toprule +every head of the chain, 400{,}274 & at the genesis's head & after the history \\ +\midrule +a row in Python a head (the read replaced) & 1.74--1.79~s & 1.82--1.86~s \\ +counted & 66~ms & 90--95~ms \\ +three columns: position, key, digest & 219--224~ms & 236--241~ms \\ +eight columns & 433--437~ms & 440--442~ms \\ +\bottomrule +\end{tabular} +\caption{Every head of the corpus chain. The columns equal the rows in both runs.}\label{tab:heads} +\end{table} + +\begin{table}[t] +\centering\small +\begin{tabular}{@{}rrrrrr@{}} +\toprule +positions & removed, added, replaced & counts & sides as columns & sorted & two reads \\ +\midrule +1 & 1, 0, 0 & 0.02 & 0.02, 0.02 & 0.08 & 3{,}670--3{,}728 \\ +1{,}000 & 248, 224, 528 & 2.5 & 0.4, 1.9--2.0 & 2.7--2.9 & 3{,}684--3{,}742 \\ +100{,}000 & 24{,}995, 25{,}010, 49{,}995 & 279--305 & 42, 218--238 & 318--362 & 3{,}655--3{,}787 \\ +200{,}000 & 50{,}000, 50{,}000, 100{,}000 & 560--604 & 83--90, 448--463 & 657--682 & 3{,}634--3{,}812 \\ +600{,}276 & 0, 400{,}274, 0 & 144--147 & 238--260, 0.01 & 398--448 & 1{,}783--1{,}879 \\ +\bottomrule +\end{tabular} +\caption{The signed difference ending at the head, over spans of positions, in milliseconds: its +counts, its two sides as columns (come, then gone), its rows sorted, and two reads of every head +with a set difference. Every side equalled the set difference.}\label{tab:delta} +\end{table} + +\paragraph{Every head.} Counted, every head of the chain takes 66~ms, 0.17~$\mu$s an event walked +and no row built, 27 times faster than the rows it replaces, so a count passes a tenth of a second +up to about 600{,}000 events. Three columns take 0.22~s, eight times faster than the rows and over +that bar: beyond the walk a head costs 0.39~$\mu$s as three columns, against 4.2~$\mu$s as a row. +Three columns pass the bar near 180{,}000 heads on a chain whose events are its heads. That is the +size at which the design keeps heads at recorded cuts or walks the differences from a first read, +and the corpus chain is over it. + +\paragraph{The difference.} Counted, it costs what changed: 0.02~ms for one position, 2.5~ms for +a thousand (2.7 to 2.9~ms read and sorted), 0.28 to 0.31~s for 100{,}000 and 0.56 to 0.60~s for +the whole history, against 3.6 to 3.8~s for two reads of every head and a set difference at every +span that ends at the head from inside the history, and 1.8 to 1.9~s from the bottom, where one +of the two reads is empty. The planner took the primary key for the rows come and the index of +closing stamps for the rows gone, unprompted. The +rows gone cost 2.9 to 3.2~$\mu$s a row against 0.57 for the rows come, since each is found on the +index and then read from the table by its position, where the rows come are one run of the +primary key. + +\paragraph{A family.} For ten cuts spread over the history, the counts walked by the differences +took 0.43 to 0.49~s against 0.79 to 0.83~s for ten counts, and equalled them; what persisted +through all took 64~ms, one walk to the least position; what existed in any 99~ms; and the +pairwise table 0.32~s, equal to the hundred differences' sizes. + +\section{Limitations}\label{sec:limits} + +The model states the laws over lists, and the statements the code runs are not in it: that each +runs as its predicate is the property test's, not a theorem's. Every head as columns is over the +bar at the corpus's size, so a reader of every head of such a chain reads it once and walks the +differences. The rows gone are read through an index and the table, five times the cost a row of +the rows come. The measurements are of one chain of one class, so a difference between two cuts +neither of which is under the other was tested and not measured, and the history purged nothing. +A position named under a chain's head is checked against the chain's horizon by a walk back to +the horizon's row, once a call for each chain, since no index finds it. A change of class writes +a row in each of two chains in one transaction, and a frontier can hold one without the other, +so that the path is in both classes or in neither; such a frontier is read as asked and the tool +says so, and whether the pair becomes a reference the resolver follows is left to the next +stage. And this is not yet the graph: the edges by species and the graph's quantities at a cut +are the next stage's. + +\section{Future work} + +The next stages add the store's other chains (the chat log, the attestation ledger, the commit +order) to the same cut value, then build the graph at a cut on this algebra: the nodes as the +versions a cut holds, each handed to an operator as its parts, the edges by species and their +differences between two cuts, and the quantities updated over a difference where that is cheaper. +On synthetic nearest-neighbour graphs the design measured where each update pays: a low-rank +correction of a factor up to about a hundred changed edges, eigenvectors carried from the earlier +cut with its factor as the preconditioner at every edit measured, and union-find for added edges +up to a few hundred to a few thousand. A later stage writes the algebra's regions into the query +language, and whether an agent outside the owner's grant may call the tool is left to the owner. + +\section{Conclusion} + +A cut is a handful of positions. Reading what it holds as rows built in Python cost a row object +a head; reading it as a predicate on two columns costs a walk, and the difference of two cuts +costs what changed between them. The two meanings of union and intersection differ by a theorem +and by their types, the seven laws the code relies on are machine-checked, and the code is tested +against them on random histories. + +\bibliographystyle{plainnat} +\bibliography{refs} +\end{document} diff --git a/papers/2026-11-13-cut-algebra/refs.bib b/papers/2026-11-13-cut-algebra/refs.bib new file mode 100644 index 00000000..65bcc1e4 --- /dev/null +++ b/papers/2026-11-13-cut-algebra/refs.bib @@ -0,0 +1,182 @@ +@article{chandy1985snapshots, + author = {Chandy, K. Mani and Lamport, Leslie}, + title = {Distributed Snapshots: Determining Global States of Distributed Systems}, + journal = {ACM Transactions on Computer Systems}, + volume = {3}, + number = {1}, + pages = {63--75}, + year = {1985}, + doi = {10.1145/214451.214456} +} + +@incollection{mattern1989virtual, + author = {Mattern, Friedemann}, + title = {Virtual Time and Global States of Distributed Systems}, + booktitle = {Parallel and Distributed Algorithms}, + editor = {Cosnard, M. and Quinton, P. and Raynal, M. and Robert, Y.}, + pages = {215--226}, + publisher = {North-Holland}, + year = {1989} +} + +@book{davey2002lattices, + author = {Davey, B. A. and Priestley, H. A.}, + title = {Introduction to Lattices and Order}, + edition = {Second}, + publisher = {Cambridge University Press}, + year = {2002}, + doi = {10.1017/CBO9780511809088} +} + +@article{allen1983intervals, + author = {Allen, James F.}, + title = {Maintaining Knowledge about Temporal Intervals}, + journal = {Communications of the ACM}, + volume = {26}, + number = {11}, + pages = {832--843}, + year = {1983}, + doi = {10.1145/182.358434} +} + +@article{salzberg1999access, + author = {Salzberg, Betty and Tsotras, Vassilis J.}, + title = {Comparison of Access Methods for Time-Evolving Data}, + journal = {ACM Computing Surveys}, + volume = {31}, + number = {2}, + pages = {158--221}, + year = {1999}, + doi = {10.1145/319806.319816} +} + +@article{kulkarni2012sql2011, + author = {Kulkarni, Krishna and Michels, Jan-Eike}, + title = {Temporal Features in {SQL}:2011}, + journal = {ACM SIGMOD Record}, + volume = {41}, + number = {3}, + pages = {34--43}, + year = {2012}, + doi = {10.1145/2380776.2380786} +} + +@inproceedings{kriegel2000intervals, + author = {Kriegel, Hans-Peter and P{\"o}tke, Marco and Seidl, Thomas}, + title = {Managing Intervals Efficiently in Object-Relational Databases}, + booktitle = {Proceedings of the 26th International Conference on Very Large Data Bases ({VLDB})}, + pages = {407--418}, + year = {2000} +} + +@inproceedings{kaufmann2013timeline, + author = {Kaufmann, Martin and Manjili, Amin Amiri and Vagenas, Panagiotis and Fischer, Peter + Michael and Kossmann, Donald and F{\"a}rber, Franz and May, Norman}, + title = {Timeline Index: A Unified Data Structure for Processing Queries on Temporal Data in + {SAP} {HANA}}, + booktitle = {Proceedings of the 2013 ACM SIGMOD International Conference on Management of Data}, + pages = {1173--1184}, + year = {2013}, + doi = {10.1145/2463676.2465293} +} + +@inproceedings{khurana2013deltagraph, + author = {Khurana, Udayan and Deshpande, Amol}, + title = {Efficient Snapshot Retrieval over Historical Graph Data}, + booktitle = {2013 IEEE 29th International Conference on Data Engineering ({ICDE})}, + pages = {997--1008}, + year = {2013}, + doi = {10.1109/ICDE.2013.6544892} +} + +@inproceedings{moffitt2017tga, + author = {Moffitt, Vera Zaychik and Stoyanovich, Julia}, + title = {Temporal Graph Algebra}, + booktitle = {Proceedings of the 16th International Symposium on Database Programming Languages + ({DBPL})}, + pages = {10:1--10:12}, + year = {2017}, + doi = {10.1145/3122831.3122838} +} + +@article{holme2012temporal, + author = {Holme, Petter and Saram{\"a}ki, Jari}, + title = {Temporal Networks}, + journal = {Physics Reports}, + volume = {519}, + number = {3}, + pages = {97--125}, + year = {2012}, + doi = {10.1016/j.physrep.2012.03.001} +} + +@techreport{woodbury1950inverting, + author = {Woodbury, Max A.}, + title = {Inverting Modified Matrices}, + institution = {Statistical Research Group, Princeton University}, + type = {Memorandum Report}, + number = {42}, + year = {1950} +} + +@article{knyazev2001lobpcg, + author = {Knyazev, Andrew V.}, + title = {Toward the Optimal Preconditioned Eigensolver: Locally Optimal Block Preconditioned + Conjugate Gradient Method}, + journal = {SIAM Journal on Scientific Computing}, + volume = {23}, + number = {2}, + pages = {517--541}, + year = {2001}, + doi = {10.1137/S1064827500366124} +} + +@article{tarjan1975union, + author = {Tarjan, Robert Endre}, + title = {Efficiency of a Good But Not Linear Set Union Algorithm}, + journal = {Journal of the ACM}, + volume = {22}, + number = {2}, + pages = {215--225}, + year = {1975}, + doi = {10.1145/321879.321884} +} + +@article{maciver2019hypothesis, + author = {MacIver, David and Hatfield-Dodds, Zac and {Many Contributors}}, + title = {Hypothesis: A New Approach to Property-Based Testing}, + journal = {Journal of Open Source Software}, + volume = {4}, + number = {43}, + pages = {1891}, + year = {2019}, + doi = {10.21105/joss.01891} +} + +@inproceedings{moura2021lean4, + author = {de Moura, Leonardo and Ullrich, Sebastian}, + title = {The {Lean} 4 Theorem Prover and Programming Language}, + booktitle = {Automated Deduction -- {CADE} 28}, + series = {Lecture Notes in Computer Science}, + pages = {625--635}, + publisher = {Springer}, + year = {2021}, + doi = {10.1007/978-3-030-79876-5_37} +} + +@inproceedings{mathlib2020, + author = {{The mathlib Community}}, + title = {The {Lean} Mathematical Library}, + booktitle = {Proceedings of the 9th ACM SIGPLAN International Conference on Certified Programs + and Proofs}, + pages = {367--381}, + year = {2020}, + doi = {10.1145/3372885.3373824} +} + +@misc{serranocalva2026palace, + author = {Serrano-Calva, Alberto}, + title = {mind-palace}, + howpublished = {\url{https://github.com/ascalva/mind-palace}}, + year = {2026} +} diff --git a/tests/property/test_cut_algebra.py b/tests/property/test_cut_algebra.py new file mode 100644 index 00000000..67a23ff3 --- /dev/null +++ b/tests/property/test_cut_algebra.py @@ -0,0 +1,888 @@ +"""The algebra of cuts on the code (dn-temporal-snapshot §4.4, §10; stage SN-1b). + +`core/stores/cuts.py` reads the landing log's rows as a cut's contents, through a predicate on a +row's position and its closing stamp. Each law is checked here against a plain fold of the log +kept in this file: on every chain, each path's last event at or under a position, kept when it is +a `store` that keeps its content. The catalogs are SN-1's random ones, a build before the log +followed by random catalog writes with retires, renames, relabels, re-keys, changes of class and +both purges among them, so the logs have holes, closed rows and classes of several chains. The +cuts are the heads taken after every write and frontiers drawn at random, ordered and not. The +properties, each with the law it transcribes (§12, SN-1b): + +1. the lattice laws on positions, and the events between two cuts read from their meet and to + their join (SNP-11); +2. the four interval statements against the fold at every position and at pairs of positions, + contiguity, and one row a path in every cut's contents (SNP-12); +3. the signed difference against the fold's set difference in both orders and for cuts neither + of which is under the other; applied; composed through a cut between, with the composition + through a cut outside as the control; the count walked along a family; the three classes + disjoint and covering; every path of a difference among the paths of the events between + (SNP-13); +4. expressions of any depth read lazily against the same operations on the fold's sets, results + of each operator given to others, no statement run by combining, the count without the rows, + and the family operations (SNP-14); +5. every set, difference and count at cuts inside the log unchanged by further writes, up to the + holes a later purge leaves (SNP-14, with SNP-1); +6. on a class with no closes the contents of the join are the union of the contents and those of + the meet the intersection; after one edit they differ, as the control (SNP-15); +7. the sets and differences of one class read only that class's chains: unchanged by writes to + another class and by the positions named on its chains (SNP-16); +8. after a purge no set and no difference holds a row of the purged digest and every other row + is the row it was; a retire is a removal in every difference that spans it (SNP-17); +9. the default: an evaluation with no cut named reads one head in every part, names it, and + gives the same result when asked again with the positions it named after further writes + (D27, SNF-19). + +The tool's property, the tenth, is `tests/unit/test_cut_tool.py`'s. +""" + +from __future__ import annotations + +import itertools +import re +from collections.abc import Iterator +from contextlib import contextmanager +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +import numpy as np +import pytest +from hypothesis import HealthCheck, given, settings +from hypothesis import strategies as st + +from core.kernel.provenance import Provenance +from core.stores.catalog import VaultCatalog +from core.stores.cuts import ( + BOTTOM, + Cut, + CutError, + Delta, + Evaluation, + Text, + Versions, + join_all, + meet_all, +) +from core.stores.landings import Landing +from tests.property.test_landing_log import CLASSES, apply, from_legacy, legacy, ops + +ALL = [str(c) for c in CLASSES] + +Row = tuple[int, int] # a version, named by its position: (chain, seq) +Rows = frozenset[Row] +SETTINGS = settings(max_examples=120, deadline=None, + suppress_health_check=[HealthCheck.too_slow, HealthCheck.data_too_large]) + + +# --- the reference fold, in test code ------------------------------------------------------------ + +@dataclass +class Fold: + """Each chain's rows, and what every position of it holds by a fold of the prefix: each + path's last event at or under the position, kept when it is a `store` that keeps its + content.""" + + rows: dict[int, list[Landing]] + alive: dict[int, list[frozenset[int]]] + + @classmethod + def of(cls, cat: VaultCatalog) -> Fold: + rows: dict[int, list[Landing]] = {} + alive: dict[int, list[frozenset[int]]] = {} + for ch in cat._log.all_chains(): + rows[ch] = cat.read_at(ch, cat.head(ch)) + last: dict[bytes, Landing] = {} + at = [frozenset[int]()] + for row in rows[ch]: + if row.path_key is not None: + last[row.path_key] = row + at.append(frozenset(r.seq for r in last.values() + if r.kind == "store" and not r.hole)) + alive[ch] = at + return cls(rows, alive) + + def held(self, cut: Cut, chains: tuple[int, ...]) -> Rows: + return frozenset((ch, s) for ch in chains for s in self.alive[ch][cut.at(ch)]) + + def row(self, r: Row) -> Landing: + return self.rows[r[0]][r[1] - 1] + + def between(self, a: Cut, b: Cut, chains: tuple[int, ...]) -> list[Row]: + return [(ch, r.seq) for ch in chains for r in self.rows[ch] + if a.at(ch) < r.seq <= b.at(ch)] + + +def rows_of(s: Versions) -> Rows: + cols = s.columns() + return frozenset(zip(cols.ints("chain").tolist(), cols.ints("seq").tolist(), strict=True)) + + +def keyed(fold: Fold, rows: Rows) -> dict[tuple[int, bytes], Row]: + out: dict[tuple[int, bytes], Row] = {} + for r in rows: + key = fold.row(r).path_key + assert key is not None + assert (r[0], key) not in out, "a cut holds one row a path on a chain" + out[(r[0], key)] = r + return out + + +def build(before: list[tuple[Any, ...]], writes: list[tuple[Any, ...]]) -> tuple[ + VaultCatalog, list[Cut]]: + """A random catalog's genesis and writes, with the head taken after each.""" + cat = from_legacy(before) + taken = [Cut.of(heads(cat))] + for op in writes: + apply(cat, op) + taken.append(Cut.of(heads(cat))) + return cat, taken + + +def heads(cat: VaultCatalog) -> dict[int, int]: + return {ch: cat.head(ch) for ch in cat._log.all_chains()} + + +def frontier(data: st.DataObject, head: Cut, chains: tuple[int, ...]) -> Cut: + """A frontier inside the log drawn at random, one position a chain.""" + return Cut.of({ch: data.draw(st.integers(0, head.at(ch))) for ch in chains}) + + +def cuts_of(data: st.DataObject, taken: list[Cut], ev: Evaluation, n: int) -> list[Cut]: + """`n` cuts: heads taken after writes and frontiers drawn at random, in a random mix.""" + out = [] + for _ in range(n): + if data.draw(st.booleans()): + out.append(ev.cut(data.draw(st.sampled_from(taken)))) + else: + out.append(frontier(data, ev.head, ev.chains)) + return out + + +@contextmanager +def statements(cat: VaultCatalog) -> Iterator[list[str]]: + """The statements the catalog's connection runs inside the block.""" + seen: list[str] = [] + cat._conn.set_trace_callback(seen.append) + try: + yield seen + finally: + cat._conn.set_trace_callback(None) + + +# --- 1. the lattice of cuts (SNP-11) -------------------------------------------------------------- + +positions = st.dictionaries(st.integers(1, 4), st.integers(0, 12), max_size=4) + + +@given(positions, positions, positions) +def test_cuts_are_a_lattice_on_positions(x: dict[int, int], y: dict[int, int], + z: dict[int, int]) -> None: + """A cut is a value: equal positions are one cut and one key, and a chain left out stands + at 0. The join and the meet are the pointwise maximum and minimum, and they satisfy the laws + of a distributive lattice as equalities of values, with the empty cut at the bottom; the + order is the pointwise one, and a cut prints as positions it parses back from.""" + a, b, c = Cut.of(x), Cut.of(y), Cut.of(z) + assert Cut.of({**x, 9: 0}) == a and hash(Cut.of({**x, 9: 0})) == hash(a) + for k in range(1, 6): + assert a.join(b).at(k) == max(a.at(k), b.at(k)) + assert a.meet(b).at(k) == min(a.at(k), b.at(k)) + assert a.join(b) == b.join(a) and a.meet(b) == b.meet(a) + assert a.join(b.join(c)) == a.join(b).join(c) and a.meet(b.meet(c)) == a.meet(b).meet(c) + assert a.join(a.meet(b)) == a == a.meet(a.join(b)) + assert a.join(a) == a == a.meet(a) + assert a.meet(b.join(c)) == a.meet(b).join(a.meet(c)) + assert a.join(b.meet(c)) == a.join(b).meet(a.join(c)) + assert BOTTOM <= a and BOTTOM.join(a) == a and BOTTOM.meet(a) == BOTTOM + assert (a <= b) == all(a.at(k) <= b.at(k) for k in range(1, 6)) == (a.join(b) == b) \ + == (a.meet(b) == a) + assert a.meet(b) <= a <= a.join(b) + order = a.order(b) + assert order == {(True, True): "equal", (True, False): "before", (False, True): "after", + (False, False): "unordered"}[(a <= b, b <= a)] + assert Cut.parse(a.name(range(1, 6))) == a + assert join_all([a, b, c]) == a.join(b).join(c) and meet_all([a, b, c]) == a.meet(b).meet(c) + + +@SETTINGS +@given(legacy, ops, st.data()) +def test_the_join_and_meet_are_cuts_and_the_events_between_read_from_either( + before: list[tuple[Any, ...]], writes: list[tuple[Any, ...]], + data: st.DataObject) -> None: + """On a random log the join and the meet of two cuts inside it are inside it; the events + between two cuts are the fold's rows in the range, chain by chain, the same read from their + meet and to their join; the events between the meet and the join are those between the two + in either order (SNP-11).""" + cat, taken = build(before, writes) + ev = cat.cuts(ALL) + fold = Fold.of(cat) + for _ in range(6): + a, b = cuts_of(data, taken, ev, 2) + assert ev.cut(a.join(b)) <= ev.head and ev.cut(a.meet(b)) <= ev.head + cols = ev.between(a, b).columns("kind") + got = list(zip(cols.ints("chain").tolist(), cols.ints("seq").tolist(), strict=True)) + assert got == fold.between(a, b, ev.chains) + assert ev.between(a, b).count() == len(got) + assert rows_between(ev, a.meet(b), b) == rows_between(ev, a, b) == \ + rows_between(ev, a, a.join(b)) + assert rows_between(ev, a.meet(b), a.join(b)) == \ + rows_between(ev, a, b) | rows_between(ev, b, a) + kinds = cols["kind"] + assert isinstance(kinds, Text) + assert [kinds[i] for i in range(len(kinds))] == \ + [fold.row(r).kind for r in got] + cat.close() + + +def rows_between(ev: Evaluation, a: Cut, b: Cut) -> Rows: + cols = ev.between(a, b).columns() + return frozenset(zip(cols.ints("chain").tolist(), cols.ints("seq").tolist(), strict=True)) + + +# --- 2. a version lives on an interval (SNP-12) --------------------------------------------------- + +@settings(SETTINGS, max_examples=60) +@given(legacy, ops, st.data()) +def test_a_version_lives_on_an_interval_and_the_four_reads_are_its_statements( + before: list[tuple[Any, ...]], writes: list[tuple[Any, ...]], + data: st.DataObject) -> None: + """At every position of every chain the contents are the fold's, one row a path, and the + positions a row is held at are one run: contiguity. At every pair of positions `a <= b`, what + `b` holds and `a` does not, what `a` holds and `b` does not, and what both hold are the + fold's set operations. What every position of a family holds is what its least and its + greatest hold, and what some position holds lies among the rows stored by the greatest and + not closed by the least (SNP-12).""" + cat, _ = build(before, writes) + fold = Fold.of(cat) + for ch in cat._log.all_chains(): + ev = Evaluation(cat._conn, [cls for cls in ALL if ch in cat.chains(cls)]) + one = (ch,) + head = ev.head.at(ch) + at = [Cut.of({ch: c}) for c in range(head + 1)] + got = [rows_of(ev.held(c)) for c in at] + for c, rows in zip(at, got, strict=True): + assert rows == fold.held(c, one) + keyed(fold, rows) + for r in frozenset().union(*got): + held_at = [c for c in range(head + 1) if r in got[c]] + assert held_at == list(range(held_at[0], held_at[-1] + 1)) + for a, b in itertools.combinations_with_replacement(range(head + 1), 2): + fa, fb = got[a], got[b] + assert rows_of(ev.held(at[b]) - ev.held(at[a])) == fb - fa + assert rows_of(ev.held(at[a]) - ev.held(at[b])) == fa - fb + assert rows_of(ev.held(at[a]) & ev.held(at[b])) == fa & fb + for _ in range(4): + family = [at[p] for p in data.draw( + st.lists(st.integers(0, head), min_size=1, max_size=5))] + held = [fold.held(c, one) for c in family] + assert rows_of(ev.persisted(family)) == frozenset.intersection(*held) + some = frozenset.union(*held) + assert rows_of(ev.existed(family)) == some + lo, hi = min(c.at(ch) for c in family), max(c.at(ch) for c in family) + assert all(fold.row(r).seq <= hi and (fold.row(r).closed_at or hi + 1) > lo + for r in some) + cat.close() + + +# --- 3. the signed difference (SNP-13) ------------------------------------------------------------ + +@SETTINGS +@given(legacy, ops, st.data()) +def test_the_signed_difference_is_the_folds_and_composes_through_a_cut_between( + before: list[tuple[Any, ...]], writes: list[tuple[Any, ...]], + data: st.DataObject) -> None: + """For cuts in either order and cuts neither of which is under the other, the two sides of + the signed difference are the fold's set differences, and the counts sort them by path within + a chain into removed, added and replaced, disjoint and covering, one row a path a side; + applied to what the first cut holds it gives what the second holds; through a cut between the + two on every chain it composes, and through one outside the composition is refused; every + path of the difference is a path the events between the meet and the join name; and the + count at each cut of a family, walked by the differences, is the count read (SNP-13).""" + cat, taken = build(before, writes) + ev = cat.cuts(ALL) + fold = Fold.of(cat) + for _ in range(6): + a, b = cuts_of(data, taken, ev, 2) + fa, fb = fold.held(a, ev.chains), fold.held(b, ev.chains) + d = ev.delta(a, b) + assert (rows_of(d.gone), rows_of(d.come)) == (fa - fb, fb - fa) + back = ev.delta(b, a) + assert (rows_of(back.gone), rows_of(back.come)) == (fb - fa, fa - fb) + gone, come = keyed(fold, fa - fb), keyed(fold, fb - fa) + counts = d.counts() + assert counts.replaced == len(gone.keys() & come.keys()) + assert counts.removed == len(gone.keys() - come.keys()) + assert counts.added == len(come.keys() - gone.keys()) + assert counts.removed + counts.replaced == len(fa - fb) == d.sizes()[0] + assert counts.added + counts.replaced == len(fb - fa) == d.sizes()[1] + s = d.sorted("source_path") + removed = set(zip(s.removed.ints("chain").tolist(), s.removed.ints("seq").tolist(), + strict=True)) + added = set(zip(s.added.ints("chain").tolist(), s.added.ints("seq").tolist(), + strict=True)) + old, new = s.replaced + pairs = list(zip(zip(old.ints("chain").tolist(), old.ints("seq").tolist(), strict=True), + zip(new.ints("chain").tolist(), new.ints("seq").tolist(), strict=True), + strict=True)) + assert removed == {r for k, r in gone.items() if k not in come} + assert added == {r for k, r in come.items() if k not in gone} + assert sorted(pairs) == sorted((gone[k], come[k]) for k in gone.keys() & come.keys()) + assert removed.isdisjoint(p for p, _ in pairs) and added.isdisjoint(q for _, q in pairs) + assert rows_of(d.apply(ev.held(a))) == fb + named = {(r[0], fold.row(r).path_key) + for r in fold.between(a.meet(b), a.join(b), ev.chains)} + assert gone.keys() | come.keys() <= named + # composition through a cut between, chain by chain in either direction + m = Cut.of({k: data.draw(st.integers(min(a.at(k), b.at(k)), max(a.at(k), b.at(k)))) + for k in ev.chains}) + both = ev.delta(a, m).then(ev.delta(m, b)) + assert (both.a, both.b) == (a, b) + assert (rows_of(both.gone), rows_of(both.come)) == (fa - fb, fb - fa) + outside = [k for k in ev.chains + if not min(a.at(k), b.at(k)) <= taken[0].at(k) <= max(a.at(k), b.at(k))] + if outside: + with pytest.raises(CutError, match="not between"): + ev.delta(a, ev.cut(taken[0])).then(ev.delta(ev.cut(taken[0]), b)) + elsewhere = next((x for x in (a, m, BOTTOM, ev.head) if x != b), None) + if elsewhere is not None: + with pytest.raises(CutError, match="compose through the cut they share"): + d.then(ev.delta(elsewhere, b)) + family = cuts_of(data, taken, ev, 5) + walked = ev.count_series(family) + assert walked.cuts == tuple(family) + assert list(walked.values) == [len(fold.held(c, ev.chains)) for c in family] + cat.close() + + +def test_a_composition_through_a_cut_outside_the_two_is_not_the_difference() -> None: + """The control of the composition (`Witness.delta_through_outside`): a path landed after `a` + and `c` and edited after that, so a cut `b` past both lies outside them. The formula of the + composition through `b` is not the difference from `a` to `c`, and `then` refuses it.""" + cat = VaultCatalog(Path(":memory:")) + cat.record("p.md", "d1", "P") + ev0 = cat.cuts(ALL) + a = ev0.head + cat.record("q.md", "d2", "Q") + c = cat.cuts(ALL).head + cat.record("p.md", "d3", "P") + ev = cat.cuts(ALL) + b = ev.head + ab, bc = ev.delta(a, b), ev.delta(b, c) + formula = (ab.come - bc.gone) | bc.come + assert rows_of(formula) != rows_of(ev.delta(a, c).come) + with pytest.raises(CutError, match="not between"): + ab.then(bc) + cat.close() + + +# --- 4. closure (SNP-14) -------------------------------------------------------------------------- + +Expr = tuple[Any, ...] +leaf = st.integers(0, 3).map(lambda i: ("held", i)) +expressions: st.SearchStrategy[Expr] = st.recursive( + leaf, lambda sub: st.tuples(st.sampled_from(["|", "&", "-", "^"]), sub, sub), max_leaves=8) + + +def lazily(ev: Evaluation, e: Expr, cuts: list[Cut]) -> Versions: + if e[0] == "held": + return ev.held(cuts[e[1]]) + p, q = lazily(ev, e[1], cuts), lazily(ev, e[2], cuts) + return {"|": p | q, "&": p & q, "-": p - q, "^": p ^ q}[e[0]] + + +def folded(fold: Fold, chains: tuple[int, ...], e: Expr, cuts: list[Cut]) -> Rows: + if e[0] == "held": + return fold.held(cuts[e[1]], chains) + p, q = folded(fold, chains, e[1], cuts), folded(fold, chains, e[2], cuts) + return {"|": p | q, "&": p & q, "-": p - q, "^": p ^ q}[e[0]] + + +@SETTINGS +@given(legacy, ops, st.lists(expressions, min_size=1, max_size=4), st.data()) +def test_a_set_of_any_depth_is_read_lazily_as_the_folds_set( + before: list[tuple[Any, ...]], writes: list[tuple[Any, ...]], es: list[Expr], + data: st.DataObject) -> None: + """Random expressions of any depth over the contents of four cuts are composed with no + statement run, and each is read by one statement as the same operations on the fold's sets; + its count is the size of that set, by one statement that returns two numbers. The results of + the other operators are operands too: the sides of a signed difference, what persisted and + what existed, and a difference applied, each combined with a set. In how many of a family's + cuts a row is held, and the sizes of the pairwise differences, are the fold's (SNP-14).""" + cat, taken = build(before, writes) + ev = cat.cuts(ALL) + fold = Fold.of(cat) + cuts = cuts_of(data, taken, ev, 4) + for e in es: + with statements(cat) as seen: + s = lazily(ev, e, cuts) + assert seen == [] # combining reads nothing + want = folded(fold, ev.chains, e, cuts) + with statements(cat) as seen: + n = s.count() + assert n == len(want) and len(seen) <= 1 + assert all(re.match(r"SELECT coalesce\(sum\(n\), 0\), coalesce\(sum\(h\), 0\) FROM", q) + for q in seen) + with statements(cat) as seen: + got = rows_of(s) + assert got == want and len(seen) <= 1 + assert set(s.cuts) <= set(cuts) + a, b = cuts[0], cuts[1] + fa, fb = fold.held(a, ev.chains), fold.held(b, ev.chains) + d = ev.delta(a, b) + other = lazily(ev, es[0], cuts) + want_other = folded(fold, ev.chains, es[0], cuts) + assert rows_of(d.gone | other) == (fa - fb) | want_other + assert rows_of(d.come & other) == (fb - fa) & want_other + assert rows_of(d.apply(other)) == (want_other - (fa - fb)) | (fb - fa) + held = [fold.held(c, ev.chains) for c in cuts] + assert rows_of(ev.persisted(cuts) ^ other) == frozenset.intersection(*held) ^ want_other + assert rows_of(ev.existed(cuts) - other) == frozenset.union(*held) - want_other + counted = ev.in_how_many(other, cuts, names=("digest",)) + pairs = zip(counted.rows.ints("chain").tolist(), counted.rows.ints("seq").tolist(), + strict=True) + assert [int(x) for x in counted.counts] == [sum(r in h for h in held) for r in pairs] + table = ev.pairwise(cuts) + assert table.sizes == tuple(tuple(len(hi - hj) for hj in held) for hi in held) + cat.close() + + +def test_a_count_builds_no_row_and_the_rows_are_one_buffer_a_column() -> None: + """A count runs one statement and builds no row; the rows come back as columns, each one + buffer: an integer column an array of int64, the key an array of 32-byte values, text one + run of bytes with its offsets. So reading the rows makes fewer than one Python object a + row, whatever their number; a value of text is decoded only when it is asked for.""" + cat = VaultCatalog(Path(":memory:")) + with cat.deferred(): + for i in range(500): + cat.record(f"notes/n{i:03}.md", f"d{i}", f"title {i} é", version=i + 1) + ev = cat.cuts(ALL) + with statements(cat) as seen: + assert ev.held().count() == 500 + assert len(seen) == 1 and "count(salt)" in seen[0] + with statements(cat) as seen: + cols = ev.held().columns("path_key", "source_path", "title", "version", "closed_at") + assert len(seen) == 1 and len(cols) == 500 + for name in ("chain", "seq", "version", "closed_at"): + col = cols[name] + assert isinstance(col, np.ndarray) and col.dtype == np.int64 + key = cols["path_key"] + assert isinstance(key, np.ndarray) and key.dtype == np.dtype("V32") + for name in ("source_path", "title"): + text = cols[name] + assert isinstance(text, Text) and isinstance(text.data, bytes) + assert text.offsets.dtype == np.int64 and len(text.offsets) == 501 + assert cols.row(7) == {"chain": 1, "seq": 10, "path_key": cols.row(7)["path_key"], + "source_path": "notes/n007.md", "title": "title 7 é", "version": 8, + "closed_at": None} + assert len(str(cols.row(7)["path_key"])) == 64 + assert cols.ints("seq").tolist() == sorted(cols.ints("seq").tolist()) + with pytest.raises(CutError, match="no column"): + ev.held().columns("salt") + cat.close() + + +def test_a_symmetric_difference_names_each_operand_once() -> None: + """`^` is a node of its own, whose statement names each operand once: sixty-three of them + nested over three cuts name sixty-four cuts and run as a statement of that size, where `(a - + b) | (b - a)` would double the statement at every level. Its rows are what an odd number of + the cuts it names hold, as the fold's symmetric differences give them.""" + cat = VaultCatalog(Path(":memory:")) + cuts: list[Cut] = [] + for i in range(6): + cat.record(f"notes/n{i % 4}.md", f"d{i}", "t") + cuts.append(Cut.of(heads(cat))) + ev = cat.cuts(ALL) + fold = Fold.of(cat) + picked = [cuts[1], cuts[3], cuts[5]] + s, want = ev.held(picked[0]), fold.held(picked[0], ev.chains) + for i in range(1, 64): + s, want = s ^ ev.held(picked[i % 3]), want ^ fold.held(picked[i % 3], ev.chains) + assert s.terms == 64 + with statements(cat) as seen: + assert s.count() == len(want) + (q,) = seen + assert q.count("closed_at IS NULL OR closed_at >") <= 64 + 1 and len(q) < 8_000 + assert rows_of(s) == want + cat.close() + + +def test_each_side_of_a_difference_walks_what_changed() -> None: + """The rows come between two cuts are read on the primary key from the first cut's position, + and the rows gone on `landings_closed` between the two positions: neither walks the prefix, + so a difference costs what changed and not what is held (§4.4). What a cut holds walks its + prefix.""" + cat = VaultCatalog(Path(":memory:")) + with cat.deferred(): + for i in range(2000): + cat.record(f"notes/n{i:04}.md", f"d{i}", "t") + ev0 = cat.cuts(ALL) + a = ev0.head + with cat.deferred(): + for i in range(0, 2000, 100): + cat.record(f"notes/n{i:04}.md", f"e{i}", "t") + ev = cat.cuts(ALL) + d = ev.delta(a) + + def plan(q: str) -> str: + return " ".join(str(tuple(r)[-1]) for r in cat._conn.execute("EXPLAIN QUERY PLAN " + q)) + + with statements(cat) as seen: + d.come.count() + d.gone.count() + ev.held().count() + come, gone, held = (plan(q) for q in seen) + assert "PRIMARY KEY (chain=? AND seq>? AND seq? AND closed_at None: + """Sets, signed differences and counts taken at cuts inside the log read the same after any + further writes, up to the holes a later purge leaves: a row emptied since is gone from them, + and nothing else changes. So does the same lazy value made before the writes (SNP-14, SNP-1).""" + cat, taken = build(before, first) + ev = cat.cuts(ALL) + a, b = cuts_of(data, taken, ev, 2) + sets = {"a": ev.held(a), "b": ev.held(b), "union": ev.held(a) | ev.held(b), + "gone": ev.delta(a, b).gone, "come": ev.delta(a, b).come, + "persisted": ev.persisted([a, b])} + then = {name: rows_of(s) for name, s in sets.items()} + rows_then = {r: cat.read_at(r[0], r[1])[-1] for rs in then.values() for r in rs} + for op in later: + apply(cat, op) + holes = {r for r in rows_then if cat.read_at(r[0], r[1])[-1].hole} + again = cat.cuts(ALL) + a2, b2 = again.cut(a), again.cut(b) + now = {"a": again.held(a2), "b": again.held(b2), "union": again.held(a2) | again.held(b2), + "gone": again.delta(a2, b2).gone, "come": again.delta(a2, b2).come, + "persisted": again.persisted([a2, b2])} + for name, s in now.items(): + assert rows_of(s) == then[name] - holes == rows_of(sets[name]) + assert s.count() == len(then[name] - holes) + for r in set(rows_then) - holes: + row = cat.read_at(r[0], r[1])[-1] + assert (row.seq, row.digest, row.source_path, row.doc_id) == \ + (rows_then[r].seq, rows_then[r].digest, rows_then[r].source_path, + rows_then[r].doc_id) + cat.close() + + +# --- 6. contents against positions (SNP-15) ------------------------------------------------------- + +@SETTINGS +@given(st.lists(st.tuples(st.integers(0, 40), st.sampled_from(CLASSES)), min_size=1, + max_size=30, unique_by=lambda w: w[0]), st.data()) +def test_on_a_class_with_no_closes_the_join_holds_the_union( + landings: list[tuple[int, Provenance]], data: st.DataObject) -> None: + """In classes each of whose paths lands once and is never written again, no row is ever + closed, and the contents of the join of two cuts are the union of their contents and those + of the meet their intersection, for every pair of cuts taken; on any log, what either holds + is what their join holds with the rows closed between their meet and their join (SNP-15).""" + cat = VaultCatalog(Path(":memory:")) + taken = [Cut()] + for i, cls in landings: + cat.record(f"once/{i}.md", f"d{i}", "t", provenance=cls) + taken.append(Cut.of(heads(cat))) + ev = cat.cuts(ALL) + assert tuple(cat._conn.execute( + "SELECT count(*) FROM landings WHERE closed_at IS NOT NULL").fetchone()) == (0,) + pairs = list(itertools.combinations(taken, 2)) + for a, b in data.draw(st.lists(st.sampled_from(pairs), max_size=12)) if pairs else []: + x, y = ev.cut(a), ev.cut(b) + assert rows_of(ev.held(x.join(y))) == rows_of(ev.held(x) | ev.held(y)) + assert rows_of(ev.held(x.meet(y))) == rows_of(ev.held(x) & ev.held(y)) + cat.close() + + +@SETTINGS +@given(legacy, ops, st.data()) +def test_the_union_is_the_join_with_the_rows_closed_between( + before: list[tuple[Any, ...]], writes: list[tuple[Any, ...]], + data: st.DataObject) -> None: + """On any log, what either of two cuts holds is what their join holds with the rows gone + between their meet and their join, and what both hold is what the meet and the join both + hold (`Held.has_union_cut`, `Held.has_inter_cut`).""" + cat, taken = build(before, writes) + ev = cat.cuts(ALL) + for _ in range(6): + a, b = cuts_of(data, taken, ev, 2) + lo, hi = a.meet(b), a.join(b) + assert rows_of(ev.held(a) | ev.held(b)) == rows_of(ev.held(hi) | ev.delta(lo, hi).gone) + assert rows_of(ev.held(a) & ev.held(b)) == rows_of(ev.held(lo) & ev.held(hi)) + cat.close() + + +def test_after_one_edit_the_union_holds_both_versions_and_the_join_one() -> None: + """The control (`Witness.union_ne_join`): a note edited between two cuts. The union on + contents holds both its versions, the contents of the join, a cut, the later one alone.""" + cat = VaultCatalog(Path(":memory:")) + cat.record("note.md", "first", "N") + a = cat.cuts(ALL).head + cat.record("note.md", "second", "N") + ev = cat.cuts(ALL) + b = ev.head + union = (ev.held(a) | ev.held(b)).columns("digest") + join = ev.held(a.join(b)).columns("digest") + assert [union.row(i)["digest"] for i in range(len(union))] == ["first", "second"] + assert [join.row(i)["digest"] for i in range(len(join))] == ["second"] + assert a.join(b) == b and (ev.held(a) | ev.held(b)).count() == 2 + cat.close() + + +# --- 7. the grant (SNP-16) ------------------------------------------------------------------------ + +@SETTINGS +@given(legacy, ops, st.lists(st.tuples(st.integers(0, 5), st.sampled_from(["x", "y"])), + min_size=1, max_size=12), st.data()) +def test_one_class_reads_only_its_chains( + before: list[tuple[Any, ...]], writes: list[tuple[Any, ...]], + others: list[tuple[int, str]], data: st.DataObject) -> None: + """The sets and signed differences of one class read only its chains: every statement names + those chains and no other; the results are the same after writes to another class and + whatever positions a cut names on another class's chains; and a cut given with such + positions reads none of them (SNP-16).""" + cat, taken = build(before, writes) + classes = [cls for cls in ALL if cat.chains(cls)] + if not classes: + return + mine = data.draw(st.sampled_from(classes)) + elsewhere = next(c for c in ALL if c != mine) + ev = cat.cuts([mine]) + assert set(ev.chains) == set(cat.chains(mine)) + a, b = cuts_of(data, taken, ev, 2) + with statements(cat) as seen: + before_rows = (rows_of(ev.held(a)), rows_of(ev.delta(a, b).gone), + rows_of(ev.delta(a, b).come), ev.delta(a, b).counts()) + named = {int(x) for q in seen for x in re.findall(r"chain = (\d+)", q)} + assert named <= set(ev.chains) + for i, tag in others: # writes to another class only + cat.record(f"elsewhere/{i}.md", f"other-{tag}", "t", provenance=Provenance(elsewhere)) + again = cat.cuts([mine]) + assert again.chains == ev.chains + noise = {k: 10_000 + k for k in cat._log.all_chains() if k not in ev.chains} + a2, b2 = Cut.of({**a.as_dict(), **noise}), Cut.of({**b.as_dict(), **noise}) + assert again.cut(a2) == a and again.cut(b2) == b + after = (rows_of(again.held(a2)), rows_of(again.delta(a2, b2).gone), + rows_of(again.delta(a2, b2).come), again.delta(a2, b2).counts()) + assert after == before_rows + cat.close() + + +# --- 8. erasure and retire (SNP-17) --------------------------------------------------------------- + +@SETTINGS +@given(legacy, ops, st.data()) +def test_a_purge_takes_its_rows_out_of_every_set_and_a_retire_is_a_removal( + before: list[tuple[Any, ...]], writes: list[tuple[Any, ...]], + data: st.DataObject) -> None: + """After a purge of a digest no path holds, no set and no difference at any cut holds a row + that carried it, every other row of every set is the row it was, and every count falls by + the rows purged. A retire is a removal in every difference from a cut that holds the retired + version to a cut at the retire or after it while the path stays retired, and every cut + between the version's landing and the retire holds it (SNP-17).""" + cat, taken = build(before, writes) + ev = cat.cuts(ALL) + fold = Fold.of(cat) + cuts = [ev.cut(c) for c in taken] + digests = sorted({str(fold.row(r).digest) for c in cuts for r in fold.held(c, ev.chains)}) + if digests: + digest = data.draw(st.sampled_from(digests)) + if cat.active_refs(digest) == 0: + sets = {c: rows_of(ev.held(c)) for c in cuts} + holes = {c: ev.held(c).holes() for c in cuts} + purged = {r for rs in sets.values() for r in rs if fold.row(r).digest == digest} + pairs = list(zip(cuts, cuts[1:], strict=False)) + deltas = {p: (rows_of(ev.delta(*p).gone), rows_of(ev.delta(*p).come)) for p in pairs} + cat.remove_digest(digest) + after = cat.cuts(ALL) + for c, rows in sets.items(): + assert rows_of(after.held(c)) == rows - purged + assert after.held(c).count() == len(rows - purged) + assert after.held(c).holes() == holes[c] + len(rows & purged) + for pair, (g, c2) in deltas.items(): + d = after.delta(*pair) + assert (rows_of(d.gone), rows_of(d.come)) == (g - purged, c2 - purged) + for r in {r for rs in sets.values() for r in rs} - purged: + assert cat.read_at(r[0], r[1])[-1] == fold.row(r) # the row it was + ev, fold = after, Fold.of(cat) + for ch, chain_rows in fold.rows.items(): + if ch not in ev.chains: + continue + for retire in (r for r in chain_rows if r.kind == "retire"): + version = next((r for r in reversed(chain_rows[:retire.seq - 1]) + if r.path_key == retire.path_key), None) + if version is None or version.kind != "store" or version.hole: + continue + for at in range(version.seq, retire.seq): + assert (ch, version.seq) in rows_of(ev.held(Cut.of({ch: at}))) + end = retire.closed_at or ev.head.at(ch) + 1 + for at in {version.seq, retire.seq - 1}: + for q in {retire.seq, end - 1}: + s = ev.delta(Cut.of({ch: at}), Cut.of({ch: q})).sorted() + removed = set(zip(s.removed.ints("chain").tolist(), + s.removed.ints("seq").tolist(), strict=True)) + assert (ch, version.seq) in removed + cat.close() + + +# --- 9. the default (D27) ------------------------------------------------------------------------- + +@SETTINGS +@given(legacy, ops, ops) +def test_an_evaluation_reads_one_head_in_every_part_and_names_it( + before: list[tuple[Any, ...]], first: list[tuple[Any, ...]], + later: list[tuple[Any, ...]]) -> None: + """Every operation of one evaluation that names no cut reads the head the evaluation read when + it started, even with writes between its parts, and its result names that head; asked again + in a new evaluation with the positions named, after further writes, it is the same up to the + holes a later purge leaves (D27, SNF-19).""" + cat, _ = build(before, first) + ev = cat.cuts(ALL) + head = ev.head + held = ev.held() + apply_first = rows_of(held) + for op in later[: len(later) // 2]: + apply(cat, op) + since = ev.delta(BOTTOM) + assert held.cuts == (head,) and (since.a, since.b) == (BOTTOM, head) + assert ev.between().upto == head and ev.persisted().cuts == (head,) + assert ev.count_series().cuts == (head,) + for op in later[len(later) // 2:]: + apply(cat, op) + again = cat.cuts(ALL) + holes = {r for r in apply_first if cat.read_at(r[0], r[1])[-1].hole} + assert rows_of(again.held(again.cut(head))) == apply_first - holes == rows_of(held) + assert rows_of(since.come) == apply_first - holes + assert again.head >= head + cat.close() + + +def test_a_cut_past_the_head_or_of_an_unread_chain_is_refused() -> None: + """A cut is taken inside the log: a position past a chain's head is refused, and the refusal + names the head. A name of a chain the evaluation does not read is refused in the words used + for a chain that does not exist; a cut given with positions on such a chain reads none of + them. A malformed name is refused and says how a cut is named.""" + cat = VaultCatalog(Path(":memory:")) + cat.record("a.md", "d1", "A") + cat.record("c.md", "d2", "C", provenance=Provenance.CURATED) + ev = cat.cuts(["authored-solo"]) + (solo,) = ev.chains + (cur,) = cat.chains(Provenance.CURATED) + head = ev.head.at(solo) + with pytest.raises(CutError, match=rf"land.{solo}@{head + 1} is past the chain's head, " + rf"land.{solo}@{head}"): + ev.held(Cut.of({solo: head + 1})) + with pytest.raises(CutError, match=rf"there is no chain land.{cur}; the chains read here " + rf"are land.{solo}"): + ev.named(f"land.{cur}@1") + with pytest.raises(CutError, match="there is no chain land.99"): + ev.named("land.99@1") + assert ev.cut(Cut.of({solo: head, cur: 3})) == Cut.of({solo: head}) + for bad in ("land.1", "land.x@2", "1@2", "land.1@2 land.1@3", ""): + with pytest.raises(CutError): + ev.named(bad) + assert ev.named("head") == ev.head and ev.named("bottom") == BOTTOM + with pytest.raises(CutError, match="a cut is expected"): + ev.held(ev.held()) # type: ignore[arg-type] + with pytest.raises(CutError, match="combines with a set of versions, not with a cut"): + ev.held() | ev.head # type: ignore[operator] + cat.close() + + +def test_a_position_under_a_chains_horizon_is_read_at_its_empty_prefix() -> None: + """A chain's positions before its horizon are its genesis block, which is not history (§8): + a cut asked there is read at the chain's empty prefix, and the chain is named as read below + the position asked. The horizon and every position after it are served, and the head with + no walk.""" + db_rows: list[tuple[str, str, str, Provenance, bool, str | None]] = [ + ("v/a.md", "da", "A", Provenance.AUTHORED_SOLO, True, None), + ("v/b.md", "db", "B", Provenance.AUTHORED_SOLO, True, None)] + cat = from_legacy(db_rows) + (solo,) = cat.chains(Provenance.AUTHORED_SOLO) + horizon = cat.head(solo) # genesis, two stores, the horizon + cat.record("v/c.md", "dc", "C") + ev = cat.cuts(ALL) + for p in range(1, horizon): + read, lowered = ev.served(Cut.of({solo: p})) + assert read == BOTTOM and lowered == [(solo, p)] + for p in range(horizon, ev.head.at(solo) + 1): + assert ev.served(Cut.of({solo: p})) == (Cut.of({solo: p}), []) + assert ev.served(BOTTOM) == (BOTTOM, []) + assert ev.held(Cut.of({solo: horizon})).count() == 2 + cat.close() + + +def test_each_chain_is_walked_for_its_horizon_once_an_evaluation() -> None: + """No index finds a chain's horizon row, so the first position named under a chain's head + walks back to it, and no row is walked twice in one evaluation: every later position on the + chain is then answered with no statement, a position found to lie under the horizon answers + every position under it, and one above it walks only down to it.""" + db_rows: list[tuple[str, str, str, Provenance, bool, str | None]] = [ + (f"v/{i}.md", f"d{i}", "t", Provenance.AUTHORED_SOLO, True, None) for i in range(6)] + cat = from_legacy(db_rows) + (solo,) = cat.chains(Provenance.AUTHORED_SOLO) + horizon = cat.head(solo) # the genesis, six stores, the horizon: 8 + for i in range(4): + cat.record(f"v/{i}.md", f"e{i}", "t") + ev = cat.cuts(ALL) + with statements(cat) as seen: + assert [ev.serves(solo, p) for p in (3, 2, 1, 3)] == [False] * 4 + assert len(seen) == 1 # 3 walked down to the first row; 2, 1 known + with statements(cat) as seen: + assert ev.serves(solo, 5) is False # walks 5 down to 4 only + assert len(seen) == 1 and "seq <= 5 AND seq > 3 " in seen[0] + with statements(cat) as seen: + assert [ev.serves(solo, p) for p in (10, horizon, 9, 6, 11)] == [ + True, True, True, False, True] + assert len(seen) == 1 # 10 found the horizon; the rest read nothing + with statements(cat) as seen: + read, lowered = ev.served(Cut.of({solo: 7})) + assert (read, lowered, seen) == (BOTTOM, [(solo, 7)], []) + cat.close() + + +def test_a_cut_can_split_a_change_of_class_and_is_read_as_asked() -> None: + """A change of class writes a `leave` in the chain the path leaves, then its `store` in the + chain of its new class. No reference of §3.5 joins the two rows, so a cut that holds one of + them and not the other is served as asked: one holds the path in both chains, the other in + neither, and neither is a state the catalog had. The head holds it once (§3.5, §7.5).""" + cat = VaultCatalog(Path(":memory:")) + cat.record("a.md", "d1", "A", provenance=Provenance.AUTHORED_SOLO) + cat.record("b.md", "d2", "B", provenance=Provenance.CURATED) + cat.record("a.md", "d1", "A", provenance=Provenance.CURATED) + (solo,), (cur,) = cat.chains(Provenance.AUTHORED_SOLO), cat.chains(Provenance.CURATED) + assert [r.kind for r in cat.read_at(solo, cat.head(solo))][-2:] == ["store", "leave"] + ev = cat.cuts(ALL) + + def paths(c: Cut) -> list[str]: + text = ev.held(c).columns("source_path")["source_path"] + assert isinstance(text, Text) + return sorted(str(text[i]) for i in range(len(text))) + + twice, neither = Cut.of({solo: 3, cur: 4}), Cut.of({solo: 4, cur: 3}) + for c in (twice, neither): + assert ev.served(c) == (c, []) + assert paths(twice) == ["a.md", "a.md", "b.md"] + assert paths(neither) == ["b.md"] + assert paths(ev.head) == ["a.md", "b.md"] + cat.close() + + +def test_a_delta_from_another_evaluation_or_of_another_kind_is_refused() -> None: + cat = VaultCatalog(Path(":memory:")) + cat.record("a.md", "d1", "A") + one, two = cat.cuts(ALL), cat.cuts(ALL) + with pytest.raises(CutError, match="inside one evaluation"): + one.held() | two.held() + d: Delta = one.delta(BOTTOM) + with pytest.raises(CutError, match="composes with a signed difference, not with a set"): + d.then(one.held()) # type: ignore[arg-type] + cat.close() diff --git a/tests/property/test_landing_log.py b/tests/property/test_landing_log.py index 8ef9a2c7..41426730 100644 --- a/tests/property/test_landing_log.py +++ b/tests/property/test_landing_log.py @@ -22,7 +22,9 @@ * SNP-4, idempotence: the read at the head is the chain, and the state at the head the catalog. * SNP-5, three reads: at every position of every chain, the genesis's included, the seek by key, the closing-stamp read and the fold of the prefix give each path the same row, before and after - rows are emptied, and no path has two rows alive. + rows are emptied, and no path has two rows alive. The closing-stamp read over a class is the + contents of the cut (`core/stores/cuts.py`), which replaced SN-1's `heads_at`: its versions are + the fold's `store` rows that keep their content, and its holes the ones a purge emptied. Then the stage's own cases: a record that changes nothing, and a store the UNCHANGED check skips, append nothing; the writer, its batched landing too, and the sync carry the version each landing @@ -32,8 +34,9 @@ tombstoned paths included, closes each tombstoned path's `store` and ends at a horizon; a relabel into a class that has rows changes no row of the log, closed rows and holes included, and every chain verifies; a history over two chains of a class follows a rule of the prefixes; a purge of an -old version of a live path leaves a hole that all three reads return at a cut where it was the -head, and a purge of every version of a deleted note leaves no row that names it; `verify` fails +old version of a live path leaves a hole that the seek and the fold return at a cut where it was +the head, and that the contents of the cut count as a hole and hold as no version, and a purge of +every version of a deleted note leaves no row that names it; `verify` fails on an edited row and on a hole that keeps any one column of its content; the secret is required by what appends or seeks a path by its key and by nothing else, and another one is refused; a statement by path seeks the key index, and a purge by digest walks the log twice. @@ -56,6 +59,7 @@ from core.kernel.provenance import Provenance from core.stores.authored_supersession import owner_declaration from core.stores.catalog import VaultCatalog +from core.stores.cuts import Cut from core.stores.landings import ( LANDING_LOG_KEY, Landing, @@ -179,6 +183,15 @@ def alive(row: Landing, c: int) -> bool: return row.seq <= c and (row.closed_at is None or row.closed_at > c) +def paths_held(cat: VaultCatalog, cls: Provenance | str, + cut: dict[int, int] | None = None) -> list[str | None]: + """The paths of the versions a cut holds over a class, the head when no cut is given, in + position order: the contents of the cut (`core/stores/cuts.py`).""" + ev = cat.cuts([str(cls)]) + text = ev.held(Cut.of(cut) if cut is not None else None).columns("source_path")["source_path"] + return [text[i] for i in range(len(text))] + + def emptied(row: Landing) -> bool: """A hole as a purge leaves it (§6.1): no salt, and none of the path, the identity, the digest, the title or the bookmark (`CONTENT`).""" @@ -342,9 +355,10 @@ def assert_unchanged(cat: VaultCatalog, taken: Taken) -> None: def assert_three_reads(cat: VaultCatalog) -> None: """SNP-5: at every position of every chain, for every path, the seek by key, the closing-stamp - read and the fold of the prefix agree, and no path has two rows alive. The heads of the class - at the position are the rows of the fold that are `store`s, and the history of a path is its - `store` rows in the prefix.""" + read and the fold of the prefix agree, and no path has two rows alive. What the position holds + over the class, the contents of the cut, is the rows of the fold that are `store`s keeping + their content, its holes those a purge emptied, and the history of a path is its `store` rows + in the prefix.""" names = sorted({*PATHS, "id-x", "id-y", *catalog_rows(cat)}) cls_of = classes(cat) for ch in chains(cat): @@ -363,8 +377,13 @@ def assert_three_reads(cat: VaultCatalog) -> None: assert {k: rs[0] for k, rs in living.items()} == \ {k[1]: r for k, r in f.last.items()} cut = {ch: c} - assert cat.heads_at(cls, cut) == [r for r in prefix if r.kind == "store" - and alive(r, c)] + held = cat.cuts([cls]).held(Cut.of(cut)) + cols = held.columns() + assert list(zip(cols.ints("chain").tolist(), cols.ints("seq").tolist(), + strict=True)) == \ + [(ch, r.seq) for r in prefix if r.kind == "store" and not r.hole and alive(r, c)] + assert held.holes() == sum(1 for r in prefix + if r.kind == "store" and r.hole and alive(r, c)) for name in names: key = cat._log.path_key(ch, name) assert cat.state_at(cls, name, cut) == f.last.get((ch, key)) @@ -711,9 +730,8 @@ def test_the_genesis_is_the_catalog_and_ends_at_a_horizon(tmp_path: Path) -> Non # a tombstoned path's store is closed at its tombstone, and an active path's is open, so the # closing-stamp read at the head serves the active paths alone assert [r.closed_at for r in block] == [None, block[2].seq, None, block[4].seq, None, None] - assert [r.source_path for r in cat.heads_at(Provenance.AUTHORED_SOLO, heads(cat))] == \ - ["v/a.md", "v/d.md"] - assert [r.source_path for r in cat.heads_at(Provenance.CURATED, heads(cat))] == [] + assert paths_held(cat, Provenance.AUTHORED_SOLO) == ["v/a.md", "v/d.md"] + assert paths_held(cat, Provenance.CURATED) == [] state = cat.state_at(Provenance.AUTHORED_SOLO, "v/b.md", heads(cat)) assert state is not None and state.kind == "retire" assert_consistent(cat) @@ -792,8 +810,8 @@ def test_a_purged_old_version_of_a_live_path_is_a_hole_by_the_three_reads() -> N assert state is not None and state.hole and state.seq == at_d2 and state.kind == "store" assert emptied(state) and state.version == 2 # §6.1: the content goes, the count stays assert state.path_key == cat._log.path_key(chain, "live.md") - (head_row,) = cat.heads_at(Provenance.AUTHORED_SOLO, cut) - assert head_row.hole and head_row.seq == at_d2 and head_row.source_path is None + held = cat.cuts([Provenance.AUTHORED_SOLO]).held(Cut.of(cut)) + assert held.count() == 0 and held.holes() == 1 # no version: the hole, counted as one history = cat.history_at(Provenance.AUTHORED_SOLO, "live.md", cut) assert [r.digest for r in history] == ["d1", None] and history[-1].hole assert fold(cat, cut).last[(chain, state.path_key)] == state @@ -935,7 +953,7 @@ def test_without_the_secret_what_appends_or_seeks_a_path_by_its_key_refuses( assert all(r.source_path != "old.md" for r in log_rows(cat)) assert cat.read_at(solo, 2) == cat.read_at(solo, cat.head(solo))[:2] assert cat.read_between(solo, 1, 3) == cat.read_at(solo, 3)[1:] - assert [r.source_path for r in cat.heads_at(Provenance.AUTHORED_SOLO, head)] == ["a.md"] + assert paths_held(cat, Provenance.AUTHORED_SOLO, head) == ["a.md"] assert cat.chains(Provenance.OBSERVED) and all(cat.verify(c).ok for c in chains(cat)) assert_consistent(cat) cat.close() diff --git a/tests/unit/test_ambassador_surface.py b/tests/unit/test_ambassador_surface.py index a199f039..868b113b 100644 --- a/tests/unit/test_ambassador_surface.py +++ b/tests/unit/test_ambassador_surface.py @@ -511,6 +511,71 @@ def query(self, **_: Any) -> None: assert "refused" in reply["result"]["content"][0]["text"] +def test_the_cut_tool_is_the_ambassadors_and_answers_through_the_dispatch( + tmp_path: Path) -> None: + """The algebra of cuts is a tool of the Ambassador's table (dn-temporal-snapshot §7.5): it is + listed with its schema, and a call through the server's own dispatch reads the instance's + catalog under the classes the Ambassador's grant reads, a call written as an operand + included; a refusal is an error result. The call reads through a connection that only reads, + so it answers while a writer holds the catalog's write lock, and writes nothing. The guest's + table is unchanged, so a guest is told the tool does not exist (D34, until the owner rules).""" + import sqlite3 + from types import SimpleNamespace + + from agents.ambassador import mcp + from core.stores.catalog import VaultCatalog + + db = tmp_path / "vault_catalog.sqlite" + cat = VaultCatalog(db) + cat.record("a.md", "d1", "A") # land.1@3, after the chain's genesis + cat.record("b.md", "d2", "B") # land.1@4 + cat.record("a.md", "d3", "A") # land.1@5: a.md replaced + cat.close() + amb = mcp.Ambassador.__new__(mcp.Ambassador) # no query engine: the tool reads the catalog + amb.engine = cast(Any, SimpleNamespace(config=SimpleNamespace( + paths=SimpleNamespace(vault_catalog=db)))) + server = mcp.Server() + server._amb = amb + listed = server.handle({"jsonrpc": "2.0", "id": 1, "method": "tools/list"}) + assert listed is not None + (tool,) = [t for t in listed["result"]["tools"] if t["name"] == "cut"] + assert tool["inputSchema"]["required"] == ["op"] + + def call(arguments: dict[str, Any]) -> dict[str, Any]: + reply = server.handle({"jsonrpc": "2.0", "id": 2, "method": "tools/call", + "params": {"name": "cut", "arguments": arguments}}) + assert reply is not None + return cast(dict[str, Any], reply["result"]) + + result = call({"op": "delta", "a": "land.1@4"}) + assert result["isError"] is False + body = json.loads(result["content"][0]["text"]) + assert (body["removed"], body["added"], body["replaced"]) == (0, 0, 1) + assert body["cuts"] == [{"read": "land.1@4"}, {"read": "land.1@5"}] + nested = json.loads(call({"op": "count", "a": {"op": "union", "a": "land.1@4"}}) + ["content"][0]["text"]) + assert (nested["type"], nested["value"]) == ("number", 3) + writer = sqlite3.connect(db, isolation_level=None, timeout=0.1) + writer.execute("BEGIN IMMEDIATE") # a writer's transaction holds the lock + try: + locked = call({"op": "count"}) + finally: + writer.execute("ROLLBACK") + writer.close() + assert locked["isError"] is False + assert json.loads(locked["content"][0]["text"])["value"] == 2 + refused = call({"op": "join", "a": {"op": "held"}}) + assert refused["isError"] is True + assert refused["content"][0]["text"] == ("CutError: join takes a cut as a, and a set of " + "versions was given") + guest = mcp.Server("guest") + assert "cut" not in {t[0] for t in mcp.GUEST_TOOLS} + reply = guest.handle({"jsonrpc": "2.0", "id": 3, "method": "tools/call", + "params": {"name": "cut", "arguments": {"op": "head"}}}) + assert reply is not None and reply["error"] == {"code": -32602, + "message": "unknown tool 'cut'"} + + def _calls(*calls: tuple[str, dict[str, Any]]) -> io.StringIO: return io.StringIO("".join(json.dumps({ "jsonrpc": "2.0", "id": i, "method": "tools/call", diff --git a/tests/unit/test_cut_tool.py b/tests/unit/test_cut_tool.py new file mode 100644 index 00000000..6d3a4db7 --- /dev/null +++ b/tests/unit/test_cut_tool.py @@ -0,0 +1,419 @@ +"""The `cut` tool's handler, called as the MCP server calls it (dn-temporal-snapshot §7.5, SN-1b). + +The server opens the catalog's file to only read, decodes a call's arguments from JSON and passes +both to the handler, and writes the answer back as JSON (`agents/ambassador/mcp.py`, +`Ambassador.cut`, `Server.handle`); `ask` does the same around +`agents/ambassador/cut_tool.py::cut`. The property, the tenth of §12's list for SN-1b: every +operator answers by its name; an operand may be a call, and the whole call is one expression, +which reads the heads when it starts, the horizon of a chain once when a position under its head +is named, and then one statement for its outermost operator; the head is read once a call, so +writes that land while a call runs change nothing in its answer; a set, a signed difference or a +number given where a cut is expected is refused by its type; a call whose sets would name more +than `TERMS` cuts is refused before any statement is written, and a nested symmetric difference +grows the statement by its operands only; a position past a chain's head is refused with the +head; a chain the grant does not read is refused in the words used for one that does not exist; +and the note says that the head was read where no cut was named, which chain was read below each +position asked, that a cut can split a change of class, how many rows of the ranges read are +holes, and that edges and graph mathematics at a cut arrive with SN-4. The registration in the +server is `tests/unit/test_ambassador_surface.py`'s. +""" + +from __future__ import annotations + +import json +import re +from collections.abc import Iterable, Iterator +from pathlib import Path +from typing import Any + +import pytest + +from agents.ambassador import cut_tool +from core.kernel.provenance import Provenance +from core.stores.catalog import VaultCatalog +from core.stores.cuts import CutError, Evaluation, read_only + +SOLO, CURATED = Provenance.AUTHORED_SOLO, Provenance.CURATED +BOTH = ["authored-solo", "curated"] +START = "SELECT chain, class, (SELECT max(seq) FROM landings" # the heads, when a call starts + + +def ask(cat: VaultCatalog, classes: Iterable[str] = BOTH, seen: list[str] | None = None, + **arguments: Any) -> dict[str, Any]: + """A call as the server makes it: over a connection that only reads the catalog's file, the + arguments through JSON, the answer back through it. `seen` collects the statements the call + runs.""" + conn = read_only(cat.path) + if seen is not None: + conn.set_trace_callback(seen.append) + try: + answer = cut_tool.cut(conn, classes, json.loads(json.dumps(arguments))) + finally: + conn.close() + text = json.dumps(answer, ensure_ascii=False) # plain JSON: no default needed + out: dict[str, Any] = json.loads(text) + return out + + +@pytest.fixture +def cat(tmp_path: Path) -> Iterator[VaultCatalog]: + """A chain of authored-solo notes, land.1, and one of curated papers, land.2, in a file the + calls read through their own connection. land.1: the genesis and the horizon at 1 and 2, a.md + and b.md at 3 and 4; then a.md edited at 5, b.md retired at 6 and c.md landed at 7. land.2: + x.md at 3.""" + c = VaultCatalog(tmp_path / "catalog.sqlite") + c.record("a.md", "d1", "A", provenance=SOLO) + c.record("b.md", "d2", "B", provenance=SOLO) + c.record("x.md", "dx", "X", provenance=CURATED) + c.record("a.md", "d3", "A", provenance=SOLO) + c.tombstone("b.md") + c.record("c.md", "d4", "C", provenance=SOLO) + assert c.chains(SOLO) == [1] and c.chains(CURATED) == [2] + yield c + c.close() + + +A = "land.1@4" # a.md at d1, b.md at d2 +SOLO_ONLY = {"over": ["authored-solo"]} + + +def test_every_operator_answers_by_its_name(cat: VaultCatalog) -> None: + head = "land.1@7 land.2@3" + assert ask(cat, op="head")["cut"] == head + assert ask(cat, op="bottom")["cut"] == "land.1@0 land.2@0" + assert ask(cat, op="join", a=A, b="land.2@3")["cut"] == "land.1@4 land.2@3" + assert ask(cat, op="meet", a=A, b="head")["cut"] == "land.1@4 land.2@0" + assert ask(cat, op="order", a=A, b="head")["order"] == "before" + assert ask(cat, op="order", a=A, b="land.2@3")["order"] == "unordered" + between = ask(cat, op="between", a=A, list=True, **SOLO_ONLY) + assert (between["type"], between["count"]) == ("events", 3) + assert [(r["seq"], r["kind"], r["path"]) for r in between["rows"]] == [ + (5, "store", "a.md"), (6, "retire", "b.md"), (7, "store", "c.md")] + held = ask(cat, op="held", a=A, list=True) + assert (held["type"], held["count"]) == ("set", 2) + assert [(r["path"], r["digest"], r["identity"], r["title"]) for r in held["rows"]] == [ + ("a.md", "d1", "a.md", "A"), ("b.md", "d2", "b.md", "B")] + sets = {op: ask(cat, op=op, a=A, b="head", **SOLO_ONLY)["count"] + for op in ("union", "intersection", "difference", "symmetric_difference")} + assert sets == {"union": 4, "intersection": 0, "difference": 2, "symmetric_difference": 4} + delta = ask(cat, op="delta", a=A, **SOLO_ONLY) + assert (delta["type"], delta["removed"], delta["added"], delta["replaced"]) == \ + ("delta", 1, 1, 1) + applied = ask(cat, op="apply", a=A, b={"op": "delta", "a": A}, list=True, **SOLO_ONLY) + assert [r["digest"] for r in applied["rows"]] == ["d3", "d4"] + composed = ask(cat, op="compose", a={"op": "delta", "a": "bottom", "b": A}, + b={"op": "delta", "a": A}, **SOLO_ONLY) + assert (composed["removed"], composed["added"], composed["replaced"]) == (0, 2, 0) + assert ask(cat, op="persisted", cuts=[A, "head"], **SOLO_ONLY)["count"] == 0 + assert ask(cat, op="existed", cuts=[A, "head"], **SOLO_ONLY)["count"] == 4 + count = ask(cat, op="count", a=A) + assert (count["type"], count["value"]) == ("number", 2) + counted = ask(cat, op="in_how_many", cuts=[A, "land.1@5", "head"], + a={"op": "existed", "cuts": [A, "head"]}, **SOLO_ONLY) + assert [(r["path"], r["digest"], r["cuts_holding"]) for r in counted["rows"]] == [ + ("a.md", "d1", 1), ("b.md", "d2", 2), ("a.md", "d3", 2), ("c.md", "d4", 1)] + assert counted["held_by_every_cut"] == 0 + seen: list[str] = [] + first = ask(cat, seen=seen, op="in_how_many", cuts=["land.1@5", "head"], + a={"op": "existed", "cuts": ["land.1@5", "head"]}, limit=1, **SOLO_ONLY) + assert [(r["digest"], r["cuts_holding"]) for r in first["rows"]] == [("d2", 1)] + assert (first["count"], first["truncated"], first["held_by_every_cut"]) == (3, True, 1) + assert sum(q.endswith("LIMIT 1)") for q in seen) == 1 # the rows listed, and no more + series = ask(cat, op="measure", cuts=["bottom", A, "head"], of="count", **SOLO_ONLY) + assert [(s["cut"], s["value"]) for s in series["series"]] == [ + ("land.1@0", 0), ("land.1@4", 2), ("land.1@7", 2)] + table = ask(cat, op="pairwise", cuts=[A, "head"], **SOLO_ONLY)["table"] + assert table == {"cuts": ["land.1@4", "land.1@7"], "sizes": [[0, 2], [2, 0]]} + assert set(cut_tool.OPERATORS) == { + "head", "bottom", "join", "meet", "order", "between", "held", "union", "intersection", + "difference", "symmetric_difference", "delta", "apply", "compose", "persisted", + "existed", "count", "in_how_many", "measure", "pairwise"} + + +def test_the_two_meanings_of_union_differ_by_name_and_type(cat: VaultCatalog) -> None: + """`join` is the union on positions and returns a cut, whose contents hold the later version + of a.md alone; `union` is the union on contents and returns a set holding both versions.""" + joined = ask(cat, op="held", a={"op": "join", "a": A, "b": "head"}, list=True, **SOLO_ONLY) + united = ask(cat, op="union", a=A, b="head", list=True, **SOLO_ONLY) + assert [r["digest"] for r in joined["rows"]] == ["d3", "d4"] + assert [r["digest"] for r in united["rows"]] == ["d1", "d2", "d3", "d4"] + assert ask(cat, op="join", a=A, b="head")["type"] == "cut" + assert united["type"] == "set" + + +def test_a_call_reads_the_heads_a_horizon_once_and_one_statement_for_its_result( + cat: VaultCatalog) -> None: + """The union of two differences is one call with a `difference` in `a` and another in `b`: + the whole is one expression. Every statement the call runs, in order: the heads, when it + starts; the horizon of land.1, once though land.1@4 is named twice, since a position under a + chain's head is served from the chain's horizon on (§7.1); and the one statement that counts + the union. An operator on positions reads what its names need and nothing more, and `head` + and `bottom` need nothing.""" + seen: list[str] = [] + answer = ask(cat, seen=seen, op="union", a={"op": "difference", "a": "head", "b": A}, + b={"op": "difference", "a": A, "b": "head"}, **SOLO_ONLY) + assert answer["count"] == 4 + assert [c["read"] for c in answer["cuts"]] == ["land.1@7", "land.1@4"] + assert len(seen) == 3, seen + assert seen[0].startswith(START) + assert "kind = 'horizon'" in seen[1] and "seq <= 4 " in seen[1] + assert re.match(r"SELECT coalesce\(sum\(n\), 0\), coalesce\(sum\(h\), 0\) FROM", seen[2]) + for args, n in (({"op": "order", "a": A, "b": "land.1@5"}, 2), + ({"op": "join", "a": A, "b": "land.1@3"}, 2), + ({"op": "order", "a": "head", "b": "bottom"}, 1)): + seen.clear() + ask(cat, seen=seen, **args, **SOLO_ONLY) + assert len(seen) == n and seen[0].startswith(START), (args, seen) + + +def test_the_head_is_read_once_a_call_whatever_lands_while_it_runs( + cat: VaultCatalog, monkeypatch: pytest.MonkeyPatch) -> None: + """Writes that land after a call has read the heads change nothing in its answer: an operand + left out is the head the call read when it started, in a signed difference, a set, a join and + a family alike, and so is the cut the `head` operator names; the answer's cuts, its note and + its counts are those of that head (D27, SNF-19). The writes land from the catalog's own + connection right after the call's evaluation reads the heads, two a call.""" + + class Racing(Evaluation): + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + n = cat.head(1) + cat.record("d.md", f"d{n}", "D") + cat.record("a.md", f"e{n}", "A") + + monkeypatch.setattr(cut_tool, "Evaluation", Racing) + + def said(head: str) -> str: + return f"No cut was named for an operand, so the head was read, once for the whole " \ + f"call: {head}." + + delta = ask(cat, op="delta", a="bottom", **SOLO_ONLY) # read at 7; 8 and 9 land + assert (delta["removed"], delta["added"], delta["replaced"]) == (0, 2, 0) + assert delta["cuts"] == [{"read": "land.1@0"}, {"read": "land.1@7"}] + assert delta["note"].startswith(said("land.1@7")) + held = ask(cat, op="held", list=True, **SOLO_ONLY) # read at 9; 10 and 11 land + assert [(r["seq"], r["digest"]) for r in held["rows"]] == [(7, "d4"), (8, "d7"), (9, "e7")] + assert held["cuts"] == [{"read": "land.1@9"}] and held["note"].startswith(said("land.1@9")) + joined = ask(cat, op="join", a=A, **SOLO_ONLY) # read at 11; 12 and 13 land + assert joined["cut"] == "land.1@11" and joined["note"].startswith(said("land.1@11")) + assert joined["cuts"] == [{"read": "land.1@4"}, {"read": "land.1@11"}] + series = ask(cat, op="measure", **SOLO_ONLY) # read at 13; 14 and 15 land + assert [(s["cut"], s["value"]) for s in series["series"]] == [("land.1@13", 3)] + assert series["cuts"] == [{"read": "land.1@13"}] + assert series["note"].startswith(said("land.1@13")) + named = ask(cat, op="head", **SOLO_ONLY) # read at 15; 16 and 17 land + assert named["cut"] == "land.1@15" and named["cuts"] == [{"read": "land.1@15"}] + assert cat.head(1) == 17 + + +def test_a_call_is_bounded_by_the_cuts_its_statement_names(cat: VaultCatalog) -> None: + """A symmetric difference names each operand once, so thirty-one nested in one call make a + statement that names thirty-two cuts, where writing each as two differences would double it + at every level. A call whose sets would name more than `TERMS` cuts, counted each time the + statement names one, is refused with the bound, and nothing but the heads is read.""" + names = [A, "land.1@5", "head"] + nested: dict[str, Any] = {"op": "held", "a": names[0]} + for i in range(1, cut_tool.DEPTH): + nested = {"op": "symmetric_difference", "a": nested, "b": names[i % 3]} + rows = {n: {(r["chain"], r["seq"]) for r in + ask(cat, op="held", a=n, list=True, **SOLO_ONLY)["rows"]} for n in names} + want = rows[names[0]] + for i in range(1, cut_tool.DEPTH): + want = want ^ rows[names[i % 3]] + seen: list[str] = [] + answer = ask(cat, seen=seen, op="count", a=nested, **SOLO_ONLY) + assert answer["value"] == len(want) + assert seen[-1].count("closed_at IS NULL OR closed_at >") <= cut_tool.DEPTH + 1 + family = ["head"] * cut_tool.FAMILY + big: dict[str, Any] = {"op": "existed", "cuts": family} + for _ in range(cut_tool.TERMS // cut_tool.FAMILY): + big = {"op": "union", "a": big, "b": {"op": "existed", "cuts": family}} + seen.clear() + with pytest.raises(CutError, match=rf"a call's sets name at most {cut_tool.TERMS} cuts, " + rf".* and this call's name " + rf"{cut_tool.TERMS + cut_tool.FAMILY}$"): + ask(cat, seen=seen, op="count", a=big, **SOLO_ONLY) + assert len(seen) == 1 and seen[0].startswith(START) + + +def test_a_set_or_a_difference_or_a_number_where_a_cut_is_expected_is_refused_by_type( + cat: VaultCatalog) -> None: + refusals: list[tuple[dict[str, Any], str]] = [ + ({"op": "join", "a": {"op": "held"}, "b": "head"}, + "join takes a cut as a, and a set of versions was given"), + ({"op": "delta", "a": {"op": "count"}}, + "delta takes a cut as a, and a number was given"), + ({"op": "held", "a": {"op": "delta", "a": A}}, + "held takes a cut as a, and a signed difference was given"), + ({"op": "apply", "a": A, "b": "head"}, + "apply takes a signed difference as b, and a cut was given"), + ({"op": "union", "a": {"op": "between", "a": A}, "b": "head"}, + "union takes a set of versions or a cut as a, and the events between two cuts"), + ({"op": "persisted", "cuts": [A, {"op": "held"}]}, + "persisted takes a cut as a member of cuts, and a set of versions was given"), + ({"op": "meet", "a": {"op": "order", "a": A}, "b": "head"}, + "meet takes a cut as a, and an order was given"), + ] + for args, said in refusals: + with pytest.raises(CutError, match=said): + ask(cat, **args) + + +def test_a_position_past_the_head_is_refused_with_the_head(cat: VaultCatalog) -> None: + with pytest.raises(CutError, match=r"land.1@8 is past the chain's head, land.1@7"): + ask(cat, op="held", a="land.1@8") + with pytest.raises(CutError, match=r"land.2@4 is past the chain's head, land.2@3"): + ask(cat, op="delta", a="bottom", b="land.1@7 land.2@4") + + +def test_a_chain_the_grant_does_not_read_is_refused_as_one_that_does_not_exist( + cat: VaultCatalog) -> None: + """Under a grant that reads authored-solo alone, land.2 is refused in the words used for + land.9, which no catalog has; the answer names land.1 alone; and `over` cannot name a class + the grant does not read.""" + with pytest.raises(CutError) as unread: + ask(cat, ["authored-solo"], op="held", a="land.2@1") + with pytest.raises(CutError) as absent: + ask(cat, ["authored-solo"], op="held", a="land.9@1") + assert str(unread.value).replace("land.2", "land.N") == \ + str(absent.value).replace("land.9", "land.N") == \ + "there is no chain land.N; the chains read here are land.1" + assert ask(cat, ["authored-solo"], op="head")["cut"] == "land.1@7" + with pytest.raises(CutError, match="over names a class this grant does not read: curated"): + ask(cat, ["authored-solo"], op="head", over=["curated"]) + + +def test_the_note_says_the_head_the_horizon_the_holes_and_what_waits_for_sn4( + tmp_path: Path) -> None: + """With no cut named the note says the head was read, once for the call, and names it. A + position under a chain's horizon, inside its genesis, is read at 0, and the note and the cuts + read say so. The holes a purge left in the ranges read are counted. And every note ends by + saying the result is of versions, and that edges and graph mathematics wait for SN-4.""" + db = tmp_path / "catalog.sqlite" + import sqlite3 + with sqlite3.connect(db) as conn: + conn.execute("CREATE TABLE vault_files (source_path TEXT PRIMARY KEY, digest TEXT NOT " + "NULL, title TEXT NOT NULL, provenance TEXT NOT NULL DEFAULT " + "'authored-solo', active INTEGER NOT NULL DEFAULT 1, updated_at TEXT NOT " + "NULL, doc_id TEXT)") + conn.executemany("INSERT INTO vault_files VALUES (?, ?, ?, 'authored-solo', 1, " + "'2026-11-01', ?)", [("v/a.md", "da", "A", "v/a.md"), + ("v/b.md", "db", "B", "v/b.md")]) + cat = VaultCatalog(db) # the genesis: land.1@1 to land.1@4, the horizon + cat.record("v/a.md", "da2", "A") # land.1@5 closes v/a.md's genesis row + answer = ask(cat, ["authored-solo"], op="delta") + assert answer["note"].startswith("No cut was named for an operand, so the head was read, " + "once for the whole call: land.1@5.") + assert answer["note"].endswith(cut_tool.GRAPH) + assert answer["cuts"] == [{"read": "land.1@5"}] + under = ask(cat, ["authored-solo"], op="held", a="land.1@2") + assert under["count"] == 0 + assert under["cuts"] == [{"read": "land.1@0", "asked": "land.1@2"}] + assert "land.1 was read at 0, below the position asked, 2: the positions under a chain's " \ + "horizon are its genesis" in under["note"] + assert ask(cat, ["authored-solo"], op="held", a="land.1@4")["count"] == 2 + assert "No row of the ranges read is a hole." in under["note"] + both = ask(cat, ["authored-solo"], op="union", a="land.1@2", b="land.1@3") + assert both["cuts"] == [{"read": "land.1@0", "asked": "land.1@2"}, + {"read": "land.1@0", "asked": "land.1@3"}] + assert "below the position asked, 2:" in both["note"] + assert "below the position asked, 3:" in both["note"] + assert cat.active_refs("da") == 0 + cat.remove_digest("da") # v/a.md's first version, a hole from now on + purged = ask(cat, ["authored-solo"], op="held", a="land.1@4") + assert purged["count"] == 1 + assert "1 row of the ranges read is a hole: versions a purge emptied, which no set holds." \ + in purged["note"] + for a in (ask(cat, ["authored-solo"], op=op) for op in ("head", "between", "measure")): + assert a["note"].endswith(cut_tool.GRAPH) + cat.close() + + +def test_a_cut_that_splits_a_change_of_class_is_read_as_asked_and_the_note_says_so( + tmp_path: Path) -> None: + """A change of class writes a `leave` in the chain the path leaves and then a `store` in the + chain of its new class. A cut that holds the `store` and not the `leave` holds the path in + both chains, and one that holds the `leave` and not the `store` in neither; no reference of + §3.5 lowers either, so each is read as asked, and the note says that such a cut can split a + change of class (§7.5). The head, a cut of one chain and an answer that reads no contents + say nothing of it.""" + cat = VaultCatalog(tmp_path / "catalog.sqlite") + cat.record("a.md", "d1", "A", provenance=SOLO) # land.1: genesis, horizon, a.md at 3 + cat.record("b.md", "d2", "B", provenance=CURATED) # land.2: genesis, horizon, b.md at 3 + cat.record("a.md", "d1", "A", provenance=CURATED) # land.1@4 its leave, land.2@4 a.md + twice = ask(cat, op="held", a="land.1@3 land.2@4", list=True) + assert [(r["chain"], r["path"]) for r in twice["rows"]] == [ + (1, "a.md"), (2, "b.md"), (2, "a.md")] + assert twice["cuts"] == [{"read": "land.1@3 land.2@4"}] + assert cut_tool.SPLIT in twice["note"] + neither = ask(cat, op="held", a="land.1@4 land.2@3", list=True) + assert [r["path"] for r in neither["rows"]] == ["b.md"] + assert cut_tool.SPLIT in neither["note"] + for quiet in (ask(cat, op="held"), ask(cat, ["curated"], op="held", a="land.2@3"), + ask(cat, op="join", a="land.1@3 land.2@4", b="bottom")): + assert cut_tool.SPLIT not in quiet["note"] + cat.close() + + +def test_list_returns_the_rows_and_says_when_the_limit_cut_them(cat: VaultCatalog) -> None: + one = ask(cat, op="held", list=True, limit=1, **SOLO_ONLY) + assert one["count"] == 2 and len(one["rows"]) == 1 and one["truncated"] is True + assert "rows" not in ask(cat, op="held", **SOLO_ONLY) + listed = ask(cat, op="delta", a=A, list=True, **SOLO_ONLY)["rows"] + assert [r["path"] for r in listed["removed"]] == ["b.md"] + assert [r["path"] for r in listed["added"]] == ["c.md"] + assert [(p["from"]["digest"], p["to"]["digest"]) for p in listed["replaced"]] == \ + [("d1", "d3")] + assert set(listed["removed"][0]) == {"chain", "seq", "path", "identity", "digest", "title", + "version"} + + +def test_the_same_call_with_the_positions_printed_is_the_same_answer_later( + cat: VaultCatalog) -> None: + """An answer prints the head it read by its positions; asked again with them after further + writes, the call gives the same answer, where the head itself has moved (D27).""" + first = ask(cat, op="delta", a=A, **SOLO_ONLY) + printed = first["cuts"][-1]["read"] + cat.record("d.md", "d5", "D") + cat.record("a.md", "d6", "A") + again = ask(cat, op="delta", a=A, b=printed, **SOLO_ONLY) + moved = ask(cat, op="delta", a=A, **SOLO_ONLY) + keys = ("removed", "added", "replaced") + assert [again[k] for k in keys] == [first[k] for k in keys] == [1, 1, 1] + assert [moved[k] for k in keys] == [1, 2, 1] + + +def test_what_the_tool_does_not_take_is_refused(cat: VaultCatalog) -> None: + refusals: list[tuple[dict[str, Any], str]] = [ + ({"op": "nope"}, "op is one of head"), + ({"op": "held", "sentence": "x"}, "no argument sentence"), + ({"op": "held", "a": {"op": "held", "over": ["curated"]}}, + "are arguments of the outermost call"), + ({"op": "head", "a": A}, "head takes no operand, and was given a"), + ({"op": "held", "b": A}, "held takes a, and was given b"), + ({"op": "held", "limit": 0}, "limit is a whole number from 1 to 1000"), + ({"op": "held", "list": "yes"}, "list is true or false"), + ({"op": "held", "a": 3}, "an operand is a cut's name or a call"), + ({"op": "held", "a": "land.1@2 land.1@3"}, "land.1 is named twice"), + ({"op": "held", "a": "yesterday"}, "'yesterday' is not a position"), + ({"op": "measure", "of": "degree"}, "the one measure at this stage is count"), + ({"op": "persisted", "cuts": ["head"] * 65}, "a family has at most 64 cuts"), + ({"op": "compose", "a": {"op": "delta", "a": A}, "b": {"op": "delta", "a": A}}, + "compose through the cut they share"), + ({"op": "compose", "a": {"op": "delta", "a": "bottom", "b": "head"}, + "b": {"op": "delta", "a": "head", "b": A}}, "not between"), + ] + for args, said in refusals: + with pytest.raises(CutError, match=said): + ask(cat, **args) + deep: dict[str, Any] = {"op": "held"} + for _ in range(40): + deep = {"op": "union", "a": deep, "b": "head"} + with pytest.raises(CutError, match="a call nests at most 32 calls"): + ask(cat, **deep) + + +def test_the_schema_names_every_operator_and_argument() -> None: + assert cut_tool.SCHEMA["required"] == ["op"] + assert cut_tool.SCHEMA["properties"]["op"]["enum"] == sorted(cut_tool.OPERATORS) + assert set(cut_tool.SCHEMA["properties"]) == set(cut_tool.ARGUMENTS)