lingologos-physics / tests /test_protocol.py
tailot's picture
update physics bundle
875f067 verified
Raw History Blame Contribute Delete
6.17 kB
"""The envelope of one turn: what a node receives, what it hands back, and what survives the trip.
A dossier is a nest of exact rationals, and the channel between two nodes is a JSON string inside a
natural language field. The two things that have to survive that trip are the value of a number and
the memory of what the earlier nodes saw, so these tests watch both closely: a number that arrives
rounded, or a dossier that arrives with the earlier turns forgotten, would silently turn a verified
answer into an unsupported one.
"""
import json
import re
from fractions import Fraction
from pathlib import Path
import pytest
from lgphys import agents, families, pipeline, protocol, smt
ROOT = Path(__file__).resolve().parents[1]
CONVERT = "convert 5 km/h to m/s"
def _chain(question: str):
"""Run the eleven nodes the way the orchestrator would, one envelope at a time."""
seed = json.loads((ROOT / "nodes" / "arbiter" / "seed_payload.json").read_text(encoding="utf-8"))
seed["payload"]["naturalLanguage"] = question
seed["payload"]["abstractSyntaxTree"] = "PhysicsProblem " + question
handed, envelopes = seed, []
for name in agents.ALL_AGENTS:
handed = protocol.respond(name, handed, name)
envelopes.append(handed)
return envelopes
def test_a_fraction_survives_the_trip_unchanged():
dossier = protocol.start(CONVERT)
dossier["roads"] = {"read_a": Fraction(25, 18), "read_b": Fraction(25, 18)}
text = protocol.encode(CONVERT, dossier)
assert "25/18" in text
assert not re.search(r"\d+\.\d", text), "a decimal point in an exact rational"
problem, back = protocol.decode(text)
assert problem == CONVERT
assert Fraction(back["roads"]["read_a"]) == Fraction(25, 18)
assert Fraction(back["roads"]["read_b"]) == Fraction(25, 18)
def test_the_marker_keeps_the_prose_and_the_memory_apart():
text = protocol.encode(CONVERT, protocol.start(CONVERT))
assert text.startswith(CONVERT + "\n" + protocol.MARK)
assert text.count(protocol.MARK) == 1
def test_an_envelope_carries_the_three_parts_of_a_claim():
claim = (["declare-fun x () Int"], ["(assert (> x 0))"], "sat")
envelope = protocol.envelope("reader_a", "arbiter", 3, 7, CONVERT, protocol.start(CONVERT), claim)
assert envelope["sender"] == "reader_a" and envelope["recipient"] == "arbiter"
assert envelope["turn"] == 3 and envelope["volatileState"]["internalTimeTick"] == 7
payload = envelope["payload"]
assert payload["abstractSyntaxTree"].startswith("PhysicsProblem")
assert payload["smtConstraints"] == {"declarations": ["declare-fun x () Int"],
"assertions": ["(assert (> x 0))"], "z3Status": "sat"}
def test_an_envelope_without_a_recipient_omits_the_field():
envelope = protocol.envelope("arbiter", None, 0, 0, "", protocol.start(""), ([], ["(assert true)"], "sat"))
assert "recipient" not in envelope
def test_a_node_echoes_the_turn_it_was_handed():
handed = protocol.envelope("reader_b", "reader_a", 4, 11, CONVERT, protocol.start(CONVERT),
([], ["(assert true)"], "sat"))
outgoing = protocol.respond("reader_a", handed, "reader_a")
# The orchestrator keeps the count of the turns; a node that booked its own turn would end the
# session early or run it past the pipeline the topology declares.
assert outgoing["turn"] == 4
assert outgoing["volatileState"]["internalTimeTick"] == 11
assert outgoing["sender"] == "reader_a" and outgoing["recipient"] == "reader_b"
def test_a_node_that_stops_leaves_a_note_instead_of_stopping_the_chain(monkeypatch):
def explode(role, dossier):
raise ZeroDivisionError("the reading fell over")
monkeypatch.setattr(agents, "run_step", explode)
handed = protocol.envelope("domain_a", "reader_b", 2, 5, CONVERT, protocol.start(CONVERT),
([], ["(assert true)"], "sat"))
outgoing = protocol.respond("domain_a", handed, "domain_a")
_problem, dossier = protocol.decode(outgoing["payload"]["naturalLanguage"])
assert "ZeroDivisionError" in dossier["crash"]["domain_a"]
assert outgoing["payload"]["smtConstraints"]["assertions"] == ["(assert true)"]
assert outgoing["payload"]["smtConstraints"]["z3Status"] == "sat"
@pytest.fixture(scope="module")
def envelopes():
"""One chain run, shared by the tests that read it: eleven nodes and one question."""
return _chain(CONVERT)
@pytest.fixture(scope="module")
def carried(envelopes):
"""The dossier as it stands in the last envelope of that chain."""
return protocol.decode(envelopes[-1]["payload"]["naturalLanguage"])[1]
@pytest.fixture(scope="module")
def referee(envelopes):
"""Each claim re-checked by Z3 over the ontology of the node that wrote it."""
checked = []
for name, envelope in zip(agents.ALL_AGENTS, envelopes):
base = (ROOT / "nodes" / name / "ontology.smt2").read_text(encoding="utf-8")
constraints = envelope["payload"]["smtConstraints"]
checked.append({"sender": name, "claimed": constraints["z3Status"],
"referee": smt.referee(base, constraints["declarations"],
constraints["assertions"])})
return checked
def test_the_chain_hands_the_same_answer_through_envelopes_as_in_one_process(carried):
assert not carried.get("crash"), carried.get("crash")
inside = pipeline.run(CONVERT)
assert carried.get("answer") == inside["dossier"].get("answer")
assert sorted(carried.get("states")) == sorted(agents.ALL_AGENTS)
def test_every_claim_holds_against_the_ontology_of_the_node_that_made_it(referee):
for record in referee:
assert record["referee"] == record["claimed"], record
def test_the_verdict_of_the_envelope_chain_is_the_verdict_of_the_session(carried, referee):
decision = pipeline.checked_verdict(carried, referee)
assert decision["status"] == "VERIFIED"
assert decision["assurance"] == 2
family = families.family_for(str(carried.get("kind")))
assert family.gold_equal(carried["answer"], {"value": "25/18", "unit": "m/s"})