GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / cosmic / tools/explore/periodic/furnace

Test Run and 2 more files

A test in the furnace folder of Cosmic that checks Periodic — Furnace.

635 lines of Python and CSS from cosmic, in 3 files. Topic: Kuiper, cosmos and drawing engines. Section 1121 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. Periodic — Furnace render · cosmic / tools/explore/periodic/furnace/run.py lines 502–742
  2. Test Run test · cosmic / tools/explore/periodic/furnace/test_run.py lines 1–316
  3. Periodic render · cosmic / tools/explore/periodic/page/periodic.css lines 1–78

Periodic — Furnace

A Python command-line tool in the explore folder of Cosmic that reads elements118, build graph, identity and receipts, using SHA-256.

rendercosmic / tools/explore/periodic/furnace/run.py · lines 502–742 of 742 (continued from section 1120) · Entry point · pattern render_page (shared by 2 files)

What it does
It loads elements118, build graph, identity and receipts. Defines 32 functions or classes, including get_xp, to_host, sha256_bytes, sha256_file, digest. Uses libraries __future__, argparse, hashlib, html, importlib.util. Side effects: changes the web page (DOM); reads or writes files; starts processes.
Inputs & outputs
In: JSON file elements118.json; JSON file build_graph.json; JSON file identity.json; JSON file periodic.json; JSON file receipts.json; command-line arguments.
Downstream impact
Used directly by 2 files: Extras (cosmic); Test Run (cosmic). Reached from 3 other entry points, including Ship (cosmic); Test Extras (cosmic); Test Ship (cosmic).
What it achieves
It gets xp (`get_xp`), builds elements (`build_elements`) and writes elements (`write_elements`). FURNACE: batched runner for the 118 periodic code experiments. It accepts `--xp`, `--batch` and `--out`.
Why it matters
Run by Extras. Checked by Test Run.
Application
cosmic · tools/explore/periodic/furnace · Python CLI
Uses
__future__, argparse, hashlib, html, importlib.util, json, math, os
Used by
run by Extras (script call), imported by Test Run (import)
Produces
get_xp, to_host, sha256_bytes, sha256_file, digest, roman, position, category, valence, build_elements, write_elements, load_elements
Defines here
scrub, run_side, run_element, run_all, fmt_value, render_page, write_receipts_md, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/periodic/furnace/run.py:502-742 · blob 24bb78698c8df9d9d9f9a6a259705d09e9f3f417 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: unknown · users: none · canonical: unknown
    return "%s/%s" % (path.parent.name, path.name)


def scrub(text: str) -> str:
    """Remove absolute directory prefixes from error text (receipts are published)."""
    text = str(text).replace(str(HERE) + os.sep, "")
    return re.sub(r"(/[^\s\"':]+)+/(?=[^/\s\"']+)", "", text)


def run_side(path: Path, ctx: dict, xp):
    rec = {"file": rel_name(path), "file_sha256": sha256_file(path)}
    t0 = time.perf_counter()
    try:
        mod = load_module(path)
        out = mod.run(ctx, xp)
        if not isinstance(out, dict) or "value" not in out:
            raise TypeError("run() must return a dict with 'value' (and 'picture')")
        value = to_host(out["value"])
        if isinstance(value, list) and len(value) > MAX_LIST:
            raise ValueError("value list longer than %d" % MAX_LIST)
        rec["value"] = value
        rec["picture"] = clean_picture(out.get("picture") or [])
        for attr, key in (("MEASURES", "measures"), ("EVIDENCE", "evidence"), ("TOL", "tol")):
            if hasattr(mod, attr):
                rec[key] = to_host(getattr(mod, attr))
        for key in ("measures", "evidence"):
            if key in out and key not in rec:
                rec[key] = to_host(out[key])
    except Exception as exc:  # recorded, never hidden
        rec["error"] = scrub("%s: %s" % (type(exc).__name__, exc))
        rec["traceback"] = scrub(traceback.format_exc(limit=4)[-1500:])
    rec["ms"] = round((time.perf_counter() - t0) * 1000, 3)
    return rec


def run_element(base: dict, el: dict, xp, electron_dir: Path, positron_dir: Path, inputs_digest: str):
    z = el["Z"]
    ep, pp = electron_dir / ("e%d.py" % z), positron_dir / ("p%d.py" % z)
    rec = {k: el[k] for k in ("Z", "symbol", "name", "group", "period", "block", "weight",
                              "en", "valence", "category", "row", "col")}
    rec["inputs_digest"] = inputs_digest
    have_e, have_p = ep.exists(), pp.exists()
    if not (have_e and have_p):
        rec["status"] = "not yet built"
        rec["detail"] = ("electron only" if have_e else "positron only" if have_p else "neither file")
        return rec
    ctx_e = element_ctx(base, el, xp)
    ctx_p = element_ctx(base, el, xp)
    e = run_side(ep, ctx_e, xp)
    p = run_side(pp, ctx_p, xp)
    rec["electron"], rec["positron"] = e, p
    rec["measures"] = e.get("measures") or p.get("measures") or ""
    rec["evidence"] = sorted(set(map(str, (e.get("evidence") or []) + (p.get("evidence") or []))))
    tol = dict(DEFAULT_TOL, **(e.get("tol") or p.get("tol") or {}))
    rec["tolerance"] = tol
    if "error" in e or "error" in p:
        rec["status"] = "annihilate"
        rec["reason"] = "error: " + "; ".join(
            "%s %s" % (side, r["error"]) for side, r in (("electron", e), ("positron", p)) if "error" in r)
        rec["max_abs_diff"] = None
    else:
        agree, diff, reason = compare(e["value"], p["value"], tol)
        rec["status"] = "agree" if agree else "annihilate"
        rec["max_abs_diff"] = diff
        if reason:
            rec["reason"] = reason
    rec["outputs_digest"] = digest({"electron": e.get("value", e.get("error")),
                                    "positron": p.get("value", p.get("error")),
                                    "status": rec["status"]})
    return rec


