test: fixed three-level/two-region nested shear preset (nested_shear_n128)

Test-only opt-in. New shear_nested.py: fixed parent-frame rectangles
(L0->L1 (16,16,60,112),(68,24,112,120); L1->L2 (44,44,108,212),
(148,60,212,228)), exact leaves/hops/work/nu/tau, depth-3 + 4N-finest
generalization of the shear assessment (same summaries/screens/budgets),
bounded final macro snapshot writer/reader (packed ACTIVE leaves + rho/u,
metadata, sha256, 8 MiB cap; no populations/restart/time series).
run_case: --diagnostic nested_shear_n128 (U128, U512, constant/projected
R128 depth 3), --final-snapshot only for projected depth 3, shear_nested.py
path+hash pin. assess_shear_wave: assess_nested contract and CLI.
shear_wave.py and oracle.py byte-identical; old guards/defaults unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
ClaudeandClaude Opus 5.5 committed 2026-10-19 02:14:23 +00:00
1 parent 9748ef91ef
commit 335624c27b
5 files changed
+575 -11

No files matched your search

@@ -571,3 +571,208 @@ class DefaultPathTests(unittest.TestCase):
if __name__ == "__main__":
unittest.main()
class NestedPresetTests(unittest.TestCase):
"""Fixed three-level/two-region shear preset (nested_shear_n128)."""
def setUp(self):
import assess_shear_wave
import shear_nested
self.mod, self.nested = assess_shear_wave, shear_nested
def test_exact_geometry_work_and_levels(self):
nested = self.nested
masks = nested.leaf_masks()
self.assertEqual([int(m.sum()) for m in masks], [7936, 12288, 86016])
self.assertEqual(nested.LEAVES, [7936, 12288, 86016])
self.assertEqual(nested.HOPS, [2048, 4096, 8192])
self.assertEqual(nested.WORK, 771227648)
uniform = 128 * 128 * 2048 + 512 * 512 * 8192
self.assertEqual(uniform + 2 * nested.WORK, 3723493376)
np.testing.assert_allclose(nested.NU, [.0384, .0768, .1536], rtol=0, atol=1e-15)
np.testing.assert_allclose(nested.TAU, [.6152, .7304, .9608], rtol=0, atol=1e-14)
self.assertEqual(sum(float(m.sum()) * 0.25**l for l, m in enumerate(masks)), 128.0**2)
# Production host hierarchy builds the same leaves from the same rectangles.
from CelerisLab.lbm.hierarchy import build_hierarchy, leaf_partition
from CelerisLab.lbm.refinement import ACTIVE
h = build_hierarchy(run_case.config(128, 100), nested.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)
def test_historical_shear_identity_is_preserved(self):
digest = hashlib.sha256((HERE / "shear_wave.py").read_bytes()).hexdigest()
self.assertEqual(digest, "81d5c8ee60864372887cddf9239580c82fb6750d956038f1e3ee9de61aa4e877")
self.assertEqual(run_case.SHEAR_WAVE_SHA256, digest)
nested_digest = hashlib.sha256((HERE / "shear_nested.py").read_bytes()).hexdigest()
self.assertEqual(run_case.SHEAR_NESTED_SHA256, nested_digest)
def nested_set(self):
out = []
for n, depth, scheme in ((128, 1, "constant"), (512, 1, "constant"),
(128, 3, "constant"), (128, 3, "projected_linear")):
r = receipt(n, depth, scheme, diagnostic=run_case.NESTED_SHEAR)
r["source"]["shear_nested_sha256"] = run_case.SHEAR_NESTED_SHA256
if depth == 3:
cells, hops = self.nested.LEAVES, self.nested.HOPS
r["refinements"] = [list(level) for level in self.nested.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.nested.WORK)
out.append(r)
return out
def test_nested_contract_and_rejections(self):
a = self.mod.assess_nested
good = self.nested_set()
result = a(good, "r")
self.assertTrue(result["contract_valid"], [k for k, v in result["checks"].items() if not v])
self.assertEqual(result["status"], "PASS")
self.assertIn("finest", result["physics"]["refined"]["constant"]["control_ratios"])
wrong_finest = self.nested_set()
wrong_finest[1] = receipt(256, 1, diagnostic=run_case.NESTED_SHEAR)
wrong_finest[1]["source"]["shear_nested_sha256"] = run_case.SHEAR_NESTED_SHA256
self.assertEqual(a(wrong_finest, "r")["status"], "INVALID_SET")
for mutate in (
lambda s: s[2].update(refinements=[s[2]["refinements"][1], s[2]["refinements"][0]]),
lambda s: s[3].update(refinements=rectangles(128, 3)),
lambda s: s[2]["rows"][2].update(spurious_pressure_scaled_by_level=[0.0, 0.0]),
lambda s: s[0].update(diagnostic=run_case.SCALED_SHEAR),
lambda s: s[2]["source"].pop("shear_nested_sha256"),
lambda s: s[2].update(final_snapshot=dict(kept=True, sha256="a" * 64, bytes=10,
leaf_counts=self.nested.LEAVES, step=2048)),
lambda s: s[3].update(final_snapshot=dict(kept=True, sha256="a" * 64,
bytes=self.nested.SNAPSHOT_MAX_BYTES + 1,
leaf_counts=self.nested.LEAVES, step=2048)),
):
records = self.nested_set()
mutate(records)
self.assertNotEqual(a(records, "r")["status"], "PASS")
ok = self.nested_set()
ok[3]["final_snapshot"] = dict(kept=True, sha256="a" * 64, bytes=1000,
leaf_counts=self.nested.LEAVES, step=2048)
self.assertEqual(a(ok, "r")["status"], "PASS")
with self.assertRaises(ValueError):
self.nested.assess(good[0], good[1], [good[2], dict(good[2])])
def test_nested_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"]
nest = ["--flow", "shear_wave", "--diagnostic", run_case.NESTED_SHEAR]
proj = ["--explosion", "projected_linear"]
for extra, valid in (
(["--n", "128", "--depth", "1"] + nest, True),
(["--n", "512", "--depth", "1"] + nest, True),
(["--n", "128", "--depth", "3"] + nest, True),
(["--n", "128", "--depth", "3"] + proj + nest + ["--final-snapshot"], True),
(["--n", "256", "--depth", "1"] + nest, False), # finest control is 4N
(["--n", "128", "--depth", "2"] + nest, False),
(["--n", "128", "--depth", "3", "--flow", "shear_wave"], False),
(["--n", "128", "--depth", "3", "--diagnostic", run_case.NESTED_SHEAR], False),
(["--n", "128", "--depth", "3"] + nest + ["--final-snapshot"], False),
(["--n", "128", "--depth", "3"] + proj + ["--flow", "shear_wave"], False),
(["--n", "128", "--depth", "2", "--flow", "shear_wave", "--final-snapshot"], 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_nested")
else:
with self.assertRaises(SystemExit):
run_case.main()
def test_mocked_nested_execution_with_bounded_snapshot(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.nested.REFINEMENTS)
nu = U * 128 / sw.RE
arrays = [sw.initial(k.shape, level, 128, nu) for level, k in enumerate(h.kinds)]
class FakeRun:
def __init__(self, *args, **kwargs):
self.step_count = 0
self.kwargs = kwargs
def __enter__(self):
return self
def __exit__(self, *args):
pass
def initialize(self, *given):
assert len(given) == 3
def step(self, count):
assert count >= 0
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_nested.json"
argv = ["run_case.py", "--repo", str(repo), "--re", "100", "--n", "128", "--depth", "3",
"--explosion", "projected_linear", "--flow", "shear_wave",
"--diagnostic", run_case.NESTED_SHEAR, "--final-snapshot",
"--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.NESTED_SHEAR)
self.assertEqual(rec["workload"]["active_cells_by_level"], self.nested.LEAVES)
self.assertEqual(rec["workload"]["active_collision_updates"], self.nested.WORK)
self.assertEqual(rec["tau_by_level"], self.nested.TAU)
self.assertTrue(all(len(r["spurious_pressure_scaled_by_level"]) == 3 for r in rec["rows"]))
snap = rec["final_snapshot"]
path = output.with_name(output.stem + ".final_macro.npz")
self.assertTrue(snap["kept"])
self.assertEqual(snap["sha256"], hashlib.sha256(path.read_bytes()).hexdigest())
self.assertLessEqual(snap["bytes"], self.nested.SNAPSHOT_MAX_BYTES)
meta, fields = self.nested.read_snapshot(path)
self.assertEqual((meta["step"], meta["phase"]), (2048, sw.PHI))
self.assertEqual(meta["tstar"], 2048 * U / 128)
self.assertEqual(meta["leaf_counts"], self.nested.LEAVES)
self.assertEqual(sorted(fields), ["i", "j", "level", "rho", "ux", "uy"])
np.testing.assert_allclose(fields["rho"], 1.0, atol=1e-12)
def test_snapshot_contents_and_cap(self):
nested = self.nested
masks = nested.leaf_masks()
arrays = [sw.initial(m.shape, level, 128, 0.0384) for level, m in enumerate(masks)]
meta = nested.snapshot_meta(2048, 0.0384, "projected_linear", "r")
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / "s.npz"
block = nested.write_snapshot(path, arrays, masks, meta)
self.assertTrue(block["kept"])
got, fields = nested.read_snapshot(path)
self.assertEqual(got["refinements"], [[list(r) for r in level] for level in nested.REFINEMENTS])
self.assertEqual(int(fields["level"].max()), 2)
with self.assertRaises(FileExistsError):
nested.write_snapshot(path, arrays, masks, meta)
bad = Path(tmp) / "bad.npz"
np.savez_compressed(bad, populations=np.zeros(3), **{k: np.zeros(1) for k in ("level", "i", "j", "rho", "ux", "uy")}, meta=np.array("{}"))
with self.assertRaises(ValueError):
nested.read_snapshot(bad)
with patch.object(nested, "SNAPSHOT_MAX_BYTES", 10):
capped = nested.write_snapshot(Path(tmp) / "c.npz", arrays, masks, meta)
self.assertFalse(capped["kept"])
self.assertFalse((Path(tmp) / "c.npz").exists())