lingologos-struc / tests /test_protocol.py
tailot's picture
update structures bundle
f317f7f verified
Raw History Blame Contribute Delete
7.79 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 -- a
reaction of 45 over 2 must arrive as 45 over 2, not as 22.5 -- and the memory of what the earlier
nodes saw, because a chain that forgets the road the solver of the forces reported cannot compare the
two roads any more.
"""
import json
import re
from fractions import Fraction
from pathlib import Path
import pytest
from lgstruc import agents, pipeline, protocol, smt
ROOT = Path(__file__).resolve().parents[1]
BEAM = ("reactions frame nodes [ 1 0 0 ; 2 2 0 ; 3 4 0 ] members [ 1 1 2 ; 2 2 3 ] "
"props [ 1 210000000 1/5 2/1875 ; 2 210000000 1/5 2/1875 ] "
"supports [ 1 pin ; 3 roller 0 1 ] loads [ member 1 udl 0 -15 ; member 2 udl 0 -15 ]")
GOLD = {"reactions": {"1_first": "0", "1_second": "30", "3_second": "30"}}
def _chain(question: str):
"""Run the thirteen 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"] = "StructureProblem " + question
handed, envelopes = seed, []
for name in agents.ALL_AGENTS:
handed = protocol.respond(name, handed, name)
envelopes.append(handed)
return envelopes
def _plain_json(value: object) -> str:
"""The JSON an envelope carries: rationals as exact strings, so two answers can be compared."""
return json.dumps(value, sort_keys=True, default=protocol.plain)
def test_a_fraction_survives_the_trip_unchanged():
dossier = protocol.start(BEAM)
dossier["roads"] = {"forces": Fraction(45, 2), "stiffness": Fraction(45, 2)}
text = protocol.encode(BEAM, dossier)
assert "45/2" in text
assert not re.search(r"\d+\.\d", text), "a decimal point in an exact rational"
problem, back = protocol.decode(text)
assert problem == BEAM
assert Fraction(back["roads"]["forces"]) == Fraction(45, 2)
assert Fraction(back["roads"]["stiffness"]) == Fraction(45, 2)
def test_the_marker_keeps_the_prose_and_the_memory_apart():
text = protocol.encode(BEAM, protocol.start(BEAM))
assert text.startswith(BEAM + "\n" + protocol.MARK)
assert text.count(protocol.MARK) == 1
def test_a_payload_without_the_marker_is_an_idle_seed_and_not_an_error():
problem, dossier = protocol.decode("Idle until the problem arrives.")
assert problem == "Idle until the problem arrives."
assert dossier == {}
def test_an_envelope_carries_the_three_parts_of_a_claim():
claim = (["(declare-const reaction_1_second Real)"],
["(assert (= reaction_1_second (/ 30 1)))"], "sat")
envelope = protocol.envelope("reader_a", "arbiter", 3, 7, BEAM, protocol.start(BEAM), 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("StructureProblem")
assert payload["smtConstraints"] == {"declarations": [claim[0][0]], "assertions": [claim[1][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, BEAM, protocol.start(BEAM),
([], ["(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, *rest):
raise ZeroDivisionError("the reading fell over")
monkeypatch.setattr(agents, "run_step", explode)
handed = protocol.envelope("solver_a", "coverage", 9, 5, BEAM, protocol.start(BEAM),
([], ["(assert true)"], "sat"))
outgoing = protocol.respond("solver_a", handed, "solver_a")
_problem, dossier = protocol.decode(outgoing["payload"]["naturalLanguage"])
assert "ZeroDivisionError" in dossier["crash"]["solver_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: thirteen nodes and one question."""
return _chain(BEAM)
@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_no_envelope_of_the_chain_crashed(envelopes):
for name, envelope in zip(agents.ALL_AGENTS, envelopes):
_problem, dossier = protocol.decode(envelope["payload"]["naturalLanguage"])
assert not dossier.get("crash"), (name, dossier.get("crash"))
def test_the_chain_hands_the_same_answer_through_envelopes_as_in_one_process(carried):
inside = pipeline.run(BEAM)
# Inside one process the notebook holds rationals; through envelopes it holds their exact textual
# form. The answer is the same answer, and that is what a reader of the transcript sees.
assert _plain_json(carried.get("answer")) == _plain_json(inside["dossier"].get("answer"))
assert sorted(carried.get("states")) == sorted(inside["dossier"].get("states"))
# Only the nine nodes that hand something on report a state; the four who stand guard
# over the assumptions stay silent unless they have a doubt to raise.
assert len(carried.get("states")) == 9
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"] == agents.VERIFIED, decision
assert decision["assurance"] == 2
# The gold line of the corpus, reached by thirteen envelopes instead of one interpreter.
assert decision["detail"] == ("reaction at 1 first is 0; reaction at 1 second is 30; "
"reaction at 3 second is 30")
assert _plain_json(carried["answer"]["reactions"]) == _plain_json(GOLD["reactions"])