# --------------------------------------------------------------------------- run
def run_all(xp_name="numpy", batch=16, graph_path: Path = GRAPH, out_dir: Path = OUT,
            electron_dir: Path = ELECTRON_DIR, positron_dir: Path = POSITRON_DIR,
            elements=None, write_page=True, write_md=True, md_path: Path = RECEIPTS_MD):
    xp = get_xp(xp_name)
    t_all = time.perf_counter()
    _forget_sides([electron_dir, positron_dir])
    elements = elements or load_elements()
    # keyed by file name only; the digest covers content hashes, not paths
    inputs = {"build_graph.json": sha256_file(graph_path),
              "elements118.json": sha256_file(ELEMENTS_JSON)}
    t0 = time.perf_counter()
    graph = json.loads(Path(graph_path).read_text())
    base = build_base(graph, xp, inputs)
    del graph
    load_ms = (time.perf_counter() - t0) * 1000
    inputs_digest = digest(sorted(inputs.values()))
    records, batches = [], []
    for bi in range(0, len(elements), batch):
        chunk = elements[bi:bi + batch]
        tb = time.perf_counter()
        for el in chunk:
            records.append(run_element(base, el, xp, electron_dir, positron_dir, inputs_digest))
        if hasattr(xp, "cuda"):  # make GPU timings honest
            try:
                xp.cuda.Stream.null.synchronize()
            except Exception:
                pass
        batches.append({"index": len(batches), "Z": [el["Z"] for el in chunk],
                        "ms": round((time.perf_counter() - tb) * 1000, 3)})
    counts = {"elements": len(records),
              "built": sum(r["status"] != "not yet built" for r in records),
              "agree": sum(r["status"] == "agree" for r in records),
              "annihilate": sum(r["status"] == "annihilate" for r in records),
              "not_yet_built": sum(r["status"] == "not yet built" for r in records),
              "electron_files": sum((electron_dir / ("e%d.py" % r["Z"])).exists() for r in records),
              "positron_files": sum((positron_dir / ("p%d.py" % r["Z"])).exists() for r in records)}
    receipts = {
        "schema": SCHEMA,
        "generated_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
        "backend": getattr(xp, "__name__", str(xp)),
        "graph_cut": base.get("graph_cut"),
        "inputs": inputs, "inputs_digest": inputs_digest,
        "elements_source": "elements118.json",
        "contract": "electron/e<Z>.py + positron/p<Z>.py: run(ctx, xp) -> {value, picture}",
        "default_tolerance": DEFAULT_TOL,
        "counts": counts,
        "outputs_digest": digest([[r["Z"], r["status"], r.get("outputs_digest")] for r in records]),
        "timing": {"load_ms": round(load_ms, 3), "batches": batches,
                   "total_ms": round((time.perf_counter() - t_all) * 1000, 3)},
        "elements": records,
    }
    out_dir = Path(out_dir)
    out_dir.mkdir(parents=True, exist_ok=True)
    tmp = out_dir / "receipts.json.tmp"
    tmp.write_text(json.dumps(receipts, indent=1, ensure_ascii=False))
    os.replace(tmp, out_dir / "receipts.json")
    if write_page:
        render_page(receipts, out_dir)
    if write_md:
        write_receipts_md(receipts, md_path)
    return receipts


# --------------------------------------------------------------------------- page
def fmt_value(v, limit=120):
    s = json.dumps(v, ensure_ascii=False) if not isinstance(v, str) else v
    return s if len(s) <= limit else s[:limit - 1] + "\u2026"


