"""The daemon reads every frame a kernel writes, and survives what no kernel writes. A kernel's frame the daemon misreads is dropped or misrouted: a host call that never gets its reply, a cell result lost. The two sides are different languages and JSON libraries, so only running both catches a disagreement. The reverse direction, the daemon's frames read by the kernel, is driven from Gleam (apps/albedo/test/albedo/contract/kernel_frames.gleam). """ import base64 import json import os from pathlib import Path import sys from typing import cast import unittest HERE = Path(__file__).resolve().parent sys.path.insert(0, str(HERE)) sys.path.insert(0, str(HERE.parent)) sys.path.insert(0, str(HERE.parents[1] / "python")) import hypothesis_profiles # noqa: E402,F401 from hypothesis import given, settings, strategies as st # noqa: E402 import albedo_link # noqa: E402 import kernel_frames # noqa: E402 from kernel_frames import b64, kernel_packets, near_valid_kernel_packets # noqa: E402 from support import GleamPeer # noqa: E402 # What `frame.read` calls each kernel frame type; anything else is `other`. KINDS = { "ready": "ready", "startup_error": "startup_error", "done": "done", "call": "call", "job": "job", "job_start": "job_start", "job_stop": "job_stop", "cleanup": "cleanup", "cells": "cells", "jobs": "jobs", "trace": "trace", "blob": "blob", "job_list": "answer:job_list", "job_read": "answer:job_read", "cell_claim": "answer:cell_claim", } class KernelFramesTest(unittest.TestCase): peer: GleamPeer @classmethod def setUpClass(cls) -> None: cls.peer = GleamPeer() @classmethod def tearDownClass(cls) -> None: cls.peer.close() def read(self, packets: list[bytes]) -> list[dict]: cases: list[object] = [{"packet": b64(packet)} for packet in packets] results = self.peer.call(kernel_frames.CONTRACT, "kernel_packets", cases) return [cast(dict, result) for result in results] @settings(max_examples=hypothesis_profiles.cases(25)) @given(st.lists(kernel_packets(), min_size=1, max_size=40)) def test_the_daemon_reads_every_kernel_packet(self, cases: list[dict]) -> None: results = self.read([case["packet"] for case in cases]) for case, result in zip(cases, results): self.assertEqual(result["outcome"], case["expect"], (case, result)) if case["expect"] == "framed": frame = case["frame"] self.assertEqual( (result["seq"], result["ack"]), (case["seq"], case["ack"]) ) self.assertEqual(result["kind"], KINDS.get(frame["type"], "other")) self.assertEqual(json.loads(result["frame"]), frame) data = result["data"] self.assertEqual( None if data is None else base64.b64decode(data), case.get("data") ) if frame["type"] == "done" and result["status"] is not None: self.assertEqual(result["status"], frame["status"]) elif case["expect"] == "acked": self.assertEqual(result["ack"], case["ack"]) elif case["expect"] == "pong": self.assertEqual(result["seq"], case["seq"]) else: self.assertEqual(json.loads(result["hello"]), case["hello"]) @settings(max_examples=hypothesis_profiles.cases(25)) @given(st.lists(near_valid_kernel_packets(), min_size=1, max_size=40)) def test_the_daemon_survives_packets_no_kernel_writes( self, packets: list[bytes] ) -> None: for packet, result in zip(packets, self.read(packets)): self.assertNotEqual(result["outcome"], "crashed", (packet[:200], result)) def assert_sent_or_refused(self, frames: list[dict]) -> None: """Each frame the kernel's encoder accepts is one the daemon reads. A frame the daemon cannot read makes the driver abandon the kernel with its namespace, so `albedo_link.encode` must refuse it with ValueError before it is sequenced, and the call fails in the cell. """ sent = [] for frame in frames: try: sent.append(albedo_link.envelope(1, 0, albedo_link.encode(frame))) except ValueError: continue for packet, result in zip(sent, self.read(sent)): self.assertEqual(result["outcome"], "framed", (packet[:200], result)) @settings(max_examples=hypothesis_profiles.cases(25)) @given(st.lists(kernel_frames.unreadable_call_frames, min_size=1, max_size=20)) def test_the_kernel_sends_only_frames_the_daemon_reads( self, frames: list[dict] ) -> None: self.assert_sent_or_refused(frames) def test_the_kernel_refuses_nan_infinity_and_lone_surrogates(self) -> None: # Regression for 2dc0961f9: json.dumps wrote these, OTP's json refused # them, and the driver abandoned the kernel. A surrogateescape path is # how a lone surrogate reaches a host call in practice. values = [ float("nan"), float("inf"), float("-inf"), os.fsdecode(b"/tmp/\xff"), "\ud800", ] frames = [ {"type": "call", "id": "k", "method": "files.read", "args": {"path": v}} for v in values ] for frame in frames: with self.assertRaises(ValueError, msg=repr(frame)): albedo_link.encode(frame) self.assert_sent_or_refused(frames) def test_text_a_frame_only_shows_crosses_with_lone_surrogates_replaced( self, ) -> None: # A file-change trace naming a path decoded with surrogateescape was # refused whole, and before 2dc0961f9 it made the daemon abandon the # kernel. Only a host call, whose arguments name what it acts on, is # refused instead. path = os.fsdecode(b"/tmp/\xff") trace = { "type": "trace", "id": "s/c", "trace": {"activities": [{"kind": "read", "target": path}]}, } packet = albedo_link.envelope(1, 0, albedo_link.encode_frame(trace)) [result] = self.read([packet]) self.assertEqual(result["outcome"], "framed", result) frame = json.loads(result["frame"]) self.assertEqual(frame["trace"]["activities"][0]["target"], "/tmp/\ufffd") with self.assertRaises(ValueError): albedo_link.encode_frame( { "type": "call", "id": "k", "method": "files.read", "args": {"path": path}, } ) if __name__ == "__main__": unittest.main()