In this section
- Law — Index Page render · law / index.html lines 701–824
- Replay storage · legislation / case/replay/replay.py lines 1–154
- Verify Ia6 ingest · legislation / case/verify_ia6.py lines 1–47
- Screen other · legislation / contracts/screen.py lines 1–85
- Verify Catalogue ingest · legislation / data/verify_catalogue.py lines 1–36
- Compare ingest · legislation / editions/compare.py lines 1–73
- Benchmark storage · legislation / engine/benchmark.py lines 1–81
Law — Index Page
A web page that draws laws, cables, solar and 33kV, using IEC 60904-3 and BS 7870-4.
renderlaw / index.html · lines 701–824 of 824 (continued from section 1997) · Entry point
- What it does
- It draws laws, cables, solar and 33kV. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain terms in the code: cables, solar, 33kV, 132kV, 19kV, 5kV. README: "L14 to L25 are on the page (`index.html`) and in `laws.json`."
- Inputs & outputs
- In: JSON file laws.json. Out: web page. Voltage levels named: 132kV, 33kV, 19kV, 5kV, 2.9kV, 1.5kV, 1500V.
- Downstream impact
- Used directly by 1 file: Watch (time-stone). Reached from 1 other entry point, including Watch Workflow (time-stone).
- What it achieves
- The README says: L14 to L25 are on the page (`index.html`) and in `laws.json`. Its code works with 33 kV, 50 Hz and 1.5 kV.
- Why it matters
- Imported by Watch, from Time Stone.
- Application
- law · / · page
- Uses
- Build (link)
- Used by
- named by URL in Watch (estate URL)
- Produces
- none declared
- Defines here
- none
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- law@53c6c3218e7c56bce3fe6ca7727f82f2fb505dc4 index.html:701-824 · blob 6e255832c5b4c84eec3b1f374875ce3095ffbccc · GitHub at these lines
- State
- achieves: readme · context: auto · stage: output · effects: dom · domain stage: unknown · users: none · canonical: unknown
<li><b>min( , )</b> whichever of the two is smaller. It stops one very long absence swallowing the whole picture.</li>
<li><b>cap</b> fourteen days, in seconds. No silence counts for more than that.</li>
</ul>
<span class="lab">A worked number</span>
<p class="work">Across 9,940 commits from May 2025 to September 2026: <b>37,929,255,811</b> keys issued and <b>15,373,462,200</b> left unissued, so 28.84% of the wafer is measured silence. One ordinary night of eight hours is 28,800 seconds, which is 17,280,000 unissued keys, a ring you can see.</p>
<span class="lab">How to show it is wrong</span>
<p class="wrong">Find a dark ring on the wafer that does not sit between two commit timestamps separated by the silence its width claims.</p>
<span class="lab">Keys</span>
<table class="keys">
<tr><td class="k">issued and unissued totals</td><td>tools/wafer_keys.py in Ventusltd/kuiper-belt, cosmos/wafer-meta.json, 2026-09-19</td><td class="st st-measured">measured</td></tr>
<tr><td class="k">G = 600 keys per second, cap 14 days</td><td>declared constants in tools/wafer_keys.py; a choice, stated, not a measurement</td><td class="st st-derived">derived</td></tr>
<tr><td class="k">an unissued number still has a place</td><td>the addressing law of the line wafer, lib.mjs place(key)</td><td class="st st-measured">measured</td></tr>
</table>
</div>
</details>
<details class="nest"><summary>L23 · Keep a running total and any range is one subtraction</summary>
<div class="body">
<p class="say">If you write down the running total as you go, then how much lies between any two points is the later total minus the earlier one, however much lies between them.</p>
<span class="lab">What it means</span>
<p class="t">This is how a key finds its commit among ten thousand without walking past the others, and how every pixel on the wafer knows what share of itself is work and what share is silence. The running totals are kept once. After that, finding where a number falls is a matter of halving the list until it is found, fourteen halvings for ten thousand commits, and the amount in any stretch i … [line shortened here: 526 characters; full line on GitHub]
<span class="lab">In the real world</span>
<p class="r">The running total must be exact or every answer after the first error is wrong by that error forever, which is why the tools here refuse when a level does not sum to the level above it rather than carrying on. On a graphics card the totals are held in a format good to about seven figures, so the wafer's shading is right to a few thousand keys in thirty seven billion while the addr … [line shortened here: 475 characters; full line on GitHub]
<span class="lab">The maths</span>
<div class="eq">amount between a and b = T(b) − T(a)</div>
<ul class="sym">
<li><b>T( )</b> the running total up to a point: everything counted so far.</li>
<li><b>a, b</b> the two points you are asking between.</li>
<li>Finding which entry a number falls in is done by halving: look at the middle, keep the half it is in, repeat. Ten thousand entries take fourteen looks, a million take twenty.</li>
</ul>
<span class="lab">A worked number</span>
<p class="work">A random key among 53,302,718,011 addresses is traced to its commit in <b>14 comparisons</b>, to its file by walking that one commit, and to its text by opening one blob. The unattended proof does this about twice a second and stops at the first failure.</p>
<span class="lab">How to show it is wrong</span>
<p class="wrong">Find any stretch where the later total minus the earlier total differs from adding the stretch up directly.</p>
<span class="lab">Keys</span>
<table class="keys">
<tr><td class="k">prefix sums and binary search</td><td>standard results; Knuth, The Art of Computer Programming, vol. 3</td><td class="st st-published">published</td></tr>
<tr><td class="k">keys followed to their text by tools/key.py --prove-until</td><td>E:/particles-runs/PROVE-KEYS.json on the measuring machine; Ventusltd/kuiper-belt tools/key.py</td><td class="st st-measured">measured</td></tr>
</table>
</div>
</details>
<details class="nest"><summary>L24 · A number too big for its container loses its small digits, silently</summary>
<div class="body">
<p class="say">Every container for numbers holds only so many figures, and when a number outgrows it the smallest figures are dropped without any warning, so two different big numbers quietly become the same number.</p>
<span class="lab">What it means</span>
<p class="t">The usual container on a graphics card holds about seven figures. The keys here run past thirty seven billion, which is eleven figures, so stored that way every key would be rounded to the nearest 4,096 and four thousand different lines would land on one spot. This happened: an early version drew every pass onto the same positions and looked correct. The cure is to do the part tha … [line shortened here: 589 characters; full line on GitHub]
<span class="lab">In the real world</span>
<p class="r">This failure does not announce itself. The picture still looks like a picture and the total still prints. It is found only by asking whether two neighbouring keys really land in two places, which nobody does unless they already suspect. The same trap is in every spreadsheet that holds a long account number as a number, and in any energy total summed from many small readings in the … [line shortened here: 417 characters; full line on GitHub]
<span class="lab">The maths</span>
<div class="eq">a 32 bit float keeps 24 binary figures so beyond 2²⁴ = 16,777,216 it can no longer count in ones</div>
<ul class="sym">
<li><b>bit</b> one binary figure, a 0 or a 1.</li>
<li><b>32 bit float</b> the graphics card's everyday number. Of its 32 bits, 24 hold the figures and the rest say where the point goes.</li>
<li><b>2²⁴</b> two multiplied by itself twenty four times, which is 16,777,216: the largest stretch it can count one by one.</li>
</ul>
<span class="lab">A worked number</span>
<p class="work">At 37.9 billion the gap between neighbouring values a 32 bit float can hold is <b>4,096</b>. Keys 37,929,255,000 and 37,929,255,001 are the same number to it. In whole number arithmetic they differ by exactly one, always.</p>
<span class="lab">How to show it is wrong</span>
<p class="wrong">Store 37,929,255,811 and 37,929,255,812 in 32 bit floats and find them different.</p>
<span class="lab">Keys</span>
<table class="keys">
<tr><td class="k">24 bit significand of single precision</td><td>IEEE 754-2019, binary32</td><td class="st st-standard">standard</td></tr>
<tr><td class="k">the defect as it occurred</td><td>Ventusltd/cosmic, fixed in commit cc7a807: the ordinal does not fit in a float</td><td class="st st-measured">measured</td></tr>
</table>
</div>
</details>
</details>
<details class="area"><summary>Cells and programs</summary>
<details class="nest"><summary>L26 · A dot that answers to other dots is a gate, and gates compute</summary>
<div class="body">
<p class="say">Give every dot one rule, let the rule of one dot depend on whether other dots were lit a moment earlier, and the dots can work out any sum that can be written down.</p>
<span class="lab">What it means</span>
<p class="t">A dot that is lit because somebody chose it is only a lamp. A dot that is lit UNLESS two other dots were both lit is a switch driven by other switches, which is exactly what a transistor gate in a processor is. One kind of such gate is enough: every other kind of logic can be built from it, and so can an adder, and from adders everything else. Nothing has to be stored in a dot for … [line shortened here: 515 characters; full line on GitHub]
<span class="lab">In the real world</span>
<p class="r">This says what cells run by that rule can do. It does not say a page that shows dots is calculating anything: a picture of lit dots is a display until a rule of this kind is actually running behind it, and the engineering sums of this project are done by its calculation engine, not by the dots. The cost is real too. A sum needs many cells and takes many ticks, one tick per cell th … [line shortened here: 600 characters; full line on GitHub]
<span class="lab">The maths</span>
<div class="eq">lit(c, t) = NOT ( lit(a, t − 1) AND lit(b, t − 1) )</div>
<ul class="sym">
<li><b>c</b> the cell being asked about. <b>a</b> and <b>b</b> the two cells its rule names.</li>
<li><b>t</b> the tick: time counted in whole steps. <b>t − 1</b> the step before.</li>
<li><b>lit(c, t)</b> one if cell c is lit at tick t, nought if it is dark.</li>
<li><b>AND</b> true only when both are true. <b>NOT</b> turns true into false and false into true. Together they are the gate engineers call NAND.</li>
<li>At tick nought every gate cell is dark. Input cells are lit when the person using it says so.</li>
</ul>
<span class="lab">A worked number</span>
<p class="work">A half adder of <b>8</b> cells read from the dots: 0 and 0 give 0; 0 and 1 give 1; 1 and 0 give 1; 1 and 1 give sum 0 carry 1, which is two. A four bit adder of <b>69</b> cells got <b>256 of 256</b> sums right, 0 + 0 up to 15 + 15 = 30; the slowest settled at tick 16. The carry cell first lit exactly 2 ticks after its inputs, never sooner.</p>
<span class="lab">How to show it is wrong</span>
<p class="wrong">Run the command below and find one row of the truth table, or one of the 256 sums, that the cells get wrong; or find two machines that give different states for the same key, program and tick. Either ends the law.</p>
<span class="lab">Keys</span>
<table class="keys">
<tr><td class="k">half adder, four bit adder, propagation delay</td><td>Ventusltd/faraday, apparatus/cells.test.mjs; run: node apparatus/cells.test.mjs (Faraday entries 16, 17, 18)</td><td class="st st-measured">measured</td></tr>
<tr><td class="k">one gate is enough to build all logic</td><td>H. M. Sheffer, A set of five independent postulates for Boolean algebras, Transactions of the American Mathematical Society 14 (1913)</td><td class="st st-published">published</td></tr>
</table>
</div>
</details>
<details class="nest"><summary>L27 · Memory is the history of the inputs; what it costs is time</summary>
<div class="body">
<p class="say">Dots can remember without anything being stored in any dot, because what they remember is already written in the history of what was done to them.</p>
<span class="lab">What it means</span>
<p class="t">Two gate cells that each answer to the other will hold a state: set them with a short pulse and they stay set long after the pulse has gone. Neither cell stores a thing. The state at any moment is worked out again from the record of the inputs, from the start to that moment. So the claim that nothing is stored per dot survives memory. What is paid instead is time: the later the mo … [line shortened here: 459 characters; full line on GitHub]
<span class="lab">In the real world</span>
<p class="r">Any real page would keep the last frame so as not to work everything out again. That is a cache: it can be thrown away and rebuilt from the program at any time, which is the difference between a cache and a stored bit. And a memory that is never put into a known state first does not settle; ours flickered lit, dark, lit, dark for ever until it was given a reset. Silicon has the sa … [line shortened here: 431 characters; full line on GitHub]
<span class="lab">The maths</span>
<div class="eq">state(t) = F( program, inputs from 0 to t ) work ∝ t</div>
<ul class="sym">
<li><b>state(t)</b> whether the remembering cell is lit at tick t.</li>
<li><b>F</b> the working out: apply the rule of L26 backwards from tick t to tick nought.</li>
<li><b>inputs from 0 to t</b> the record of when set and reset were pressed. It belongs to the program, not to any cell.</li>
<li><b>∝</b> grows in step with: twice the ticks, about twice the work.</li>
</ul>
<span class="lab">A worked number</span>
<p class="work">Reset held for ticks 0 to 5; a set pulse for ticks 10 to 13; read at tick 39, which is <b>26 ticks after the pulse ended: still lit</b>. A reset pulse at ticks 40 to 43; read at tick 60: dark. With no cache the working asked <b>25</b> questions for tick 12 and <b>49</b> for tick 24. Never reset: 1, 0, 1, 0, 1, 0, 1, 0.</p>
<span class="lab">How to show it is wrong</span>
<p class="wrong">Show the latch forgetting: lit by the set pulse and dark again with no reset given. Or show that the state at a tick cannot be recovered from the program and the input record alone.</p>
<span class="lab">Keys</span>
<table class="keys">
<tr><td class="k">the latch, its flicker, and the cost</td><td>Ventusltd/faraday, apparatus/cells.test.mjs; run: node apparatus/cells.test.mjs (Faraday entry 19)</td><td class="st st-measured">measured</td></tr>
</table>
</div>
</details>
</details>
</main>
<div class="footer"><b>Disclaimer:</b> Content provided for general technical documentation and research purposes only. Laws are stated so that they can be shown to be wrong. Every number carries a key saying where it came from; a key marked <span class="st st-candidate">candidate</span> was quoted from memory or is illustrative and must be checked against the standard before anyone builds anythin … [line shortened here: 643 characters; full line on GitHub]
</body>
</html>Replay
A Python command-line tool in the case folder of Legislation that reads ia6 and legal evidence, using SHA-256.
storagelegislation / case/replay/replay.py · lines 1–154 of 154 · Entry point · pattern fixtures (shared by 3 files)
- What it does
- It loads ia6 and legal evidence. Defines 13 functions or classes, including verify, full_scan, start, end, fixtures. Uses libraries argparse, hashlib, json, pathlib, re. Side effects: reads or writes files; uses storage (browser storage, DuckDB or Parquet).
- Inputs & outputs
- In: JSON file ia6.json; JSON file legal-evidence.json; SQLite database; command-line arguments.
- Downstream impact
- Used directly by 1 file: Test Replay (legislation).
- What it achieves
- It is built from the verify step (`verify`), the full scan helper (`full_scan`) and the start step (`start`). Bounded replay of a fictional evidence gap against one dated XML manifestation. It accepts `--rounds`.
- Why it matters
- Checked by Test Replay.
- Application
- legislation · case/replay · Python CLI
- Uses
- Legal (sys.path import), argparse, hashlib, json, pathlib, re, sqlite3, statistics, sys
- Used by
- imported by Test Replay (import)
- Produces
- verify, full_scan, fixtures, unresolved, full_evidence, selective_evidence, measured, replay
- Defines here
- verify, full_scan, start, end, fixtures, unresolved, full_evidence, selective_evidence, measured, replay, setup, scan, select
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- legislation@960afbd0f5393e818b400a7f1a523acd6814e217 case/replay/replay.py:1-154 · blob 802eeff244536c5810739338d6231c7b846ba06e · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, storage · domain stage: unknown · users: none · canonical: supporting_data
"""Bounded replay of a fictional evidence gap against one dated XML manifestation."""
import argparse
import hashlib
import json
from pathlib import Path
import re
import sqlite3
from statistics import median
import sys
from tempfile import TemporaryDirectory
from time import perf_counter_ns, process_time_ns
from xml.parsers import expat
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / 'engine'))
from legal import get, ingest
DATE = '2024-01-01'
DOCUMENT = 'http://www.legislation.gov.uk/ukpga/1989/29'
LOCATOR = 'schedule/4/paragraph/6'
URI = f'{DOCUMENT}/{LOCATOR}/{DATE}'
URL = f'{DOCUMENT}/{DATE}/data.xml'.replace('http:', 'https:')
XML_SHA = '9fccdeb8430d2accbc1299ae24d793270577d1e1efd1bb91eddea2f7f458cccb'
FRAGMENT_SHA = '6246a910e5cbfc52e8f1b0fa3b1b64cb0fc8c5e808ccdf72c59033516af5b88c'
CASE_SHA = '1529585a56354fe11ad3f20e0fc0b3357c6c1102d2fc05d3ca237df6146617d9'
QUESTION_SHA = '4fc31dc9081b80dec3015136e551fa6082dc428394728d170a51245b1a4db02c'
CASE = ROOT / 'case/ia6.json'
QUESTION = ROOT / '.cvaa/contracts/legal-evidence.json'
REQUIRED = ('assessed licence', 'grant', 'signed easement')
def verify(data, expected):
if hashlib.sha256(data).hexdigest() != expected:
raise ValueError('changed source or fixture')
return data
def full_scan(xml, target_uri):
parser = expat.ParserCreate()
stack, spans = [], []
def start(_, attrs):
stack.append(parser.CurrentByteIndex if attrs.get('DocumentURI') == target_uri else None)
def end(_):
start_at = stack.pop()
if start_at is not None:
stop_at = parser.CurrentByteIndex
if xml[stop_at:stop_at+2] != b'</':
raise ValueError('expected a non-empty provision')
spans.append(xml[start_at:xml.index(b'>', stop_at) + 1])
parser.StartElementHandler, parser.EndElementHandler = start, end
parser.Parse(xml, True)
if len(spans) != 1:
raise ValueError('expected exactly one matching dated provision')
return spans[0]
def fixtures():
case = verify(CASE.read_bytes(), CASE_SHA)
question = verify(QUESTION.read_bytes(), QUESTION_SHA)
return json.loads(case)['synthetic_example'], json.loads(question), len(case) + len(question)
def unresolved(case, question, missing):
if case['actor'] != 'Unlicensed solar developer' or question['evidence'] != {}:
raise ValueError('unsupported project or evidence')
if set(missing) != set(REQUIRED):
raise ValueError('fixture does not declare the expected missing evidence')
return {'finding': 'insufficient_evidence', 'missing_for_land_rights': sorted(missing),
'question': question['claim']['open_questions'], 'applicability': 'unassessed'}
def full_evidence(case, question):
inventories = [line.removeprefix('No ').removesuffix(' is supplied.')
for line in case['facts'] if line.startswith('No ') and line.endswith(' is supplied.')]
absent = {term for line in inventories for term in re.split(r', | or ', line)}
return unresolved(case, question, [term for term in REQUIRED if term in absent])
def selective_evidence(case, question):
# Independent recogniser for the bounded negative evidence statement in this fixture.
missing = set()
for line in case['facts']:
match = re.fullmatch(r'No (.+) is supplied\.', line)
if match:
for term in REQUIRED:
if re.search(r'(?:^|, | or )' + re.escape(term) + r'(?=, | or |$)', match[1]):
missing.add(term)
return unresolved(case, question, missing)
def measured(call):
wall, cpu = perf_counter_ns(), process_time_ns()
result = call()
return result, {'wall_ns': perf_counter_ns() - wall, 'cpu_ns': process_time_ns() - cpu}
def replay(path, rounds):
if rounds < 1:
raise ValueError('rounds must be positive')
with TemporaryDirectory() as tmp:
index = Path(tmp) / 'index.sqlite'
with sqlite3.connect(index) as db:
def setup():
data = verify(path.read_bytes(), XML_SHA)
return ingest(db, data, URL, '2026-11-28')
digest, cost = measured(setup)
cost.update(xml_bytes_read=path.stat().st_size, sqlite_bytes=index.stat().st_size)
def scan():
xml = verify(path.read_bytes(), XML_SHA)
passage = full_scan(xml, URI)
case, question, extra = fixtures()
return verify(passage, FRAGMENT_SHA), full_evidence(case, question), extra
def select():
passage, receipt = get(db, digest, LOCATOR)
if receipt['version'] != DATE or receipt['provision_url'] != URI.replace('http:', 'https:'):
raise ValueError('wrong source edition')
case, question, extra = fixtures()
return verify(passage, FRAGMENT_SHA), selective_evidence(case, question), extra
stats = {'full': [], 'selective': []}
for i in range(rounds):
results = {}
for name, run in ([('full', scan), ('selective', select)] if i % 2 == 0
else [('selective', select), ('full', scan)]):
results[name], times = measured(run)
stats[name].append(times)
if results['full'] != results['selective']:
raise ValueError('evidence or source passage differs')
passage, evidence, fixture_bytes = results['full']
timing = {arm: {key: int(median(sample[key] for sample in samples)) for key in samples[0]}
for arm, samples in stats.items()}
return {'retrieved': '2026-11-28', 'source': URL, 'source_sha256': digest,
'locator': LOCATOR, 'edition': DATE, 'passage_sha256': FRAGMENT_SHA,
'pointer_only': {'pipeline_news_release': '202611232245', 'repd_reference': '12588'},
'fictional_case_sha256': CASE_SHA, 'question_sha256': QUESTION_SHA, 'result': evidence,
'full_selective_bytes_identical': True, 'independent_fixture_outputs_equal': True,
'one_time_index_setup': cost, 'rounds_per_arm': rounds, 'median_per_query': timing,
'logical_bytes_per_query': {'full_xml': path.stat().st_size, 'selective_xml': len(passage),
'additional_fixture_and_question_bytes_each_arm': fixture_bytes},
'network_bytes_during_offline_replay': 0, 'ai_calls_during_offline_replay': 0,
'energy_joules': None, 'physical_storage_io_bytes': None}
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('xml', type=Path)
parser.add_argument('--rounds', type=int, default=7)
args = parser.parse_args()
print(json.dumps(replay(args.xml, args.rounds), indent=2))Verify Ia6
A Python command-line tool in the case folder of Legislation that verifies the original repository PDF and optionally compare Parliament's bytes, using SHA-256.
ingestlegislation / case/verify_ia6.py · lines 1–47 of 47 · Entry point · pattern identity (shared by 11 files)
- What it does
- It fetches data. Defines identity, verify, main. Uses libraries argparse, hashlib, json, pathlib, urllib.request. Side effects: reads or writes files; makes network requests.
- Inputs & outputs
- In: JSON file ia6.json; command-line arguments.
- Downstream impact
- Used directly by 1 file: Verify (legislation). Reached from 1 other entry point, including Verify Workflow (legislation).
- What it achieves
- Defines `identity` and `verify`. It accepts `--repository` and `--online`.
- Why it matters
- Run by Verify.
- Application
- legislation · case · Python CLI
- Uses
- argparse, hashlib, json, pathlib, urllib.request
- Used by
- run by Verify (script call)
- Produces
- identity, verify, main
- Defines here
- identity, verify, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- legislation@960afbd0f5393e818b400a7f1a523acd6814e217 case/verify_ia6.py:1-47 · blob e5d1696f242ba79abfad9ff7d2ed8874e22505f1 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: ingest · effects: filesystem, network · domain stage: unknown · users: none · canonical: unknown
"""Verify the original repository PDF and optionally compare Parliament's bytes."""
import argparse
import hashlib
import json
from pathlib import Path
from urllib.request import Request, urlopen
HERE = Path(__file__).resolve().parent
def identity(data):
header = b"blob " + str(len(data)).encode() + b"\0"
return {
"bytes": len(data),
"sha256": hashlib.sha256(data).hexdigest(),
"git_blob_sha1": hashlib.sha1(header + data).hexdigest(),
}
def verify(data, expected):
actual = identity(data)
if any(expected[key] != value for key, value in actual.items()):
raise ValueError(f"PDF identity mismatch: {actual}")
return actual
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--repository", type=Path, default=HERE.parent)
parser.add_argument("--online", action="store_true")
args = parser.parse_args()
doc = json.loads((HERE / "ia6.json").read_text())["document"]
local = (args.repository / doc["repository_file"]).read_bytes()
result = {"repository": verify(local, doc)}
if args.online:
request = Request(doc["url"], headers={"User-Agent": "Ventus-Legislation-IA6/1"})
with urlopen(request, timeout=30) as response:
official = response.read(doc["bytes"] + 1)
result["official"] = verify(official, doc)
if official != local:
raise ValueError("Official and repository bytes differ")
result["identical"] = True
print(json.dumps(result, sort_keys=True))
if __name__ == "__main__":
main()Screen
A Python command-line tool in the contracts folder of Legislation that replays one fictional civilian screening question, using SHA-256.
otherlegislation / contracts/screen.py · lines 1–85 of 85 · Entry point · pattern evaluate (shared by 18 files)
- What it does
- Defines appraisal, evaluate. Uses libraries argparse, datetime, decimal, hashlib, json. Side effects: reads or writes files.
- Inputs & outputs
- In: command-line arguments.
- Downstream impact
- Used directly by 1 file: Test Screen (legislation).
- What it achieves
- Defines `appraisal` and `evaluate`.
- Why it matters
- Checked by Test Screen.
- Application
- legislation · contracts · Python CLI
- Uses
- argparse, datetime, decimal, hashlib, json, pathlib
- Used by
- imported by Test Screen (import)
- Produces
- appraisal, evaluate
- Defines here
- appraisal, evaluate
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- legislation@960afbd0f5393e818b400a7f1a523acd6814e217 contracts/screen.py:1-85 · blob b35f058cf8081e9ffbdb8d4eadeba4176835a9fd · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: unknown · users: none · canonical: unknown
"""Replay one fictional civilian screening question. Data never grants permission."""
import argparse
from datetime import date
from decimal import Decimal
import hashlib
import json
from pathlib import Path
REQUIRED = {
"planning_decision": "planning",
"land_agreement": "land",
"engineering_record": "physical_connectivity",
"connection_contract": "commercial_agreement",
"capacity_assessment": "electrical_capacity",
}
STATES = {"satisfied", "contradicted", "unknown"}
def appraisal(rows, annual_real_discount_rate):
"""Present value for a bounded fictional, two-period real-GBP comparison."""
rate = Decimal(annual_real_discount_rate)
if not rate.is_finite() or rate < 0:
raise ValueError("Expected a finite non-negative real discount rate")
if len(rows) != 2 or [r["year"] for r in rows] != [0, 1]:
raise ValueError("Expected exactly one cash flow for each of years zero and one")
if any(r["unit"] != "GBP real base year zero" for r in rows):
raise ValueError("Inconsistent currency or price basis")
amounts = {}
for scenario in ("baseline", "option"):
values = [r[scenario] for r in rows]
if None in values:
amounts[scenario] = None
continue
numbers = [Decimal(v) for v in values]
if any(not n.is_finite() for n in numbers):
raise ValueError("Cash flows must be finite")
amounts[scenario] = numbers[0] + numbers[1] / (1 + rate)
delta = None if None in amounts.values() else amounts["option"] - amounts["baseline"]
return {key: None if value is None else str(value.quantize(Decimal("0.01")))
for key, value in {**amounts, "delta": delta}.items()}
def evaluate(case):
if case["scope"] != "fictional civilian screening":
raise ValueError("Only fictional civilian screening fixtures are accepted")
as_of = date.fromisoformat(case["as_of"])
ledger = {}
for kind, gate in REQUIRED.items():
observations = []
for row in case["evidence"]:
if row["kind"] != kind:
continue
if row["gate"] != gate or row["state"] not in STATES:
raise ValueError("Mismatched evidence type or state")
if not row["source"].startswith("fixture:") or not row["source"][8:]:
raise ValueError("Expected an identified fixture observation")
if (row["asset_class"], row["territory"], row["project"]) != (
case["asset_class"], case["territory"], case["project"]
):
continue
if row["basis"] != "assumed_baseline":
continue
start, end = (date.fromisoformat(row[k]) for k in ("from", "through"))
if start > end:
raise ValueError("Reversed validity interval")
if start <= as_of <= end:
observations.append(row)
states = {row["state"] for row in observations}
state = next(iter(states)) if len(states) == 1 else "unknown"
ledger[gate] = {"state": state, "conflict": len(states) > 1,
"sources": sorted({row["source"] for row in observations})}
blockers = sorted(k for k, v in ledger.items() if v["state"] == "contradicted")
unknowns = sorted(k for k, v in ledger.items() if v["state"] == "unknown")
result = "blocked" if blockers else "insufficient_evidence" if unknowns else "screen_passed"
return {"scope": case["scope"], "result": result, "blockers": blockers,
"unknowns": unknowns, "ledger": ledger,
"scenario_pv_gbp": appraisal(case["annual_flows"], case["real_discount_rate"])}
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("fixture", type=Path)
data = parser.parse_args().fixture.read_bytes()
print(json.dumps({"fixture_sha256": hashlib.sha256(data).hexdigest(),
**evaluate(json.loads(data))}, indent=2, sort_keys=True))Verify Catalogue
A Python command-line tool in the data folder of Legislation that verifies every preserved introduction against its record without network access, using SHA-256.
ingestlegislation / data/verify_catalogue.py · lines 1–36 of 36 · Entry point · pattern verify (shared by 34 files)
- What it does
- It loads data. Defines verify. Uses libraries hashlib, json, pathlib, xml.etree.ElementTree, zipfile. Side effects: reads or writes files.
- Inputs & outputs
- In: JSON file catalogue.json.
- Downstream impact
- Used directly by 1 file: Verify Workflow (legislation).
- What it achieves
- Its name says it verifies catalogue. Defines `verify`.
- Why it matters
- Run by Verify Workflow.
- Application
- legislation · data · Python CLI
- Uses
- hashlib, json, pathlib, xml.etree.ElementTree, zipfile
- Used by
- run by Verify Workflow (workflow run)
- Produces
- verify
- Defines here
- verify
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- legislation@960afbd0f5393e818b400a7f1a523acd6814e217 data/verify_catalogue.py:1-36 · blob 836dfc1afdd59de9edef0e5484ec0b61b09058d4 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: unknown · users: none · canonical: unknown
"""Verify every preserved introduction against its record without network access."""
import hashlib
import json
from pathlib import Path
import xml.etree.ElementTree as ET
import zipfile
DATA = Path(__file__).resolve().parent
def verify():
records = json.loads((DATA / 'catalogue.json').read_text())
if not records:
raise ValueError('Empty instrument catalogue')
ids = [row['id'] for row in records]
if len(set(ids)) != len(ids):
raise ValueError('Duplicate instrument identifier')
with zipfile.ZipFile(DATA / 'introductions-20261128.zip') as archive:
members = [row['snapshot_sha256'] + '.xml' for row in records]
if sorted(archive.namelist()) != sorted(members):
raise ValueError('Archive and catalogue membership differ')
for row, name in zip(records, members):
data = archive.read(name)
root = ET.fromstring(data)
title = root.findtext('.//{http://purl.org/dc/elements/1.1/}title')
if (len(data) != row['snapshot_bytes']
or hashlib.sha256(data).hexdigest() != row['snapshot_sha256']
or root.get('IdURI') != row['external_id']
or row['external_id'].split('/id/')[-1] != row['id']
or ' '.join(title.split()) != row['title']):
raise ValueError(f'Archive evidence mismatch for {row["id"]}')
return len(records)
if __name__ == '__main__':
print(f'{verify()} instrument snapshots verified.')Compare
A Python command-line tool in the editions folder of Legislation that reads edition (`read_edition`), using SHA-256.
ingestlegislation / editions/compare.py · lines 1–73 of 73 · Entry point · pattern replay (shared by 12 files)
- What it does
- It loads data. Defines digest, read_edition, compare, replay. Uses libraries datetime, hashlib, json, pathlib, urllib.parse. Side effects: reads or writes files.
- Inputs & outputs
- In: command-line arguments.
- Downstream impact
- Used directly by 1 file: Test Compare (legislation).
- What it achieves
- It is built from the digest step (`digest`), the compare step (`compare`) and the replay step (`replay`). Compare exact publisher editions of one addressed CLML provision. It accepts `--source-directory`.
- Why it matters
- Checked by Test Compare.
- Application
- legislation · editions · Python CLI
- Uses
- datetime, hashlib, json, pathlib, urllib.parse, xml.etree.ElementTree, difflib, argparse
- Used by
- imported by Test Compare (import)
- Produces
- digest, read_edition, compare, replay
- Defines here
- digest, read_edition, compare, replay
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- legislation@960afbd0f5393e818b400a7f1a523acd6814e217 editions/compare.py:1-73 · blob 7364c63193fb551cb3fd6ee4c898899264da1135 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: unknown · users: none · canonical: unknown
"""Compare exact publisher editions of one addressed CLML provision."""
from datetime import date
import hashlib
import json
from pathlib import Path
from urllib.parse import urlsplit
import xml.etree.ElementTree as ET
DC = "{http://purl.org/dc/elements/1.1/}"
CLML = "{http://www.legislation.gov.uk/namespaces/legislation}"
def digest(body):
return hashlib.sha256(body).hexdigest()
def read_edition(path, expected):
raw = path.read_bytes()
if digest(raw) != expected:
raise ValueError("Edition digest mismatch")
root = ET.fromstring(raw)
identifier = root.findtext(".//" + DC + "identifier")
if not identifier:
raise ValueError("Missing publisher identifier")
uri = urlsplit(identifier)
if uri.hostname != "www.legislation.gov.uk" or uri.query or uri.fragment:
raise ValueError("Unrecognised publisher identifier")
provision, edition = uri.path.rsplit("/", 1)
if edition not in ("enacted", "made"):
date.fromisoformat(edition)
nodes = [n for n in root.iter() if n.get("DocumentURI") == identifier and n.get("IdURI")]
if len(nodes) != 1 or urlsplit(nodes[0].get("IdURI")).path != "/id" + provision:
raise ValueError("Edition lacks a unique matching provision")
# Keep inline amendments and editorial marks as supplied by the publisher.
lines = [" ".join("".join(n.itertext()).split()) for n in nodes[0].iter(CLML + "Text")]
if not lines:
raise ValueError("Empty provision")
return {"provision": provision, "edition": edition, "url": identifier.replace("http:", "https:", 1),
"sha256": expected, "text_blocks": lines}
def compare(before, after):
import difflib
if before["provision"] != after["provision"] or before["edition"] == after["edition"]:
raise ValueError("Comparison requires one provision and distinct editions")
a, b = before["text_blocks"], after["text_blocks"]
changes = [{"operation": op, "old_blocks": [i, j], "new_blocks": [k, m]}
for op, i, j, k, m in difflib.SequenceMatcher(None, a, b, autojunk=False).get_opcodes() if op != "equal"]
return {"provision": before["provision"], "editions": [before["edition"], after["edition"]],
"source_sha256": [before["sha256"], after["sha256"]], "changed_block_ranges": changes,
"block_numbering": "zero-based, end-exclusive", "applicability": "requires separate legal evidence"}
def replay(source_directory=None):
base = Path(__file__).resolve().parent
manifest = json.loads((base / "manifest.json").read_text())
editions = []
for row in manifest["snapshots"]:
projection = row["projection"]
if source_directory is not None:
raw = read_edition(source_directory / (projection["edition"] + ".xml"), row["sha256"])
raw["text_blocks"] = [digest(line.encode()) for line in raw["text_blocks"]]
if raw != projection:
raise ValueError("Projection differs from publisher evidence")
editions.append(projection)
return [compare(a, b) for a, b in zip(editions, editions[1:])]
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--source-directory", type=Path)
print(json.dumps(replay(parser.parse_args().source_directory), indent=2))Benchmark
A Python command-line tool in the engine folder of Legislation that replays the Electricity Act 1989 whole-source vs selective retrieval experiment. It is built from the end step (`end`).
storagelegislation / engine/benchmark.py · lines 1–81 of 81 · Entry point · pattern measure (shared by 35 files)
- What it does
- It loads data. Defines measure, scan, start, end, main. Uses libraries argparse, json, pathlib, sqlite3, tempfile. Side effects: reads or writes files; uses storage (browser storage, DuckDB or Parquet).
- Inputs & outputs
- In: SQLite database; command-line arguments.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- Defines `measure`, `scan`, `start` and 1 more.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- legislation · engine · Python CLI
- Uses
- Legal (import), argparse, json, pathlib, sqlite3, tempfile, time, tracemalloc, xml.parsers
- Used by
- none found
- Produces
- measure, scan, main
- Defines here
- measure, scan, start, end, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- legislation@960afbd0f5393e818b400a7f1a523acd6814e217 engine/benchmark.py:1-81 · blob f475db02ad49f5decad3fbcee83768f1b12d631c · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: ingest · effects: filesystem, storage · domain stage: unknown · users: none · canonical: supporting_data
"""Replay the Electricity Act 1989 whole-source vs selective retrieval experiment."""
from argparse import ArgumentParser
import json
from pathlib import Path
import sqlite3
from tempfile import TemporaryDirectory
from time import process_time_ns
import tracemalloc
from xml.parsers import expat
from legal import get, ingest, sha, tag_end
URL = 'https://www.legislation.gov.uk/ukpga/1989/29/enacted/data.xml'
EXPECTED = '24c7ab3c6fe208103c7a902679ffaf2735aa9fe8a0cb3c64b26ae27b8f1c1711'
LOCATOR = 'schedule/4/paragraph/6'
def measure(fn):
tracemalloc.start()
start = process_time_ns()
result = fn()
cpu = process_time_ns() - start
_, peak = tracemalloc.get_traced_memory()
tracemalloc.stop()
return result, dict(cpu_ns=cpu, python_peak_allocated_bytes=peak)
def scan(path):
data = path.read_bytes()
if sha(data) != EXPECTED:
raise ValueError('upstream manifestation differs from the measured specimen')
parser = expat.ParserCreate()
found = []
depth = 0
selected = None
target = 'http://www.legislation.gov.uk/id/ukpga/1989/29/' + LOCATOR
def start(_name, attrs):
nonlocal depth, selected
depth += 1
if attrs.get('IdURI') == target:
selected = depth, parser.CurrentByteIndex
def end(_name):
nonlocal depth, selected
if selected and selected[0] == depth:
found.append(data[selected[1]:tag_end(data, parser.CurrentByteIndex)])
selected = None
depth -= 1
parser.StartElementHandler = start
parser.EndElementHandler = end
parser.Parse(data, True)
if len(found) != 1:
raise ValueError('absent or ambiguous provision')
return found[0]
def main():
parser = ArgumentParser(description=__doc__)
parser.add_argument('xml',type=Path)
parser.add_argument('retrieved',help='actual retrieval date, ISO format')
args = parser.parse_args()
with TemporaryDirectory() as tmp:
path = Path(tmp)/'store.sqlite'
with sqlite3.connect(path) as db:
data, full = measure(lambda: scan(args.xml))
digest, build = measure(lambda: ingest(db,args.xml.read_bytes(),URL,args.retrieved))
(fragment,receipt), selective = measure(lambda: get(db,digest,LOCATOR))
if data != fragment or fragment != Path(__file__).with_name('wayleave-enacted.fragment.xml').read_bytes():
raise ValueError('known-answer comparison failed')
count = db.execute('SELECT count(*) FROM provisions').fetchone()[0]
print(json.dumps(dict(receipt=receipt,source_bytes=args.xml.stat().st_size,provision_count=count,
sqlite_bytes=path.stat().st_size,full_reparse=full,build=build,
selective=selective,comparison='byte-identical to full scan and checked-in excerpt',
network_bytes_during_benchmark=0,ai_calls_during_benchmark=0),indent=2))
if __name__=='__main__':
main()