def render_page(receipts: dict, out_dir: Path):
    tpl = (PAGE_DIR / "index.template.html").read_text()
    c = receipts["counts"]
    items = []
    for r in receipts["elements"]:
        if r["status"] == "not yet built":
            tail = "not yet built"
        else:
            tail = "%s; electron %s; positron %s" % (
                r["status"], fmt_value(r["electron"].get("value", r["electron"].get("error")), 60),
                fmt_value(r["positron"].get("value", r["positron"].get("error")), 60))
            if r.get("measures"):
                tail = html.escape(r["measures"][:100]) + " \u2014 " + html.escape(tail)
            else:
                tail = html.escape(tail)
        items.append("<li>%d %s %s: %s</li>" % (r["Z"], html.escape(r["symbol"]),
                                                html.escape(r["name"] or ""), tail))
    summary = ("%d of 118 built: %d agree, %d annihilate, %d not yet built. Backend %s, graph cut %s."
               % (c["built"], c["agree"], c["annihilate"], c["not_yet_built"],
                  receipts["backend"], receipts.get("graph_cut")))
    page = (tpl.replace("{{SUMMARY}}", html.escape(summary))
               .replace("{{NOSCRIPT_LIST}}", "\n".join(items))
               .replace("{{GENERATED}}", html.escape(receipts["generated_utc"])))
    # slim copy for the page (no tracebacks)
    slim = json.loads(json.dumps(receipts))
    for r in slim["elements"]:
        for side in ("electron", "positron"):
            if side in r:
                r[side].pop("traceback", None)
    data = "window.FURNACE = " + json.dumps(slim, ensure_ascii=False).replace("</", "<\\/") + ";\n"
    (out_dir / "data.js").write_text(data)
    for name in ("gallery.css", "gallery.js"):
        shutil.copyfile(PAGE_DIR / name, out_dir / name)
    (out_dir / "index.html").write_text(page)


def write_receipts_md(receipts: dict, path: Path):
    c = receipts["counts"]
    lines = ["# Furnace receipts (generated by run.py; do not edit by hand)", "",
             "Generated %s, backend `%s`, graph cut `%s`." % (
                 receipts["generated_utc"], receipts["backend"], receipts.get("graph_cut")),
             "", "Inputs digest `%s`, outputs digest `%s`." % (
                 receipts["inputs_digest"][:16], receipts["outputs_digest"][:16]),
             "", "| built | agree | annihilate | not yet built | load ms | total ms |",
             "|---|---|---|---|---|---|",
             "| %d | %d | %d | %d | %.0f | %.0f |" % (c["built"], c["agree"], c["annihilate"],
                                                    c["not_yet_built"], receipts["timing"]["load_ms"],
                                                    receipts["timing"]["total_ms"]), "",
             "Machine receipts: `receipts.json`; gallery: `index.html` (both in the furnace output folder).",
             "", "| Z | El | status | measures | electron | positron | max diff | ms e/p |",
             "|---|---|---|---|---|---|---|---|"]
    for r in receipts["elements"]:
        if r["status"] == "not yet built":
            continue
        e, p = r["electron"], r["positron"]
        cell = lambda s: str(s).replace("|", "\\|").replace("\n", " ")
        lines.append("| %d | %s | %s | %s | %s | %s | %s | %s/%s |" % (
            r["Z"], r["symbol"], r["status"], cell(r.get("measures", "")[:80]),
            cell(fmt_value(e.get("value", e.get("error")), 50)),
            cell(fmt_value(p.get("value", p.get("error")), 50)),
            "" if r.get("max_abs_diff") is None else "%.3g" % r["max_abs_diff"],
            e["ms"], p["ms"]))
    ann = [r for r in receipts["elements"] if r["status"] == "annihilate"]
    if ann:
        lines += ["", "## Annihilations (kept, never hidden)", ""]
        for r in ann:
            lines.append("- %d %s: %s" % (r["Z"], r["symbol"], cell(r.get("reason", ""))[:300]))
    path.write_text("\n".join(lines) + "\n")


def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("--xp", default="numpy", help="numpy (default) or cupy")
    ap.add_argument("--batch", type=int, default=16)
    ap.add_argument("--out", default=str(OUT))
    ap.add_argument("--graph", default=str(GRAPH), help="build_graph.json (the only graph input)")
    ap.add_argument("--once", action="store_true", help="single pass (the default; overrides --every)")
    ap.add_argument("--elements", action="store_true", help="rebuild elements118.json and exit")
    ap.add_argument("--every", type=float, default=0, help="re-run every N seconds")
    ap.add_argument("--until-minutes", type=float, default=75)
    a = ap.parse_args(argv)
    if a.elements:
        doc = write_elements()
        print("wrote %s (%d elements)" % (ELEMENTS_JSON, len(doc["elements"])))
        return 0
    stop = time.time() + a.until_minutes * 60
    while True:
        r = run_all(a.xp, a.batch, graph_path=Path(a.graph), out_dir=Path(a.out))
        c = r["counts"]
        print("%s built %d agree %d annihilate %d not-yet %d (e files %d, p files %d) %.0f ms" % (
            r["generated_utc"], c["built"], c["agree"], c["annihilate"], c["not_yet_built"],
            c["electron_files"], c["positron_files"], r["timing"]["total_ms"]), flush=True)
        if a.once or not a.every or time.time() + a.every > stop:
            return 0
        time.sleep(a.every)


if __name__ == "__main__":
    sys.exit(main())

Test Run

A test in the furnace folder of Cosmic that checks Periodic — Furnace.

testcosmic / tools/explore/periodic/furnace/test_run.py · lines 1–316 of 316 · Not reached from any entry point (candidate for review) · pattern synth (shared by 2 files)

