In this section
- Verdict Gate other · worlds- / src/verdict_gate.py lines 639–673
- Watch Breakpoint storage · worlds- / src/watch_breakpoint.py lines 1–267
- Watch Collapse ingest · worlds- / src/watch_collapse.py lines 1–379
Verdict Gate
A Python command-line tool in Worlds that marks specimens (`mark_specimens`). It is built from the tokens step (`tokens`), the polarity step (`polarity`) and the is limit helper (`is_limit`).
otherworlds- / src/verdict_gate.py · lines 639–673 of 673 (continued from section 2036) · Entry point · pattern self_test (shared by 2 files)
- What it does
- It lists and searches its content. Defines 26 functions or classes, including tokens, polarity, is_limit, is_pure, bearing_limit. Uses libraries argparse, ast, io, json, os. Side effects: reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage field_execution (path word 'gate'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work. Domain terms in the code: 1500V.
- Inputs & outputs
- In: JSON file verdict-gate.json; command-line arguments. Voltage levels named: 1500V.
- Downstream impact
- Used directly by 2 files: Weekly Gates Workflow (worlds-); All Gates (worlds-).
- What it achieves
- A GATE ON THIS REPOSITORY'S VERDICTS - not on IEEE arithmetic. It accepts `--run`, `--ci` and `--self-test`.
- Why it matters
- Run by Weekly Gates Workflow and All Gates.
- Application
- worlds- · src · Python CLI
- Uses
- argparse, ast, io, json, os, re, subprocess, sys
- Used by
- run by Weekly Gates Workflow (workflow run), run by All Gates (script call)
- Produces
- tokens, polarity, is_limit, is_pure, bearing_limit, widest_pure, Feed, feed, finding, module_constants, from_python, c_to_python
- 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
- worlds-@83817c34790800d4af5057629121d83d0d67a332 src/verdict_gate.py:639-673 · blob 9a9f339993f25f7e86aa2d5879a4e251620de65e · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: unknown
"defects": [{"file": f["file"], "line": f["line"], "name": f["name"],
"expr": f["expr"], "probes": f["probes"]} for f in bad],
"findings": findings,
"reading":
"Every verdict named here is fed a non-number. `over = v > LIMIT` "
"answers false, so the design is reported inside the limit - a "
"pass on a design that was never evaluated. `over = not "
"(v <= LIMIT)` answers true and the value is refused upstream. On "
"every real number the two agree exactly, so the fix changes no "
"real design.",
"not_claimed":
"This gate checks comparisons, not designs. It says nothing about "
"whether the limits are right, nothing about any physics, and "
"nothing about comparisons it left alone - those are absent from "
"the count, not clean.",
"anonymised": "No project, site, maker or model anywhere."}
p = os.path.join(ROOT, "night-results", "verdict-gate.json")
os.makedirs(os.path.dirname(p), exist_ok=True)
io.open(p, "w", encoding="utf-8", newline="\n").write(
json.dumps(out, indent=1) + "\n")
print("\n wrote night-results/verdict-gate.json")
if not st_ok:
print("\n GATE FAILS: it could not show itself failing AND passing.")
return 1
if a.ci and bad:
print("\n GATE FAILS: %d verdict%s in this repository accept%s a "
"non-number." % (len(bad), "" if len(bad) == 1 else "s",
"s" if len(bad) == 1 else ""))
return 1
return 0
if __name__ == "__main__":
sys.exit(main())Watch Breakpoint
A Python module in Worlds that works with biggest steps (`biggest_steps`). It is built from the diam step (`diam`), the agree step (`agree`) and the profile step (`profile`).
storageworlds- / src/watch_breakpoint.py · lines 1–267 of 267 · Not reached from any entry point (candidate for review) · pattern profile (shared by 6 files)
- What it does
- It loads data. Defines 6 functions or classes, including _diam_array, _diam_kernel, diam, agree, profile. Uses libraries json, os, cupy. Side effects: reads or writes files.
- Inputs & outputs
- Out: JSON file.
- What it achieves
- This repository is public and an absolute path names a machine and an account.
- Why it matters
- No other file in the estate was found to import it.
- Application
- worlds- · src · Python module
- Uses
- json, os, cupy
- Used by
- none found
- Produces
- diam, agree, profile, biggest_steps
- Defines here
- _diam_array, _diam_kernel, diam, agree, profile, biggest_steps
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- worlds-@83817c34790800d4af5057629121d83d0d67a332 src/watch_breakpoint.py:1-267 · blob d9f072801594d9e5d4586f7ff7dd450e3b250a1d · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: unknown · users: none · canonical: unreached_review
"""
PATHS ARE NOT WRITTEN DOWN HERE. This repository is public and an
absolute path names a machine and an account. Set GRID_DATA (and where
needed GRID_REPOS or CLAUDE_TRANSCRIPT) in the environment instead.
See src/paths.py for why.
watch_breakpoint.py -- the photon that did not return, turned into code.
WHAT THIS IS
Predicate K05-05 ("the 640/641 step: one CSS pixel changes which furniture the
layout stacks") was one of 18,231 cases that failed to annihilate when a fused
5.3-billion-case grid computed every predicate twice, once as written and once
with every comparison made STRICT. A predicate that survives strictness is a
predicate sitting exactly on a boundary. This file finds that boundary, on the
GPU, at 1 px resolution, and measures it.
THE MODEL (read from source, not invented)
shell ...\\i0094\\releases\\003100000000-kuiper-shell\\index.html
:125 @media (max-width:640px){ ... }
:529 const narrow = () => innerWidth <= 640;
:540 layout() narrow -> HUD pushed under the header; card lifted off the foot
:546 safeBox() x0=8, x1=innerWidth-8, y0=top+8, y1=max(top+24, bot-8)
:561 homeCamera() R = min(s.x1-s.x0, s.y1-s.y0)/2*0.80 ; z = R/sqrt(SPACE)
:328 gl_PointSize = clamp(u_zoom*0.34, 1.0, 9.0)
cartridge ...\\i0094\\cartridges\\009400000000-kuiper-programs.js
:581, :2819 innerWidth >= 500 && innerWidth < 700 -> 'micro' vs 'macro'
:1999, :2586 @media (max-width:700px)
So the shell restacks at 640 and the cartridge restacks at 700. 641..700 px is a
band 60 px wide in which the two files disagree about what kind of screen this is.
Derived clear height (this is exactly the K05-05 `maths` sentence):
wide (w > brk): H = max(16, h - hdr - foot - 16) HUD beside header, card floats
narrow (w <= brk): H = max(16, h - hdr - hud - foot - cardh - 26) HUD under header, card on the foot
fitted disc diameter on screen D = 0.80 * min(w - 16, H)
The dot is clamp(z*0.34, 1, 9) px across; the sunflower nearest-neighbour gap is
~1 wafer unit, i.e. z px on screen, so the "three dot radii" rule is z >= 1.5*dot,
which binds only while the 1 px floor is active, i.e. it fails exactly when z < 1.5.
ONE CuPy ElementwiseKernel and ONE CuPy array-expression path compute every
number independently. Nothing is reported unless the two agree exactly.
PASTE-READY EDITS THAT CLOSE THE BAND
(1) FILE ...\\i0094\\releases\\003100000000-kuiper-shell\\index.html LINE 529
FROM const narrow = () => innerWidth <= 640; // one number, used by the layout and by the test
TO const narrow = () => innerWidth <= 700; // one number, used by the layout and by the test
(2) FILE ...\\i0094\\releases\\003100000000-kuiper-shell\\index.html LINE 125
FROM @media (max-width:640px){
TO @media (max-width:700px){
(the CSS breakpoint must move with narrow(), or the strip restyle and the
camera's idea of the furniture part company and you have made a SECOND band)
The cartridge already uses 700 in all four places (:581, :1999, :2586, :2819), so
it needs no edit. After (1)+(2) both files agree on one number.
HONEST COST: this does NOT delete the step, it MOVES it from 640/641 to 700/701.
The step is not caused by the number; it is caused by the two layouts carrying
different furniture. Any single number leaves a 1 px cliff somewhere. And it is
not free: every width in 641..700 -- screens that are fine today -- switches to
the narrow branch and the fitted disc there SHRINKS by the measured ratio. The
numbers printed below say by how much, for how many, and how many of those newly
narrow cases fall under the three-radii rule.
WHAT THIS DOES NOT PROVE
It models a camera read from source. It renders nothing: no WebGL context, no
shader, no real getBoundingClientRect -- the furniture heights are swept, not
measured. It holds no real device, so it cannot tell you what any phone shows.
It is arithmetic about arithmetic, and it is only as true as the lines above.
"""
import json
import os
import cupy as cp
OUT = os.environ.get("GRID_REPOS", "")
W0, W1 = 600, 760 # the band under test, 1 px resolution
SH_BRK, CT_BRK = 640, 700 # shell narrow(), cartridge media query
H = cp.arange(320, 2161, 8, dtype=cp.int32)
HD = cp.arange(24, 121, 8, dtype=cp.int32) # header
HU = cp.arange(24, 161, 8, dtype=cp.int32) # hud
FT = cp.arange(24, 121, 8, dtype=cp.int32) # foot
CD = [int(v) for v in range(0, 261, 20)] # short card
SPACE = cp.asarray([1000, 4000, 16000, 65536, 262144, 1048576, 4000000],
dtype=cp.float64)
_SHAPE = (H.size, HD.size, HU.size, FT.size)
_h = cp.broadcast_to(H[:, None, None, None], _SHAPE).astype(cp.int32)
_hd = cp.broadcast_to(HD[None, :, None, None], _SHAPE).astype(cp.int32)
_hu = cp.broadcast_to(HU[None, None, :, None], _SHAPE).astype(cp.int32)
_ft = cp.broadcast_to(FT[None, None, None, :], _SHAPE).astype(cp.int32)
_kern = cp.ElementwiseKernel(
'int32 w, int32 h, int32 hd, int32 hu, int32 ft, int32 cd, int32 brk',
'float64 d',
'''
int HH;
if (w <= brk) { HH = h - hd - hu - ft - cd - 26; }
else { HH = h - hd - ft - 16; }
if (HH < 16) HH = 16;
int wa = w - 16;
int m = (wa < HH) ? wa : HH;
d = 0.80 * (double)m;
''', 'kuiper_diam')
def _diam_array(w, cd, brk):
"""Path A: pure CuPy array expressions."""
if w <= brk:
clear = cp.maximum(16, _h - _hd - _hu - _ft - cd - 26)
else:
clear = cp.maximum(16, _h - _hd - _ft - 16)
return 0.80 * cp.minimum(w - 16, clear).astype(cp.float64)
def _diam_kernel(w, cd, brk):
"""Path B: one CUDA kernel, branch inside the kernel."""
return _kern(cp.int32(w), _h, _hd, _hu, _ft, cp.int32(cd), cp.int32(brk))
def diam(w, cd, brk):
a = _diam_array(w, cd, brk)
b = _diam_kernel(w, cd, brk)
if not bool(cp.all(a == b)):
raise SystemExit("DISAGREEMENT array vs kernel at w=%d cd=%d -- nothing reported" % (w, cd))
return a
def agree(x, y, tag):
if abs(float(x) - float(y)) > 1e-12:
raise SystemExit("DISAGREEMENT (%s): %r vs %r -- nothing reported" % (tag, x, y))
return float(x)
def profile(brk):
"""Mean fitted diameter at every width in the sweep, for one breakpoint."""
out = {}
for w in range(W0, W1 + 1):
tot = 0.0
n = 0
for cd in CD:
d = diam(w, cd, brk)
tot += float(d.sum())
n += d.size
out[w] = tot / n
return out
def biggest_steps(prof):
return sorted(((prof[w + 1] - prof[w], w) for w in range(W0, W1)),
key=lambda t: -abs(t[0]))
# ---- 1. locate the discontinuity, 1 px resolution, as shipped -------------
prof640 = profile(SH_BRK)
steps = biggest_steps(prof640)
jump_delta, jump_w = steps[0]
runner_delta, runner_w = steps[1]
# ---- 2. size of the jump: ratio of disc diameter either side -------------
parts = []
for cd in CD:
lo = diam(jump_w, cd, SH_BRK) # narrow branch
hi = diam(jump_w + 1, cd, SH_BRK) # wide branch
parts.append((hi / lo).ravel())
RAT = cp.concatenate(parts)
ratio_mean = agree(float(RAT.mean()), float(RAT.sum()) / RAT.size, "ratio_mean")
srt = cp.sort(RAT)
ratio_max = agree(float(RAT.max()), float(srt[-1]), "ratio_max")
ratio_min = agree(float(RAT.min()), float(srt[0]), "ratio_min")
ratio_med = float(cp.median(RAT))
frac_step = agree(float((RAT != 1.0).mean()),
float((RAT != 1.0).sum()) / RAT.size, "frac_step")
# ---- 3. combinations inside the disagreement band ------------------------
band_lo, band_hi = SH_BRK + 1, CT_BRK # shell says wide, cartridge styles a phone
sqrt_space = cp.sqrt(SPACE)[None, :]
in_band = 0
bad_today = 0
bad_after = 0
shrink_sum = 0.0
shrink_n = 0
for w in range(band_lo, band_hi + 1):
for cd in CD:
dw = diam(w, cd, SH_BRK).ravel() # what ships today (wide branch)
dn = diam(w, cd, CT_BRK).ravel() # what the fix gives (narrow branch)
shrink_sum += float((dn / dw).sum())
shrink_n += dn.size
zw = (dw / 2.0)[:, None] / sqrt_space
zn = (dn / 2.0)[:, None] / sqrt_space
in_band += zw.size
bad_today += int(agree(int(cp.count_nonzero(zw < 1.5)),
int((zw < 1.5).sum()), "bad_today"))
bad_after += int(agree(int(cp.count_nonzero(zn < 1.5)),
int((zn < 1.5).sum()), "bad_after"))
mean_shrink = shrink_sum / shrink_n
# ---- 4. does unifying on 700 remove the step or move it? -----------------
prof700 = profile(CT_BRK)
j700_delta, j700_w = biggest_steps(prof700)[0]
res = {
"band": {
"cartridge_breakpoint_px": CT_BRK,
"disagreement_band_px": [band_lo, band_hi],
"disagreement_band_width_px": band_hi - band_lo + 1,
"shell_breakpoint_px": SH_BRK,
},
"cases": {
"combos_in_band": in_band,
"combos_in_band_failing_three_radii_after_fix": bad_after,
"combos_in_band_failing_three_radii_today": bad_today,
"furniture_grid_size": int(H.size * HD.size * HU.size * FT.size * len(CD)),
"space_values": [int(v) for v in SPACE.get()],
"widths_swept": [W0, W1],
},
"jump": {
"discontinuity_between_px": [int(jump_w), int(jump_w) + 1],
"mean_diameter_delta_px": round(float(jump_delta), 9),
"ratio_max": round(ratio_max, 9),
"ratio_mean": round(ratio_mean, 9),
"ratio_median": round(ratio_med, 9),
"ratio_min": round(ratio_min, 9),
"runner_up_step_at_px": int(runner_w),
"runner_up_step_delta_px": round(float(runner_delta), 9),
"share_of_cases_that_step": round(frac_step, 9),
},
"unify_on_700": {
"cost_mean_diameter_ratio_in_band": round(mean_shrink, 9),
"largest_step_after_delta_px": round(float(j700_delta), 9),
"largest_step_after_px": [int(j700_w), int(j700_w) + 1],
"removes_step": False,
"verdict": "moves, does not remove",
},
"verification": {
"method": "cupy ElementwiseKernel vs cupy array expressions, exact equality",
"status": "agreed",
},
}
os.makedirs(os.path.dirname(OUT), exist_ok=True)
with open(OUT, "w", encoding="utf-8") as f:
json.dump(res, f, indent=2, sort_keys=True)
f.write("\n")
print()
print("THE JUMP IS BETWEEN %d px AND %d px." % (jump_w, jump_w + 1))
print(" At %d px the shell restacks: HUD under the header, card on the foot." % jump_w)
print(" Crossing one CSS pixel changes the fitted disc diameter by a factor of")
print(" %.4f on average, %.4f at worst, %.4f at best; %.1f%% of all cases step."
% (ratio_mean, ratio_max, ratio_min, 100.0 * frac_step))
print(" Mean fitted diameter moves %.2f px across that single pixel." % jump_delta)
print(" The next largest step anywhere in %d..%d is only %.4f px (at %d)."
% (W0, W1, runner_delta, runner_w))
print()
print("THE DISAGREEMENT BAND is %d..%d px, %d px wide: the shell calls it wide, the"
% (band_lo, band_hi, band_hi - band_lo + 1))
print(" cartridge still styles it as a phone. %d viewport x furniture x SPACE" % in_band)
print(" combinations sit inside it. %d already break the three-radii rule;" % bad_today)
print(" after unifying on 700 that becomes %d." % bad_after)
print()
print("DOES 700 FIX IT? No -- it MOVES it. With both files on 700 the largest step")
print(" in the sweep is %.2f px between %d and %d px: the same cliff, %d px right."
% (j700_delta, j700_w, j700_w + 1, j700_w - jump_w))
print(" And it is not free: across %d..%d the fitted disc becomes %.4f of what it"
% (band_lo, band_hi, mean_shrink))
print(" is today -- a real shrink on screens that are fine right now.")
print()
print("NOT PROVEN: a camera read from source; rendered nothing; held no device.")
print("wrote", OUT)Watch Collapse
A Python command-line tool in Worlds that converts to py strict (`to_py_strict`), using SHA-256.
ingestworlds- / src/watch_collapse.py · lines 1–379 of 379 · Entry point · pattern decode (shared by 19 files)
- What it does
- It loads data. Defines build, to_py_strict, decode, on_the_line, main. Uses libraries ast, hashlib, io, json, math. Side effects: reads or writes files; starts processes.
- Inputs & outputs
- In: JSON file collapse.json.
- 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 build step (`build`), the decode step (`decode`) and the on the line helper (`on_the_line`). Not how many pairs parted - WHICH ones.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- worlds- · src · Python CLI
- Uses
- Annihilate (import), ast, hashlib, io, json, math, os, re, sys
- Used by
- none found
- Produces
- build, to_py_strict, decode, on_the_line, main
- Defines here
- build, to_py_strict, decode, on_the_line, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- worlds-@83817c34790800d4af5057629121d83d0d67a332 src/watch_collapse.py:1-379 · blob 0200ba75e55a2716d37d992e9e0b69176552cdfb · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: unknown · users: none · canonical: unknown
"""WATCH THE COLLAPSE. Not how many pairs parted - WHICH ones.
WHAT CAME BEFORE, AND WHAT WAS MISSING FROM IT
annihilate.py fuses every worksheet predicate into one kernel and computes each
case twice in the same thread: the electron channel is the predicate as the
worksheet wrote it, the positron channel is the same predicate with every
comparison made STRICT. Those two differ on exactly one set of cases - the ones
where the two sides are EQUAL. It counted the partings. It never recorded which
cases they were, so nobody could look at one. A count is not evidence. A count
you cannot open is a rumour with a number on it.
This records the collapse. The kernel carries a BOUNDED buffer and a per
predicate cursor. When a thread's two channels disagree it atomically claims a
slot and writes its case index. Two counters come back for every predicate:
how many partings it SAW, and how many it STORED. When those differ the buffer
was full, and that is printed and written as a number - never a silent
truncation, never a quiet shrug.
THE PAIR, BECAUSE A NUMBER IS BORN AS A PAIR OR NOT AT ALL
Every recorded case is re-evaluated on the HOST in plain Python - a second,
independent implementation of the same two channels, on a different machine
(the CPU), through a different compiler (CPython, not nvrtc). If the host does
not agree that the case parts, it is reported as a DISAGREEMENT and not as a
finding. The parting counts are likewise carried as a pair: the card's per
predicate total against the sum it stored plus the overflow it saw.
<venv>\\Scripts\\python.exe watch_collapse.py
"""
import ast
import hashlib
import io
import json
import math
import os
import re
import sys
import time
import numpy as np
import annihilate
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
OUT = os.path.join(ROOT, "night-results", "collapse.json")
KEEP = 40 # at most this many recorded examples per predicate
# The fused kernel declares each axis as a local double inside the dispatch
# block. Any axis whose NAME is also a kernel identifier would shadow it - an
# axis called `e` shadows the electron accumulator `int e`, so the assignment
# `e = (...)` writes the axis instead of the verdict and the positron channel
# then reads a corrupted axis. That does not produce a wrong-ish answer, it
# produces a fabricated parting. The host channel in this file caught exactly
# that. Such predicates are REFUSED BY NAME here rather than counted wrongly.
RESERVED = {"e", "q", "r", "rr", "p", "i", "lo", "hi", "mid", "stride",
"total", "offset", "npred", "keep", "seen", "part_seen",
"part_cur", "out_case", "blockIdx", "blockDim", "threadIdx",
"gridDim", "int", "double", "long", "if", "else", "for", "while"}
KERNEL = r"""
extern "C" __global__ void watch(
const long long total,
const long long* __restrict__ offset,
const int npred,
const int keep,
long long* seen, /* npred: cases visited */
long long* part_seen, /* npred: partings the kernel SAW */
int* part_cur, /* npred: slot cursor, may exceed keep */
long long* out_case) /* npred*keep: flat case index of a parting */
{
long long i = (long long)blockIdx.x * blockDim.x + threadIdx.x;
long long stride = (long long)gridDim.x * blockDim.x;
for (; i < total; i += stride) {
int lo = 0, hi = npred - 1, p = 0;
while (lo <= hi) {
int mid = (lo + hi) >> 1;
if (offset[mid] <= i) { p = mid; lo = mid + 1; } else { hi = mid - 1; }
}
long long r = i - offset[p];
int e = 0, q = 0;
__DISPATCH__
atomicAdd((unsigned long long*)&seen[p], 1ULL);
if (e != q) {
atomicAdd((unsigned long long*)&part_seen[p], 1ULL);
int slot = atomicAdd(&part_cur[p], 1);
if (slot < keep) out_case[(long long)p * keep + slot] = i;
}
}
}
"""
def build(specs):
blocks = []
for pi, s in enumerate(specs):
lines = [" %s (p == %d) {" % ("if" if pi == 0 else "else if", pi)]
lines.append(" long long rr = r;")
for ai, a in enumerate(s["axes"]):
lines.append(" int a%d = (int)(rr %% %d); rr /= %d;"
% (ai, a["n"], a["n"]))
for ai, a in enumerate(s["axes"]):
lines.append(" double %s = %.17g + (%.17g - %.17g) * (double)a%d"
" / (%d - 1.0);"
% (a["name"], a["lo"], a["hi"], a["lo"], ai, a["n"]))
lines.append(" e = (%s) ? 1 : 0;" % s["c"])
lines.append(" q = (%s) ? 1 : 0;" % s["cm"])
lines.append(" }")
blocks.append("\n".join(lines))
return KERNEL.replace("__DISPATCH__", "\n".join(blocks))
# ---------------------------------------------------------------------------
# the second, independent implementation: the same two channels, in Python
# ---------------------------------------------------------------------------
PYENV = {"abs": abs, "min": min, "max": max, "sqrt": math.sqrt,
"log": math.log, "exp": math.exp, "pow": pow, "__builtins__": {}}
def to_py_strict(pred):
"""The positron channel again, written for Python rather than for C. Same
rule, different text: every comparison made strict."""
e = re.sub(r"([^<>!=])>=([^=])", r"\1 MIRROR_GE \2", pred)
e = re.sub(r"([^<>!=])<=([^=])", r"\1 MIRROR_LE \2", e)
e = e.replace("MIRROR_GE", "> ").replace("MIRROR_LE", "< ")
return e
def decode(spec, r):
"""A flat case index within a predicate becomes its axis values. The same
arithmetic the kernel does, done again here in Python."""
vals = {}
for a in spec["axes"]:
idx = r % a["n"]
r //= a["n"]
vals[a["name"]] = a["lo"] + (a["hi"] - a["lo"]) * idx / (a["n"] - 1.0)
return vals
def on_the_line(pred, vals):
"""WHICH quantity is sitting exactly on its limit. The predicate is parsed,
every comparison in it is evaluated on both sides, and the ones whose sides
are EQUAL are the ones the verdict turns on."""
out = []
try:
tree = ast.parse(pred.replace("\n", " "), mode="eval")
except Exception:
return out
for node in ast.walk(tree):
if not isinstance(node, ast.Compare) or len(node.ops) != 1:
continue
try:
lhs = eval(compile(ast.Expression(node.left), "<c>", "eval"),
dict(PYENV), dict(vals))
rhs = eval(compile(ast.Expression(node.comparators[0]), "<c>",
"eval"), dict(PYENV), dict(vals))
except Exception:
continue
if lhs == rhs:
out.append({"left": ast.unparse(node.left).strip(),
"right": ast.unparse(node.comparators[0]).strip(),
"value": lhs})
return out
def main():
specs, refused = [], []
for p in annihilate.sheets():
try:
d = json.load(io.open(p, encoding="utf-8"))
except Exception as e:
refused.append((os.path.basename(p), "unreadable: %s" % e))
continue
for f in d.get("features", []):
pr = f.get("properties", {})
got, why = annihilate.parse(pr.get("maths"))
if not got:
refused.append((f.get("id", "?"), why))
continue
clash = sorted({a["name"] for a in got["axes"]} & RESERVED)
if clash:
refused.append((f.get("id", "?"),
"axis name %s shadows a kernel identifier, so "
"its channels cannot be trusted"
% ", ".join(clash)))
continue
size = 1
for ax in got["axes"]:
size *= ax["n"]
size = min(size, annihilate.PER_MAX)
got.update({"id": f.get("id", "?"),
"what": (pr.get("what") or "")[:90],
"size": size,
"c": annihilate.to_c(got["pred"]),
"cm": annihilate.to_c_strict(got["pred"])})
specs.append(got)
if not specs:
print("FAIL: no sentence parsed. Nothing to watch.")
return 1
total = sum(s["size"] for s in specs)
print("WATCH THE COLLAPSE: which cases parted, not how many")
print(" predicates fused %d" % len(specs))
print(" refused by name %d" % len(refused))
for rid, why in refused:
print(" REFUSED %-28s %s" % (str(rid)[:28], why))
print(" cases in the grid %s" % "{:,}".format(total))
print(" buffer %d per predicate, %d slots in all"
% (KEEP, KEEP * len(specs)))
import cupy as cp
mod = cp.RawModule(code=build(specs), backend="nvrtc",
options=("--std=c++11",))
fn = mod.get_function("watch")
off = np.zeros(len(specs) + 1, dtype=np.int64)
for i, s in enumerate(specs):
off[i + 1] = off[i] + s["size"]
d_off = cp.asarray(off)
seen = cp.zeros(len(specs), dtype=cp.int64)
pseen = cp.zeros(len(specs), dtype=cp.int64)
pcur = cp.zeros(len(specs), dtype=cp.int32)
ocase = cp.full(len(specs) * KEEP, -1, dtype=cp.int64)
cp.cuda.Stream.null.synchronize()
t0 = time.perf_counter()
fn((70 * 6,), (256,), (np.int64(total), d_off, np.int32(len(specs)),
np.int32(KEEP), seen, pseen, pcur, ocase))
cp.cuda.Stream.null.synchronize()
sec = time.perf_counter() - t0
S = [int(x) for x in cp.asnumpy(seen)]
P = [int(x) for x in cp.asnumpy(pseen)]
C = [int(x) for x in cp.asnumpy(pcur)]
CASES = cp.asnumpy(ocase).reshape(len(specs), KEEP)
if sum(S) != total:
print(" FAIL: the grid did not visit every case (%s of %s)."
% ("{:,}".format(sum(S)), "{:,}".format(total)))
return 1
# the pair on the counts: the kernel's parting total against its cursor
mismatch = [i for i in range(len(specs)) if P[i] != C[i]]
print("\n ran %s cases in %.3f s" % ("{:,}".format(total), sec))
print(" partings SEEN %s" % "{:,}".format(sum(P)))
print(" slots CLAIMED %s" % "{:,}".format(sum(C)))
print(" partings STORED %s" % "{:,}".format(sum(min(c, KEEP)
for c in C)))
print(" overflowed (seen but not stored) %s"
% "{:,}".format(sum(max(0, c - KEEP) for c in C)))
# ---- the host channel: every stored case re-evaluated in Python ----
per, agree, disagree = [], 0, 0
for i, s in enumerate(specs):
stored = [int(x) for x in CASES[i] if x >= 0]
stored.sort()
ex = []
pys = to_py_strict(s["pred"])
for flat in stored:
vals = decode(s, flat - int(off[i]))
try:
he = bool(eval(s["pred"], dict(PYENV), dict(vals)))
hq = bool(eval(pys, dict(PYENV), dict(vals)))
ok = (he != hq)
except Exception as e:
ok, he, hq = None, None, "host could not evaluate: %s" % e
if ok is True:
agree += 1
else:
disagree += 1
ex.append({
"axes": {k: repr(v) for k, v in sorted(vals.items())},
"case_index": flat,
"host_agrees_it_parts": ok,
"on_the_line": [{"left": t["left"], "right": t["right"],
"value": repr(t["value"])}
for t in on_the_line(s["pred"], vals)],
"verdict_as_written": he,
"verdict_if_strict": hq,
})
per.append({
"buffer_full": C[i] > KEEP,
"cases": S[i],
"id": s["id"],
"partings_seen": P[i],
"partings_stored": len(stored),
"predicate": s["pred"],
"recorded": ex,
"slots_claimed": C[i],
"what": s["what"],
})
print(" host re-evaluated %d recorded cases: %d agree, %d DISAGREE"
% (agree + disagree, agree, disagree))
if mismatch:
print(" WARNING: %d predicates whose parting total and cursor differ"
% len(mismatch))
# ---- the ten most interesting partings, in plain words ----
flat = []
for row in per:
for ex in row["recorded"]:
flat.append((row["id"], row["partings_seen"], ex))
flat.sort(key=lambda t: (-len(t[2]["on_the_line"]), -t[1], t[0],
t[2]["case_index"]))
print("\n THE TEN MOST INTERESTING PARTINGS")
print(" each of these is a design sitting EXACTLY on a threshold, where")
print(" the words 'or equal to' decide it and the design does not:")
for pid, _, ex in flat[:10]:
av = ", ".join("%s = %s" % (k, v) for k, v in ex["axes"].items())
print("\n %s %s" % (pid, av))
if ex["on_the_line"]:
for t in ex["on_the_line"]:
print(" exactly on its limit: %s = %s = %s"
% (t["left"], t["right"], t["value"]))
else:
print(" (the host found no comparison with equal sides here)")
print(" as written %s, if strict %s"
% (ex["verdict_as_written"], ex["verdict_if_strict"]))
if not flat:
print(" none: not one case in this grid parted.")
body = {
"anonymised": "No project, site, client, maker or model anywhere.",
"buffer_per_predicate": KEEP,
"cases": total,
"host_check":
"Every recorded case was re-evaluated on the CPU in Python - a "
"second, independent implementation of the same two channels, "
"through a different compiler. host_agrees_it_parts is true only "
"where the host also found the two channels disagreeing. A false "
"or null there is a DISAGREEMENT between card and host and is not "
"a finding.",
"host_agreed": agree,
"host_disagreed": disagree,
"not_proved":
"This does NOT prove any of these designs is wrong, unsafe or "
"non-compliant. It proves only that in the spaces the worksheets "
"state, these cases land exactly on a threshold, so their verdict "
"is decided by whether the rule says 'or equal to' rather than by "
"the design. It does not say the space is the right space or the "
"predicate the right question. It holds no site, no weather "
"record and no as-built drawing, so it says nothing about any "
"real installation. The recorded examples are a BOUNDED sample: "
"where buffer_full is true, more partings exist than are shown, "
"and partings_seen is the honest total. The axis values are "
"written as Python repr of the double, so no precision is hidden.",
"partings_seen": sum(P),
"partings_stored": sum(min(c, KEEP) for c in C),
"per_predicate": per,
"predicates": len(specs),
"refused": [{"id": str(i), "why": w} for i, w in refused],
"refused_count": len(refused),
"schema": "ggs.collapse/1",
"slots_claimed": sum(C),
"the_pair":
"The electron channel is the predicate as written; the positron "
"channel is the same predicate with every comparison made strict. "
"They differ on exactly one set of cases - where the two sides are "
"EQUAL. The counts are carried as a pair too: partings_seen from "
"the kernel's own counter against slots_claimed from its cursor; "
"if those ever differ the run is not to be trusted.",
"totals_agree": not mismatch,
}
body["body_sha256"] = hashlib.sha256(
json.dumps(body, sort_keys=True).encode("utf-8")).hexdigest()
os.makedirs(os.path.dirname(OUT), exist_ok=True)
io.open(OUT, "w", encoding="utf-8", newline="\n").write(
json.dumps(body, indent=1, sort_keys=True) + "\n")
print("\n body sha256 %s" % body["body_sha256"][:32])
print(" wrote night-results/collapse.json")
print("\n WHAT THIS DOES NOT PROVE: nothing here says a design is wrong.")
print(" It says the verdict on these cases is a convention - the words")
print(" 'or equal to' - and not a measurement. The sample is bounded;")
print(" partings_seen, not the list, is the honest total.")
return 0
if __name__ == "__main__":
sys.exit(main())