"""Remote values cross a JSON boundary between Python runtimes. A remote call's result is encoded by the remote kernel, sent through its link and decoded by the local one; it must read exactly like the same call made locally. A value that cannot cross stays a live reference (Unencodable), and whatever a peer sends decodes or raises InvalidValue, never anything else. """ from collections.abc import Sequence from dataclasses import dataclass import json import math from pathlib import Path import sys from typing import cast import 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: E402 from albedo_api import Record # noqa: E402 import hypothesis_profiles # noqa: E402 from hypothesis import given, settings, strategies as st # noqa: E402 from 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() @dataclass class 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))