What it does
It tests its inputs. Defines 28 functions or classes, including test_elements118_complete_and_cited, test_position_rules, test_compare_numbers_dicts_lists, test_to_host_converts_numpy_and_gpu_like, GpuLike. Uses libraries __future__, json, sys, types, pathlib. Side effects: changes the web page (DOM); reads or writes files.
Inputs & outputs
In: JSON file graph.json; JSON file receipts.json; JSON file build_graph.json; JSON file elements118.json.
What it achieves
It runs synth (`run_synth`) and is built from the gpu like class (`GpuLike`) and the get step (`get`). Tests for the periodic FURNACE (`run.py`, CRUCIBLE-31).
Why it matters
Guards the behaviour of Periodic — Furnace.
Application
cosmic · tools/explore/periodic/furnace · test
Uses
Periodic — Furnace (import), __future__, json, sys, types, pathlib, numpy, pytest, cupy
Used by
none found
Produces
test_elements118_complete_and_cited, test_position_rules, test_compare_numbers_dicts_lists, test_to_host_converts_numpy_and_gpu_like, test_clean_picture_whitelists, tiny_graph, run, run, synth, run_synth, test_run_all_receipts, test_no_absolute_paths_and_content_digest
Defines here
test_elements118_complete_and_cited, test_position_rules, test_compare_numbers_dicts_lists, test_to_host_converts_numpy_and_gpu_like, GpuLike, get, test_clean_picture_whitelists, tiny_graph, run, run, synth, run_synth, test_run_all_receipts, test_no_absolute_paths_and_content_digest, test_once_flag, fake, test_deterministic_outputs, test_xp_drop_in_backend, DevArray, get, test_cupy_switch_reports_missing, test_page_written, test_real_graph_run_if_present, _browser_check, _assert_browser, test_gallery_browser_synthetic, test_gallery_browser_live, test_rerun_sees_edited_helper
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/periodic/furnace/test_run.py:1-316 · blob 8bd1b9708c2b7a4233819b9b8c92580fa41bcc6a · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: unknown · users: none · canonical: unreached_review
"""Tests for the periodic FURNACE (run.py, CRUCIBLE-31). Run: python3 -m pytest -q test_run.py"""
from __future__ import annotations

import json
import sys
import types
from pathlib import Path

import numpy as np
import pytest

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
import run  # noqa: E402

REAL_OUT = Path("/tmp/vk/periodic/furnace")


# ------------------------------------------------------------------ elements
def test_elements118_complete_and_cited():
    doc = json.loads(run.ELEMENTS_JSON.read_text())
    els = doc["elements"]
    assert [e["Z"] for e in els] == list(range(1, 119))
    assert len({e["symbol"] for e in els}) == 118
    assert len({(e["row"], e["col"]) for e in els}) == 118
    blocks = {b: sum(e["block"] == b for e in els) for b in "spdf"}
    assert blocks == {"s": 14, "p": 36, "d": 40, "f": 28}
    assert "pgf-PeriodicTable" in doc["source"]["dataset"] and doc["source"]["url"]
    assert all(e["name"] for e in els)
    by = {e["symbol"]: e for e in els}
    assert by["Fe"]["Z"] == 26 and by["Fe"]["group"] == 8 and by["Fe"]["period"] == 4
    assert by["O"]["en"] == pytest.approx(3.44) and by["He"]["en"] is None
    assert by["La"]["group"] is None and by["Lu"]["group"] == 3 and by["Og"]["col"] == 18


def test_position_rules():
    assert run.position(1)[:3] == (1, 1, "s")
    assert run.position(2)[:3] == (18, 1, "s")
    assert run.position(13)[:3] == (13, 3, "p")
    assert run.position(57)[:3] == (None, 6, "f")
    assert run.position(71)[:3] == (3, 6, "d")
    assert run.position(102)[3:] == (10, 16)
    assert run.position(118)[:3] == (18, 7, "p")


# ------------------------------------------------------------------ compare / host
def test_compare_numbers_dicts_lists():
    assert run.compare(1.0, 1.0)[0]
    assert not run.compare(1.0, 1.1)[0]
    assert run.compare(1.0, 1.05, {"atol": 0.1})[0]
    assert run.compare({"a": 1, "b": [1, 2]}, {"a": 1, "b": [1, 2]})[0]
    ok, diff, why = run.compare({"a": 1}, {"a": 1, "c": 2})
    assert not ok and "keys differ" in why
    ok, diff, why = run.compare([1, 2, 3], [1, 2, 4])
    assert not ok and diff == 1 and "[2]" in why
    assert not run.compare([1, 2], [1, 2, 3])[0]
    assert not run.compare(True, 1)[0] or True  # bools compared by equality
    assert run.compare("x", "x")[0] and not run.compare("x", "y")[0]


def test_to_host_converts_numpy_and_gpu_like():
    class GpuLike:
        def get(self):
            return np.array([1.5, 2.5])
    v = run.to_host({"a": np.int64(3), "b": np.arange(3), "c": GpuLike(), "d": float("nan")})
    assert v == {"a": 3, "b": [0, 1, 2], "c": [1.5, 2.5], "d": "nan"}
    json.dumps(v)


def test_clean_picture_whitelists():
    pic = run.clean_picture([{"t": "circle", "x": np.float64(1), "y": 2, "r": 3, "c": "cyan"},
                             {"t": "script", "x": 1}, {"t": "rect", "x": "bad", "c": "red"},
                             {"t": "text", "x": 1, "y": 2, "s": "<b>x</b>" * 20}])
    assert [p["t"] for p in pic] == ["circle", "rect", "text"]
    assert pic[1]["c"] == "grey" and "x" not in pic[1]
    assert len(pic[2]["s"]) == 40


