Something went wrong. Try again.
small gleam coding and persistent agent daemon with a detachable cli and a canvas ui forked from okami.mom/albedo
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177"""Remote values cross a JSON boundary between Python runtimes.
A remote call's result is encoded by the remote kernel, sent through its linkand decoded by the local one; it must read exactly like the same call madelocally. A value that cannot cross stays a live reference (Unencodable), andwhatever a peer sends decodes or raises InvalidValue, never anything else."""
from collections.abc import Sequencefrom dataclasses import dataclassimport jsonimport mathfrom pathlib import Pathimport sysfrom typing import castimport unittest
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "python"))sys.path.insert(0, str(Path(__file__).resolve().parents[1]))import albedo_link # noqa: E402from albedo_api import Record # noqa: E402import hypothesis_profiles # noqa: E402from hypothesis import given, settings, strategies as st # noqa: E402from albedo_values import InvalidValue, Unencodable, decode, encode # noqa: E402
# Keys and text that look like the codec's own markers, and lone surrogates.MARKERS = ["__bytes__", "__class__", "__record__", "__list__", "__float__"]MARKERS += ["__str__", "fields", "items"]texts = st.text(max_size=6) | st.sampled_from(MARKERS) | st.just("/tmp/\udcff")scalars = ( st.none() | st.booleans() | st.integers() | st.floats() | texts | st.binary(max_size=8))keys = texts | st.integers(-3, 3) | st.booleans() | st.none()
@dataclassclass Row: """A typed result, rebuilt by its class name on the caller's side."""
count: object
values = st.recursive( scalars, lambda inner: ( st.lists(inner, max_size=3) | st.lists(inner, max_size=3).map(tuple) | st.dictionaries(keys, inner, max_size=3) | st.builds(Row, inner) | st.dictionaries(st.text(max_size=4), inner, max_size=3).map(Record) ), max_leaves=10,)
def same(a: object, b: object) -> bool: """Equality that also holds for NaN and keeps bool, int and float apart.""" if type(a) is not type(b): return False if isinstance(a, float): return a == b or (math.isnan(a) and math.isnan(cast(float, b))) if isinstance(a, (list, tuple)): other = cast(Sequence[object], b) return len(a) == len(other) and all(map(same, a, other)) if isinstance(a, dict): other = cast(dict[object, object], b) return list(a) == list(other) and all(same(a[k], other[k]) for k in a) if isinstance(a, Row): return same(a.count, cast(Row, b).count) return a == b
def nested(depth: int) -> object: value: object = "leaf" for _ in range(depth): value = [value] return value
class RemoteValuePropertyTests(unittest.TestCase): @settings(max_examples=hypothesis_profiles.cases(300)) @given(values) def test_a_value_crosses_the_link_unchanged_or_stays_a_reference(self, value): try: wire = encode(value) except Unencodable: return received = json.loads(albedo_link.encode(wire)) self.assertTrue(same(decode(received), value), (value, received))
@settings(max_examples=hypothesis_profiles.cases(200)) @given( st.recursive( st.none() | st.booleans() | st.integers() | st.floats() | texts, lambda inner: ( st.lists(inner, max_size=3) | st.dictionaries(texts, inner, max_size=3) ), max_leaves=12, ) ) def test_whatever_a_peer_sends_decodes_or_is_invalid(self, wire): try: decode(wire) except InvalidValue: pass
class RemoteValueTests(unittest.TestCase): def test_plain_dict_keeps_keys_that_resemble_output_page_fields(self) -> None: value = {"__output_page__": "x", "next_offset": 4} self.assertEqual(decode(json.loads(json.dumps(encode(value)))), value)
def test_a_dict_keeps_keys_json_objects_cannot_hold(self) -> None: # A JSON object's keys are strings: these came back as {"None": 1}, # {"1": "a", "False": "b"} and a key the link refused. for value in ( {None: 1}, {1: "a", False: "b", 2.5: "c", (1, "x"): "d", b"k": "e"}, {"/tmp/\udcff": None}, ): with self.subTest(value=value): wire = json.loads(albedo_link.encode(encode(value))) self.assertEqual(decode(wire), value)
def test_a_dict_shaped_like_a_marker_stays_a_dict(self) -> None: # These decoded as bytes, an object built from a class name, a # record, or a list. for value in ( {"__bytes__": ""}, {"__class__": "builtins.dict", "fields": {}}, {"__record__": "x", "fields": {}}, {"__list__": "builtins.list", "items": []}, {"__dict__": []}, ): with self.subTest(value=value): wire = json.loads(albedo_link.encode(encode(value))) self.assertEqual(decode(wire), value)
def test_a_peer_cannot_send_an_unhashable_dict_key(self) -> None: with self.assertRaises(InvalidValue): decode({"__dict__": [[[1], 2]]})
def test_whatever_nests_shallow_enough_to_encode_also_decodes(self) -> None: # Every depth around the cap, as lists, dicts and typed values: an # encode cap past the decoder's would send what the caller refuses. for depth in range(28, 38): for wrap in (lambda v: [v], lambda v: {"k": v}, Row): value: object = "leaf" for _ in range(depth): value = wrap(value) try: wire = encode(value) except Unencodable: continue self.assertTrue(same(decode(json.loads(json.dumps(wire))), value))
def test_nesting_beyond_the_encode_cap_cannot_encode(self) -> None: with self.assertRaises(Unencodable): encode(nested(40))
def test_deeply_nested_wire_input_raises_invalid_value(self) -> None: # A hostile or buggy peer can send nesting `encode` never produces; # decoding it must refuse, not exhaust the stack. with self.assertRaises(InvalidValue) as raised: decode(json.loads(json.dumps(nested(40)))) self.assertIn("nests too deeply", str(raised.exception))
def test_decode_of_legal_shapes_still_reaches_the_cap_and_no_earlier(self) -> None: self.assertEqual(decode(nested(32)), nested(32)) with self.assertRaises(InvalidValue): decode(nested(40))