diff --git a/tests/link.py b/tests/link.py index 5a122ad2..dcd341b4 100644 --- a/tests/link.py +++ b/tests/link.py @@ -8,6 +8,7 @@ import shlex import threading import time import random +from collections import deque from unittest import skipIf import RNS import os @@ -29,6 +30,7 @@ fixed_keys = [ BUFFER_TEST_TARGET = 256000 BUFFER_TEST_TARGET_SLOW = 1800 SLOW_TEST_MARKER = b"@SLOW_TEST_MARKER" +PACKET_CB_MARKER = b"@PACKET_CB_ECHO" LINK_UP_WAIT = 0.050 LINK_TIMEOUT = 1.000 @@ -794,6 +796,277 @@ class TestLink(unittest.TestCase): def test_13_buffer_round_trip_big_slow(self): self.test_12_buffer_round_trip_big(local_bitrate=410) + # Generated with lc/qwen3.8_flash_next_iq4_xs + # Reviewed and approved by Mark Qvist + @skipIf(os.getenv('SKIP_NORMAL_TESTS') != None, "Skipping") + def test_14_packet_callback(self): + init_rns(self) + print("") + print("Link packet callback test") + + # TODO: Load this from public bytes only + id1 = RNS.Identity.from_bytes(bytes.fromhex(fixed_keys[0][0])) + self.assertEqual(id1.hash, bytes.fromhex(fixed_keys[0][1])) + + RNS.Transport.request_path(bytes.fromhex("fb48da0e82e6e01ba0c014513f74540d")) + time.sleep(0.2) + + dest = RNS.Destination(id1, RNS.Destination.OUT, RNS.Destination.SINGLE, APP_NAME, "link", "establish") + self.assertEqual(dest.hash, bytes.fromhex("fb48da0e82e6e01ba0c014513f74540d")) + + l1 = RNS.Link(dest) + await_link(l1, LINK_TIMEOUT) + self.assertEqual(l1.status, RNS.Link.ACTIVE) + + # The callback handler thread is spawned lazily on the first + # packet, and must not exist on a fresh link. + self.assertIsNone(l1.callback_thread) + self.assertEqual(l1.inbound_dropped, 0) + + delivered = [] + delivered_lock = threading.Lock() + blocked_hook = threading.Event() + release_block = threading.Event() + special = {"block_on": None, "raise_on": None} + + # Records invocations as (sequence, thread_id) tuples. All + # assertions are made on the main thread, since exceptions + # raised on the callback handler thread are contained there. + def handle_packet(plaintext, packet): + sequence = None + if plaintext[:len(PACKET_CB_MARKER)] == PACKET_CB_MARKER and len(plaintext) == len(PACKET_CB_MARKER)+4: + sequence = int.from_bytes(plaintext[len(PACKET_CB_MARKER):], "big") + with delivered_lock: + delivered.append((sequence, threading.get_ident())) + if special["block_on"] == sequence: + blocked_hook.set() + release_block.wait(30) + if special["raise_on"] == sequence: + raise RuntimeError("Test-induced packet callback exception") + + sent = {"n": 0} + def send_echo_packet(): + sequence = sent["n"] + sent["n"] += 1 + RNS.Packet(l1, PACKET_CB_MARKER+sequence.to_bytes(4, "big")).send() + return sequence + + def await_delivered(count, timeout=15): + deadline = time.time()+timeout + c = 0 + while c < count and time.time() < deadline: + time.sleep(0.02) + with delivered_lock: + c = len(delivered) + return c + + def delivered_snapshot(): + with delivered_lock: + return list(delivered) + + l1.set_packet_callback(handle_packet) + + print("Testing in-order delivery on a single handler thread...") + num_packets = 64 + for i in range(num_packets): + send_echo_packet() + time.sleep(0.004) + + self.assertEqual(await_delivered(num_packets), num_packets) + snapshot = delivered_snapshot() + sequences = [s for s, _ in snapshot] + thread_ids = {t for _, t in snapshot} + self.assertEqual(sequences, list(range(num_packets))) + self.assertEqual(len(thread_ids), 1, "Packet callbacks ran on more than one thread") + + handler_thread = l1.callback_thread + self.assertIsNotNone(handler_thread) + self.assertTrue(handler_thread.is_alive()) + self.assertTrue(handler_thread.daemon) + self.assertEqual(handler_thread.ident, next(iter(thread_ids))) + self.assertNotEqual(threading.get_ident(), next(iter(thread_ids)), "Packet callback ran on the main thread") + self.assertEqual(l1.inbound_dropped, 0) + print("Handler thread stable and delivery in order. OK!") + + print("Testing callback exception resilience...") + special["raise_on"] = sent["n"] + for i in range(3): + send_echo_packet() + time.sleep(0.004) + + self.assertEqual(await_delivered(num_packets+3), num_packets+3) + snapshot = delivered_snapshot() + sequences = [s for s, _ in snapshot] + thread_ids = {t for _, t in snapshot} + self.assertEqual(sequences, list(range(num_packets+3))) + self.assertEqual(len(thread_ids), 1, "Callback exception spawned a new handler thread") + self.assertEqual(handler_thread.ident, next(iter(thread_ids))) + self.assertTrue(handler_thread.is_alive(), "Handler thread died on callback exception") + self.assertEqual(l1.inbound_dropped, 0) + print("Handler survived callback exception and continued delivery. OK!") + + print("Testing link operation with a blocked packet callback...") + special["block_on"] = sent["n"] + send_echo_packet() + self.assertTrue(blocked_hook.wait(15), "Packet callback did not run") + + num_blocked = 25 + block_receipts = [] + for i in range(num_blocked): + block_receipts.append(RNS.Packet(l1, PACKET_CB_MARKER+sent["n"].to_bytes(4, "big")).send()) + sent["n"] += 1 + time.sleep(0.01) + + # Even with the external callback blocked indefinitely, the link + # itself must remain fully operational, since the packet handler + # never waits for external callback completion. + resource_timeout = 60 + resource_size = 128 + data = os.urandom(resource_size) + print("Sending "+self.size_str(resource_size)+" resource while callback is blocked...") + resource = RNS.Resource(data, l1, timeout=resource_timeout) + start = time.time() + while resource.status < RNS.Resource.COMPLETE and time.time() < start+resource_timeout: + time.sleep(0.01) + self.assertEqual(resource.status, RNS.Resource.COMPLETE) + + # All packets sent while blocked must have been accepted into + # the pending queue rather than dropped or blocked on. + with l1.callback_condition: + pending = len(l1.pending_packets) + self.assertGreater(pending, 1) + self.assertEqual(l1.inbound_dropped, 0) + + print("Releasing blocked callback...") + release_block.set() + total = num_packets+3+1+num_blocked + self.assertEqual(await_delivered(total), total) + snapshot = delivered_snapshot() + sequences = [s for s, _ in snapshot] + thread_ids = {t for _, t in snapshot} + self.assertEqual(sequences, list(range(total))) + self.assertEqual(len(thread_ids), 1) + self.assertEqual(handler_thread.ident, next(iter(thread_ids))) + self.assertTrue(handler_thread.is_alive()) + self.assertEqual(l1.inbound_dropped, 0) + with l1.callback_condition: + self.assertEqual(len(l1.pending_packets), 0) + print("Full in-order delivery after unblocked callback. OK!") + + l1.teardown() + time.sleep(LINK_UP_WAIT) + self.assertEqual(l1.status, RNS.Link.CLOSED) + + # Generated with lc/qwen3.8_flash_next_iq4_xs + # Reviewed and approved by Mark Qvist + @skipIf(os.getenv('SKIP_NORMAL_TESTS') != None, "Skipping") + def test_15_packet_callback_overflow(self): + init_rns(self) + print("") + print("Link packet callback overflow test") + + # TODO: Load this from public bytes only + id1 = RNS.Identity.from_bytes(bytes.fromhex(fixed_keys[0][0])) + self.assertEqual(id1.hash, bytes.fromhex(fixed_keys[0][1])) + + RNS.Transport.request_path(bytes.fromhex("fb48da0e82e6e01ba0c014513f74540d")) + time.sleep(0.2) + + dest = RNS.Destination(id1, RNS.Destination.OUT, RNS.Destination.SINGLE, APP_NAME, "link", "establish") + self.assertEqual(dest.hash, bytes.fromhex("fb48da0e82e6e01ba0c014513f74540d")) + + l1 = RNS.Link(dest) + await_link(l1, LINK_TIMEOUT) + self.assertEqual(l1.status, RNS.Link.ACTIVE) + + # The real pending limit (Link.PACKET_MAX_PENDING) is too high to + # reach through the local test interfaces in reasonable time, so + # shrink the pending queue to exercise the drop policy and its + # accounting with a modest number of packets. Must be done before + # any callback is set, while no handler thread exists. + overflow_max = 8 + l1.pending_packets = deque(maxlen=overflow_max) + self.assertEqual(l1.pending_packets.maxlen, overflow_max) + + delivered = [] + delivered_lock = threading.Lock() + first_hook = threading.Event() + release_block = threading.Event() + state = {"first": False} + + # First invocation blocks the handler, so inbound packets arrive + # faster than the callback consumes them and the queue overflows. + def handle_packet(plaintext, packet): + sequence = int.from_bytes(plaintext[len(PACKET_CB_MARKER):], "big") + with delivered_lock: + delivered.append(sequence) + if not state["first"]: + state["first"] = True + first_hook.set() + release_block.wait(30) + + l1.set_packet_callback(handle_packet) + + total_packets = 40 + print("Flooding "+str(total_packets)+" echo packets while callback is blocked...") + for i in range(total_packets): + RNS.Packet(l1, PACKET_CB_MARKER+i.to_bytes(4, "big")).send() + + self.assertTrue(first_hook.wait(15), "Packet callback did not run") + time.sleep(0.75) + + dropped_during_block = l1.inbound_dropped + self.assertGreater(dropped_during_block, 0, "No packets dropped on overflowing queue") + + print("Releasing blocked callback, checking drop accounting...") + release_block.set() + deadline = time.time()+15 + while time.time() < deadline: + with delivered_lock: + count = len(delivered) + with l1.callback_condition: + pending = len(l1.pending_packets) + if count+l1.inbound_dropped >= total_packets and pending == 0: + break + time.sleep(0.02) + + with delivered_lock: + sequences = list(delivered) + print("Delivered "+str(len(sequences))+" of "+str(total_packets)+", dropped "+str(l1.inbound_dropped)) + + # Every packet was either delivered or accounted for as dropped + self.assertEqual(len(sequences)+l1.inbound_dropped, total_packets) + # Delivery remained strictly in order of arrival + self.assertEqual(sequences, sorted(sequences)) + self.assertEqual(len(set(sequences)), len(sequences)) + # Drop-oldest policy: the newest packet is never dropped + self.assertEqual(sequences[-1], total_packets-1) + # The queue actually dropped packets + self.assertLess(len(sequences), total_packets) + + # Link and callback machinery remain healthy after overflow + with delivered_lock: + baseline = len(delivered) + RNS.Packet(l1, PACKET_CB_MARKER+total_packets.to_bytes(4, "big")).send() + deadline = time.time()+15 + found = False + while time.time() < deadline: + with delivered_lock: + if len(delivered) > baseline: + found = delivered[-1] == total_packets + if found: break + time.sleep(0.02) + self.assertTrue(found, "No packet callback delivery after queue overflow") + with delivered_lock: + all_sequences = list(delivered) + self.assertEqual(all_sequences, sorted(all_sequences)) + self.assertEqual(len(set(all_sequences)), len(all_sequences)) + self.assertEqual(all_sequences[-1], total_packets) + + l1.teardown() + time.sleep(LINK_UP_WAIT) + self.assertEqual(l1.status, RNS.Link.CLOSED) + def size_str(self, num, suffix='B'): units = ['','K','M','G','T','P','E','Z'] last_unit = 'Y' @@ -861,6 +1134,13 @@ def targets(yp=False): channel.register_message_type(MessageTest) channel.add_message_handler(handle_message) + # Echo plain data packets prefixed with PACKET_CB_MARKER back to + # the sender verbatim, for testing link packet callback handling. + def echo_packet(plaintext, packet): + if plaintext[:len(PACKET_CB_MARKER)] == PACKET_CB_MARKER: + RNS.Packet(link, plaintext).send() + link.set_packet_callback(echo_packet) + buffer = None response_data = []