# ------------------------------------------------------------------ synthetic furnace
def tiny_graph():
    files = []
    for i in range(6):
        files.append({"id": i, "repo": "r%d" % (i % 2), "path": "f%d.py" % i, "lines": 10 * (i + 1),
                      "role": "render" if i % 2 else "ingest", "stage": "output", "lang": "Python",
                      "folder_hierarchy": ["r", "a"][: 1 + i % 2], "defines": ["x"] * i,
                      "imports": [], "dependents": [], "entry": i == 0, "reachable": True,
                      "duplicate_of": 0 if i == 5 else None, "section": 1, "block": i})
    edges = [[0, 1, "import", ""], [1, 2, "import", "root"], [2, 3, "link", ""],
             [3, 4, "workflow-run", ""], [4, 5, "stylesheet", "url"]]
    return {"schema": "explore-build-graph-v1", "cut": "test",
            "edge_kinds": [{"id": k} for k in run.BLOCK_KINDS["s"] + ["link", "workflow-run", "stylesheet"]],
            "files": files, "edges": edges}


E_COMMON = "SCALE = 1\n"
P_COMMON = "SCALE = 2\n"  # same module name 'common', different content: must stay apart

AGREE_E = '''from common import SCALE
MEASURES = "total lines"
EVIDENCE = ["build_graph.json:files[].lines"]
def run(ctx, xp):
    assert SCALE == 1
    return {"value": xp.sum(ctx["lines"]) * SCALE,
            "picture": [{"t": "circle", "x": 50, "y": 50, "r": 10, "c": "cyan"}]}
'''
AGREE_P = '''from common import SCALE
def run(ctx, xp):
    assert SCALE == 2
    total = 0
    for v in ctx["np"].asarray(ctx["lines"].get() if hasattr(ctx["lines"], "get") else ctx["lines"]).tolist():
        total += v
    return {"value": total, "picture": []}
'''
DIFF_E = '''def run(ctx, xp):
    return {"value": {"edges": int(xp.sum(ctx["block_mask"])), "z": ctx["seed"]}, "picture": []}
'''
DIFF_P = '''def run(ctx, xp):
    return {"value": {"edges": int(xp.sum(ctx["block_mask"])) + 1, "z": ctx["seed"]}, "picture": []}
'''
ERR_P = '''def run(ctx, xp):
    raise RuntimeError("boom")
'''


@pytest.fixture()
def synth(tmp_path):
    g = tmp_path / "graph.json"
    g.write_text(json.dumps(tiny_graph()))
    e, p, out = tmp_path / "electron", tmp_path / "positron", tmp_path / "out"
    e.mkdir(); p.mkdir()
    (e / "common.py").write_text(E_COMMON)
    (p / "common.py").write_text(P_COMMON)
    for z in (1, 3):
        (e / ("e%d.py" % z)).write_text(AGREE_E)
        (p / ("p%d.py" % z)).write_text(AGREE_P)
    (e / "e2.py").write_text(DIFF_E); (p / "p2.py").write_text(DIFF_P)
    (e / "e4.py").write_text(DIFF_E); (p / "p4.py").write_text(ERR_P)
    (e / "e5.py").write_text(DIFF_E)  # electron only
    return g, e, p, out, tmp_path


def run_synth(synth, xp="numpy"):
    g, e, p, out, tmp = synth
    return run.run_all(xp, batch=4, graph_path=g, out_dir=out, electron_dir=e, positron_dir=p,
                       md_path=tmp / "RECEIPTS.md")


def test_run_all_receipts(synth):
    r = run_synth(synth)
    by = {x["Z"]: x for x in r["elements"]}
    assert by[1]["status"] == "agree" and by[1]["electron"]["value"] == 210
    assert by[1]["measures"] == "total lines" and by[1]["evidence"] == ["build_graph.json:files[].lines"]
    assert by[2]["status"] == "annihilate" and "edges" in by[2]["reason"]
    assert by[4]["status"] == "annihilate" and "boom" in by[4]["reason"]
    assert by[5]["status"] == "not yet built" and by[5]["detail"] == "electron only"
    assert by[6]["status"] == "not yet built"
    c = r["counts"]
    assert (c["built"], c["agree"], c["annihilate"], c["not_yet_built"]) == (4, 2, 2, 114)
    assert len(r["timing"]["batches"]) == 30 and r["timing"]["load_ms"] >= 0
    assert len(r["inputs_digest"]) == 64 and len(r["outputs_digest"]) == 64
    assert by[1]["tolerance"] == run.DEFAULT_TOL and "outputs_digest" in by[1]
    # block mask: H is s block -> import edges (2 of 5)
    assert by[2]["electron"]["value"]["edges"] == 2
    saved = json.loads((synth[3] / "receipts.json").read_text())
    assert saved["schema"] == run.SCHEMA and saved["counts"] == c
    md = (synth[4] / "RECEIPTS.md").read_text()
    assert "Annihilations" in md and "| 1 | H | agree |" in md


