In this section
- Model Test test · galaxies-wafers / iterations/11-the-bond/model.test.mjs lines 1–17
- Test Adversarial V2 test · galaxies-wafers / iterations/11-the-bond/test_adversarial_v2.py lines 1–131
- Test Bond Validator test · galaxies-wafers / iterations/11-the-bond/test_bond_validator.py lines 1–198
- Test V2 Contract test · galaxies-wafers / iterations/11-the-bond/test_v2_contract.py lines 1–89
- Test Verify Bundle test · galaxies-wafers / iterations/11-the-bond/test_verify_bundle.py lines 1–204
Model Test
A test in the iterations folder of Galaxies Wafers that checks Model.
testgalaxies-wafers / iterations/11-the-bond/model.test.mjs · lines 1–17 of 17 · Not reached from any entry point (candidate for review) · pattern report (shared by 21 files)
- What it does
- It tests its inputs. Defines row, report. Uses libraries node:test, node:assert/strict.
- What it achieves
- Defines `row` and `report`.
- Why it matters
- Guards the behaviour of Model.
- Application
- galaxies-wafers · iterations/11-the-bond · test
- Uses
- Model (import), node:test, node:assert/strict
- Used by
- none found
- Produces
- row, report
- Defines here
- row, report
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/11-the-bond/model.test.mjs:1-17 · blob 6cd5ffa78b6bcaf0ea3e1e8c44ea18215fb9dcfc · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: unreached_review
import {test} from 'node:test';
import assert from 'node:assert/strict';
import {validateReport,filterRows,summarise,selectionFromHash,layerHash} from './model.mjs';
const row = () => ({layer_id:'sample',claim_text:'A numbered Anchor',status:'PARTIALLY EVALUATED',predicates:[{status:'PASSED',checked:2,total:2,passed:2,failed:0}],not_evaluated:[{text:'A broader claim'}],disclosed:[]});
const report = () => ({schema:'bond.v1',provenance:{commit:'a'.repeat(40)},input_checks:[{status:'PASSED'}],rows:[row()]});
test('accepts bounded partial report',()=>assert.equal(validateReport(report()).rows.length,1));
test('rejects duplicate layer identifiers',()=>{const r=report();r.rows.push(row());assert.throws(()=>validateReport(r),/duplicate/);});
test('rejects failed source inputs',()=>{const r=report();r.input_checks[0].status='FAILED';assert.throws(()=>validateReport(r),/input/);});
test('rejects incomplete predicate passed',()=>{const r=report();r.rows[0].predicates[0].total=3;assert.throws(()=>validateReport(r),/Incomplete/);});
test('rejects inconsistent counters',()=>{const r=report();r.rows[0].predicates[0].passed=1;assert.throws(()=>validateReport(r),/coverage/);});
test('rejects a contradiction hidden in partial status',()=>{const r=report();Object.assign(r.rows[0].predicates[0],{status:'FAILED',passed:1,failed:1});assert.throws(()=>validateReport(r),/Contradiction/);});
test('does not honour remaining prose',()=>{const r=report();r.rows[0].status='HONOURED';assert.throws(()=>validateReport(r),/honoured/);});
test('counts rows and check units from predicates',()=>{const s=summarise([row()]);assert.equal(s.checked,2);assert.equal(s.total,2);assert.equal(s.statements,1);assert.equal(s.statuses['PARTIALLY EVALUATED'],1);});
test('filters case insensitive name or claim with result',()=>{const rows=[row()];assert.equal(filterRows(rows,' anchor ','PARTIALLY EVALUATED').length,1);assert.equal(filterRows(rows,'anchor','HONOURED').length,0);});
test('selection hash round trips exact identity',()=>{const r=row();r.layer_id='a & b';assert.equal(selectionFromHash(layerHash(r.layer_id),[r]).row,r);});
test('unknown selection does not invent a layer',()=>assert.match(selectionFromHash('#layer=absent',[row()]).why,/absent/));
test('duplicate selection is refused',()=>assert.match(selectionFromHash('#layer=sample&layer=sample',[row()]).why,/more than one/));Test Adversarial V2
A test in the iterations folder of Galaxies Wafers that checks Bond Validator, using SHA-256.
testgalaxies-wafers / iterations/11-the-bond/test_adversarial_v2.py · lines 1–131 of 131 · Entry point · pattern audit (shared by 7 files)
- What it does
- It tests its inputs. Defines 27 functions or classes, including point, route, module_doc, copy_doc, register. Uses libraries copy, hashlib, unittest, json.
- Downstream impact
- Used directly by 1 file: Test V2 Contract (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/11-the-bond/). It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/11-the-bond/.
- What it achieves
- It copies doc (`copy_doc`) and is built from the point step (`point`) and the route step (`route`). Ordinary v2 regressions converted from all twelve demonstrated v1 gaps.
- Why it matters
- Checked by Test V2 Contract.
- Application
- galaxies-wafers · iterations/11-the-bond · test
- Uses
- Bond Validator (import), copy, hashlib, unittest, json
- Used by
- imported by Test V2 Contract (import)
- Produces
- point, route, module_doc, copy_doc, register, audit, row, FormerV1Gaps, Controls
- Defines here
- point, route, module_doc, copy_doc, register, audit, row, FormerV1Gaps, test_module_empty_rendering_does_not_honour_three_line_claim, test_module_point_only_does_not_honour_missing_route, test_module_duplicate_logical_features_are_not_honoured, test_module_route_cannot_escape_validation_by_omitting_marker, test_duplicate_block_symbols_cannot_be_silently_last_wins, test_duplicate_independent_family_membership_not_counted_twice, test_negative_copying_owner_ids_are_invalid, test_known_forty_one_owners_defeat_claimed_two_owner_subset, test_supplied_owner_family_arrays_must_contain_the_line, test_incomplete_owner_membership_does_not_prove_upper_bound, test_null_independent_line_record_returns_report_not_exception, test_null_block_array_returns_report_not_exception, Controls, test_valid_full_module_with_exact_register_and_route, test_explicit_wrong_route_marker_is_already_caught, test_no_independent_copying_input_is_already_withheld, test_genuine_two_owner_independent_input_passes, test_unknown_owner_count_is_already_withheld, test_public_prose_keeps_module_partial_despite_structural_gap
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/11-the-bond/test_adversarial_v2.py:1-131 · blob 0ab99648fe3a6cc2709666b98fd552bbe43ac883 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: unknown
"""Ordinary v2 regressions converted from all twelve demonstrated v1 gaps."""
import copy
import hashlib
import unittest
import json
import bond_validator as validator
def point(family=9, key=101):
return {"type": "Feature", "geometry": {"type": "Point", "key": key}, "properties": {"family": family, "mark": "first line"}}
def route(keys=None, marked=True):
f = {"type": "Feature", "geometry": {"type": "LineString", "keys": [101, 102, 103] if keys is None else keys}, "properties": {"family": 9}}
if marked:
f["properties"]["route"] = validator.ROUTE
return f
def module_doc(features, named=1, lines=3):
return {"type": "CodeFeatureCollection", "substrate": "wafer.v1", "layer": {"id": "module-Ga", "evidence": f"the live block register: block Ga #14, {named} named families, {lines} numbered lines, repository Public/repo"}, "stats": {"features": len(features), "families": named, "lines": lines}, "features": features}
def copy_doc():
return {"type": "CodeFeatureCollection", "substrate": "wafer.v1", "layer": {"id": "copying", "evidence": validator.COPYING}, "stats": {"features": 1}, "features": [{"type": "Feature", "geometry": {"type": "Point", "key": 101}, "properties": {}}]}
def register(inside=None):
return {"blocks": [{"symbol": "Ga", "number": 14, "inside": [{"family": 9}] if inside is None else inside, "repos": ["Public/repo"]}]}
DEFAULT_FAMILIES = [{"n": 9, "lines": [101, 102, 103]}, {"n": 10, "lines": [101]}]
def audit(doc, *, families=None, blocks=None, independent=None):
raw = json.dumps(doc, separators=(",", ":")).encode()
ident = doc["layer"]["id"]
manifest = {"substrate": "wafer.v1", "layers": [{"id": ident, "file": ident + ".json", "features": len(doc["features"]), "bytes": len(raw), "sha256": hashlib.sha256(raw).hexdigest()}]}
return validator.audit(manifest, {ident: doc}, [101, 102, 103], DEFAULT_FAMILIES if families is None else families, raw_bytes={ident: raw}, block_register=blocks, independent_lines=independent)
def row(report):
return report["rows"][0]
class FormerV1Gaps(unittest.TestCase):
def test_module_empty_rendering_does_not_honour_three_line_claim(self):
result = audit(module_doc([]), blocks=register())
self.assertNotEqual(row(result)["status"], "HONOURED")
def test_module_point_only_does_not_honour_missing_route(self):
result = audit(module_doc([point()]), blocks=register())
self.assertNotEqual(row(result)["status"], "HONOURED")
def test_module_duplicate_logical_features_are_not_honoured(self):
result = audit(module_doc([point(), point(), route(), route()]), blocks=register())
self.assertNotEqual(row(result)["status"], "HONOURED")
def test_module_route_cannot_escape_validation_by_omitting_marker(self):
result = audit(module_doc([point(), route([101, 103, 102], marked=False)]), blocks=register())
self.assertNotEqual(row(result)["status"], "HONOURED")
def test_duplicate_block_symbols_cannot_be_silently_last_wins(self):
blocks = register()
stale = copy.deepcopy(blocks["blocks"][0])
stale["inside"] = [{"family": 10}]
blocks["blocks"].insert(0, stale)
result = audit(module_doc([point(), route()]), blocks=blocks)
self.assertTrue(any(p["status"] == "FAILED" for p in result["input_checks"]) or row(result)["status"] != "HONOURED")
def test_duplicate_independent_family_membership_not_counted_twice(self):
result = audit(module_doc([point(), route()], named=2, lines=6), blocks=register([{"family": 9}, {"family": 9}]))
self.assertNotEqual(row(result)["status"], "HONOURED")
def test_negative_copying_owner_ids_are_invalid(self):
result = audit(copy_doc(), independent={101: {"owners": [-1, -2], "chars": 12}})
self.assertNotEqual(row(result)["status"], "HONOURED")
def test_known_forty_one_owners_defeat_claimed_two_owner_subset(self):
families = [{"n": n, "lines": [101]} for n in range(1, 42)]
result = audit(copy_doc(), families=families, independent={101: {"owners": [1, 2], "chars": 12}})
self.assertEqual(row(result)["status"], "CONTRADICTED")
def test_supplied_owner_family_arrays_must_contain_the_line(self):
families = [{"n": 9, "lines": [102]}, {"n": 10, "lines": [103]}]
result = audit(copy_doc(), families=families, independent={101: {"owners": [9, 10], "chars": 12}})
self.assertEqual(row(result)["status"], "CONTRADICTED")
def test_incomplete_owner_membership_does_not_prove_upper_bound(self):
result = audit(copy_doc(), independent={101: {"owners": [9, 10], "owners_complete": False, "chars": 12}})
self.assertNotEqual(row(result)["status"], "HONOURED")
def test_null_independent_line_record_returns_report_not_exception(self):
result = audit(copy_doc(), independent={101: None})
self.assertNotEqual(row(result)["status"], "HONOURED")
def test_null_block_array_returns_report_not_exception(self):
result = audit(module_doc([point(), route()]), blocks={"blocks": None})
self.assertNotEqual(row(result)["status"], "HONOURED")
class Controls(unittest.TestCase):
def test_valid_full_module_with_exact_register_and_route(self):
result = audit(module_doc([point(), route()]), blocks=register())
self.assertEqual(row(result)["status"], "PARTIALLY EVALUATED")
def test_explicit_wrong_route_marker_is_already_caught(self):
result = audit(module_doc([point(), route([101, 103, 102])]), blocks=register())
self.assertEqual(row(result)["status"], "CONTRADICTED")
def test_no_independent_copying_input_is_already_withheld(self):
result = audit(copy_doc())
self.assertEqual(row(result)["status"], "NOT EVALUATED")
def test_genuine_two_owner_independent_input_passes(self):
result = audit(copy_doc(), independent={101: {"owners": [9, 10], "owners_complete": True, "chars": 12}})
self.assertEqual(row(result)["status"], "HONOURED")
def test_unknown_owner_count_is_already_withheld(self):
result = audit(copy_doc(), independent={101: {"chars": 12}})
self.assertNotEqual(row(result)["status"], "HONOURED")
def test_public_prose_keeps_module_partial_despite_structural_gap(self):
doc = module_doc([])
doc["layer"]["note"] = "A human explanation remains outside machine checks."
result = audit(doc, blocks=register())
self.assertEqual(row(result)["status"], "PARTIALLY EVALUATED")
if __name__ == "__main__":
unittest.main(verbosity=2)Test Bond Validator
A test in the iterations folder of Galaxies Wafers that checks Bond Validator, using SHA-256.
Set aside from the main view: 97% of its lines are the same as sandbox/202609151802-galaxy-bond/test_bond_validator.py (testcode), which stays. (near-copy-of, proposed by families.py). 97% of lines shared with Test Bond Validator; read that one first. All set-aside files, with reasons. Nothing was deleted.
Evidence
- line-jaccard 0.9739 to testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 sandbox/202609151802-galaxy-bond/test_bond_validator.py:1-198 40d51c205b47f3b72f907e9b1defec20f03865f4
- sha256 7a484dbe66c797c324e4e7b2d3f84dc1d66582050b83a2213c36ab7b4decf730
- target sha256 e579dd1b516d28da51b3999972c608d6f9cd2b2c23c0a9d77103993624bd5afd
- group of 2 (identity.json near-copy edges >= 0.9)
- canonical rule: reachable, newest stamp, core repo, most lines
testgalaxies-wafers / iterations/11-the-bond/test_bond_validator.py · lines 1–198 of 198 · Entry point · pattern test_duplicate_family_metadata_is_not_resolved_arbitrarily (shared by 2 files)
- What it does
- It tests its inputs. Defines 31 functions or classes, including feature, fixture, run, predicate, BondTests. Uses libraries copy, hashlib, json, pathlib, unittest. Side effects: reads or writes files.
- Inputs & outputs
- In: JSON file example.json.
- Downstream impact
- It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/11-the-bond/.
- What it achieves
- It is built from the predicate step (`predicate`), the bond tests class (`BondTests`) and the corrupt step (`corrupt`). Defines `feature`, `fixture`, `run` and 28 more.
- Why it matters
- Guards the behaviour of Bond Validator.
- Application
- galaxies-wafers · iterations/11-the-bond · test
- Uses
- Bond Validator (import), copy, hashlib, json, pathlib, unittest
- Used by
- none found
- Produces
- feature, fixture, run, predicate, BondTests
- Defines here
- feature, fixture, run, predicate, BondTests, test_known_valid_point, test_unissued_key, test_family_number_is_not_key, test_family_number_can_be_issued_but_wrong_anchor, test_first_line_mismatch, test_anchor_family, test_coordinates_forbidden_even_with_valid_key, test_stale_manifest_count_hash_bytes, corrupt, test_duplicate_manifest_ids, duplicate, test_duplicate_feature_ids, test_honest_empty_disclosed, test_disclosure_does_not_waive_bad_key, test_unresolved_disclosure_exact_field, test_issued_keys_reject_non_uint32_values, test_cli_refuses_existing_output_before_reading_inputs, test_unsupported_prose_is_verbatim_and_not_honoured, test_copying_does_not_trust_same_feature_fields, test_copying_independent_both_predicates, test_copying_independent_detects_short_and_one_owner, test_route_numbering_array_not_numeric_sort, test_module_counts_need_independent_register, test_unknown_family_is_unevaluated, test_duplicate_family_metadata_is_not_resolved_arbitrarily
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/11-the-bond/test_bond_validator.py:1-198 · blob 1d6ebc245593181f3ea9d13a258ab4d86de749b8 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: unknown · users: none · canonical: duplicate_candidate
import copy
import hashlib
import json
from pathlib import Path
import unittest
from bond_validator import audit, main, COPYING, BLOCKS, ROUTE
def feature(key=101, family=9):
return {"type": "Feature", "geometry": {"type": "Point", "key": key}, "properties": {"family": family}}
def fixture(features=None, evidence=BLOCKS, note=""):
features = [feature()] if features is None else features
doc = {"type": "CodeFeatureCollection", "substrate": "wafer.v1", "layer": {"id": "example", "evidence": evidence, "note": note}, "stats": {"features": len(features)}, "features": features}
return doc
def run(doc, *, manifest_edit=None, families=None, keys=None, independent_lines=None, block_register=None):
raw = json.dumps(doc, separators=(",", ":")).encode()
entry = {"id": "example", "file": "layers/example.json", "features": len(doc["features"]), "bytes": len(raw), "sha256": hashlib.sha256(raw).hexdigest()}
manifest = {"substrate": "wafer.v1", "layers": [entry]}
if manifest_edit:
manifest_edit(manifest)
return audit(manifest, {"example": doc}, [101, 102, 103] if keys is None else keys, [{"n": 9, "lineOffset": 0, "lineCount": 3}] if families is None else families, [101, 102, 103], raw_bytes={"example": raw}, independent_lines=independent_lines, block_register=block_register)
def predicate(report, name):
return next(p for p in report["rows"][0]["predicates"] if p["id"] == name)
class BondTests(unittest.TestCase):
def test_known_valid_point(self):
report = run(fixture())
self.assertEqual(predicate(report, "geometry.issued_keys")["status"], "PASSED")
self.assertEqual(predicate(report, "family.first_line")["status"], "PASSED")
self.assertEqual(report["rows"][0]["coverage"]["features"], 1)
self.assertEqual(report["rows"][0]["status"], "PARTIALLY EVALUATED")
def test_unissued_key(self):
report = run(fixture([feature(999)]))
p = predicate(report, "geometry.issued_keys")
self.assertEqual(p["status"], "FAILED")
self.assertEqual(p["first_deviation"]["feature_index"], 0)
self.assertEqual(p["first_deviation"]["field"], "geometry.key")
self.assertEqual(report["rows"][0]["status"], "CONTRADICTED")
def test_family_number_is_not_key(self):
report = run(fixture([feature(9)]))
self.assertEqual(predicate(report, "geometry.issued_keys")["failed"], 1)
self.assertEqual(predicate(report, "family.first_line")["failed"], 1)
def test_family_number_can_be_issued_but_wrong_anchor(self):
report = run(fixture([feature(9)]), keys=[9, 101, 102, 103])
self.assertEqual(predicate(report, "geometry.issued_keys")["status"], "PASSED")
self.assertEqual(predicate(report, "family.first_line")["status"], "FAILED")
def test_first_line_mismatch(self):
report = run(fixture([feature(102)]))
self.assertEqual(predicate(report, "family.first_line")["first_deviation"]["expected"], 101)
def test_anchor_family(self):
f = feature()
f["properties"] = {"anchor_family": 9}
self.assertEqual(predicate(run(fixture([f])), "family.first_line")["status"], "PASSED")
def test_coordinates_forbidden_even_with_valid_key(self):
f = feature()
f["geometry"]["coordinates"] = [0, 0]
report = run(fixture([f]))
self.assertEqual(predicate(report, "geometry.key_only")["status"], "FAILED")
self.assertEqual(report["rows"][0]["coverage"]["structurally_valid_features"], 0)
def test_stale_manifest_count_hash_bytes(self):
def corrupt(m):
m["layers"][0].update(features=2, bytes=1, sha256="0" * 64)
report = run(fixture(), manifest_edit=corrupt)
for name in ("manifest.features", "manifest.bytes", "manifest.sha256"):
self.assertEqual(predicate(report, name)["status"], "FAILED")
def test_duplicate_manifest_ids(self):
def duplicate(m):
m["layers"].append(copy.deepcopy(m["layers"][0]))
report = run(fixture(), manifest_edit=duplicate)
self.assertEqual(len(report["rows"]), 2)
self.assertTrue(all(r["status"] == "CONTRADICTED" for r in report["rows"]))
def test_duplicate_feature_ids(self):
f, g = feature(), feature(102)
f["id"] = g["id"] = "a"
report = run(fixture([f, g]))
self.assertEqual(predicate(report, "features.unique_ids")["failed"], 2)
def test_honest_empty_disclosed(self):
doc = fixture([], evidence="The register has no exact anchor; no marks are placed.")
doc["stats"]["why"] = "No exact numbered anchor exists in the supplied register."
report = run(doc)
row = report["rows"][0]
self.assertEqual(row["coverage"]["features"], 0)
self.assertEqual(row["status"], "NOT EVALUATED")
self.assertEqual(row["disclosed"][0]["status"], "DISCLOSED")
self.assertEqual(predicate(report, "stats.features")["status"], "PASSED")
def test_disclosure_does_not_waive_bad_key(self):
doc = fixture([feature(999)])
doc["stats"]["unanchored"] = [{"reason": "The target is unknown"}]
report = run(doc)
self.assertEqual(report["rows"][0]["status"], "CONTRADICTED")
self.assertEqual(len(report["rows"][0]["disclosed"]), 1)
def test_unresolved_disclosure_exact_field(self):
doc = fixture()
doc["stats"]["unresolved"] = [12, 13]
self.assertEqual(run(doc)["rows"][0]["disclosed"][0]["field"], "stats.unresolved")
def test_issued_keys_reject_non_uint32_values(self):
report = run(fixture(), keys=[101, 102, 103, 0x100000000, True, -1])
self.assertEqual(report["input_checks"][1]["status"], "FAILED")
self.assertEqual(report["inputs"]["issued_keys"], 3)
def test_cli_refuses_existing_output_before_reading_inputs(self):
existing = Path(__file__)
before = existing.read_bytes()
with self.assertRaises(SystemExit) as result:
main(["--manifest", "unused", "--layers-map", "unused", "--issued-keys", "unused", "--output", str(existing)])
self.assertEqual(result.exception.code, 2)
self.assertEqual(existing.read_bytes(), before)
def test_unsupported_prose_is_verbatim_and_not_honoured(self):
prose = "Every function is safe and all outcomes have been established."
report = run(fixture(evidence=prose))
row = report["rows"][0]
self.assertNotEqual(row["status"], "HONOURED")
self.assertEqual(row["not_evaluated"][0]["text"], prose)
def test_copying_does_not_trust_same_feature_fields(self):
f = feature()
f["properties"] = {"families": 2, "chars": 30}
report = run(fixture([f], COPYING))
self.assertEqual(predicate(report, "copying.owner_count")["status"], "NOT EVALUATED")
self.assertEqual(predicate(report, "copying.minimum_length")["status"], "NOT EVALUATED")
def test_copying_independent_both_predicates(self):
f = feature()
f["properties"] = {"families": 2, "chars": 30}
report = run(fixture([f], COPYING), independent_lines={101: {"owners": [9, 10], "owners_complete": True, "chars": 15}}, families=[{"n": 9, "lines": [101, 102, 103]}, {"n": 10, "lines": [101]}])
self.assertEqual(report["rows"][0]["status"], "HONOURED")
self.assertNotIn("UNDERCLAIMED", json.dumps(report))
def test_copying_independent_detects_short_and_one_owner(self):
report = run(fixture(evidence=COPYING), independent_lines={101: {"owners": [9], "owners_complete": True, "chars": 4}})
self.assertEqual(predicate(report, "copying.owner_count")["status"], "FAILED")
self.assertEqual(predicate(report, "copying.minimum_length")["status"], "FAILED")
def test_route_numbering_array_not_numeric_sort(self):
route = {"type": "Feature", "geometry": {"type": "LineString", "keys": [103, 101, 103]}, "properties": {"family": 9, "route": ROUTE}}
report = run(fixture([route]), families=[{"n": 9, "lines": [103, 101, 103]}])
self.assertEqual(predicate(report, "family.numbering_order")["status"], "PASSED")
route["geometry"]["keys"] = [101, 103, 103]
p = predicate(run(fixture([route]), families=[{"n": 9, "lines": [103, 101, 103]}]), "family.numbering_order")
self.assertEqual(p["status"], "FAILED")
self.assertEqual(p["first_deviation"]["field"], "geometry.keys[0]")
def test_module_counts_need_independent_register(self):
text = "the live block register: block Ga #14, 1 named families, 3 numbered lines, repository Public/repo"
doc = fixture(evidence=text)
doc["stats"].update(families=1, lines=3)
report = run(doc)
self.assertTrue(any("independent block register" in x["reason"] for x in report["rows"][0]["not_evaluated"]))
independent = {"blocks": [{"symbol": "Ga", "number": 14, "inside": [{"family": 9}], "repos": ["Public/repo"]}]}
report = run(doc, block_register=independent)
self.assertEqual(predicate(report, "module.named_families")["status"], "PASSED")
self.assertEqual(predicate(report, "module.numbered_lines")["status"], "PASSED")
def test_unknown_family_is_unevaluated(self):
report = run(fixture([feature(family=10)]))
p = predicate(report, "family.first_line")
self.assertEqual((p["checked"], p["total"], p["status"]), (0, 1, "NOT EVALUATED"))
def test_duplicate_family_metadata_is_not_resolved_arbitrarily(self):
report = run(fixture(), families=[{"n": 9, "lines": [101]}, {"n": 9, "lines": [102]}])
self.assertEqual(predicate(report, "family.first_line")["status"], "NOT EVALUATED")
self.assertEqual(len(report["inputs"]["family_input_issues"]), 2)
def test_deterministic_json_and_inputs_unchanged(self):
doc = fixture()
before = copy.deepcopy(doc)
a, b = run(doc), run(doc)
self.assertEqual(json.dumps(a, sort_keys=True, allow_nan=False), json.dumps(b, sort_keys=True, allow_nan=False))
self.assertEqual(doc, before)
serialized = json.dumps(a)
self.assertNotIn("C:\\", serialized)
self.assertNotIn("AppData", serialized)
if __name__ == "__main__":
unittest.main()Test V2 Contract
A test in the iterations folder of Galaxies Wafers that checks Bond Validator and Test Adversarial V2. It is built from the v2 contract tests class (`V2ContractTests`).
testgalaxies-wafers / iterations/11-the-bond/test_v2_contract.py · lines 1–89 of 89 · Entry point
- What it does
- It tests its inputs. Defines 13 functions or classes, including pred, V2ContractTests, test_report_schema_is_compatible_and_validator_version_separate, test_complete_owner_index_with_canonical_string_key_passes, test_complete_flag_with_missing_owner_array_stays_unevaluated. Uses libraries json, unittest.
- Downstream impact
- It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/11-the-bond/.
- What it achieves
- Defines `pred`, `V2ContractTests`, `test_report_schema_is_compatible_and_validator_version_separate` and 10 more.
- Why it matters
- Guards the behaviour of Bond Validator and Test Adversarial V2.
- Application
- galaxies-wafers · iterations/11-the-bond · test
- Uses
- Bond Validator (import), Test Adversarial V2 (import), json, unittest
- Used by
- none found
- Produces
- pred, V2ContractTests
- Defines here
- pred, V2ContractTests, test_report_schema_is_compatible_and_validator_version_separate, test_complete_owner_index_with_canonical_string_key_passes, test_complete_flag_with_missing_owner_array_stays_unevaluated, test_declared_complete_list_cannot_omit_an_observed_owner, test_repeated_key_in_one_family_counts_as_one_owner, test_over_forty_observed_owners_fails_without_an_owner_map, test_two_observed_owners_without_completeness_do_not_prove_bound, test_module_has_explicit_missing_coverage_even_when_exact, test_family_array_unissued_keys_are_input_failure, test_malformed_optional_tables_never_throw, test_malformed_raw_bytes_and_family_line_sequence_return_issues
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/11-the-bond/test_v2_contract.py:1-89 · blob 08a70ba8e9f6666cdfe9f1ee81416d18b73a87c7 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: unknown
import json
import unittest
from bond_validator import audit as core_audit
from test_adversarial_v2 import audit, copy_doc, module_doc, point, route, register, row
def pred(result, ident):
return next(p for p in row(result)["predicates"] if p["id"] == ident)
class V2ContractTests(unittest.TestCase):
def test_report_schema_is_compatible_and_validator_version_separate(self):
result = audit(copy_doc())
self.assertEqual(result["schema"], "bond.v1")
self.assertEqual(result["validator_version"], "2.0.0")
def test_complete_owner_index_with_canonical_string_key_passes(self):
result = audit(copy_doc(), independent={"101": {"owners": [9, 10], "owners_complete": True, "chars": 12}})
self.assertEqual(row(result)["status"], "HONOURED")
def test_complete_flag_with_missing_owner_array_stays_unevaluated(self):
result = audit(copy_doc(), independent={101: {"owners": [9, 99], "owners_complete": True, "chars": 12}})
self.assertEqual(pred(result, "copying.owner_count")["status"], "NOT EVALUATED")
self.assertNotEqual(row(result)["status"], "HONOURED")
def test_declared_complete_list_cannot_omit_an_observed_owner(self):
result = audit(copy_doc(), independent={101: {"owners": [9], "owners_complete": True, "chars": 12}})
self.assertEqual(pred(result, "copying.complete_owner_consistency")["status"], "FAILED")
self.assertEqual(row(result)["status"], "CONTRADICTED")
def test_repeated_key_in_one_family_counts_as_one_owner(self):
families = [{"n": 9, "lines": [101, 101, 101]}, {"n": 10, "lines": [101]}]
result = audit(copy_doc(), families=families, independent={101: {"owners": [9, 10], "owners_complete": True, "chars": 12}})
self.assertEqual(pred(result, "copying.owner_count")["status"], "PASSED")
self.assertEqual(row(result)["coverage"]["copying_owner_memberships_total"], 2)
def test_over_forty_observed_owners_fails_without_an_owner_map(self):
result = audit(copy_doc(), families=[{"n": n, "lines": [101]} for n in range(1, 42)])
self.assertEqual(pred(result, "copying.owner_count")["status"], "FAILED")
self.assertEqual(row(result)["status"], "CONTRADICTED")
def test_two_observed_owners_without_completeness_do_not_prove_bound(self):
result = audit(copy_doc(), independent={101: {"owners": [9, 10], "chars": 12}})
self.assertEqual(pred(result, "copying.owner_count")["status"], "NOT EVALUATED")
def test_module_has_explicit_missing_coverage_even_when_exact(self):
result = audit(module_doc([point(), route()]), blocks=register())
coverage = pred(result, "module.rendered_coverage")
self.assertEqual((coverage["checked"], coverage["total"], coverage["status"]), (0, 1, "NOT EVALUATED"))
self.assertEqual(row(result)["status"], "PARTIALLY EVALUATED")
def test_family_array_unissued_keys_are_input_failure(self):
result = audit(copy_doc(), families=[{"n": 9, "lines": [999]}])
self.assertEqual(next(p for p in result["input_checks"] if p["id"] == "inputs.family_arrays")["status"], "FAILED")
def test_malformed_optional_tables_never_throw(self):
malformed_blocks = [[], 1, "x", {"blocks": None}, {"blocks": 1}, {"blocks": [None]}, {"Ga": None}, {"blocks": [{"symbol": "Ga", "inside": [{"family": []}]}]}, {"blocks": [{"symbol": "Ga", "inside": [], "repos": None}]}]
for value in malformed_blocks:
with self.subTest(input="block_register", value=value):
result = audit(module_doc([point()]), blocks=value)
self.assertTrue(any(p["status"] == "FAILED" for p in result["input_checks"]))
json.dumps(result, allow_nan=False)
malformed_lines = [[], 1, "x", {101: None}, {101: []}, {101: {"owners": None}}, {101: {"owners": [True, 2]}}, {101: {"owners": [1, 1]}}, {101: {"owners": [{}, 2]}}, {101: {"chars": "12"}}, {101: {"owners_complete": "true"}}, {"0101": {}}, {0: {}}, {101: {}, "101": {}}]
for value in malformed_lines:
with self.subTest(input="independent_lines", value=value):
result = audit(copy_doc(), independent=value)
self.assertTrue(any(p["status"] == "FAILED" for p in result["input_checks"]))
self.assertNotEqual(row(result)["status"], "HONOURED")
json.dumps(result, allow_nan=False)
for value in [1, "x", {"families": 1}, [{"n": []}], [{"n": -1, "lines": [101]}]]:
with self.subTest(input="families", value=value):
result = audit(copy_doc(), families=value)
self.assertTrue(result["inputs"]["family_input_issues"])
json.dumps(result, allow_nan=False)
def test_malformed_raw_bytes_and_family_line_sequence_return_issues(self):
for value in [1, [], "x", {"copying": "not bytes"}]:
with self.subTest(input="raw_bytes", value=value):
result = core_audit({"substrate": "wafer.v1", "layers": []}, {}, [101], raw_bytes=value)
self.assertTrue(result["inputs"]["optional_input_issues"])
for value in [1, {}, "x", b"binary"]:
with self.subTest(input="family_lines", value=value):
result = core_audit({"substrate": "wafer.v1", "layers": []}, {}, [101], [{"n": 9, "lineOffset": 0, "lineCount": 1}], value)
self.assertTrue(result["inputs"]["family_input_issues"])
if __name__ == "__main__":
unittest.main()Test Verify Bundle
A test in the iterations folder of Galaxies Wafers that checks Verify Bundle, using SHA-256. It sets up (`setUp`) and saves report (`save_report`).
testgalaxies-wafers / iterations/11-the-bond/test_verify_bundle.py · lines 1–204 of 204 · Entry point · pattern runner (shared by 3 files)
- What it does
- It tests its inputs. Defines 34 functions or classes, including report_fixture, successes, ReportChecks, test_partial_and_not_evaluated_rows_are_valid_reports, test_honest_contradiction_is_valid_report. Uses libraries copy, hashlib, json, pathlib, subprocess. Side effects: reads or writes files; starts processes.
- Inputs & outputs
- In: JSON file report.json; JSON file receipt.json; JSON file existing.json. Out: JSON file report.json.
- Downstream impact
- It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/11-the-bond/.
- What it achieves
- Defines `report_fixture`, `successes`, `ReportChecks` and 31 more. It writes `report.json`.
- Why it matters
- Guards the behaviour of Verify Bundle.
- Application
- galaxies-wafers · iterations/11-the-bond · test
- Uses
- Verify Bundle (import), copy, hashlib, json, pathlib, subprocess, tempfile, unittest, unittest.mock
- Used by
- none found
- Produces
- report_fixture, successes, ReportChecks, BundleChecks
- Defines here
- report_fixture, successes, ReportChecks, test_partial_and_not_evaluated_rows_are_valid_reports, test_honest_contradiction_is_valid_report, test_short_commit_fails, test_source_input_must_be_evaluated_and_passed, test_passed_input_with_incomplete_denominator_fails, test_optional_source_issues_fail, test_advertised_aggregate_count_mismatch_fails, test_status_count_type_and_value_mismatch_fail, test_row_count_mismatch_fails, test_contradiction_cannot_be_hidden_as_honoured, test_duplicate_layer_ids_fail, BundleChecks, setUp, tearDown, save_report, runner, verify, test_good_bundle_passes_with_relative_hashes_only, test_canonical_pin_normalizes_crlf_only, test_report_digest_uses_exact_bytes, test_optional_contradiction_gate, test_node_runtime_disagreement_fails, runner, test_missing_browser_entrypoint_fails, test_timeout_and_no_test_count_fail, runner, test_evidence_output_is_excluded_from_hash_inventory
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/11-the-bond/test_verify_bundle.py:1-204 · blob adc7c3e88f90bf12d8b1da7be879d20aeb2e4e6d · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem, process · domain stage: unknown · users: none · canonical: unknown
import copy
import hashlib
import json
from pathlib import Path
import subprocess
import tempfile
import unittest
from unittest.mock import patch
import verify_bundle as verifier
def report_fixture(status="PARTIALLY EVALUATED"):
pending = status in ("PARTIALLY EVALUATED", "NOT EVALUATED")
failed = status == "CONTRADICTED"
predicate = {"id": "fixture", "text": "A public fixture", "status": "FAILED" if failed else "NOT EVALUATED" if pending else "PASSED", "checked": 0 if pending else 1, "total": 1, "passed": 0 if pending or failed else 1, "failed": int(failed), "first_deviation": None}
row = {"layer_id": "example", "status": status, "predicates": [predicate], "not_evaluated": [{"field": "layer.evidence", "text": "A source claim", "reason": "Outside the fixture"}] if pending else [], "disclosed": [], "coverage": {"checks_evaluated": predicate["checked"], "checks_total": 1, "predicates": 1, "predicates_passed": int(predicate["status"] == "PASSED"), "predicates_failed": int(fai … [line shortened here: 502 characters; full line on GitHub]
input_check = {"id": "inputs", "status": "PASSED", "checked": 1, "total": 1, "passed": 1, "failed": 0}
return {"schema": "bond.v1", "rows": [row], "input_checks": [input_check], "inputs": {"family_input_issues": []}, "provenance": {"repo": verifier.SOURCE_REPO, "commit": "a" * 40, "manifest_sha256": "b" * 64, "sources": [{"commit": "c" * 40, "sha256": "d" * 64, "git_blob": "e" * 40, "bytes": 4}]}, "coverage": {"manifest_entries": 1, "layers_reported": 1, "features": 2, "key_references": 3, "che … [line shortened here: 524 characters; full line on GitHub]
def successes(checks):
return all(c["status"] == "PASSED" for c in checks)
class ReportChecks(unittest.TestCase):
def test_partial_and_not_evaluated_rows_are_valid_reports(self):
for status in ("PARTIALLY EVALUATED", "NOT EVALUATED"):
with self.subTest(status=status):
checks, summary, _ = verifier.inspect_report(report_fixture(status))
self.assertTrue(successes(checks))
self.assertEqual(summary["statuses"][status], 1)
def test_honest_contradiction_is_valid_report(self):
self.assertTrue(successes(verifier.inspect_report(report_fixture("CONTRADICTED"))[0]))
def test_short_commit_fails(self):
report = report_fixture()
report["provenance"]["commit"] = "abc123"
self.assertFalse(successes(verifier.inspect_report(report)[0]))
def test_source_input_must_be_evaluated_and_passed(self):
for status in ("FAILED", "NOT EVALUATED"):
report = report_fixture()
report["input_checks"][0]["status"] = status
self.assertFalse(successes(verifier.inspect_report(report)[0]))
def test_passed_input_with_incomplete_denominator_fails(self):
report = report_fixture()
report["input_checks"][0]["total"] = 2
self.assertFalse(successes(verifier.inspect_report(report)[0]))
def test_optional_source_issues_fail(self):
report = report_fixture()
report["inputs"]["optional_input_issues"] = [{"reason": "invalid source"}]
self.assertFalse(successes(verifier.inspect_report(report)[0]))
def test_advertised_aggregate_count_mismatch_fails(self):
for field in ("features", "key_references", "checks_evaluated", "checks_total", "layers_reported"):
report = report_fixture()
report["coverage"][field] += 1
self.assertFalse(successes(verifier.inspect_report(report)[0]))
def test_status_count_type_and_value_mismatch_fail(self):
for value in (True, 2):
report = report_fixture()
report["coverage"]["status_counts"]["PARTIALLY EVALUATED"] = value
self.assertFalse(successes(verifier.inspect_report(report)[0]))
def test_row_count_mismatch_fails(self):
report = report_fixture()
report["rows"][0]["coverage"]["checks_total"] = 2
self.assertFalse(successes(verifier.inspect_report(report)[0]))
def test_contradiction_cannot_be_hidden_as_honoured(self):
report = report_fixture("CONTRADICTED")
report["rows"][0]["status"] = "HONOURED"
self.assertFalse(successes(verifier.inspect_report(report)[0]))
def test_duplicate_layer_ids_fail(self):
report = report_fixture()
report["rows"].append(copy.deepcopy(report["rows"][0]))
self.assertFalse(successes(verifier.inspect_report(report)[0]))
class BundleChecks(unittest.TestCase):
def setUp(self):
# Temporary fixture writes stay under this verifier's own directory.
self.temp = tempfile.TemporaryDirectory(prefix="verifier-fixture-", dir=Path(__file__).parent)
self.root = Path(self.temp.name).resolve()
self.report = report_fixture()
self.wafer = b"export const frozen = 1;\n"
for name in verifier.REQUIRED_FILES:
(self.root / name).write_bytes(self.wafer if name == "wafer.mjs" else b"// fixture\n")
(self.root / "test_sample.py").write_text("# fixture\n", encoding="utf-8")
self.save_report()
self.pin = patch.object(verifier, "CANONICAL_WAFER_LF_SHA256", hashlib.sha256(self.wafer).hexdigest())
self.pin.start()
self.calls = []
def tearDown(self):
self.pin.stop()
self.assertEqual(self.root.parent, Path(__file__).parent.resolve())
self.temp.cleanup()
def save_report(self):
(self.root / "report.json").write_text(json.dumps(self.report), encoding="utf-8")
def runner(self, argv, cwd, timeout):
self.calls.append((argv, cwd, timeout))
out = {"exit_code": 0, "timed_out": False, "available": True, "duration_ms": 1, "stdout": b"", "stderr": b"private machine path must stay out of receipt\n"}
if "unittest" in argv:
out["stderr"] += b"Ran 3 tests in 0.001s\nOK\n"
elif "--test" in argv:
out["stdout"] = b"# tests 2\n# pass 2\n# fail 0\n# cancelled 0\n# skipped 0\n# todo 0\n"
elif "--input-type=module" in argv:
out["stdout"] = json.dumps(verifier.inspect_report(self.report)[1]).encode()
return out
def verify(self, **kwargs):
return verifier.verify_bundle(self.root, runner=self.runner, **kwargs)
def test_good_bundle_passes_with_relative_hashes_only(self):
result = self.verify()
self.assertEqual(result["status"], "PASSED")
self.assertTrue(all("/" not in a["file"] and "\\" not in a["file"] for a in result["artifacts"]))
text = json.dumps(result)
self.assertNotIn(str(self.root), text)
self.assertNotIn("private machine path", text)
self.assertTrue(all(call[2] == 60 for call in self.calls))
def test_canonical_pin_normalizes_crlf_only(self):
(self.root / "wafer.mjs").write_bytes(self.wafer.replace(b"\n", b"\r\n"))
self.assertEqual(self.verify()["status"], "PASSED")
(self.root / "wafer.mjs").write_bytes(self.wafer.replace(b"\n", b"\r"))
self.assertEqual(self.verify()["status"], "FAILED")
def test_report_digest_uses_exact_bytes(self):
first = self.verify()
(self.root / "report.json").write_bytes((self.root / "report.json").read_bytes() + b"\n")
second = self.verify()
get_hash = lambda r: next(a["sha256"] for a in r["artifacts"] if a["file"] == "report.json")
self.assertNotEqual(get_hash(first), get_hash(second))
def test_optional_contradiction_gate(self):
self.report = report_fixture("CONTRADICTED")
self.save_report()
self.assertEqual(self.verify()["status"], "PASSED")
self.assertEqual(self.verify(fail_on_contradiction=True)["status"], "FAILED")
def test_node_runtime_disagreement_fails(self):
def runner(argv, cwd, timeout):
result = self.runner(argv, cwd, timeout)
if "--input-type=module" in argv:
result["stdout"] = b"{}"
return result
self.assertEqual(verifier.verify_bundle(self.root, runner=runner)["status"], "FAILED")
def test_missing_browser_entrypoint_fails(self):
(self.root / "index.html").unlink()
result = self.verify()
self.assertEqual(result["status"], "FAILED")
self.assertEqual(next(c for c in result["checks"] if c["id"] == "bundle.required_files")["status"], "FAILED")
def test_timeout_and_no_test_count_fail(self):
def runner(argv, cwd, timeout):
result = self.runner(argv, cwd, timeout)
if "unittest" in argv:
result.update(exit_code=None, timed_out=True, stdout=b"", stderr=b"")
return result
self.assertEqual(verifier.verify_bundle(self.root, runner=runner)["status"], "FAILED")
def test_evidence_output_is_excluded_from_hash_inventory(self):
output = self.root / "receipt.json"
output.write_text("{}", encoding="utf-8")
result = self.verify(excluded_paths=[output])
self.assertNotIn("receipt.json", [a["file"] for a in result["artifacts"]])
def test_bundle_mutation_during_checks_fails(self):
def runner(argv, cwd, timeout):
result = self.runner(argv, cwd, timeout)
if "unittest" in argv:
(self.root / "model.mjs").write_text("// changed", encoding="utf-8")
return result
self.assertEqual(verifier.verify_bundle(self.root, runner=runner)["status"], "FAILED")
def test_existing_output_is_not_overwritten(self):
output = self.root / "existing.json"
output.write_text("preserve", encoding="utf-8")
with self.assertRaises(SystemExit) as error:
verifier.main(["--version-dir", str(self.root), "--output", str(output)])
self.assertEqual(error.exception.code, 2)
self.assertEqual(output.read_text(), "preserve")
def test_subprocess_timeout_is_bounded_and_sanitized(self):
with patch.object(verifier.subprocess, "run", side_effect=subprocess.TimeoutExpired(["python"], 1, output=b"private path")):
result = verifier.run_process(["python"], self.root, 1)
public = verifier._public_process(result)
self.assertTrue(public["timed_out"])
self.assertNotIn("private path", json.dumps(public))
if __name__ == "__main__":
unittest.main()