test: depth-2 twin of the nested shear preset (twin_shear_n128)

Test-only opt-in. New shear_twin.py: same two L0->L1 boxes as
shear_nested, no L2; leaves [7936,33792], hops [2048,4096], work
154664960. Four fresh cases U128/U256/constant R128 d2/projected R128 d2;
physics is the unchanged depth-2/2N shear_wave.assess. run_case:
--diagnostic twin_shear_n128 with shear_twin.py+shear_nested.py pins, no
snapshot. assess_shear_wave: nested contract made preset-generic (PRESETS)
with nested behaviour unchanged. Labels: twin vs nested = effect of adding
this nested refinement (not abstract depth). shear_wave.py, shear_nested.py
and oracle.py byte-identical.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
ClaudeandClaude Opus 5.5 committed 2026-10-19 02:52:20 +00:00
1 parent 335624c27b
commit 02bde0f751
5 files changed
+304 -41

No files matched your search

@@ -776,3 +776,157 @@ class NestedPresetTests(unittest.TestCase):
capped = nested.write_snapshot(Path(tmp) / "c.npz", arrays, masks, meta)
self.assertFalse(capped["kept"])
self.assertFalse((Path(tmp) / "c.npz").exists())
class TwinPresetTests(unittest.TestCase):
"""Depth-2 twin (twin_shear_n128): nested L0->L1 boxes, no L2, fresh U128/U256."""
def setUp(self):
import assess_shear_wave
import shear_nested
import shear_twin
self.mod, self.nested, self.twin = assess_shear_wave, shear_nested, shear_twin
def test_exact_geometry_work_and_nested_identity(self):
twin = self.twin
masks = twin.leaf_masks()
self.assertEqual([int(m.sum()) for m in masks], [7936, 33792])
self.assertEqual((twin.LEAVES, twin.HOPS, twin.WORK), ([7936, 33792], [2048, 4096], 154664960))
self.assertEqual(128 * 128 * 2048 + 256 * 256 * 4096 + 2 * twin.WORK, 611319808)
self.assertEqual(twin.REFINEMENTS, [self.nested.REFINEMENTS[0]])
np.testing.assert_array_equal(masks[0], self.nested.leaf_masks()[0]) # same root leaves
from CelerisLab.lbm.hierarchy import build_hierarchy, leaf_partition
from CelerisLab.lbm.refinement import ACTIVE
h = build_hierarchy(run_case.config(128, 100), twin.REFINEMENTS)
np.testing.assert_array_equal(leaf_partition(h), np.ones((128, 128)))
for mine, kinds in zip(masks, h.kinds):
np.testing.assert_array_equal(mine, kinds == ACTIVE)
# Historical nested identity is unchanged; the twin is pinned separately.
self.assertEqual(hashlib.sha256((HERE / "shear_nested.py").read_bytes()).hexdigest(),
"fa6cfe87fb4df8c6d732c637c885276833c81973b950c7724d734f8fc350bcb0")
self.assertEqual(run_case.SHEAR_TWIN_SHA256,
hashlib.sha256((HERE / "shear_twin.py").read_bytes()).hexdigest())
def twin_set(self):
out = []
for n, depth, scheme in ((128, 1, "constant"), (256, 1, "constant"),
(128, 2, "constant"), (128, 2, "projected_linear")):
r = receipt(n, depth, scheme, diagnostic=run_case.TWIN_SHEAR)
r["source"].update(shear_nested_sha256=run_case.SHEAR_NESTED_SHA256,
shear_twin_sha256=run_case.SHEAR_TWIN_SHA256)
if depth == 2:
cells, hops = self.twin.LEAVES, self.twin.HOPS
r["refinements"] = [list(level) for level in self.twin.REFINEMENTS]
r["workload"] = dict(active_cells_by_level=cells, level_hops=hops, root_intervals=2048,
active_collision_updates_by_level=[c * h for c, h in zip(cells, hops)],
active_collision_updates=self.twin.WORK)
out.append(r)
return out
def test_twin_contract_and_rejections(self):
a = lambda records: self.mod.assess_nested(records, "r", run_case.TWIN_SHEAR)
result = a(self.twin_set())
self.assertTrue(result["contract_valid"], [k for k, v in result["checks"].items() if not v])
self.assertEqual(result["status"], "PASS")
self.assertIn("does not isolate abstract depth", result["scope"])
self.assertEqual(result["finest_control"], "uniform 2N (U256)")
for mutate in (
lambda s: s.__setitem__(1, receipt(512, 1, diagnostic=run_case.TWIN_SHEAR)), # 4N control
lambda s: s[2].update(refinements=[list(level) for level in self.nested.REFINEMENTS]),
lambda s: s[3].update(refinements=rectangles(128, 2)), # old single box
lambda s: s[2]["rows"][1].update(spurious_pressure_scaled_by_level=[0.0, 0.0, 0.0]),
lambda s: s[0].update(diagnostic=run_case.NESTED_SHEAR),
lambda s: s[2]["source"].pop("shear_twin_sha256"),
lambda s: s[3].update(final_snapshot=dict(kept=True, sha256="a" * 64, bytes=10,
leaf_counts=self.twin.LEAVES, step=2048)),
):
records = self.twin_set()
mutate(records)
self.assertNotEqual(a(records)["status"], "PASS")
# Twin and nested sets never validate as each other.
self.assertEqual(self.mod.assess_nested(self.twin_set(), "r")["status"], "INVALID_SET")
def test_twin_runner_options(self):
repo = Path(__file__).resolve().parents[3]
with tempfile.TemporaryDirectory() as tmp:
base = ["run_case.py", "--repo", str(repo), "--expected-revision", "f" * 40,
"--output", str(Path(tmp) / "case.json"), "--dry-run", "--re", "100"]
tw = ["--flow", "shear_wave", "--diagnostic", run_case.TWIN_SHEAR]
proj = ["--explosion", "projected_linear"]
for extra, valid in (
(["--n", "128", "--depth", "1"] + tw, True),
(["--n", "256", "--depth", "1"] + tw, True),
(["--n", "128", "--depth", "2"] + tw, True),
(["--n", "128", "--depth", "2"] + proj + tw, True),
(["--n", "512", "--depth", "1"] + tw, False),
(["--n", "128", "--depth", "3"] + tw, False),
(["--n", "128", "--depth", "2"] + proj + tw + ["--final-snapshot"], False),
(["--n", "128", "--depth", "2", "--diagnostic", run_case.TWIN_SHEAR], False)):
argv = base + extra
with self.subTest(argv=argv), patch.object(sys, "argv", argv), \
patch.object(run_case, "verify_source", return_value={}) as verify, \
patch.object(run_case, "runtime_source", return_value={}), \
redirect_stdout(io.StringIO()), patch("sys.stderr", io.StringIO()):
if valid:
self.assertEqual(run_case.main(), 0)
self.assertEqual(verify.call_args.args[2], "shear_twin")
else:
with self.assertRaises(SystemExit):
run_case.main()
def test_mocked_twin_execution(self):
from types import SimpleNamespace
from contextlib import nullcontext
from CelerisLab.lbm.hierarchy import build_hierarchy
h = build_hierarchy(run_case.config(128, 100), self.twin.REFINEMENTS)
arrays = [sw.initial(k.shape, level, 128, U * 128 / sw.RE) for level, k in enumerate(h.kinds)]
selectors = []
class FakeRun:
def __init__(self, *args, **kwargs):
self.step_count = 0
if "refinements" in kwargs:
selectors.append((kwargs["explosion"], kwargs["refinements"]))
def __enter__(self):
return self
def __exit__(self, *args):
pass
def initialize(self, *given):
assert len(given) == 2
def step(self, count):
self.step_count += count
def download(self):
return arrays
modules = {"CelerisLab.cuda.context": SimpleNamespace(CudaContext=FakeRun),
"CelerisLab.lbm.block_stepper": SimpleNamespace(PeriodicBlockStepper=FakeRun),
"CelerisLab.lbm.refinement_stepper": SimpleNamespace(FixedPatchStepper=FakeRun)}
repo = Path(__file__).resolve().parents[3]
with tempfile.TemporaryDirectory() as tmp:
output = Path(tmp) / "projected_twin.json"
argv = ["run_case.py", "--repo", str(repo), "--re", "100", "--n", "128", "--depth", "2",
"--explosion", "projected_linear", "--flow", "shear_wave",
"--diagnostic", run_case.TWIN_SHEAR, "--output", str(output),
"--expected-revision", "f" * 40, "--run-gpu"]
with patch.dict(sys.modules, modules), patch.object(sys, "argv", argv), \
patch.dict("os.environ", CUDA_VISIBLE_DEVICES="mock"), \
patch.object(run_case, "verify_source", return_value=dict(revision="f" * 40)), \
patch.object(run_case, "runtime_source", return_value={}), \
patch.object(run_case, "runtime_identity", return_value={}), \
patch.object(run_case, "build_capture", return_value=nullcontext()), \
redirect_stdout(io.StringIO()):
run_case.main()
rec = json.loads(output.read_text())
self.assertTrue(rec["completed"])
self.assertEqual(rec["diagnostic"], run_case.TWIN_SHEAR)
self.assertEqual(rec["workload"]["active_cells_by_level"], self.twin.LEAVES)
self.assertEqual(rec["workload"]["active_collision_updates"], self.twin.WORK)
self.assertNotIn("final_snapshot", rec)
self.assertTrue(all(len(r["spurious_pressure_scaled_by_level"]) == 2 for r in rec["rows"]))
self.assertEqual(selectors, [("projected_linear", [list(self.twin.REFINEMENTS[0])])])
self.assertEqual(sorted(p.name for p in Path(tmp).iterdir()), ["projected_twin.json"])