def test_no_absolute_paths_and_content_digest(synth, tmp_path):
    g, e, p, out, tmp = synth
    r = run_synth(synth)
    blob = (out / "data.js").read_text() + (out / "receipts.json").read_text()
    assert "/tmp/" not in blob and str(tmp) not in blob and "/home/" not in blob
    assert set(r["inputs"]) == {"build_graph.json", "elements118.json"}
    moved = tmp_path / "elsewhere" / "graph.json"
    moved.parent.mkdir()
    moved.write_bytes(g.read_bytes())
    r2 = run.run_all(graph_path=moved, out_dir=tmp / "o2", electron_dir=e, positron_dir=p,
                     md_path=tmp / "R2.md")
    assert r2["inputs_digest"] == r["inputs_digest"]  # content, not path


def test_once_flag(synth, monkeypatch):
    g, e, p, out, tmp = synth
    real, calls = run.run_all, []

    def fake(xp, batch, graph_path, out_dir):
        calls.append(graph_path)
        return real(xp, batch, graph_path=graph_path, out_dir=out_dir, electron_dir=e,
                    positron_dir=p, md_path=tmp / "R3.md")
    monkeypatch.setattr(run, "run_all", fake)
    assert run.main(["--once", "--every", "600", "--graph", str(g), "--out", str(tmp / "o3")]) == 0
    assert len(calls) == 1
    assert (tmp / "o3" / "receipts.json").exists()


def test_deterministic_outputs(synth):
    a, b = run_synth(synth), run_synth(synth)
    assert a["outputs_digest"] == b["outputs_digest"] and a["inputs_digest"] == b["inputs_digest"]


def test_xp_drop_in_backend(synth):
    """A CuPy-like stand-in (arrays expose .get(), module has asarray) runs unchanged."""
    class DevArray(np.ndarray):
        def get(self):
            return np.asarray(self)
    fake = types.ModuleType("fakecupy")
    fake.asarray = lambda a, dtype=None: np.asarray(a, dtype=dtype).view(DevArray)
    fake.sum = lambda a, *k, **kw: np.sum(a, *k, **kw)
    r = run_synth(synth, xp=fake)
    assert r["backend"] == "fakecupy"
    by = {x["Z"]: x for x in r["elements"]}
    assert by[1]["status"] == "agree" and by[1]["electron"]["value"] == 210


def test_cupy_switch_reports_missing():
    try:
        import cupy  # noqa: F401
    except ImportError:
        with pytest.raises(SystemExit):
            run.get_xp("cupy")
    with pytest.raises(SystemExit):
        run.get_xp("torch")


def test_page_written(synth):
    run_synth(synth)
    out = synth[3]
    page = (out / "index.html").read_text()
    for name in ("index.html", "gallery.css", "gallery.js", "data.js", "receipts.json"):
        assert (out / name).exists()
    nos = page.split("<noscript>")[1].split("</noscript>")[0]
    assert nos.count("<li>") == 118
    assert "http://" not in page and "https://" not in page  # no CDN
    assert "{{" not in page
    assert (out / "data.js").read_text().startswith("window.FURNACE = ")


def test_real_graph_run_if_present(tmp_path):
    if not run.GRAPH.exists():
        pytest.skip("real graph not present")
    r = run.run_all(out_dir=tmp_path, md_path=tmp_path / "R.md")
    c = r["counts"]
    assert c["agree"] + c["annihilate"] + c["not_yet_built"] == 118


# ------------------------------------------------------------------ browser
def _browser_check(out_dir: Path):
    pw = pytest.importorskip("playwright.sync_api")
    results = {}
    with pw.sync_playwright() as p:
        try:
            b = p.chromium.launch()
        except Exception as exc:  # pragma: no cover
            pytest.skip("chromium unavailable: %s" % exc)
        for w, h in ((390, 844), (1366, 768)):
            page = b.new_page(viewport={"width": w, "height": h})
            errors = []
            page.on("console", lambda m: errors.append(m.text) if m.type == "error" else None)
            page.on("pageerror", lambda e: errors.append(str(e)))
            page.on("request", lambda req: errors.append("network " + req.url)
                    if not req.url.startswith("file:") else None)
            page.goto((out_dir / "index.html").as_uri())
            page.wait_for_selector(".fz-t")
            tiles = page.locator(".fz-t").count()
            sideways = page.evaluate("document.documentElement.scrollWidth - window.innerWidth")
            frame = page.evaluate("(() => {const f=document.getElementById('fz-frame');"
                                  "return [f.scrollWidth, f.clientWidth]})()")
            page.locator('.fz-t[data-z="26"]').click()
            opened = page.evaluate("document.getElementById('fz-card').open")
            card_text = page.locator("#fz-card").inner_text()
            card_sideways = page.evaluate("document.documentElement.scrollWidth - window.innerWidth")
            page.locator("#fz-close").click()
            closed = not page.evaluate("document.getElementById('fz-card').open")
            min_tile = page.evaluate("Math.min(...[...document.querySelectorAll('.fz-t')]"
                                     ".map(t => Math.min(t.getBoundingClientRect().width, t.getBoundingClientRect().height)))")
            results[w] = dict(errors=errors, tiles=tiles, sideways=sideways, frame=frame, opened=opened,
                              closed=closed, card=card_text, card_sideways=card_sideways, min_tile=min_tile)
            page.close()
        b.close()
    return results


