GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Websites and apps / seed-data / experiments/economical-seeds

Experiment A and 2 more files

A Python command-line tool in the economical seeds folder of Seed Data that runs worker (`run_worker`), covering larger, railways and a results, using SHA-256.

650 lines of Python from seed-data, in 3 files. Topic: Websites and apps. Section 2009 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Experiment A storage · seed-data / experiments/economical-seeds/experiment_a.py lines 1–305
  2. Experiment B storage · seed-data / experiments/economical-seeds/experiment_b.py lines 1–255
  3. History storage · seed-data / experiments/economical-seeds/history.py lines 1–90

Experiment A

A Python command-line tool in the economical seeds folder of Seed Data that runs worker (`run_worker`), covering larger, railways and a results, using SHA-256.

storageseed-data / experiments/economical-seeds/experiment_a.py · lines 1–305 of 305 · Entry point · pattern controls (shared by 3 files)

What it does
It lists and searches larger, railways and a results. Defines 14 functions or classes, including process_counters, Memory, IO, enumerate_headers, full_find. Uses libraries __future__, argparse, ctypes, hashlib, json. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage experimental (path word 'experiment'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Inputs & outputs
In: JSON file larger-index.json; GeoJSON file railways.geojson; JSON file a-results.json; command-line arguments. Out: JSON file.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
It is built from the process counters helper (`process_counters`), the memory class (`Memory`) and the enumerate headers helper (`enumerate_headers`). Benchmark Experiment A on an existing GridAtlas teleprint and read-only STARS. It accepts `--oracle`, `--capture` and `--suffix`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
seed-data · experiments/economical-seeds · Python CLI
Uses
Magnets (import), Teleprint Index (import), __future__, argparse, ctypes, hashlib, json, math, re, statistics
Used by
none found
Produces
process_counters, enumerate_headers, full_find, section_record, checked_identity, run_worker, sample, controls, medians, break_even, main
Defines here
process_counters, Memory, IO, enumerate_headers, full_find, section_record, checked_identity, run_worker, sample, controls, medians, stat, break_even, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
seed-data@e4af7ee340a38d94f21ddbba147395b569ccce11 experiments/economical-seeds/experiment_a.py:1-305 · blob 0b34f499f1c38f155b3e7f11dbe5afdcb4de3733 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: experimental · users: none · canonical: supporting_data
"""Benchmark Experiment A on an existing GridAtlas teleprint and read-only STARS."""
from __future__ import annotations

import argparse
import ctypes
import hashlib
import json
import math
import re
import statistics
import subprocess
import sys
import tempfile
import time
from pathlib import Path

from magnets import DB, read_json
from teleprint_index import index, retrieve


ROOT = Path(__file__).resolve().parent
ORACLE = ROOT / "evidence" / "teleprint" / "larger-index.json"
SECTION = re.compile(rb"={78}\nFILE: ([^\r\n]+)\n([0-9]+) chars \xc2\xb7 [^\r\n]+\n={78}\n")
END = re.compile(rb"={78}\nEND OF TELEPRINT\n={78}(?:\n|$)")


def process_counters():
    """Current Windows process counters from documented PSAPI and Win32 calls."""
    if sys.platform != "win32":
        return {"peak_working_set_bytes": None, "read_transfer_bytes": None, "cycles": None}
    from ctypes import wintypes

    class Memory(ctypes.Structure):
        _fields_ = [("cb", wintypes.DWORD), ("page_faults", wintypes.DWORD)] + [
            (name, ctypes.c_size_t) for name in ("peak_working_set", "working_set",
                "quota_peak_paged", "quota_paged", "quota_peak_nonpaged", "quota_nonpaged",
                "pagefile", "peak_pagefile")
        ]

    class IO(ctypes.Structure):
        _fields_ = [(name, ctypes.c_ulonglong)
            for name in ("read_count", "write_count", "other_count", "read_bytes",
                         "write_bytes", "other_bytes")]

    kernel = ctypes.WinDLL("kernel32", use_last_error=True)
    current = kernel.GetCurrentProcess
    current.restype = wintypes.HANDLE
    process = current()
    memory = Memory()
    memory.cb = ctypes.sizeof(Memory)
    get_memory = ctypes.WinDLL("psapi", use_last_error=True).GetProcessMemoryInfo
    get_memory.argtypes = (wintypes.HANDLE, ctypes.POINTER(Memory), wintypes.DWORD)
    get_memory.restype = wintypes.BOOL
    io = IO()
    get_io = kernel.GetProcessIoCounters
    get_io.argtypes = (wintypes.HANDLE, ctypes.POINTER(IO))
    get_io.restype = wintypes.BOOL
    total_cycles = ctypes.c_ulonglong()
    get_cycles = kernel.QueryProcessCycleTime
    get_cycles.argtypes = (wintypes.HANDLE, ctypes.POINTER(ctypes.c_ulonglong))
    get_cycles.restype = wintypes.BOOL
    return {
        "cycles": total_cycles.value if get_cycles(process, ctypes.byref(total_cycles)) else None,
        "peak_working_set_bytes": memory.peak_working_set if get_memory(process, ctypes.byref(memory), memory.cb) else None,
        "read_transfer_bytes": io.read_bytes if get_io(process, ctypes.byref(io)) else None,
    }


def enumerate_headers(raw, url):
    """Scan every header without offsets and split only the requested section."""
    encoded_url = url.encode("utf-8")
    matches = list(SECTION.finditer(raw))
    end = END.search(raw, matches[-1].end()) if matches else None
    if end is None:
        raise ValueError("No complete teleprint")
    selected = [i for i, match in enumerate(matches) if match[1] == encoded_url]
    if len(selected) != 1:
        raise ValueError(f"Expected one section, found {len(selected)}")
    i = selected[0]
    start = matches[i].end()
    stop = (matches[i+1].start() if i+1 < len(matches) else end.start()) - 2
    if raw[stop:stop+2] != b"\n\n":
        raise ValueError("Unexpected section separator")
    return start, raw[start:stop]


def full_find(raw, url):
    """Use the exact URL in a whole-file native search, without an offset index."""
    marker = b"=" * 78 + b"\nFILE: "
    needle = marker + url.encode("utf-8") + b"\n"
    found = raw.find(needle)
    if found < 0 or raw.find(needle, found + len(needle)) >= 0:
        raise ValueError("Expected one exact section header")
    header = SECTION.match(raw, found)
    if not header:
        raise ValueError("Invalid section header")
    start = header.end()
    following = raw.find(marker, start)
    end = END.search(raw, start) if following < 0 else None
    if following < 0 and end is None:
        raise ValueError("No complete teleprint")
    stop = (following if following >= 0 else end.start()) - 2
    if raw[stop:stop+2] != b"\n\n":
        raise ValueError("Unexpected section separator")
    return start, raw[start:stop]


def section_record(index_value, suffix):
    selected = [row for row in index_value["records"] if row["url"].endswith(suffix)]
    if len(selected) != 1:
        raise ValueError(f"Expected one section, found {len(selected)}")
    return selected[0]


def checked_identity(payload, record):
    digest = hashlib.sha256(payload).hexdigest()
    if len(payload) != record["byte_length"] or digest != record["text_sha256"]:
        raise ValueError("Selected section content differs from the expected digest or size")
    return {key: record[key] for key in ("section", "url", "byte_length", "text_sha256", "git_blob", "tablet")}


def run_worker(mode, capture, oracle, suffix):
    counters = process_counters()
    start = time.perf_counter_ns()
    cpu = time.process_time_ns()
    if mode == "production_index":
        generated = index(capture, DB)
        result = dict(input_sha256=generated["input_sha256"], database_sha256=generated["database_sha256"],
                      section_count=len(generated["records"]), selected=section_record(generated, suffix))
        serial = json.dumps(generated, indent=2).encode("utf-8")
        data_bytes = {"capture": capture.stat().st_size, "stars_database_hash_pass": DB.stat().st_size}
        index_bytes = len(serial)
    else:
        pinned = read_json(oracle)
        record = section_record(pinned, suffix)
        if capture.stat().st_size != pinned["bytes"]:
            raise ValueError("Capture size differs from pinned receipt")
        if mode == "indexed":
            payload = retrieve(capture, record)
            # retrieve already verifies SHA-256. Avoid hashing the selected body twice.
            identity = {key: record[key] for key in ("section", "url", "byte_length", "text_sha256", "git_blob", "tablet")}
            data_bytes = {"capture": len(payload), "provenance_receipt": oracle.stat().st_size}
        else:
            raw = capture.read_bytes()
            find = enumerate_headers if mode == "full_regex" else full_find
            offset, payload = find(raw, record["url"])
            identity = checked_identity(payload, record)
            data_bytes = {"capture": len(raw), "provenance_receipt": oracle.stat().st_size}
        result = dict(capture_sha256=pinned["input_sha256"], database_sha256=pinned["database_sha256"], selected=identity)
        if mode == "focused_setup":
            actual_sha = hashlib.sha256(raw).hexdigest()
            if actual_sha != pinned["input_sha256"]:
                raise ValueError("Whole capture content differs from pinned receipt")
            selected = dict(record, byte_start=offset)
            if offset != record["byte_start"]:
                raise ValueError("Computed offset differs from pinned receipt")
            result["derived_index"] = selected
            # The focused benchmark audits one existing offset. Invocations use the full
            # receipt in both branches, keeping receipt bytes and provenance symmetric.
        index_bytes = None
    elapsed_ms = (time.perf_counter_ns() - start) / 1e6
    cpu_ms = (time.process_time_ns() - cpu) / 1e6
    after = process_counters()
    read_start, read_end = counters["read_transfer_bytes"], after["read_transfer_bytes"]
    cycle_start, cycle_end = counters["cycles"], after["cycles"]
    return dict(elapsed_ms=elapsed_ms, cpu_ms=cpu_ms,
                process_cycles=cycle_end-cycle_start if cycle_start is not None and cycle_end is not None else None, peak_working_set_bytes=after["peak_working_set_bytes"],
                process_read_transfer_bytes=read_end-read_start if read_start is not None and read_end is not None else None,
                logical_input_bytes=sum(data_bytes.values()), input_bytes_by_role=data_bytes,
                serialised_index_bytes=index_bytes, result=result)


def sample(mode, capture, oracle, suffix):
    start = time.perf_counter_ns()
    process = subprocess.run([sys.executable, __file__, "--worker", mode, "--capture", str(capture),
                              "--oracle", str(oracle), "--suffix", suffix],
                             check=True, capture_output=True, encoding="utf-8")
    shell_ms = (time.perf_counter_ns() - start) / 1e6
    return dict(json.loads(process.stdout), fresh_process_including_startup_ms=shell_ms)


def controls(capture, pin, suffix, output):
    record = section_record(pin, suffix)
    original = capture.read_bytes()
    assert retrieve(capture, record) == full_find(original, record["url"])[1]
    with tempfile.TemporaryDirectory(dir=output.parent, prefix="a-tamper-") as temp:
        altered = Path(temp, "copy.txt")
        damaged = bytearray(original)
        damaged[record["byte_start"]] ^= 1
        altered.write_bytes(damaged)
        rejects = {}
        for name, action in (
            ("indexed", lambda: retrieve(altered, record)),
            ("full_integrity", lambda: checked_identity(full_find(altered.read_bytes(), record["url"])[1], record)),
            ("bad_offset", lambda: retrieve(capture, dict(record, byte_start=record["byte_start"]+1))),
            ("missing_resource", lambda: full_find(original, record["url"]+"__missing")),
        ):
            try:
                action()
            except ValueError as exc:
                rejects[name] = str(exc)
            else:
                raise AssertionError(f"Negative control unexpectedly accepted: {name}")
        untouched_target = bytearray(original)
        untouched_target[0] ^= 1
        altered.write_bytes(untouched_target)
        still_matches = bool(retrieve(altered, record))
        whole_changed = hashlib.sha256(untouched_target).hexdigest() != pin["input_sha256"]
        if not (still_matches and whole_changed):
            raise AssertionError("Unexpected out-of-section tamper result")
    return {"rejected": rejects, "out_of_section_tamper": {
        "selective_section_check_accepted": still_matches, "whole_capture_identity_changed": whole_changed
    }}


def medians(samples):
    def stat(key):
        values = [s[key] for s in samples if s[key] is not None]
        return dict(median=statistics.median(values), minimum=min(values), maximum=max(values)) if values else None
    return {key: stat(key) for key in (
        "elapsed_ms", "cpu_ms", "peak_working_set_bytes", "logical_input_bytes",
        "process_read_transfer_bytes", "process_cycles", "fresh_process_including_startup_ms"
    )}


def break_even(cost, baseline, indexed):
    remaining = baseline - indexed
    return math.floor(cost / remaining) + 1 if remaining > 0 else None


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--oracle", type=Path, default=ORACLE)
    parser.add_argument("--capture", type=Path)
    parser.add_argument("--suffix", default="/railways.geojson")
    parser.add_argument("--rounds", type=int, default=11)
    parser.add_argument("--setup-rounds", type=int, default=3)
    parser.add_argument("--output", type=Path, default=ROOT/"economy"/"a-results.json")
    parser.add_argument("--worker", choices=("full", "indexed", "full_regex", "focused_setup", "production_index"))
    args = parser.parse_args()
    if args.worker:
        print(json.dumps(run_worker(args.worker, args.capture, args.oracle, args.suffix)))
        return
    if args.rounds < 1 or args.setup_rounds < 1:
        parser.error("Round counts must be positive")
    args.output.parent.mkdir(exist_ok=True, parents=True)
    pinned = read_json(args.oracle)
    capture = args.capture or Path(pinned["input"])
    samples = {mode: [] for mode in ("full", "indexed", "full_regex", "focused_setup", "production_index")}
    for i in range(args.rounds):
        modes = ("full", "indexed") if i % 2 == 0 else ("indexed", "full")
        for mode in modes:
            samples[mode].append(sample(mode, capture, args.oracle, args.suffix))
    for _ in range(args.setup_rounds):
        samples["full_regex"].append(sample("full_regex", capture, args.oracle, args.suffix))
    for i in range(args.setup_rounds):
        modes = ("production_index", "focused_setup") if i % 2 == 0 else ("focused_setup", "production_index")
        for mode in modes:
            samples[mode].append(sample(mode, capture, args.oracle, args.suffix))
    selected = samples["full"][0]["result"]
    for mode in ("full", "indexed", "full_regex"):
        if any(s["result"] != selected for s in samples[mode]):
            raise AssertionError("Invocation result or selected provenance differs")
    for s in samples["production_index"]:
        if (s["result"]["input_sha256"], s["result"]["database_sha256"], s["result"]["selected"]) != (
            pinned["input_sha256"], pinned["database_sha256"], section_record(pinned, args.suffix)
        ):
            raise AssertionError("Full index reconstruction disagrees with pinned provenance")
    stats = {mode: medians(values) for mode, values in samples.items()}
    crossover = {
        mode: {key: break_even(stats[mode][key]["median"], stats["full"][key]["median"],
                               stats["indexed"][key]["median"])
               for key in ("elapsed_ms", "cpu_ms", "logical_input_bytes", "fresh_process_including_startup_ms")}
        for mode in ("focused_setup", "production_index")
    }
    receipt = dict(schema="seed.economy.selective-retrieval.v1", verified_result=selected,
                   Python=sys.version, input_capture_bytes=pinned["bytes"],
                   scope="Pinned section identity. Unrelated capture changes are outside per-query verification.",
                   measurement_notes=[
                    "Interleaved fresh Python processes. Filesystem cache was not flushed.",
                    "Elapsed and CPU times bracket the operation. End-to-end fresh-process time includes launch; "
                    "peak working set includes interpreter startup.",
                    "Logical input bytes count application data and receipt reads, not physical storage or network IO.",
                    "Both full paths read the whole capture. The primary full path uses a native exact byte-marker search."
                    " The all-header regex path demonstrates baseline sensitivity. Each verifies only the requested payload.",
                    "Windows process CPU time can quantise short samples to 0 ms. Process cycles include measurement overhead,"
                    " vary with CPU frequency and cannot be interpreted as an energy measurement.",
                    "The focused setup verifies the pinned whole capture and independently checks the requested byte offset. "
                    "It measures single-target first-use verification rather than production index construction.",
                    "The production setup reconstructs and serialises the complete existing index in memory. It hashes the "
                    "STARS database once. It excludes persistent index writes and the CLI preflight database hash.",
                    "Break-even is modelled from measured medians, excludes ongoing maintenance and uses one setup per stable capture.",
                   ], unavailable={"joules":"No validated meter or package-energy counter used",
                                    "gpu":"CPU-only implementation", "human_work_minutes":"No controlled timed participant study",
                                    "ai_development_tokens":"Per-experiment inference telemetry unavailable"},
                   calls_per_invocation={"human_query":1,"ai_inference":0,"network":0},
                   controls=controls(capture, pinned, args.suffix, args.output),
                   medians=stats, break_even_invocations=crossover, samples=samples)
    with args.output.open("x", encoding="utf-8") as stream:
        json.dump(receipt, stream, indent=2)
    print(json.dumps({"medians":stats, "break_even_invocations":crossover, "controls":receipt["controls"]}, indent=2))


if __name__ == "__main__":
    main()

Experiment B

A Python command-line tool in the economical seeds folder of Seed Data that restores bytes (`restore_bytes`), covering larger, railways, duplicate and wrong identity, using SHA-256.

storageseed-data / experiments/economical-seeds/experiment_b.py · lines 1–255 of 255 · Entry point · pattern composed (shared by 4 files)

What it does
Defines 10 functions or classes, including choose, restore_bytes, composed, process_peak, Counters. Uses libraries argparse, ctypes, ctypes.wintypes, hashlib, json. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage experimental (path word 'experiment'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Inputs & outputs
In: JSON file larger-index.json; GeoJSON file railways.geojson; JSON file duplicate-index.json; JSON file wrong-identity.json; command-line arguments. Out: JSON file.
Downstream impact
Used directly by 1 file: State Compare (seed-data). Reached from 2 other entry points, including Bench State Compare (seed-data); Test State Compare (seed-data).
What it achieves
It is built from the choose step (`choose`), the composed step (`composed`) and the process peak helper (`process_peak`). Compose selective capture retrieval with verified historical byte reconstruction. It accepts `--capture`, `--database` and `--index`.
Why it matters
Imported by State Compare.
Application
seed-data · experiments/economical-seeds · Python CLI
Uses
B Baseline (import), History (import), Magnets (import), Teleprint Index (import), argparse, ctypes, ctypes.wintypes, hashlib, json, platform, statistics, subprocess
Used by
imported by State Compare (sys.path import)
Produces
choose, restore_bytes, composed, process_peak, sample, digest_check, negative_cases, benchmark, main
Defines here
choose, restore_bytes, composed, process_peak, Counters, sample, digest_check, negative_cases, benchmark, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
seed-data@e4af7ee340a38d94f21ddbba147395b569ccce11 experiments/economical-seeds/experiment_b.py:1-255 · blob 920f805344b0e2407d5664dc4b58f7b34421772f · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: experimental · users: none · canonical: supporting_data
"""Compose selective capture retrieval with verified historical byte reconstruction."""
import argparse
import ctypes
import ctypes.wintypes as windows
import hashlib
import json
import platform
import statistics
import subprocess
import sys
import tempfile
import time
from contextlib import closing
from pathlib import Path

from economy.b_baseline import source_audit as standalone
from history import git_blob
from magnets import DB, connect, file_sha, line_ids
from teleprint_index import retrieve

ROOT = Path(__file__).resolve().parent
INDEX = ROOT / "evidence/teleprint/larger-index.json"
SELECTED = "202609241251-streaming-parquet-bridge-v9-5.js"
PRINTER = "202609062358-substation-intelligence-v9-63.js"


def choose(catalog, suffix):
    candidates = [item["url"] for item in catalog["records"] if item["url"].endswith(suffix)]
    if len(candidates) != 1:
        raise ValueError(f"Expected one URL for {suffix!r}, got {len(candidates)}")
    return candidates[0]


def restore_bytes(db, packed, sql_count):
    """Reconstruct only the selected tablet using the STARS line-ID convention."""
    order = line_ids(packed)
    ids = sorted(set(order))
    lookup = {}
    for start in range(0, len(ids), 900):
        part = ids[start:start + 900]
        placeholders = ",".join("?" for _ in part)
        lookup.update(db.execute(f"select n,text from line where n in ({placeholders})", part))
        sql_count += 1
    return b"".join(lookup[i] for i in order), sql_count


def composed(capture, url, database, index_path):
    raw_index = index_path.read_bytes()
    catalog = json.loads(raw_index)
    hits = [row for row in catalog["records"] if row["url"] == url]
    if len(hits) != 1:
        return {"status": "ambiguous" if hits else "absent", "url": url}, len(raw_index), 0
    (record,) = hits
    try:
        payload = retrieve(capture, record)
    except ValueError:
        return {"status": "capture-drift", "url": url}, len(raw_index) + record["byte_length"], 0
    digest = hashlib.sha256(payload).hexdigest()
    identity = git_blob(payload)
    data_bytes = len(raw_index) + len(payload)
    if record["git_blob"] != identity:
        return {"status": "index-identity-drift", "url": url}, data_bytes, 0
    out = dict(status="unmatched", url=url, sha256=digest, git_blob=identity, tablet=None,
               occurrences=[])
    with closing(connect(database)) as db:
        item = db.execute("select n,lines from tablet where git_blob=?", (identity,)).fetchone()
        if not item:
            return out, data_bytes, 1
        tablet, packed = item
        restored, sql_count = restore_bytes(db, packed, 1)
        if restored != payload or git_blob(restored) != identity:
            raise ValueError("Historical tablet integrity mismatch")
        occurrences = db.execute("""
            select o.repo,o.commit_sha,o.path,c.date from occurrence o
            left join commit_info c on o.repo=c.repo and o.commit_sha=c.sha
            where o.tablet=? order by o.repo,o.commit_sha,o.path
        """, (tablet,)).fetchall()
        out.update(status="byte-identical", tablet=tablet, occurrences=occurrences)
        return out, data_bytes, sql_count + 1


def process_peak():
    if sys.platform == "win32":
        class Counters(ctypes.Structure):
            _fields_ = [("cb", windows.DWORD), ("PageFaultCount", windows.DWORD)] + [
                (name, ctypes.c_size_t)
                for name in ("PeakWorkingSetSize", "WorkingSetSize", "QuotaPeakPagedPoolUsage",
                             "QuotaPagedPoolUsage", "QuotaPeakNonPagedPoolUsage",
                             "QuotaNonPagedPoolUsage", "PagefileUsage", "PeakPagefileUsage")
            ]
        kernel = ctypes.windll.kernel32
        kernel.GetCurrentProcess.restype = windows.HANDLE
        psapi = ctypes.windll.psapi
        psapi.GetProcessMemoryInfo.argtypes = (
            windows.HANDLE, ctypes.POINTER(Counters), windows.DWORD)
        values = Counters()
        values.cb = ctypes.sizeof(values)
        if psapi.GetProcessMemoryInfo(kernel.GetCurrentProcess(), ctypes.byref(values), values.cb):
            return values.PeakWorkingSetSize
    elif sys.platform.startswith(("linux", "darwin")):
        import resource
        peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
        return peak * (1024 if sys.platform.startswith("linux") else 1)
    return None


MODES = {
    "composition": composed,
    "standalone-indexed": standalone,
    "standalone-whole-capture": lambda capture, url, database, _: standalone(capture, url, database),
}


def sample(mode, capture, url, database, index_path):
    start, cpu_start = time.perf_counter_ns(), time.process_time_ns()
    result, count, queries = MODES[mode](capture, url, database, index_path)
    return dict(result=result, logical_capture_and_index_bytes=count, sqlite_selects=queries,
                elapsed_ns=time.perf_counter_ns() - start, cpu_ns=time.process_time_ns() - cpu_start,
                peak_worker_rss_bytes=process_peak())


def digest_check(path, expected):
    start, cpu_start = time.perf_counter_ns(), time.process_time_ns()
    actual = file_sha(path)
    if actual != expected:
        raise ValueError(f"Input digest drift for {path.name}")
    return dict(sha256=actual, logical_bytes=path.stat().st_size,
                elapsed_ns=time.perf_counter_ns() - start, cpu_ns=time.process_time_ns() - cpu_start)


def negative_cases(capture, database, index_path, selected, catalog):
    controls = []
    absent = selected + ".missing"
    missing_loose = choose(catalog, "/railways.geojson")
    for label, url, expected in (("missing URL", absent, "absent"),
                                 ("captured payload has no STARS tablet", missing_loose, "unmatched")):
        results = {mode: fn(capture, url, database, index_path)[0] for mode, fn in MODES.items()}
        assert all(outcome == results["composition"] for outcome in results.values())
        assert results["composition"]["status"] == expected
        controls.append(dict(label=label, expected=expected, statuses={k: v["status"] for k, v in results.items()}))

    (target,) = [record for record in catalog["records"] if record["url"] == selected]
    with tempfile.TemporaryDirectory() as tmp:
        folder = Path(tmp)
        duplicate = folder / "duplicate-index.json"
        duplicate.write_text(json.dumps(dict(catalog, records=[*catalog["records"], target])), encoding="utf-8")
        wrong_id = folder / "wrong-identity.json"
        wrong_id.write_text(json.dumps(dict(catalog, records=[
            dict(record, git_blob="0" * 40) if record["url"] == selected else record
            for record in catalog["records"]
        ])), encoding="utf-8")
        corrupt = folder / "changed-payload.txt"
        changed = bytearray(capture.read_bytes())
        changed[target["byte_start"]] ^= 1
        corrupt.write_bytes(changed)
        indexed = {mode: fn for mode, fn in MODES.items() if mode != "standalone-whole-capture"}
        for label, path, manifest, expected in (
                ("ambiguous indexed URL", capture, duplicate, "ambiguous"),
                ("selected content differs from pinned index", corrupt, index_path, "capture-drift"),
                ("index Git identity differs from digest-verified payload", capture, wrong_id, "index-identity-drift")):
            results = {mode: fn(path, selected, database, manifest)[0]["status"] for mode, fn in indexed.items()}
            assert set(results.values()) == {expected}
            controls.append(dict(label=label, expected=expected, statuses=results))
    return controls


def benchmark(capture, database, index_path, repetitions):
    initial = time.perf_counter_ns()
    catalog = json.loads(index_path.read_bytes())
    integrity = dict(capture=digest_check(capture, catalog["input_sha256"]),
                     database=digest_check(database, catalog["database_sha256"]),
                     reusable_index=file_sha(index_path))
    if repetitions < 1:
        raise ValueError("At least one measured repetition is required")
    runs = {mode: [] for mode in MODES}
    witnesses = {}
    controls = negative_cases(capture, database, index_path, choose(catalog, SELECTED), catalog)
    for step in range(repetitions):
        modes = list(MODES)
        modes = modes[step % len(modes):] + modes[:step % len(modes)]
        suffix = (SELECTED, PRINTER)[step % 2]
        url = choose(catalog, suffix)
        for mode in modes:
            proc = subprocess.run([sys.executable, __file__, "--sample", mode,
                                   "--capture", str(capture), "--database", str(database),
                                   "--index", str(index_path), "--resource", url],
                                  check=True, capture_output=True, text=True)
            reading = json.loads(proc.stdout)
            witness = reading.pop("result")
            expected_tablet = {SELECTED: 6504, PRINTER: 1648}[suffix]
            assert witness["status"] == "byte-identical" and witness["tablet"] == expected_tablet
            if suffix in witnesses:
                assert witnesses[suffix] == witness
            else:
                witnesses[suffix] = witness
            runs[mode].append(dict(resource=suffix, **reading))
    summary = {
        mode: {
            suffix: {k: statistics.median(row[k] for row in rows
                                           if row["resource"] == suffix and row[k] is not None)
                     for k in rows[0] if k != "resource" and rows[0][k] is not None}
            for suffix in witnesses
        }
        for mode, rows in runs.items()
    }
    return dict(
        platform=platform.platform(), python=sys.version, repetitions_per_mode=repetitions,
        elapsed_benchmark_ns=time.perf_counter_ns() - initial,
        prerequisite_integrity=integrity, witnesses=witnesses, controls=controls,
        raw_samples=runs, medians_by_resource=summary, inputs=dict(
            capture=capture.name, index=index_path.name, database=database.name),
        code=dict(composition_entry_sha256=file_sha(Path(__file__)),
                  independent_baseline_sha256=file_sha(ROOT / "economy/b_baseline.py"),
                  capture_retrieval_seed_sha256=file_sha(ROOT / "teleprint_index.py"),
                  historical_identity_seed_sha256=file_sha(ROOT / "history.py")),
        scope=dict(
            measured="Fresh workers, filesystem cache uncontrolled, function wall/CPU excludes process bootstrap; worker peak RSS includes Python base.",
            bytes="Logical payload/index bytes read or whole mapped input length searched, excludes SQLite page reads and physical disk I/O.",
            equivalent="Both indexed implementations pin the retrieved section digest. Whole-capture mode scans framing and verifies the selected bytes against STARS; a separate common prerequisite checks the full capture and database hashes once.",
            ai="0 calls/tokens during invocations. Historical and authoring AI token totals, human decision counts, and development effort unavailable.",
            energy="Unavailable. GPU unused.",
            exclusions="Index creation accounted in Experiment A. No claims about selected source being the originally served network response, about runtime behaviour, or about deployment."),
    )


def main():
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument("--capture", type=Path)
    p.add_argument("--database", default=DB, type=Path)
    p.add_argument("--index", default=INDEX, type=Path)
    p.add_argument("--resource", help="Exact captured URL for a single audited invocation")
    p.add_argument("--sample", choices=MODES, help=argparse.SUPPRESS)
    p.add_argument("--repetitions", default=12, type=int)
    p.add_argument("--output", type=Path)
    args = p.parse_args()
    if args.sample:
        print(json.dumps(sample(args.sample, args.capture, args.resource, args.database, args.index)))
        return
    capture = args.capture
    if capture is None:
        capture = Path(json.loads(args.index.read_bytes())["input"])
    if args.resource:
        result = composed(capture, args.resource, args.database, args.index)[0]
    else:
        result = benchmark(capture, args.database, args.index, args.repetitions)
    if args.output:
        with args.output.open("x", encoding="utf-8") as stream:
            json.dump(result, stream, indent=2)
            stream.write("\n")
    else:
        print(json.dumps(result, indent=2))


if __name__ == "__main__":
    main()

History

A Python command-line tool in the economical seeds folder of Seed Data that works with git blob (`git_blob`) and proof provenance (`proof_provenance`). It is built from the inspect step (`inspect`).

storageseed-data / experiments/economical-seeds/history.py · lines 1–90 of 90 · Entry point · pattern git_blob (shared by 4 files)

What it does
Defines git_blob, inspect, proof_provenance. Uses libraries argparse, hashlib, json, re, collections. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage experimental (path word 'experiments'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Inputs & outputs
In: command-line arguments. Out: JSON file.
Downstream impact
Used directly by 3 files: Experiment B (seed-data); State Compare (seed-data); Teleprint Index (seed-data). Reached from 3 other entry points, including Bench State Compare (seed-data); Experiment A (seed-data); Test State Compare (seed-data).
What it achieves
Verify tablet reconstruction and find exact cross-repository and historical bridges. It accepts `--db` and `--output`.
Why it matters
Imported by Experiment B, State Compare and Teleprint Index.
Application
seed-data · experiments/economical-seeds · Python CLI
Uses
Magnets (import), argparse, hashlib, json, re, collections, datetime, pathlib
Used by
imported by Experiment B (import), imported by State Compare (sys.path import), imported by Teleprint Index (import)
Produces
git_blob, inspect, proof_provenance
Defines here
git_blob, inspect, proof_provenance
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
seed-data@e4af7ee340a38d94f21ddbba147395b569ccce11 experiments/economical-seeds/history.py:1-90 · blob 1edb727a49d7fb28ab49e4f0645affff596d4a62 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: experimental · users: none · canonical: supporting_data
"""Verify tablet reconstruction and find exact cross-repository and historical bridges."""
import argparse
import hashlib
import json
import re
from collections import defaultdict
from datetime import datetime
from pathlib import Path

from magnets import DB, ROOT, connect, file_sha, line_ids


def git_blob(raw):
    return hashlib.sha1(f"blob {len(raw)}\0".encode() + raw).hexdigest()


def inspect(db):
    lines = dict(db.execute("select n,text from line"))
    tablets = {}
    mismatches = []
    for number, expected, encoded in db.execute("select n,git_blob,lines from tablet"):
        ids = line_ids(encoded)
        actual = git_blob(b"".join(lines[n] for n in ids))
        tablets[number] = ids
        if actual != expected:
            mismatches.append([number, expected, actual])
    histories = defaultdict(dict)
    tablet_repos = defaultdict(set)
    for repo, commit, path, tablet, date in db.execute("""
        select o.repo,o.commit_sha,o.path,o.tablet,c.date from occurrence o
        left join commit_info c on c.repo=o.repo and c.sha=o.commit_sha
    """):
        tablet_repos[tablet].add(repo)
        if date:
            old = histories[(repo, path)].get(tablet)
            if old is None or (date, commit) < old:
                histories[(repo, path)][tablet] = (date, commit)
    changes = []
    for (repo, path), versions in histories.items():
        if len(versions) < 2:
            continue
        ordered = sorted(versions, key=lambda n: (datetime.fromisoformat(versions[n][0]), versions[n][1], n))
        start, end = ordered[0], ordered[-1]
        a, b = set(tablets[start]), set(tablets[end])
        changes.append(dict(repo=repo, path=path, first=[start, *versions[start]],
                            last=[end, *versions[end]], introduced=sorted(b-a)[:10],
                            absent=sorted(a-b)[:10], retained=len(a&b),
                            divergence=round(len(a^b)/max(1, len(a|b)), 4)))
    bridges = [[n, sorted(repos)] for n, repos in sorted(tablet_repos.items()) if len(repos) > 1]
    return dict(tablets_checked=len(tablets), mismatches=mismatches, exact_bridges=bridges,
                changed_paths=len(changes), change_witnesses=sorted(changes, key=lambda x:
                    (-x["divergence"], x["repo"], x["path"]))[:100])


def proof_provenance(db):
    witnesses = {}
    repo = ROOT / "sources/gridatlas"
    for path in sorted((repo / "atlas/modules").glob("*.js")):
        digest = git_blob(path.read_bytes())
        row = db.execute("select n from tablet where git_blob=?", (digest,)).fetchone()
        if not row:
            # Git's Windows checkout can convert LF to CRLF.
            digest = git_blob(path.read_bytes().replace(b"\r\n", b"\n"))
            row = db.execute("select n from tablet where git_blob=?", (digest,)).fetchone()
        ids = []
        source = None
        if row:
            ids = list(db.execute("""select t.name, t.element,e.family,t.first,t.last
                  from tablet_element t join element e on e.n=t.element
                  where t.tablet=? order by t.first""", row))
            source = db.execute("""select repo,commit_sha,path from occurrence where tablet=?
                order by (repo='Ventusltd/gridatlas') desc, commit_sha, path limit 1""", row).fetchone()
        witnesses[path.name] = dict(git_blob=digest, tablet=row[0] if row else None,
                                    source=source, elements=ids)
    return witnesses


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--db", type=Path, default=DB)
    parser.add_argument("--output", type=Path, required=True)
    args = parser.parse_args()
    before = file_sha(args.db)
    with connect(args.db) as connection:
        results = inspect(connection)
        results["proof_modules"] = proof_provenance(connection)
    if file_sha(args.db) != before:
        raise RuntimeError("Original database changed during experiment")
    with args.output.open("x", encoding="utf-8") as stream:
        json.dump(dict(snapshot_sha256=before, **results), stream, indent=2)