"""The kernel half of the session layer, exercised frame by frame. Sequence, acknowledgement, and replay rules decide whether a reconnect loses or repeats a message, and E2E cannot choose where a connection drops. These tests drive albedo_link directly: the outbox's coalescing and bounds, replayed daemon frames, token checks, newest-attach-wins, and resending what the daemon never acknowledged, and a clip's raw parts, kept to be sent again. """ from collections.abc import Callable from pathlib import Path import hashlib import io import json import os import shutil import socket import struct import sys import tempfile import threading import unittest from unittest.mock import patch 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 import hypothesis_profiles # noqa: E402 from hypothesis import given, settings, strategies as st # noqa: E402 # Frames from every coalescing kind, on a few keys so copies replace each # other, and must-deliver kinds; padding varies the size against the bound. outbox_frames = st.builds( lambda kind, key, pad: { "type": kind, **({albedo_link.COALESCE[kind]: key} if albedo_link.COALESCE.get(kind) else {}), "id" if kind in ("done", "call", "blob") else "pad_key": key, "pad": "z" * pad, }, st.sampled_from(["mirror", "trace", "jobs", "cells", "done", "call", "blob"]), st.sampled_from(["a", "b"]), st.integers(0, 120), ) outbox_operations = st.lists( st.one_of( # A clip's part carries raw bytes after its frame, which count too. st.tuples(st.just("add"), outbox_frames, st.integers(0, 300)), st.tuples(st.just("ack"), st.integers(0, 30), st.just(0)), st.tuples(st.just("refused"), st.just({}), st.just(0)), ), max_size=30, ) class OutboxTest(unittest.TestCase): """The kernel's unacknowledged frames, against a list model. The contract (albedo_link.Outbox): a coalescing frame replaces its older unacknowledged copy; past the frame or byte bound the oldest coalescing frames go first, and a must-deliver frame goes only when nothing else is left, never the newest, each counted in `dropped`; an ack drops what it covers; a frame the encoder refuses changes nothing. """ @settings(max_examples=hypothesis_profiles.cases(200)) @given(st.integers(1, 5), st.integers(20, 400), outbox_operations) def test_the_outbox_keeps_what_the_model_keeps(self, frames, size, operations): outbox = albedo_link.Outbox(frames, size) model: list[tuple[int, object, int]] = [] # seq, coalescing key, bytes seq = dropped = 0 for operation, frame, extra in operations: if operation == "ack": outbox.ack(frame) model = [entry for entry in model if entry[0] > frame] elif operation == "refused": with self.assertRaises(ValueError): outbox.add({"type": "call", "id": "x", "nan": float("nan")}) else: payload = b"p" * extra if frame["type"] == "blob" else None seq += 1 field = albedo_link.COALESCE.get(frame["type"], False) key = None if field is not False: key = (frame["type"], frame.get(field) if field else None) model = [entry for entry in model if entry[1] != key] cost = len(json.dumps(frame, separators=(",", ":"))) + len( payload or b"" ) model.append((seq, key, cost)) def over(): total = sum(entry[2] for entry in model) return len(model) > frames or total > size while over() and any(entry[1] is not None for entry in model): model.remove(next(e for e in model if e[1] is not None)) while over() and len(model) > 1: model.pop(0) dropped += 1 self.assertEqual(outbox.add(frame, payload)[0], seq) self.assertEqual( [entry[0] for entry in outbox.pending()], [entry[0] for entry in model], operations, ) self.assertEqual(outbox.dropped, dropped) def test_a_replayed_daemon_frame_is_not_applied_twice(self): inbound = albedo_link.Inbound() self.assertEqual( [inbound.accept(seq) for seq in (1, 2, 2, 1, 3)], [True, True, False, False, True], ) def test_job_book_follows_started_and_proven_gone_jobs(self): book = albedo_link.JobBook() book.observe({"type": "job_start", "id": "a", "pgid": 4242}) book.observe({"type": "job_start", "id": "b", "pgid": 4243}) book.observe({"type": "job", "id": "a", "cleanup": {"gone": False}}) book.observe({"type": "job", "id": "b", "cleanup": {"gone": True}}) book.observe({"type": "jobs", "live": 2}) self.assertEqual(sorted(book.started), ["a"]) self.assertEqual(book.live(), 3) def test_job_book_keeps_the_remote_jobs_a_frame_lists(self): book = albedo_link.JobBook() item = {"id": "r", "command": "sleep 9", "service": False, "started": 1} book.observe({"type": "jobs", "live": 1, "awaited": 1, "items": [item]}) self.assertEqual(book.external_jobs, [item]) book.observe({"type": "jobs", "live": 0, "awaited": 0}) self.assertEqual(book.external_jobs, []) class UnreadableFrameTest(unittest.TestCase): """The daemon reads frames with OTP's `json`, which refuses NaN, Infinity and a string escape of a lone surrogate, and the driver abandons a kernel whose frame it cannot read. A host call whose arguments hold one, such as a path decoded with surrogateescape, must fail that call instead.""" UNREADABLE = [ float("nan"), float("inf"), float("-inf"), b"/tmp/\xff".decode("utf-8", "surrogateescape"), ] def test_the_encoder_refuses_what_the_daemon_cannot_read(self): for value in self.UNREADABLE: with self.subTest(value=value), self.assertRaises(ValueError): albedo_link.encode({"type": "call", "id": "c", "args": {"x": value}}) def test_text_outside_ascii_still_crosses(self): frame = {"type": "call", "id": "c", "args": {"x": "é\u2028😀"}} self.assertEqual(json.loads(albedo_link.encode(frame)), frame) class DeepFrameTest(unittest.TestCase): def test_a_frame_nested_past_the_reader_is_refused_as_invalid(self): """A host reply holding deeply nested data is valid JSON the daemon writes, but Python's reader recurses on it. Its RecursionError would escape the session, which handles only the errors of a bad stream.""" depth = 100_000 data = b'{"seq":1,"ack":0,"frame":{"type":"reply","id":"r","value":' data += b'{"ok":true,"value":' + b"[" * depth + b"]" * depth + b"}}}" stream = io.BytesIO(struct.pack(">I", len(data)) + data) with self.assertRaises(ValueError): albedo_link.read_frame(stream.read) class SocketLinkTest(unittest.TestCase): def setUp(self): self.run_dir = tempfile.mkdtemp(prefix="link-") self.received = [] self.link = albedo_link.SocketLink( self.run_dir, "secret", lambda: {"pid": os.getpid()}, bundle="bundle", grace=60, ) threading.Thread(target=self.serve, daemon=True).start() def serve(self): try: self.link.serve(self.received.append) except OSError: pass # the listener closed in tearDown def tearDown(self): self.link.listener.close() shutil.rmtree(self.run_dir, ignore_errors=True) def attach(self, token="secret", ack=0): connection = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) connection.settimeout(5) connection.connect(os.path.join(self.run_dir, albedo_link.SOCKET)) self.addCleanup(connection.close) attach = {"attach": {"token": token, "ack": ack, "grace": 30}} albedo_link.write_frame(connection.send, albedo_link.encode(attach)) return connection, albedo_link.read_frame(connection.recv) def frames(self, connection, count): return [albedo_link.read_frame(connection.recv) for _ in range(count)] def test_a_wrong_token_is_refused(self): _, answer = self.attach(token="guess") self.assertEqual(answer, {"refused": "wrong token"}) self.assertFalse(self.link.attached()) def test_reattach_resends_only_what_was_not_acknowledged(self): first, hello = self.attach() self.assertEqual((hello["hello"]["epoch"], hello["hello"]["ack"]), (1, 0)) self.assertEqual(self.link.grace, 30) for n in range(3): self.link.send({"type": "call", "id": str(n)}) self.assertEqual([f["seq"] for f in self.frames(first, 3)], [1, 2, 3]) albedo_link.write_frame( first.send, albedo_link.encode( {"seq": 1, "ack": 1, "frame": {"type": "release", "handle": "h"}} ), ) self.assertEqual(albedo_link.read_frame(first.recv), {"ack": 1}) second, hello = self.attach(ack=2) # Newest attach wins: the first connection is cut off. self.assertEqual(first.recv(1), b"") self.assertEqual((hello["hello"]["epoch"], hello["hello"]["ack"]), (2, 1)) (resent,) = self.frames(second, 1) self.assertEqual((resent["seq"], resent["frame"]["id"]), (3, "2")) # The daemon replays seq 1 after its restart: it is not delivered again. replay = {"seq": 1, "ack": 3, "frame": {"type": "release", "handle": "h"}} albedo_link.write_frame(second.send, albedo_link.encode(replay)) self.assertEqual(albedo_link.read_frame(second.recv), {"ack": 1}) self.assertEqual(len(self.received), 1) self.assertEqual(self.link.outbox.pending(), []) def test_a_clip_crosses_in_raw_parts_that_a_reattach_resends(self): clip = os.urandom(albedo_link.MAX_PART * 2 + 12345) first, _ = self.attach() digests = [] sender = threading.Thread( target=lambda: digests.append(self.link.send_blob("c1", clip)) ) sender.start() sent = parts_after(first, 3) sender.join(5) digest = hashlib.sha256(clip).hexdigest() self.assertEqual(digests, [digest]) self.assertEqual( [(e["seq"], e["frame"]["part"], e["frame"]["parts"]) for e, _ in sent], [(1, 0, 3), (2, 1, 3), (3, 2, 3)], ) self.assertEqual({e["frame"]["digest"] for e, _ in sent}, {digest}) self.assertTrue(all(len(data) <= albedo_link.MAX_PART for _, data in sent)) self.assertEqual(b"".join(data for _, data in sent), clip) second, _ = self.attach(ack=1) self.assertEqual(first.recv(1), b"") resent = [(e["seq"], data) for e, data in parts_after(second, 2)] self.assertEqual(resent, [(e["seq"], data) for e, data in sent[1:]]) def test_a_kept_clip_goes_again_until_newer_ones_push_it_out(self): old, new = os.urandom(300), os.urandom(200) with patch.object(albedo_link, "KEPT_CLIP_BYTES", 400): old_digest = self.link.send_blob("c1", old) # the owner can lose parts it acked, so the clip is sent again. self.link.outbox.ack(1) self.link.resend_blob("c1", old_digest) new_digest = self.link.send_blob("c2", new) self.link.resend_blob("c1", old_digest) sent = [(seq, payload) for seq, _, payload in self.link.outbox.pending()] self.assertEqual(sent, [(2, old), (3, new)]) self.assertEqual(os.listdir(os.path.join(self.run_dir, "clips")), [new_digest]) def test_frames_sent_while_detached_wait_for_the_next_attach(self): self.link.send({"type": "done", "id": "c1"}) self.assertGreater(self.link.idle_for(), 0) connection, _ = self.attach() (done,) = self.frames(connection, 1) self.assertEqual(done["frame"], {"type": "done", "id": "c1"}) self.assertEqual(self.link.idle_for(), 0) def parts_after(connection, count): """`count` binary packets: each envelope and the bytes it carries.""" read = [] for _ in range(count): size = struct.unpack(">I", albedo_link.read_exact(connection.recv, 4))[0] packet = albedo_link.read_exact(connection.recv, size) assert packet[0] == 0, packet[:16] length = struct.unpack(">I", packet[1:5])[0] read.append((json.loads(packet[5 : 5 + length]), packet[5 + length :])) return read class LivenessProbeTest(unittest.TestCase): """A `{"ping": n}` is answered on the reader thread, so the answer says whether the interpreter can run Python at all, not whether a cell is blocking the loop. The owner's wedge verdicts rest on that distinction, and no E2E scenario can hold the GIL from outside the kernel to check it.""" def setUp(self): self.run_dir = tempfile.mkdtemp(prefix="link-") self.handler: Callable[[object], None] = lambda _frame: None self.link = albedo_link.SocketLink( self.run_dir, "secret", lambda: {"pid": os.getpid()}, bundle="bundle", grace=60, ) threading.Thread(target=self.serve, daemon=True).start() def serve(self): try: self.link.serve(lambda frame: self.handler(frame)) except OSError: pass # the listener closed in tearDown def tearDown(self): self.link.listener.close() shutil.rmtree(self.run_dir, ignore_errors=True) attach = SocketLinkTest.attach def test_a_ping_is_answered_while_a_dispatched_frame_blocks(self) -> None: connection, _ = self.attach() dispatched = threading.Event() gate = threading.Event() def park(_frame: object) -> None: dispatched.set() gate.wait() self.handler = park try: albedo_link.write_frame( connection.send, albedo_link.encode({"seq": 1, "ack": 0, "frame": {"type": "release"}}), ) self.assertTrue(dispatched.wait(10), "the frame was never dispatched") # The dispatch for seq 1 parks this connection's reader thread, as # a synchronous cell parks the loop; the owner's next attach gets # a reader of its own, and its probe is answered at once. probe, _ = self.attach() albedo_link.write_frame(probe.send, albedo_link.encode({"ping": 7})) self.assertEqual(albedo_link.read_frame(probe.recv), {"pong": 7}) finally: gate.set() if __name__ == "__main__": unittest.main()