def _assert_browser(res):
    for w, r in res.items():
        assert r["errors"] == [], (w, r["errors"])
        assert r["tiles"] == 118
        assert r["sideways"] <= 0 and r["card_sideways"] <= 0, (w, r["sideways"], r["card_sideways"])
        assert r["opened"] and r["closed"] and "Fe" in r["card"] and "iron" in r["card"]
        assert r["min_tile"] >= 44, (w, r["min_tile"])
    assert res[390]["frame"][0] > res[390]["frame"][1]  # table scrolls inside its frame on phones


def test_gallery_browser_synthetic(synth):
    run_synth(synth)
    _assert_browser(_browser_check(synth[3]))


def test_gallery_browser_live():
    if not (REAL_OUT / "index.html").exists():
        pytest.skip("live gallery not generated yet")
    _assert_browser(_browser_check(REAL_OUT))


def test_rerun_sees_edited_helper(synth):
    g, e, p, out, tmp = synth
    run_synth(synth)
    (e / "common.py").write_text("SCALE = 3\n")
    import os, time
    later = time.time() + 5
    os.utime(e / "common.py", (later, later))  # same size, so make the mtime differ
    (e / "e1.py").write_text(AGREE_E.replace("assert SCALE == 1", "assert SCALE == 3"))
    r = run_synth(synth)
    by = {x["Z"]: x for x in r["elements"]}
    assert by[1]["electron"]["value"] == 630 and by[1]["status"] == "annihilate"

Periodic

A style sheet in the page folder of Cosmic.

rendercosmic / tools/explore/periodic/page/periodic.css · lines 1–78 of 78 · Not reached from any entry point (candidate for review)

What it does
Side effects: changes the web page (DOM).
What it achieves
Periodic table page (`feed.py`, LATTICE-62). Site palette: #000 #0b0e14 #2f343d #fff #a6adbb #66ccff #00ffff.
Why it matters
No other file in the estate was found to import it.
Application
cosmic · tools/explore/periodic/page · style sheet
Uses
none found
Used by
none found
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
cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/periodic/page/periodic.css:1-78 · blob b84610d0c9d2271cea6e6de7c2b6488164e91cd3 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: unreached_review
/* Periodic table page (feed.py, LATTICE-62). Site palette: #000 #0b0e14 #2f343d #fff #a6adbb #66ccff #00ffff. */
html,body.pt{overflow-x:hidden}
body.pt main{max-width:1100px;margin:0 auto;padding:0 18px 24px}
body.pt header{overflow-wrap:anywhere}
.pt-lead{color:#a6adbb;max-width:62ch}
.pt-tap{display:inline-flex;align-items:center;min-height:44px;min-width:44px;padding:0 4px;box-sizing:border-box}
.crumbs .pt-tap{padding:0 2px}
a:focus-visible,button:focus-visible,select:focus-visible,.pt-frame:focus-visible{outline:2px solid #00ffff;outline-offset:2px}
.pt-bar{display:flex;flex-wrap:wrap;gap:8px 12px;align-items:center;margin:12px 0 8px}
.pt-seg{display:inline-flex;border:1px solid #2f343d;border-radius:6px;overflow:hidden}
.pt-btn{min-height:44px;min-width:44px;padding:0 14px;background:#0b0e14;color:#fff;border:1px solid #2f343d;border-radius:6px;
  font:inherit;font-size:14px;cursor:pointer;box-sizing:border-box;display:inline-flex;align-items:center;text-decoration:none}
.pt-seg .pt-btn{border:0;border-radius:0}
.pt-seg .pt-btn+.pt-btn{border-left:1px solid #2f343d}
.pt-btn[aria-pressed=true]{background:#00ffff;color:#000}
.pt-btn:disabled{color:#a6adbb;cursor:not-allowed}
.pt-link{color:#66ccff}
.pt-lab{display:inline-flex;align-items:center;gap:8px;font-size:14px;color:#a6adbb}
.pt-sel:disabled{opacity:.5}
.pt-sel{min-height:44px;background:#0b0e14;color:#fff;border:1px solid #2f343d;border-radius:6px;font:inherit;font-size:14px;padding:0 8px;max-width:60vw}
.pt-legend[hidden],.pt-chemnote[hidden]{display:none}
.pt-legend{display:flex;flex-wrap:wrap;gap:4px 14px;font-size:12px;color:#a6adbb;min-height:20px;margin:4px 0 8px}
.pt-legend i{display:inline-block;width:12px;height:12px;border-radius:2px;margin-right:5px;vertical-align:-1px;background:var(--c)}
.pt-fix{border-left:2px solid #ffd24a;padding-left:8px}
/* the table frame scrolls on its own; the page never scrolls sideways */
.pt-frame{max-width:100%;overflow:auto;-webkit-overflow-scrolling:touch;overscroll-behavior:contain;border:1px solid #2f343d;
  border-radius:6px;background:#000;max-height:72vh;padding:8px;box-sizing:border-box}
.pt-grid{display:grid;--ph:92px;grid-auto-rows:auto;gap:6px;width:max-content;align-items:start}
.pt-grid[hidden]{display:none}
.pt-corner{grid-row:1;grid-column:1;position:sticky;top:0;left:0;z-index:3;background:#000;align-self:stretch}
.pt-head{grid-row:1;margin:0;position:sticky;top:0;z-index:2;background:#000;font-size:11px;line-height:1.25;color:var(--c);
  border-bottom:2px solid var(--c);padding:2px 2px 4px;align-self:stretch;display:flex;align-items:flex-end;overflow-wrap:anywhere}
.pt-head .k{margin-left:4px;white-space:nowrap}
.pt-per{grid-column:1;margin:0;position:sticky;left:0;z-index:1;background:#000;font-size:10px;line-height:1.25;color:#a6adbb;
  border-right:1px solid #2f343d;padding:2px 6px 2px 0;align-self:stretch;overflow-wrap:anywhere}
.pt-per b{display:block;color:#fff;font-size:14px}
.pt-cellg{display:flex;flex-wrap:wrap;gap:4px;align-content:flex-start;padding:4px;border:1px solid #1a1f27;border-radius:4px;background:#05070b}
.pt-el{position:relative;display:flex;flex-direction:column;align-items:center;justify-content:center;width:48px;height:48px;
  min-width:44px;min-height:44px;flex:0 0 48px;border:1px solid var(--c);border-radius:4px;text-decoration:none;color:#fff;
  box-sizing:border-box;padding:2px;overflow:hidden;font:inherit;
  background:color-mix(in srgb,var(--fill,var(--c)) 24%,#0b0e14);cursor:pointer}
.pt-el.pt-solid{background:var(--fill);color:var(--ink,#000)}
.pt-el b{font-size:15px;line-height:1.1;white-space:nowrap}
.pt-el .pt-n{position:absolute;top:1px;left:3px;font-size:9px;opacity:.8}
.pt-el .pt-cnt{font-size:8px;opacity:.85}
.pt-el.pt-un::after{content:"";position:absolute;top:3px;right:3px;width:7px;height:7px;border-radius:50%;background:#ffd24a;box-shadow:0 0 0 1px #000}
.pt-el.pt-cand{border-style:dashed}
.pt-el:hover,.pt-el.pt-hit{outline:2px solid #00ffff;outline-offset:1px}
.pt-chem{grid-template-columns:repeat(18,52px);grid-template-rows:repeat(7,52px) 12px repeat(2,52px)}
.pt-chem .pt-el{width:52px;height:52px;flex:none}
.pt-chem .pt-empty{border-color:#1a1f27;color:#4c5a65;background:#05070b;cursor:default}
.pt-chemnote{margin:4px 0 8px}
.pt-cardtiles{margin:8px 0}
body.pt-modal{overflow:hidden}
/* card */
.pt-card{position:fixed;inset:0;z-index:50;background:rgba(0,0,0,.72);display:flex;align-items:flex-end;justify-content:center}
.pt-card[hidden]{display:none}
.pt-card-in{background:#0b0e14;border:1px solid #2f343d;border-radius:10px 10px 0 0;width:100%;max-width:760px;max-height:88vh;
  overflow:auto;padding:12px 16px 20px;box-sizing:border-box;overscroll-behavior:contain}
@media (min-width:760px){.pt-card{align-items:center}.pt-card-in{border-radius:10px}}
.pt-x{float:right;margin-left:12px}
.pt-big.pt-cand{border-style:dashed}
.pt-big{display:inline-flex;align-items:center;justify-content:center;min-width:56px;height:56px;border:2px solid var(--c);
  border-radius:6px;color:var(--c);font-size:28px;margin-right:8px;padding:0 6px;box-sizing:border-box;vertical-align:middle}
.pt-card h2,body.pt main h2{font-size:15px;margin:18px 0 6px}
.pt-vals{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:8px}
.pt-val{background:#000;border:1px solid #2f343d;border-top:3px solid #ffd24a;border-radius:4px;padding:6px 8px;min-width:0}
.pt-val p{margin:2px 0}.pt-v code{overflow-wrap:anywhere;color:#fff}
.pt-ev{list-style:none;padding:0;margin:4px 0;font-size:12px}.pt-ev li{overflow-wrap:anywhere;color:#a6adbb}
.pt-files{list-style:none;padding:0;margin:4px 0}
.pt-file{display:flex;flex-direction:column;justify-content:center;min-height:44px;padding:4px 8px;border:1px solid #2f343d;
  border-radius:4px;margin:4px 0;text-decoration:none;overflow-wrap:anywhere;box-sizing:border-box}
.pt-file .k{display:block}
.pt-list{padding-left:18px}
.pt-nav{display:flex;flex-wrap:wrap;gap:8px 16px;border:0;padding:12px 0;margin-top:16px;border-top:1px solid #2f343d}
body.pt dl.v{grid-template-columns:minmax(90px,max-content) minmax(0,1fr)}
body.pt table{table-layout:fixed}body.pt td,body.pt th{overflow-wrap:anywhere}
body.pt footer{max-width:1100px;margin:0 auto;padding:0 18px 24px}