diff --git a/src/LibreQoS.py b/src/LibreQoS.py index a0b9e08c..cd004d71 100755 --- a/src/LibreQoS.py +++ b/src/LibreQoS.py @@ -17,10 +17,10 @@ import warnings import psutil import argparse import logging -import shutil import time from deepdiff import DeepDiff +from atomic_io import atomic_copy, atomic_write_text from virtual_tree_nodes import ( build_logical_to_physical_node_map, build_physical_network, @@ -221,26 +221,6 @@ def get_runtime_state_path(category, filename): return get_state_path(category, filename) -def ensure_parent_dir(path): - parent = os.path.dirname(path) - if parent: - os.makedirs(parent, exist_ok=True) - - -def atomic_write_text(path, text): - # Write to a sibling temp file and atomically replace the target, so an - # interrupted write (crash, VM snapshot) can never leave a truncated file. - # The file is fsync'd, but the directory rename is not; on power loss the - # worst case is the previous complete file. - ensure_parent_dir(path) - temp_path = path + ".tmp" - with open(temp_path, 'w') as file: - file.write(text) - file.flush() - os.fsync(file.fileno()) - os.replace(temp_path, path) - - def get_network_json_path(): base_dir = get_libreqos_directory() effective_path = get_runtime_state_path("topology", "network.effective.json") @@ -1036,10 +1016,13 @@ def validateNetworkAndDevices(): warnings.warn(f"network.json is missing: {network_json_path}", stacklevel=2) networkValidatedOrNot = False else: - with open(network_json_path) as file: - try: + try: + with open(network_json_path) as file: data = json.load(file) # put JSON-data to a variable - if data != {}: + if not isinstance(data, dict): + warnings.warn(f"network.json at '{network_json_path}' is not a node object", stacklevel=2) + networkValidatedOrNot = False + elif data != {}: #Traverse observedNodes = set() duplicateNodes = set() @@ -1061,9 +1044,9 @@ def validateNetworkAndDevices(): if len(observedNodes) < 1: warnings.warn("network.json had 0 valid nodes. Only {} is accepted for that scenario.", stacklevel=2) networkValidatedOrNot = False - except json.decoder.JSONDecodeError: - warnings.warn("network.json is an invalid JSON file", stacklevel=2) # in case json is invalid - networkValidatedOrNot = False + except (json.decoder.JSONDecodeError, UnicodeDecodeError, OSError) as err: + warnings.warn(f"network.json at '{network_json_path}' is unreadable or invalid: {err}", stacklevel=2) + networkValidatedOrNot = False if integration_ingress: if devicesValidatedOrNot == True: print("integration shaping ingress passed validation") @@ -1491,11 +1474,9 @@ def refreshShapers(): if (validateNetworkAndDevices() == True): if os.path.isfile(shapedDevicesFile): last_good_csv_path = get_state_path("shaping", "lastGoodConfig.csv") - ensure_parent_dir(last_good_csv_path) - shutil.copyfile(shapedDevicesFile, last_good_csv_path) + atomic_copy(shapedDevicesFile, last_good_csv_path) last_good_json_path = get_state_path("shaping", "lastGoodConfig.json") - ensure_parent_dir(last_good_json_path) - shutil.copyfile(networkJSONfile, last_good_json_path) + atomic_copy(networkJSONfile, last_good_json_path) if os.path.isfile(shapedDevicesFile): print("Backed up good config as lastGoodConfig.csv and lastGoodConfig.json") else: @@ -2936,11 +2917,11 @@ def refreshShapers(): if observe_mode: linuxTCcommands = [] linux_tc_path = get_linux_tc_path() - ensure_parent_dir(linux_tc_path) - with open(linux_tc_path, 'w') as f: - for command in linuxTCcommands: - logging.info(command) - f.write(f"{command}\n") + linux_tc_commands = [] + for command in linuxTCcommands: + logging.info(command) + linux_tc_commands.append(f"{command}\n") + atomic_write_text(linux_tc_path, "".join(linux_tc_commands)) # if logging.DEBUG <= logging.root.level: # # Do not --force in debug mode, so we can see any errors # shell("/sbin/tc -b linux_tc.txt") @@ -3014,8 +2995,7 @@ def refreshShapers(): # snapshot there instead of failing the whole scheduler refresh. if os.path.isfile(shapedDevicesFile): last_loaded_path = get_state_path("shaping", "ShapedDevices.lastLoaded.csv") - ensure_parent_dir(last_loaded_path) - shutil.copyfile(shapedDevicesFile, last_loaded_path) + atomic_copy(shapedDevicesFile, last_loaded_path) # Save for stats stats_by_circuit_path = get_stats_by_circuit_path() diff --git a/src/atomic_io.py b/src/atomic_io.py new file mode 100644 index 00000000..2d0497eb --- /dev/null +++ b/src/atomic_io.py @@ -0,0 +1,85 @@ +"""Atomic file writes for runtime state and generated shaping inputs. + +Each write goes to a sibling temporary file that is flushed and fsync'd before +an os.replace() swaps it over the destination. A reader therefore never sees a +truncated or torn file when a write is interrupted by a crash, VM snapshot, or +power loss; the worst case is the previous complete file. + +A single writer is assumed per destination path; concurrent writers to the same +path are not coordinated. +""" + +import os +import shutil +import stat + + +def _ensure_parent_dir(path): + parent = os.path.dirname(path) + if parent: + os.makedirs(parent, exist_ok=True) + + +def _remove_temp_file(temp_path): + try: + os.remove(temp_path) + except OSError: + pass + + +def _preserve_destination_metadata(path, temp_path): + # Replacing a file creates a new inode, so carry over the destination's + # ownership and permissions. Operators edit generated files over SFTP, and + # the scheduler runs as root. + try: + existing = os.stat(path) + except OSError: + return + try: + os.chmod(temp_path, stat.S_IMODE(existing.st_mode)) + except OSError: + pass + try: + os.chown(temp_path, existing.st_uid, existing.st_gid) + except OSError: + pass + + +def _atomic_replace(path, write_temp): + _ensure_parent_dir(path) + temp_path = path + ".tmp" + replaced = False + try: + with open(temp_path, "wb") as handle: + write_temp(handle) + handle.flush() + os.fsync(handle.fileno()) + _preserve_destination_metadata(path, temp_path) + os.replace(temp_path, path) + replaced = True + finally: + if not replaced: + _remove_temp_file(temp_path) + + +def atomic_write_text(path, text, encoding="utf-8"): + """Atomically replace `path` with `text`. + + Side effects: creates parent directories, writes and fsyncs `path + ".tmp"`, + preserves the destination's ownership and permissions when it exists, then + renames the temporary file over `path`. + """ + _atomic_replace(path, lambda handle: handle.write(text.encode(encoding))) + + +def atomic_copy(src, dest): + """Atomically copy `src` to `dest`, preserving the exact bytes. + + Side effects match `atomic_write_text`. + """ + + def write_temp(handle): + with open(src, "rb") as source: + shutil.copyfileobj(source, handle) + + _atomic_replace(dest, write_temp) diff --git a/src/build_dpkg.sh b/src/build_dpkg.sh index 024bab10..440154b8 100755 --- a/src/build_dpkg.sh +++ b/src/build_dpkg.sh @@ -20,6 +20,7 @@ ETC_DIR=$DPKG_DIR/etc ETC_LIBREQOS_DIR=$DPKG_DIR/etc/libreqos MOTD_DIR=$DPKG_DIR/etc/update-motd.d LQOS_FILES=( + atomic_io.py csvToNetworkJSON.py configMigrator.py integrationCommon.py diff --git a/src/integrationCommon.py b/src/integrationCommon.py index 0570c074..db5159e9 100644 --- a/src/integrationCommon.py +++ b/src/integrationCommon.py @@ -13,6 +13,8 @@ import json import os import time +from atomic_io import atomic_write_text + try: from liblqos_python import get_libreqos_state_directory as _get_state_dir_native except Exception: @@ -548,10 +550,8 @@ class NetworkGraph: return self.nodes[index].type == NodeType.ap or self.nodes[index].type == NodeType.site or self.nodes[index].type == NodeType.clientWithChildren def createNetworkJson(self): - import json topLevelNode = self.buildNetworkJson() - with open('network.json', 'w') as f: - json.dump(topLevelNode, f, indent=4) + atomic_write_text('network.json', json.dumps(topLevelNode, indent=4)) def buildNetworkJson(self): topLevelNode = {} @@ -671,14 +671,10 @@ class NetworkGraph: def createShapedDevices(self): shaped_devices_csv, circuit_anchor_file = self.buildShapedDevicesArtifacts() - with open('ShapedDevices.csv', 'w', newline='') as csvfile: - csvfile.write(shaped_devices_csv) + atomic_write_text('ShapedDevices.csv', shaped_devices_csv) anchor_path = _state_path("topology", "circuit_anchors.json") - os.makedirs(os.path.dirname(anchor_path), exist_ok=True) - with open(anchor_path, 'w', encoding='utf-8') as anchorfile: - json.dump(circuit_anchor_file, anchorfile, indent=2) - anchorfile.write('\n') + atomic_write_text(anchor_path, json.dumps(circuit_anchor_file, indent=2) + '\n') def buildShapedDevicesArtifacts(self): import csv diff --git a/src/scheduler.py b/src/scheduler.py index f0ccbd33..d5bb722b 100644 --- a/src/scheduler.py +++ b/src/scheduler.py @@ -5,6 +5,7 @@ import io import json import chardet from LibreQoS import RefreshFailure, ValidationFailure, refreshShapers, refreshShapersUpdateOnly +from atomic_io import atomic_write_text import subprocess import sys import tempfile @@ -716,10 +717,11 @@ def merge_rows_replace_by_device_id(existing_rows, override_rows): def write_shaped_devices_csv(path: str, header, rows): - with open(path, 'w', encoding='utf-8', newline='') as f: - writer = csv.writer(f) - writer.writerow(header) - writer.writerows(rows) + buffer = io.StringIO() + writer = csv.writer(buffer) + writer.writerow(header) + writer.writerows(rows) + atomic_write_text(path, buffer.getvalue()) def header_has_sqm(header): @@ -896,9 +898,7 @@ def load_topology_canonical_state(path: str): def write_topology_canonical_state(path: str, canonical_state: dict): - os.makedirs(os.path.dirname(path), exist_ok=True) - with open(path, 'w', encoding='utf-8') as f: - f.write(json.dumps(canonical_state, indent=4)) + atomic_write_text(path, json.dumps(canonical_state, indent=4)) def _format_attempt_count(attempts: int) -> str: @@ -1101,8 +1101,7 @@ def apply_network_adjustments_to_canonical_state(canonical_state: dict, adjustme def write_network_json(path: str, network: dict): - with open(path, 'w', encoding='utf-8') as f: - f.write(json.dumps(network, indent=4)) + atomic_write_text(path, json.dumps(network, indent=4)) def importAndShapeFullReload(): diff --git a/src/test_atomic_io.py b/src/test_atomic_io.py new file mode 100644 index 00000000..29197f85 --- /dev/null +++ b/src/test_atomic_io.py @@ -0,0 +1,91 @@ +import os +import stat +import tempfile +import unittest +from unittest.mock import patch + +import atomic_io + + +class TestAtomicWrite(unittest.TestCase): + def setUp(self): + temp_dir = tempfile.TemporaryDirectory() # nosec B108 + self.addCleanup(temp_dir.cleanup) + self.temp_dir = temp_dir.name + + def test_write_text_creates_parents_and_content(self): + path = os.path.join(self.temp_dir, "a", "b", "state.txt") + atomic_io.atomic_write_text(path, "hello") + with open(path, encoding="utf-8") as handle: + self.assertEqual(handle.read(), "hello") + self.assertFalse(os.path.exists(path + ".tmp")) + + def test_write_text_replaces_existing_content(self): + path = os.path.join(self.temp_dir, "state.txt") + with open(path, "w", encoding="utf-8") as handle: + handle.write("old") + atomic_io.atomic_write_text(path, "new") + with open(path, encoding="utf-8") as handle: + self.assertEqual(handle.read(), "new") + self.assertFalse(os.path.exists(path + ".tmp")) + + def test_write_text_preserves_existing_permissions(self): + path = os.path.join(self.temp_dir, "state.txt") + with open(path, "w", encoding="utf-8") as handle: + handle.write("old") + os.chmod(path, 0o600) + atomic_io.atomic_write_text(path, "new") + self.assertEqual(stat.S_IMODE(os.stat(path).st_mode), 0o600) + + def test_write_text_failure_preserves_existing_content(self): + path = os.path.join(self.temp_dir, "state.txt") + with open(path, "w", encoding="utf-8") as handle: + handle.write("old") + with patch("os.replace", side_effect=OSError(5, "replace failed")): + with self.assertRaises(OSError): + atomic_io.atomic_write_text(path, "new") + with open(path, encoding="utf-8") as handle: + self.assertEqual(handle.read(), "old") + self.assertFalse(os.path.exists(path + ".tmp")) + + +class TestAtomicCopy(unittest.TestCase): + def setUp(self): + temp_dir = tempfile.TemporaryDirectory() # nosec B108 + self.addCleanup(temp_dir.cleanup) + self.temp_dir = temp_dir.name + + def test_copy_creates_parents_and_preserves_bytes(self): + src = os.path.join(self.temp_dir, "source.bin") + with open(src, "wb") as handle: + handle.write(b"\x00\xffpayload") + dest = os.path.join(self.temp_dir, "nested", "copy.bin") + atomic_io.atomic_copy(src, dest) + with open(dest, "rb") as handle: + self.assertEqual(handle.read(), b"\x00\xffpayload") + self.assertFalse(os.path.exists(dest + ".tmp")) + + def test_copy_failure_preserves_existing_destination(self): + src = os.path.join(self.temp_dir, "source.bin") + with open(src, "wb") as handle: + handle.write(b"new") + dest = os.path.join(self.temp_dir, "dest.bin") + with open(dest, "wb") as handle: + handle.write(b"old") + with patch("os.replace", side_effect=OSError(5, "replace failed")): + with self.assertRaises(OSError): + atomic_io.atomic_copy(src, dest) + with open(dest, "rb") as handle: + self.assertEqual(handle.read(), b"old") + self.assertFalse(os.path.exists(dest + ".tmp")) + + def test_copy_missing_source_preserves_existing_destination(self): + dest = os.path.join(self.temp_dir, "dest.bin") + with open(dest, "wb") as handle: + handle.write(b"old") + missing = os.path.join(self.temp_dir, "does-not-exist.bin") + with self.assertRaises(FileNotFoundError): + atomic_io.atomic_copy(missing, dest) + with open(dest, "rb") as handle: + self.assertEqual(handle.read(), b"old") + self.assertFalse(os.path.exists(dest + ".tmp")) diff --git a/src/test_libreqos_shaping_inputs.py b/src/test_libreqos_shaping_inputs.py index 83f681b6..41a3c58e 100644 --- a/src/test_libreqos_shaping_inputs.py +++ b/src/test_libreqos_shaping_inputs.py @@ -569,37 +569,53 @@ class TestFirstRunSinceBoot(unittest.TestCase): self.assertTrue(LibreQoS.checkIfFirstRunSinceBoot()) -class TestAtomicWriteText(unittest.TestCase): +class TestValidateNetworkJsonTornWrite(unittest.TestCase): def setUp(self): temp_dir = tempfile.TemporaryDirectory() # nosec B108 self.addCleanup(temp_dir.cleanup) self.temp_dir = temp_dir.name + self.network_path = os.path.join(self.temp_dir, "network.json") + self.devices_path = os.path.join(self.temp_dir, "ShapedDevices.csv") + with open(self.devices_path, "w", encoding="utf-8", newline="") as handle: + handle.write( + "Circuit ID,Circuit Name,Device ID,Device Name,Parent Node,MAC," + "IPv4,IPv6,Download Min,Upload Min,Download Max,Upload Max,Comment\n" + "circuit-1,Circuit 1,dev-1,Device 1,Parent,00:00:00:00:00:00," + "192.168.1.2,,10,10,100,100,\n" + ) - def test_atomic_write_creates_parents_and_content(self): - path = os.path.join(self.temp_dir, "a", "b", "state.txt") - LibreQoS.atomic_write_text(path, "hello") - with open(path, encoding="utf-8") as handle: - self.assertEqual(handle.read(), "hello") - self.assertFalse(os.path.exists(path + ".tmp")) - - def test_atomic_write_replaces_existing_content(self): - path = os.path.join(self.temp_dir, "state.txt") - with open(path, "w", encoding="utf-8") as handle: - handle.write("old") - LibreQoS.atomic_write_text(path, "new") - with open(path, encoding="utf-8") as handle: - self.assertEqual(handle.read(), "new") - self.assertFalse(os.path.exists(path + ".tmp")) - - def test_atomic_write_failure_preserves_existing_content(self): - path = os.path.join(self.temp_dir, "state.txt") - with open(path, "w", encoding="utf-8") as handle: - handle.write("old") - with patch("os.replace", side_effect=OSError(5, "replace failed")): - with self.assertRaises(OSError): - LibreQoS.atomic_write_text(path, "new") - with open(path, encoding="utf-8") as handle: - self.assertEqual(handle.read(), "old") + def _validate(self): + with patch.object( + LibreQoS, "get_network_json_path", return_value=self.network_path + ), patch.object( + LibreQoS, "get_shaped_devices_path", return_value=self.devices_path + ): + return LibreQoS.validateNetworkAndDevices() + + def test_undecodable_network_json_fails_validation_without_raising(self): + with open(self.network_path, "wb") as handle: + handle.write(b"\x80\x81\x82 torn network") + with self.assertWarnsRegex(UserWarning, "unreadable or invalid"): + self.assertFalse(self._validate()) + + def test_truncated_network_json_fails_validation_without_raising(self): + with open(self.network_path, "wb") as handle: + handle.write(b'{"Root": ') + with self.assertWarnsRegex(UserWarning, "unreadable or invalid"): + self.assertFalse(self._validate()) + + def test_network_json_read_error_fails_validation_without_raising(self): + with open(self.network_path, "w", encoding="utf-8") as handle: + handle.write("{}") + with patch.object(LibreQoS.json, "load", side_effect=PermissionError(13, "denied")): + with self.assertWarnsRegex(UserWarning, "unreadable or invalid"): + self.assertFalse(self._validate()) + + def test_non_object_network_json_fails_validation_without_raising(self): + with open(self.network_path, "w", encoding="utf-8") as handle: + handle.write("null") + with self.assertWarnsRegex(UserWarning, "not a node object"): + self.assertFalse(self._validate()) if __name__ == "__main__": -- knotmirror 0.0.1 From ea7374901a54aea7bc8af7a9f41ed8a5d127ddb7 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Sat, 3 Oct 2026 11:56:51 -0500 Subject: [PATCH 02/17] Fix node minimum bandwidth accumulating across siblings findBandwidthMins() reused one minDownload/minUpload counter for both each node's own minimum and the running sibling total, so every sibling after the first inherited the circuit minimums of the siblings before it. Those inflated minimums are written to queuingStructure.json and become HTB rates, which can guarantee child nodes more bandwidth than their parent supplies. Reset the counters per node and keep a separate running total for the parent. Also fix the no-minimum-key fallback, which used minUpload for the download minimum. The function is hoisted to module level so the behavior can be unit tested, with regression coverage for sibling accumulation and order, nested roll-up, and the download fallback. --- src/LibreQoS.py | 58 +++++----- src/test_libreqos_shaping_inputs.py | 158 ++++++++++++++++++++++++++++ 2 files changed, 192 insertions(+), 24 deletions(-) diff --git a/src/LibreQoS.py b/src/LibreQoS.py index a0b9e08c..7104d937 100755 --- a/src/LibreQoS.py +++ b/src/LibreQoS.py @@ -1456,6 +1456,39 @@ def apply_effective_runtime_circuit_overrides(subscriberCircuits): return overlay_count + +def findBandwidthMins(data, subscriberCircuits): + """Raise each node's minimum bandwidth to cover its own circuits and children. + + Mutates ``data`` in place. Returns the summed minimums of all circuits and + child nodes in the tree so callers can propagate them to a parent node. + """ + totalDownload = 0 + totalUpload = 0 + for elem in data: + minDownload = 0 + minUpload = 0 + for circuit in subscriberCircuits: + if elem == circuit['ParentNode']: + minDownload += circuit['minDownload'] + minUpload += circuit['minUpload'] + if 'children' in data[elem]: + minDL, minUL = findBandwidthMins(data[elem]['children'], subscriberCircuits) + minDownload += minDL + minUpload += minUL + if 'downloadBandwidthMbpsMin' in data[elem]: + data[elem]['downloadBandwidthMbpsMin'] = max(data[elem]['downloadBandwidthMbpsMin'], minDownload) + else: + data[elem]['downloadBandwidthMbpsMin'] = max(data[elem]['downloadBandwidthMbps'], minDownload) + if 'uploadBandwidthMbpsMin' in data[elem]: + data[elem]['uploadBandwidthMbpsMin'] = max(data[elem]['uploadBandwidthMbpsMin'], minUpload) + else: + data[elem]['uploadBandwidthMbpsMin'] = max(data[elem]['uploadBandwidthMbps'], minUpload) + totalDownload += minDownload + totalUpload += minUpload + return totalDownload, totalUpload + + def refreshShapers(): # Starting @@ -1832,31 +1865,8 @@ def refreshShapers(): genPNcounter = 0 print("Generated parent nodes created") - # Find the bandwidth minimums for each node by combining mimimums of devices lower in that node's hierarchy - def findBandwidthMins(data, depth): - tabs = ' ' * depth - minDownload = 0 - minUpload = 0 - for elem in data: - for circuit in subscriberCircuits: - if elem == circuit['ParentNode']: - minDownload += circuit['minDownload'] - minUpload += circuit['minUpload'] - if 'children' in data[elem]: - minDL, minUL = findBandwidthMins(data[elem]['children'], depth+1) - minDownload += minDL - minUpload += minUL - if 'downloadBandwidthMbpsMin' in data[elem]: - data[elem]['downloadBandwidthMbpsMin'] = max(data[elem]['downloadBandwidthMbpsMin'], minDownload) - else: - data[elem]['downloadBandwidthMbpsMin'] = max(data[elem]['downloadBandwidthMbps'], minUpload) - if 'uploadBandwidthMbpsMin' in data[elem]: - data[elem]['uploadBandwidthMbpsMin'] = max(data[elem]['uploadBandwidthMbpsMin'], minUpload) - else: - data[elem]['uploadBandwidthMbpsMin'] = max(data[elem]['uploadBandwidthMbps'], minUpload) - return minDownload, minUpload logging.info("Finding the bandwidth minimums for each node") - minDownload, minUpload = findBandwidthMins(network, 0) + findBandwidthMins(network, subscriberCircuits) logging.info("Found the bandwidth minimums for each node") # Child nodes inherit bandwidth maximums of parents. We apply this here to avoid bugs when compression is applied with flattenA(). diff --git a/src/test_libreqos_shaping_inputs.py b/src/test_libreqos_shaping_inputs.py index 83f681b6..e1ff471e 100644 --- a/src/test_libreqos_shaping_inputs.py +++ b/src/test_libreqos_shaping_inputs.py @@ -522,6 +522,164 @@ class TestLibreQoSShapingInputs(unittest.TestCase): self.assertEqual(missing_parents, {}) +class TestFindBandwidthMins(unittest.TestCase): + def test_sibling_minimums_do_not_accumulate(self): + def build_network(child_order): + children = { + "Crew": { + "downloadBandwidthMbps": 100, + "uploadBandwidthMbps": 100, + "downloadBandwidthMbpsMin": 20, + "uploadBandwidthMbpsMin": 20, + }, + "Guest": { + "downloadBandwidthMbps": 178, + "uploadBandwidthMbps": 88, + "downloadBandwidthMbpsMin": 60, + "uploadBandwidthMbpsMin": 20, + }, + "Infra": { + "downloadBandwidthMbps": 82, + "uploadBandwidthMbps": 30, + "downloadBandwidthMbpsMin": 1, + "uploadBandwidthMbpsMin": 1, + }, + "MGMT": { + "downloadBandwidthMbps": 30, + "uploadBandwidthMbps": 15, + "downloadBandwidthMbpsMin": 10, + "uploadBandwidthMbpsMin": 4, + }, + } + return { + "Site": { + "downloadBandwidthMbps": 189, + "uploadBandwidthMbps": 69, + "downloadBandwidthMbpsMin": 120, + "uploadBandwidthMbpsMin": 60, + "children": {name: children[name] for name in child_order}, + } + } + + circuits = [ + {"ParentNode": "Crew", "minDownload": 10, "minUpload": 10}, + {"ParentNode": "Crew", "minDownload": 10, "minUpload": 10}, + {"ParentNode": "Guest", "minDownload": 60, "minUpload": 20}, + {"ParentNode": "Infra", "minDownload": 1, "minUpload": 1}, + {"ParentNode": "MGMT", "minDownload": 10, "minUpload": 4}, + ] + + for child_order in ( + ["Crew", "Guest", "Infra", "MGMT"], + ["MGMT", "Infra", "Guest", "Crew"], + ): + network = build_network(child_order) + totals = LibreQoS.findBandwidthMins(network, circuits) + + self.assertEqual(totals, (91, 45)) + self.assertEqual(network["Site"]["downloadBandwidthMbpsMin"], 120) + self.assertEqual(network["Site"]["uploadBandwidthMbpsMin"], 60) + generated = { + name: ( + node["downloadBandwidthMbpsMin"], + node["uploadBandwidthMbpsMin"], + ) + for name, node in network["Site"]["children"].items() + } + self.assertEqual( + generated, + { + "Crew": (20, 20), + "Guest": (60, 20), + "Infra": (1, 1), + "MGMT": (10, 4), + }, + ) + + def test_child_minimums_roll_up_once(self): + network = { + "Site": { + "downloadBandwidthMbps": 100, + "uploadBandwidthMbps": 100, + "downloadBandwidthMbpsMin": 0, + "uploadBandwidthMbpsMin": 0, + "children": { + "Tower": { + "downloadBandwidthMbps": 50, + "uploadBandwidthMbps": 50, + "downloadBandwidthMbpsMin": 0, + "uploadBandwidthMbpsMin": 0, + "children": { + "AP-1": { + "downloadBandwidthMbps": 25, + "uploadBandwidthMbps": 25, + "downloadBandwidthMbpsMin": 0, + "uploadBandwidthMbpsMin": 0, + }, + "AP-2": { + "downloadBandwidthMbps": 25, + "uploadBandwidthMbps": 25, + "downloadBandwidthMbpsMin": 0, + "uploadBandwidthMbpsMin": 0, + }, + }, + }, + "Tower-2": { + "downloadBandwidthMbps": 40, + "uploadBandwidthMbps": 40, + "downloadBandwidthMbpsMin": 0, + "uploadBandwidthMbpsMin": 0, + }, + }, + }, + } + circuits = [ + {"ParentNode": "Tower", "minDownload": 4, "minUpload": 1}, + {"ParentNode": "AP-1", "minDownload": 10, "minUpload": 2}, + {"ParentNode": "AP-2", "minDownload": 5, "minUpload": 1}, + {"ParentNode": "Tower-2", "minDownload": 7, "minUpload": 3}, + ] + + totals = LibreQoS.findBandwidthMins(network, circuits) + + self.assertEqual(totals, (26, 7)) + self.assertEqual(network["Site"]["downloadBandwidthMbpsMin"], 26) + self.assertEqual(network["Site"]["uploadBandwidthMbpsMin"], 7) + self.assertEqual( + network["Site"]["children"]["Tower"]["downloadBandwidthMbpsMin"], 19 + ) + self.assertEqual( + network["Site"]["children"]["Tower-2"]["downloadBandwidthMbpsMin"], 7 + ) + self.assertEqual( + network["Site"]["children"]["Tower"]["children"]["AP-1"][ + "downloadBandwidthMbpsMin" + ], + 10, + ) + self.assertEqual( + network["Site"]["children"]["Tower"]["children"]["AP-2"][ + "downloadBandwidthMbpsMin" + ], + 5, + ) + + def test_missing_minimum_keys_use_download_minimum(self): + network = { + "Leaf": { + "downloadBandwidthMbps": 100, + "uploadBandwidthMbps": 50, + } + } + circuits = [{"ParentNode": "Leaf", "minDownload": 150, "minUpload": 40}] + + totals = LibreQoS.findBandwidthMins(network, circuits) + + self.assertEqual(totals, (150, 40)) + self.assertEqual(network["Leaf"]["downloadBandwidthMbpsMin"], 150) + self.assertEqual(network["Leaf"]["uploadBandwidthMbpsMin"], 50) + + class TestFirstRunSinceBoot(unittest.TestCase): def setUp(self): temp_dir = tempfile.TemporaryDirectory() # nosec B108 -- knotmirror 0.0.1 From 1dd5b884054606e6570d2bf0ad9297c6e35ec9a4 Mon Sep 17 00:00:00 2001 From: Trendal Toews Date: Tue, 6 Oct 2026 23:59:17 -0700 Subject: [PATCH 03/17] Fix recent_rtt_data shift loop overwriting RTT history The forward loop (for i in 1..60) copies slot 0 into all 59 older slots, so median_latency() always returns the previous sample instead of a 60-sample median. Iterating in reverse preserves the history and drops the oldest sample. --- src/rust/lqosd/src/throughput_tracker/tracking_data.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/rust/lqosd/src/throughput_tracker/tracking_data.rs b/src/rust/lqosd/src/throughput_tracker/tracking_data.rs index d94cca13..9e7f60ef 100644 --- a/src/rust/lqosd/src/throughput_tracker/tracking_data.rs +++ b/src/rust/lqosd/src/throughput_tracker/tracking_data.rs @@ -1170,8 +1170,8 @@ impl ThroughputTracker { if let Some(rtt_median) = rtt_median && let Some(tracker) = raw_data.get_mut(local_ip) { - // Shift left - for i in 1..60 { + // Shift right (oldest falls off the end) + for i in (1..60).rev() { tracker.recent_rtt_data[i] = tracker.recent_rtt_data[i - 1]; } tracker.recent_rtt_data[0] = rtt_median; -- knotmirror 0.0.1 From 433914842ac9f82d5aab5d6d5b6339181f97deff Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Wed, 7 Oct 2026 12:29:18 -0500 Subject: [PATCH 04/17] Feat: add optional byte_counters configuration section Adds a [byte_counters] section that is absent by default, so existing configuration files keep working unchanged. The section will gate cumulative per-circuit and per-node byte counter collection in lqosd. --- src/lqos.example | 4 ++ .../lqos_config/src/etc/v15/byte_counters.rs | 38 +++++++++++++++++++ src/rust/lqos_config/src/etc/v15/example.toml | 4 ++ src/rust/lqos_config/src/etc/v15/mod.rs | 1 + .../lqos_config/src/etc/v15/top_config.rs | 8 ++++ 5 files changed, 55 insertions(+) create mode 100644 src/rust/lqos_config/src/etc/v15/byte_counters.rs diff --git a/src/lqos.example b/src/lqos.example index c3f67847..58821275 100644 --- a/src/lqos.example +++ b/src/lqos.example @@ -70,6 +70,10 @@ netflow_enabled = false # netflow_version = 9 do_not_track_subnets = [ "192.168.66.0/24" ] +[byte_counters] +# Optional cumulative byte counters for nodes and circuits, exposed by lqos_api. +enabled = false + [integration_common] circuit_name_as_address = false queue_refresh_interval_mins = 30 diff --git a/src/rust/lqos_config/src/etc/v15/byte_counters.rs b/src/rust/lqos_config/src/etc/v15/byte_counters.rs new file mode 100644 index 00000000..73c96fc2 --- /dev/null +++ b/src/rust/lqos_config/src/etc/v15/byte_counters.rs @@ -0,0 +1,38 @@ +//! Configuration for optional cumulative byte counters. +//! +//! When enabled, `lqosd` accumulates per-circuit byte totals from the +//! one-second throughput tracker and exposes cumulative per-circuit and +//! per-node counters on the local bus. + +use allocative::Allocative; +use serde::{Deserialize, Serialize}; + +/// Configuration for optional cumulative byte counters. +#[derive(Clone, Default, Serialize, Deserialize, Debug, PartialEq, Allocative)] +pub struct ByteCountersConfig { + /// Enables cumulative per-circuit and per-node byte counters. + /// + /// Defaults to `false` when the `[byte_counters]` section is absent so + /// existing configuration files keep their current behavior. + #[serde(default)] + pub enabled: bool, +} + +#[cfg(test)] +mod tests { + use super::ByteCountersConfig; + + #[test] + fn absent_section_defaults_to_disabled() { + let config: ByteCountersConfig = + toml::from_str("").expect("empty byte_counters section should parse"); + assert!(!config.enabled); + } + + #[test] + fn section_parses_enabled_flag() { + let config: ByteCountersConfig = + toml::from_str("enabled = true").expect("enabled flag should parse"); + assert!(config.enabled); + } +} diff --git a/src/rust/lqos_config/src/etc/v15/example.toml b/src/rust/lqos_config/src/etc/v15/example.toml index d440f448..3abdc404 100644 --- a/src/rust/lqos_config/src/etc/v15/example.toml +++ b/src/rust/lqos_config/src/etc/v15/example.toml @@ -102,6 +102,10 @@ collation_period_seconds = 10 license_key = "(data)" uisp_reporting_interval_seconds = 300 +[byte_counters] +# Optional cumulative byte counters for nodes and circuits, exposed by lqos_api. +enabled = false + [local_api] bearer_token = "" diff --git a/src/rust/lqos_config/src/etc/v15/mod.rs b/src/rust/lqos_config/src/etc/v15/mod.rs index b5ab63a3..baeef38c 100644 --- a/src/rust/lqos_config/src/etc/v15/mod.rs +++ b/src/rust/lqos_config/src/etc/v15/mod.rs @@ -5,6 +5,7 @@ pub use top_config::Config; pub use top_config::RttThresholds; pub use top_config::{SslConfig, normalize_external_hostname}; mod bridge; +mod byte_counters; mod dynamic_circuits; mod flows; pub mod influxdb; diff --git a/src/rust/lqos_config/src/etc/v15/top_config.rs b/src/rust/lqos_config/src/etc/v15/top_config.rs index cfc98f59..9d9feefb 100644 --- a/src/rust/lqos_config/src/etc/v15/top_config.rs +++ b/src/rust/lqos_config/src/etc/v15/top_config.rs @@ -277,6 +277,13 @@ pub struct Config { /// Enable per-ASN TemporalHeatmap collection. #[serde(default = "default_true")] pub enable_asn_heatmaps: bool, + + /// Optional cumulative byte counters for nodes and circuits. + /// + /// The section is optional so older configuration files keep working + /// unchanged; counters are disabled when it is absent. + #[serde(default)] + pub byte_counters: super::byte_counters::ByteCountersConfig, } impl Config { @@ -482,6 +489,7 @@ impl Default for Config { enable_circuit_heatmaps: true, enable_site_heatmaps: true, enable_asn_heatmaps: true, + byte_counters: super::byte_counters::ByteCountersConfig::default(), } } } -- knotmirror 0.0.1 From d52e3a6dbbdad9d84470fc6c26dd9ee7e806c7ab Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Wed, 7 Oct 2026 12:29:22 -0500 Subject: [PATCH 05/17] Feat: add byte counters bus request and response Adds GetByteCounters with cumulative per-node and per-circuit byte counter payloads. The request is read-only, so it fails fast on timeout and needs no daemon-side mutation. --- src/rust/lqos_bus/src/bus/request.rs | 5 ++++ src/rust/lqos_bus/src/bus/response.rs | 40 +++++++++++++++++++++++++++ src/rust/lqos_bus/src/lib.rs | 16 +++++------ 3 files changed, 53 insertions(+), 8 deletions(-) diff --git a/src/rust/lqos_bus/src/bus/request.rs b/src/rust/lqos_bus/src/bus/request.rs index ac2b9093..af77a416 100644 --- a/src/rust/lqos_bus/src/bus/request.rs +++ b/src/rust/lqos_bus/src/bus/request.rs @@ -633,6 +633,9 @@ pub enum BusRequest { /// Retrieve queue marks/drops totals GetQueueStatsTotal, + /// Retrieve cumulative byte counters for nodes and circuits. + GetByteCounters, + /// Retrieve current top-level QoO history. GetQoo, @@ -783,6 +786,7 @@ impl BusRequest { Self::GetProtocolFlowTimeline { .. } => "GetProtocolFlowTimeline", Self::GetSchedulerDetails => "GetSchedulerDetails", Self::GetQueueStatsTotal => "GetQueueStatsTotal", + Self::GetByteCounters => "GetByteCounters", Self::GetCircuitCapacity => "GetCircuitCapacity", Self::GetTreeCapacity => "GetTreeCapacity", Self::GetRetransmitSummary => "GetRetransmitSummary", @@ -862,6 +866,7 @@ impl BusRequest { | Self::GetProtocolFlowTimeline { .. } | Self::GetSchedulerDetails | Self::GetQueueStatsTotal + | Self::GetByteCounters | Self::GetCircuitCapacity | Self::GetTreeCapacity | Self::GetRetransmitSummary diff --git a/src/rust/lqos_bus/src/bus/response.rs b/src/rust/lqos_bus/src/bus/response.rs index ceb83bc9..ea6d0b1b 100644 --- a/src/rust/lqos_bus/src/bus/response.rs +++ b/src/rust/lqos_bus/src/bus/response.rs @@ -538,6 +538,43 @@ pub struct QueueStatsTotal { pub drops: DownUpOrder, } +/// Cumulative byte counter for one network node. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Allocative)] +pub struct NodeByteCounters { + /// Optional stable node identifier from `network.json` metadata. + pub node_id: Option, + /// Node name as it appears in `network.json`. + pub name: String, + /// Cumulative bytes (down/up) since `lqosd` started tracking. + /// + /// Node totals include traffic from descendant nodes. + pub bytes: DownUpOrder, +} + +/// Cumulative byte counter for one circuit. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Allocative)] +pub struct CircuitByteCounters { + /// Circuit ID from `ShapedDevices.csv` or a dynamic circuit. + pub circuit_id: String, + /// Circuit name from `ShapedDevices.csv` or a dynamic circuit. + pub circuit_name: String, + /// Effective parent node for this circuit. + pub parent_node: String, + /// Cumulative bytes (down/up) since `lqosd` started tracking. + pub bytes: DownUpOrder, +} + +/// Cumulative byte counters for network nodes and circuits. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Allocative)] +pub struct ByteCountersSnapshot { + /// Whether byte counters are enabled in configuration. + pub enabled: bool, + /// Cumulative counters for every node in the runtime network tree. + pub nodes: Vec, + /// Cumulative counters for circuits with recorded traffic. + pub circuits: Vec, +} + /// Circuit capacity utilization row #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Allocative)] pub struct CircuitCapacityRow { @@ -867,6 +904,9 @@ pub enum BusResponse { /// Queue stats totals (marks/drops) QueueStatsTotal(QueueStatsTotal), + /// Cumulative byte counters for nodes and circuits. + ByteCounters(ByteCountersSnapshot), + /// Current QoO data. Qoo(Option), diff --git a/src/rust/lqos_bus/src/lib.rs b/src/rust/lqos_bus/src/lib.rs index f8860b03..7a208a14 100644 --- a/src/rust/lqos_bus/src/lib.rs +++ b/src/rust/lqos_bus/src/lib.rs @@ -29,14 +29,14 @@ pub use ip_stats::{ }; mod tc_handle; pub use bus::response::{ - AsnHeatmapData, AsnListEntry, BakeryStatsSnapshot, CircuitCapacityRow, CircuitCount, - CircuitHeatmapData, CircuitRollup, CountryListEntry, DeviceCounts, ExecutiveSummaryHeader, - FlowMapPoint, FlowTimelineEntry, InsightLicenseSummary, LtsCapabilitiesSummary, NodeCapacity, - OverrideMutationResult, ProtocolListEntry, QooData, QueueStatsTotal, RetransmitSummary, - SchedulerDetails, SearchResultEntry, SiteHeatmapData, StormguardDebugDirection, - StormguardDebugEntry, StormguardRuntimeSettings, StormguardRuntimeStatus, - TreeGuardRuntimeNodeBranchSnapshot, TreeGuardRuntimeNodeOperationSnapshot, UrgentIssue, - WarningLevel, + AsnHeatmapData, AsnListEntry, BakeryStatsSnapshot, ByteCountersSnapshot, CircuitByteCounters, + CircuitCapacityRow, CircuitCount, CircuitHeatmapData, CircuitRollup, CountryListEntry, + DeviceCounts, ExecutiveSummaryHeader, FlowMapPoint, FlowTimelineEntry, InsightLicenseSummary, + LtsCapabilitiesSummary, NodeByteCounters, NodeCapacity, OverrideMutationResult, + ProtocolListEntry, QooData, QueueStatsTotal, RetransmitSummary, SchedulerDetails, + SearchResultEntry, SiteHeatmapData, StormguardDebugDirection, StormguardDebugEntry, + StormguardRuntimeSettings, StormguardRuntimeStatus, TreeGuardRuntimeNodeBranchSnapshot, + TreeGuardRuntimeNodeOperationSnapshot, UrgentIssue, WarningLevel, }; pub use bus::{ BUS_SOCKET_PATH, BakeryCapacityReportInterface, BlackboardSystem, BusClientError, BusReply, -- knotmirror 0.0.1 From ff596549916ee60b4b0632f57e61ca11e783dd1b Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Wed, 7 Oct 2026 12:29:22 -0500 Subject: [PATCH 06/17] Feat: accumulate and expose cumulative circuit byte counters When [byte_counters] enabled = true, the one-second throughput tracker batches each circuit's actual-byte deltas into a cumulative counter map. Node totals are rolled up through the runtime network tree when the bus is queried, so node values include descendants. Counters are in-memory and reset when lqosd restarts. --- src/rust/lqosd/src/byte_counters.rs | 266 ++++++++++++++++++ src/rust/lqosd/src/main.rs | 3 + .../src/throughput_tracker/tracking_data.rs | 34 ++- 3 files changed, 293 insertions(+), 10 deletions(-) create mode 100644 src/rust/lqosd/src/byte_counters.rs diff --git a/src/rust/lqosd/src/byte_counters.rs b/src/rust/lqosd/src/byte_counters.rs new file mode 100644 index 00000000..12a4b99b --- /dev/null +++ b/src/rust/lqosd/src/byte_counters.rs @@ -0,0 +1,266 @@ +//! Optional cumulative byte counters for circuits and network nodes. +//! +//! When `[byte_counters] enabled = true` is set in `/etc/lqos.conf`, the +//! one-second throughput tracker feeds per-circuit byte deltas into this +//! module. Counters are cumulative since `lqosd` started and are not +//! persisted across restarts. +//! +//! Only per-circuit totals are stored. Node totals are derived when a +//! snapshot is requested by walking each circuit's effective parent node +//! through the runtime network tree, so node totals include descendants. + +use fxhash::FxHashMap; +use lqos_bus::{ByteCountersSnapshot, CircuitByteCounters, NodeByteCounters}; +use lqos_config::NetworkJson; +use lqos_utils::units::DownUpOrder; +use once_cell::sync::Lazy; +use parking_lot::RwLock; +use std::sync::atomic::{AtomicBool, Ordering}; + +/// Cumulative bytes keyed by circuit hash. +static CIRCUIT_BYTES: Lazy>>> = + Lazy::new(|| RwLock::new(FxHashMap::default())); + +/// Whether byte counter collection is enabled. +static ENABLED: AtomicBool = AtomicBool::new(false); + +/// Enables or disables byte counter collection. +/// +/// Side effects: updates the global collection flag. Counters recorded before +/// a disable are kept until the process restarts. +pub(crate) fn set_enabled(enabled: bool) { + ENABLED.store(enabled, Ordering::Relaxed); +} + +/// Returns true when byte counter collection is enabled. +pub(crate) fn is_enabled() -> bool { + ENABLED.load(Ordering::Relaxed) +} + +/// Adds one cycle of per-circuit byte deltas to the cumulative counters. +/// +/// Side effects: mutates the shared cumulative counter map. +pub(crate) fn add_batch(deltas: FxHashMap>) { + if deltas.is_empty() { + return; + } + merge(&mut CIRCUIT_BYTES.write(), deltas); +} + +/// Merges per-circuit deltas into a cumulative counter map. +fn merge( + counters: &mut FxHashMap>, + deltas: FxHashMap>, +) { + for (circuit_hash, bytes) in deltas { + counters.entry(circuit_hash).or_default().checked_add(bytes); + } +} + +/// Builds a cumulative byte counter snapshot for the bus. +/// +/// Side effects: acquires the counter read lock and the runtime network tree +/// read lock. +pub(crate) fn snapshot() -> ByteCountersSnapshot { + if !is_enabled() { + return ByteCountersSnapshot { + enabled: false, + nodes: Vec::new(), + circuits: Vec::new(), + }; + } + + let circuit_bytes: Vec<(i64, DownUpOrder)> = CIRCUIT_BYTES + .read() + .iter() + .map(|(circuit_hash, bytes)| (*circuit_hash, *bytes)) + .collect(); + + let catalog = lqos_network_devices::network_devices_catalog(); + lqos_network_devices::with_network_json_read(|tree| { + rollup(tree, &circuit_bytes, |circuit_hash| { + let device = catalog.device_by_hashes(None, Some(circuit_hash))?; + Some(CircuitDescriptor { + circuit_id: device.circuit_id.clone(), + circuit_name: device.circuit_name.clone(), + parent_node: device.parent_node.clone(), + }) + }) + }) +} + +/// Identity fields for one circuit, resolved from the shaped-devices catalog. +struct CircuitDescriptor { + circuit_id: String, + circuit_name: String, + parent_node: String, +} + +/// Rolls circuit totals up the network tree and formats a bus snapshot. +/// +/// Node totals include every descendant circuit. Circuits whose device or +/// parent node cannot be resolved are omitted from both lists. +fn rollup( + tree: &NetworkJson, + circuits: &[(i64, DownUpOrder)], + mut lookup: impl FnMut(i64) -> Option, +) -> ByteCountersSnapshot { + let mut node_totals = vec![DownUpOrder::zeroed(); tree.nodes.len()]; + let mut node_index: FxHashMap<&str, usize> = FxHashMap::default(); + for (index, node) in tree.nodes.iter().enumerate() { + node_index.entry(node.name.as_str()).or_insert(index); + } + + let mut circuit_rows = Vec::new(); + for (circuit_hash, bytes) in circuits { + let Some(descriptor) = lookup(*circuit_hash) else { + continue; + }; + let Some(&parent_index) = node_index.get(descriptor.parent_node.as_str()) else { + continue; + }; + for &index in &tree.nodes[parent_index].parents { + if let Some(total) = node_totals.get_mut(index) { + total.checked_add(*bytes); + } + } + circuit_rows.push(CircuitByteCounters { + circuit_id: descriptor.circuit_id, + circuit_name: descriptor.circuit_name, + parent_node: descriptor.parent_node, + bytes: *bytes, + }); + } + circuit_rows.sort_by(|a, b| a.circuit_id.cmp(&b.circuit_id)); + + let nodes = tree + .nodes + .iter() + .enumerate() + .map(|(index, node)| NodeByteCounters { + node_id: node.id.clone(), + name: node.name.clone(), + bytes: node_totals[index], + }) + .collect(); + + ByteCountersSnapshot { + enabled: true, + nodes, + circuits: circuit_rows, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use lqos_config::NetworkJsonNode; + use lqos_utils::rtt::RttBuffer; + + fn node( + name: &str, + id: Option<&str>, + parents: Vec, + immediate_parent: Option, + ) -> NetworkJsonNode { + NetworkJsonNode { + name: name.to_string(), + id: id.map(str::to_string), + virtual_node: false, + max_throughput: (0.0, 0.0), + current_throughput: DownUpOrder::zeroed(), + current_packets: DownUpOrder::zeroed(), + current_tcp_packets: DownUpOrder::zeroed(), + current_udp_packets: DownUpOrder::zeroed(), + current_icmp_packets: DownUpOrder::zeroed(), + current_tcp_retransmits: DownUpOrder::zeroed(), + current_tcp_retransmit_packets: DownUpOrder::zeroed(), + current_rtt_flows: DownUpOrder::zeroed(), + current_marks: DownUpOrder::zeroed(), + current_drops: DownUpOrder::zeroed(), + rtt_buffer: RttBuffer::default(), + parents, + immediate_parent, + node_type: None, + latitude: None, + longitude: None, + active_attachment_name: None, + heatmap: None, + qoq_heatmap: None, + } + } + + fn descriptor(circuit_id: &str, parent_node: &str) -> Option { + Some(CircuitDescriptor { + circuit_id: circuit_id.to_string(), + circuit_name: format!("{circuit_id} name"), + parent_node: parent_node.to_string(), + }) + } + + fn test_tree() -> NetworkJson { + NetworkJson { + nodes: vec![ + node("Root", None, vec![0], None), + node("Site A", Some("site-a"), vec![0, 1], Some(0)), + node("Site A1", None, vec![0, 1, 2], Some(1)), + node("Site B", None, vec![0, 3], Some(0)), + ], + } + } + + #[test] + fn merge_accumulates_repeated_circuit_deltas() { + let mut counters = FxHashMap::default(); + merge( + &mut counters, + FxHashMap::from_iter([(7, DownUpOrder::new(100, 40))]), + ); + merge( + &mut counters, + FxHashMap::from_iter([(7, DownUpOrder::new(10, 5))]), + ); + + assert_eq!(counters.get(&7), Some(&DownUpOrder::new(110, 45))); + } + + #[test] + fn rollup_includes_descendant_bytes_in_ancestor_totals() { + let circuits = vec![(1, DownUpOrder::new(100, 0)), (2, DownUpOrder::new(0, 50))]; + let snapshot = rollup(&test_tree(), &circuits, |circuit_hash| match circuit_hash { + 1 => descriptor("circuit-1", "Site A1"), + 2 => descriptor("circuit-2", "Site A"), + _ => None, + }); + + assert!(snapshot.enabled); + assert_eq!(snapshot.nodes[0].bytes, DownUpOrder::new(100, 50)); + assert_eq!(snapshot.nodes[1].bytes, DownUpOrder::new(100, 50)); + assert_eq!(snapshot.nodes[2].bytes, DownUpOrder::new(100, 0)); + assert_eq!(snapshot.nodes[3].bytes, DownUpOrder::new(0, 0)); + assert_eq!(snapshot.nodes[1].node_id.as_deref(), Some("site-a")); + assert_eq!(snapshot.circuits.len(), 2); + assert_eq!(snapshot.circuits[0].circuit_id, "circuit-1"); + assert_eq!(snapshot.circuits[0].parent_node, "Site A1"); + assert_eq!(snapshot.circuits[1].bytes, DownUpOrder::new(0, 50)); + } + + #[test] + fn rollup_skips_unresolved_circuits_and_parents() { + let circuits = vec![ + (1, DownUpOrder::new(100, 0)), + (2, DownUpOrder::new(10, 10)), + (3, DownUpOrder::new(5, 5)), + ]; + let snapshot = rollup(&test_tree(), &circuits, |circuit_hash| match circuit_hash { + 1 => descriptor("circuit-1", "Site B"), + 2 => None, + _ => descriptor("circuit-3", "Missing Node"), + }); + + assert_eq!(snapshot.circuits.len(), 1); + assert_eq!(snapshot.circuits[0].circuit_id, "circuit-1"); + assert_eq!(snapshot.nodes[0].bytes, DownUpOrder::new(100, 0)); + assert_eq!(snapshot.nodes[3].bytes, DownUpOrder::new(100, 0)); + } +} diff --git a/src/rust/lqosd/src/main.rs b/src/rust/lqosd/src/main.rs index 1676fab6..29fe5ac0 100644 --- a/src/rust/lqosd/src/main.rs +++ b/src/rust/lqosd/src/main.rs @@ -4,6 +4,7 @@ #![deny(clippy::unwrap_used)] mod blackboard; +mod byte_counters; mod dynamic_circuits; mod file_lock; mod ip_mapping; @@ -216,6 +217,7 @@ fn main() -> Result<()> { // Load config let config = lqos_config::load_config()?; + byte_counters::set_enabled(config.byte_counters.enabled); let web_config = config.clone(); let radius_accounting_config = config.radius_accounting.clone(); shaping_runtime::mark_starting("LibreQoS is starting shaping services."); @@ -1209,6 +1211,7 @@ fn handle_bus_requests(requests: &[BusRequest], responses: &mut Vec let totals = queue_stats_total_data(); BusResponse::QueueStatsTotal(totals) } + BusRequest::GetByteCounters => BusResponse::ByteCounters(byte_counters::snapshot()), BusRequest::GetQoo => { let data = node_manager::local_api::executive::qoo_global(); BusResponse::Qoo(Some(data)) diff --git a/src/rust/lqosd/src/throughput_tracker/tracking_data.rs b/src/rust/lqosd/src/throughput_tracker/tracking_data.rs index d94cca13..364c4956 100644 --- a/src/rust/lqosd/src/throughput_tracker/tracking_data.rs +++ b/src/rust/lqosd/src/throughput_tracker/tracking_data.rs @@ -661,6 +661,9 @@ impl ThroughputTracker { let mut changed_circuits = HashSet::new(); + let byte_counters_enabled = crate::byte_counters::is_enabled(); + let mut byte_counter_deltas: FxHashMap> = FxHashMap::default(); + let self_cycle = self.cycle.load(std::sync::atomic::Ordering::Relaxed); let catalog = lqos_network_devices::network_devices_catalog(); let mut raw_data = self.raw_data.lock(); @@ -768,9 +771,25 @@ impl ThroughputTracker { } if entry.packets != entry.prev_packets { entry.most_recent_cycle = self_cycle; + let actual_bytes_delta = DownUpOrder::new( + entry + .actual_bytes + .down + .saturating_sub(entry.prev_actual_bytes.down), + entry + .actual_bytes + .up + .saturating_sub(entry.prev_actual_bytes.up), + ); // Call to Bakery Update for existing traffic if let Some(circuit_hash) = entry.circuit_hash { changed_circuits.insert(circuit_hash); + if byte_counters_enabled { + byte_counter_deltas + .entry(circuit_hash) + .or_default() + .checked_add(actual_bytes_delta); + } } record_dynamic_observation( @@ -795,16 +814,7 @@ impl ThroughputTracker { if let Some(parents) = &entry.network_json_parents { net_json_calc.add_throughput_cycle( parents, - ( - entry - .actual_bytes - .down - .saturating_sub(entry.prev_actual_bytes.down), - entry - .actual_bytes - .up - .saturating_sub(entry.prev_actual_bytes.up), - ), + (actual_bytes_delta.down, actual_bytes_delta.up), ( entry.packets.down.saturating_sub(entry.prev_packets.down), entry.packets.up.saturating_sub(entry.prev_packets.up), @@ -934,6 +944,10 @@ impl ThroughputTracker { } }); + if byte_counters_enabled { + crate::byte_counters::add_batch(byte_counter_deltas); + } + if !observations.is_empty() { lqos_network_devices::report_observations(&observations); } -- knotmirror 0.0.1 From 94ed100feab368468f48ebfb0c3f9b191f09005b Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Wed, 7 Oct 2026 12:29:26 -0500 Subject: [PATCH 07/17] Docs: document byte counters configuration and API endpoint Documents the optional [byte_counters] section, counter reset semantics, subtree-inclusive node totals, and the GET /byte_counters endpoint in English and Spanish. --- docs-es/v2.0/api-es.md | 3 +++ docs-es/v2.0/configuration-advanced-es.md | 17 +++++++++++++++++ docs/v2.0/api.md | 3 +++ docs/v2.0/configuration-advanced.md | 17 +++++++++++++++++ 4 files changed, 40 insertions(+) diff --git a/docs-es/v2.0/api-es.md b/docs-es/v2.0/api-es.md index 9bb97dd7..65600d8c 100644 --- a/docs-es/v2.0/api-es.md +++ b/docs-es/v2.0/api-es.md @@ -121,9 +121,12 @@ Endpoints representativos: - `GET /search` - `GET /current_throughput` - `GET /queue_stats_total` +- `GET /byte_counters` - `GET /warnings` - `GET /urgent`, `GET /urgent/status` +`GET /byte_counters` devuelve contadores de bytes acumulados por nodo y por circuito cuando `[byte_counters] enabled = true` está configurado en `/etc/lqos.conf`. Los valores son acumulados desde que `lqosd` inició, incluyen el tráfico descendiente en los nodos y se reinician cuando `lqosd` se reinicia. Consulte [Configuración avanzada](configuration-advanced-es.md). + ### 5) Operaciones de control y reload Disparar acciones de control operativo cuando sea necesario. diff --git a/docs-es/v2.0/configuration-advanced-es.md b/docs-es/v2.0/configuration-advanced-es.md index 0df8da6a..88c44f46 100644 --- a/docs-es/v2.0/configuration-advanced-es.md +++ b/docs-es/v2.0/configuration-advanced-es.md @@ -62,6 +62,23 @@ netflow_version = 5 do_not_track_subnets = ["192.168.0.0/16"] ``` +### Contadores de bytes (opcional) + +LibreQoS puede mantener contadores de bytes acumulados por circuito y por nodo de red para la contabilidad de uso de datos, y exponerlos a través de `lqos_api`. La función está deshabilitada por defecto. Para habilitarla, agregue la siguiente sección a `/etc/lqos.conf` y reinicie `lqosd`: + +```toml +[byte_counters] +enabled = true +``` + +- Los contadores acumulan el tráfico medido por el rastreador de throughput de un segundo. +- Los valores son bytes realmente transmitidos, no bytes descartados por el shaping. +- Los valores son acumulados desde que `lqosd` inició y se reinician cuando `lqosd` se reinicia. +- Los valores de un nodo incluyen el tráfico de todos sus nodos descendientes. +- Solo se listan los circuitos con tráfico registrado. + +Con los contadores habilitados, `GET /byte_counters` en la API del nodo devuelve los valores actuales. Consulte [API del nodo LibreQoS](api-es.md). + ### Contabilidad RADIUS (opcional) LibreQoS acepta una sección opcional `[radius_accounting]` para definir clientes NAS de confianza. Cuando está habilitada, `lqosd` inicia un servicio de contabilidad RADIUS, verifica paquetes de los clientes configurados, envía paquetes Accounting-Response para solicitudes aceptadas y mantiene el estado de sesión decodificado en memoria. Cuando `radius_accounting.dynamic_circuit_application.enabled` y la opción global `dynamic_circuits.enabled` están habilitadas, las sesiones Start e Interim-Update aptas se envían a la ruta de circuitos dinámicos. diff --git a/docs/v2.0/api.md b/docs/v2.0/api.md index 3f564200..dfc33982 100644 --- a/docs/v2.0/api.md +++ b/docs/v2.0/api.md @@ -121,9 +121,12 @@ Representative endpoints: - `GET /search` - `GET /current_throughput` - `GET /queue_stats_total` +- `GET /byte_counters` - `GET /warnings` - `GET /urgent`, `GET /urgent/status` +`GET /byte_counters` returns cumulative per-node and per-circuit byte counters when `[byte_counters] enabled = true` is set in `/etc/lqos.conf`. Values are cumulative since `lqosd` started, include descendant traffic for nodes, and reset when `lqosd` restarts. See [Advanced Configuration](configuration-advanced.md). + ### 5) Control and Reload Operations Trigger operational control actions when needed. diff --git a/docs/v2.0/configuration-advanced.md b/docs/v2.0/configuration-advanced.md index 7672585e..2c075db4 100644 --- a/docs/v2.0/configuration-advanced.md +++ b/docs/v2.0/configuration-advanced.md @@ -64,6 +64,23 @@ netflow_version = 5 do_not_track_subnets = ["192.168.0.0/16"] ``` +#### Byte counters (optional) + +LibreQoS can keep cumulative byte counters per circuit and per network node for data-usage accounting, and expose them through `lqos_api`. The feature is disabled by default. To enable it, add the following section to `/etc/lqos.conf` and restart `lqosd`: + +```toml +[byte_counters] +enabled = true +``` + +- Counters accumulate the traffic measured by the one-second throughput tracker. +- Values are actual transmitted bytes, not bytes dropped by shaping. +- Values are cumulative since `lqosd` started and reset when `lqosd` restarts. +- Node values include traffic from all descendant nodes. +- Only circuits with recorded traffic are listed. + +With the counters enabled, `GET /byte_counters` on the Node API returns the current values. See [LibreQoS Node API](api.md). + #### On-a-stick mode queue mapping (single interface) When running on-a-stick mode, LibreQoS splits available TX queues in half: -- knotmirror 0.0.1 From b19bf9ec14e557403d570516fdcfd5f6f27285f4 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Wed, 7 Oct 2026 12:49:28 -0500 Subject: [PATCH 08/17] Fix: keep byte counter identity across configuration changes Captures circuit identity and parent when a counter first receives traffic, so circuits removed from configuration keep contributing to their last known parent instead of dropping out of node totals. Resolves parent nodes by stable id before name, fills descriptors at read time, skips zero-byte deltas, and documents the counter lock ordering. Expands tests for the absent config section, disabled snapshots, root-attached circuits, id-preferred node resolution, and stable circuit ordering. --- docs-es/v2.0/configuration-advanced-es.md | 4 +- docs/v2.0/configuration-advanced.md | 4 +- .../lqos_config/src/etc/v15/byte_counters.rs | 2 +- .../lqos_config/src/etc/v15/top_config.rs | 10 + .../src/combined_catalog.rs | 13 + src/rust/lqosd/src/byte_counters.rs | 301 +++++++++++++----- .../src/throughput_tracker/tracking_data.rs | 16 +- 7 files changed, 257 insertions(+), 93 deletions(-) diff --git a/docs-es/v2.0/configuration-advanced-es.md b/docs-es/v2.0/configuration-advanced-es.md index 88c44f46..6f26f0ab 100644 --- a/docs-es/v2.0/configuration-advanced-es.md +++ b/docs-es/v2.0/configuration-advanced-es.md @@ -71,11 +71,11 @@ LibreQoS puede mantener contadores de bytes acumulados por circuito y por nodo d enabled = true ``` -- Los contadores acumulan el tráfico medido por el rastreador de throughput de un segundo. - Los valores son bytes realmente transmitidos, no bytes descartados por el shaping. -- Los valores son acumulados desde que `lqosd` inició y se reinician cuando `lqosd` se reinicia. +- Los valores se acumulan mientras `lqosd` se ejecuta y se reinician cuando `lqosd` se reinicia. - Los valores de un nodo incluyen el tráfico de todos sus nodos descendientes. - Solo se listan los circuitos con tráfico registrado. +- Los circuitos eliminados de `ShapedDevices.csv` siguen aportando sus bytes acumulados a su último nodo principal conocido mientras `lqosd` se ejecuta. Con los contadores habilitados, `GET /byte_counters` en la API del nodo devuelve los valores actuales. Consulte [API del nodo LibreQoS](api-es.md). diff --git a/docs/v2.0/configuration-advanced.md b/docs/v2.0/configuration-advanced.md index 2c075db4..02508517 100644 --- a/docs/v2.0/configuration-advanced.md +++ b/docs/v2.0/configuration-advanced.md @@ -73,11 +73,11 @@ LibreQoS can keep cumulative byte counters per circuit and per network node for enabled = true ``` -- Counters accumulate the traffic measured by the one-second throughput tracker. - Values are actual transmitted bytes, not bytes dropped by shaping. -- Values are cumulative since `lqosd` started and reset when `lqosd` restarts. +- Values accumulate while `lqosd` runs and reset when `lqosd` restarts. - Node values include traffic from all descendant nodes. - Only circuits with recorded traffic are listed. +- Circuits removed from `ShapedDevices.csv` keep contributing their accumulated bytes to their last known parent while `lqosd` runs. With the counters enabled, `GET /byte_counters` on the Node API returns the current values. See [LibreQoS Node API](api.md). diff --git a/src/rust/lqos_config/src/etc/v15/byte_counters.rs b/src/rust/lqos_config/src/etc/v15/byte_counters.rs index 73c96fc2..6c6677c5 100644 --- a/src/rust/lqos_config/src/etc/v15/byte_counters.rs +++ b/src/rust/lqos_config/src/etc/v15/byte_counters.rs @@ -23,7 +23,7 @@ mod tests { use super::ByteCountersConfig; #[test] - fn absent_section_defaults_to_disabled() { + fn empty_section_defaults_to_disabled() { let config: ByteCountersConfig = toml::from_str("").expect("empty byte_counters section should parse"); assert!(!config.enabled); diff --git a/src/rust/lqos_config/src/etc/v15/top_config.rs b/src/rust/lqos_config/src/etc/v15/top_config.rs index 9d9feefb..6cb4294d 100644 --- a/src/rust/lqos_config/src/etc/v15/top_config.rs +++ b/src/rust/lqos_config/src/etc/v15/top_config.rs @@ -722,6 +722,16 @@ mod test { assert_eq!(config.local_api, Default::default()); } + #[test] + fn byte_counters_config_defaults_when_section_is_absent() { + let legacy = remove_sections(include_str!("example.toml"), &["byte_counters"]); + let config = + Config::load_from_string(&legacy).expect("Cannot read config without byte_counters"); + + assert_eq!(config.byte_counters, Default::default()); + assert!(!config.byte_counters.enabled); + } + #[test] fn load_example_legacy_spylnx() { let legacy = include_str!("example.toml") diff --git a/src/rust/lqos_network_devices/src/combined_catalog.rs b/src/rust/lqos_network_devices/src/combined_catalog.rs index 83c92660..62688327 100644 --- a/src/rust/lqos_network_devices/src/combined_catalog.rs +++ b/src/rust/lqos_network_devices/src/combined_catalog.rs @@ -225,6 +225,19 @@ mod tests { ); } + #[test] + fn device_by_hashes_falls_back_to_dynamic_circuit() { + let mut dynamic = device(42); + dynamic.circuit_id = "dyn-circuit".to_string(); + + let catalog = catalog(vec![], vec![dynamic]); + let resolved = catalog + .device_by_hashes(None, Some(42)) + .expect("dynamic circuit should resolve by circuit hash"); + + assert_eq!(resolved.circuit_id, "dyn-circuit"); + } + #[test] fn mapped_circuit_count_ignores_unmapped_rows_and_counts_ipv6() { let mut unmapped = device(20); diff --git a/src/rust/lqosd/src/byte_counters.rs b/src/rust/lqosd/src/byte_counters.rs index 12a4b99b..347fbbf7 100644 --- a/src/rust/lqosd/src/byte_counters.rs +++ b/src/rust/lqosd/src/byte_counters.rs @@ -5,20 +5,24 @@ //! module. Counters are cumulative since `lqosd` started and are not //! persisted across restarts. //! -//! Only per-circuit totals are stored. Node totals are derived when a -//! snapshot is requested by walking each circuit's effective parent node -//! through the runtime network tree, so node totals include descendants. +//! Only per-circuit totals and their last-known identity are stored. Node +//! totals are derived when a snapshot is requested by walking each circuit's +//! parent node through the runtime network tree, so node totals include +//! descendants. Circuit identity is captured when a counter first receives +//! traffic, so circuits removed from configuration keep contributing their +//! accumulated bytes to their last known parent while `lqosd` runs. use fxhash::FxHashMap; use lqos_bus::{ByteCountersSnapshot, CircuitByteCounters, NodeByteCounters}; use lqos_config::NetworkJson; +use lqos_network_devices::NetworkDevicesCatalog; use lqos_utils::units::DownUpOrder; use once_cell::sync::Lazy; use parking_lot::RwLock; use std::sync::atomic::{AtomicBool, Ordering}; -/// Cumulative bytes keyed by circuit hash. -static CIRCUIT_BYTES: Lazy>>> = +/// Cumulative bytes and last-known identity keyed by circuit hash. +static CIRCUIT_BYTES: Lazy>> = Lazy::new(|| RwLock::new(FxHashMap::default())); /// Whether byte counter collection is enabled. @@ -39,28 +43,76 @@ pub(crate) fn is_enabled() -> bool { /// Adds one cycle of per-circuit byte deltas to the cumulative counters. /// +/// New circuits capture their identity from `catalog` on first sight. +/// /// Side effects: mutates the shared cumulative counter map. -pub(crate) fn add_batch(deltas: FxHashMap>) { +pub(crate) fn add_batch(deltas: FxHashMap>, catalog: &NetworkDevicesCatalog) { if deltas.is_empty() { return; } - merge(&mut CIRCUIT_BYTES.write(), deltas); + apply_deltas(&mut CIRCUIT_BYTES.write(), deltas, |circuit_hash| { + describe_circuit(catalog, circuit_hash) + }); } -/// Merges per-circuit deltas into a cumulative counter map. -fn merge( - counters: &mut FxHashMap>, +/// Merges per-circuit deltas into a cumulative counter map, capturing identity +/// through `describe` when a circuit is first seen. +fn apply_deltas( + counters: &mut FxHashMap, deltas: FxHashMap>, + describe: impl Fn(i64) -> Option, ) { for (circuit_hash, bytes) in deltas { - counters.entry(circuit_hash).or_default().checked_add(bytes); + let counter = counters.entry(circuit_hash).or_default(); + if counter.descriptor.is_none() { + counter.descriptor = describe(circuit_hash); + } + counter.bytes.checked_add(bytes); } } +/// Fills descriptors for counters that could not resolve identity when they +/// were first recorded, for example because the catalog snapshot was stale. +/// +/// Side effects: mutates the shared cumulative counter map. +fn fill_missing_descriptors() { + if CIRCUIT_BYTES + .read() + .values() + .all(|counter| counter.descriptor.is_some()) + { + return; + } + + let catalog = lqos_network_devices::network_devices_catalog(); + let mut counters = CIRCUIT_BYTES.write(); + for (circuit_hash, counter) in counters.iter_mut() { + if counter.descriptor.is_none() { + counter.descriptor = describe_circuit(&catalog, *circuit_hash); + } + } +} + +/// Resolves one circuit's identity fields from the combined device catalog. +fn describe_circuit( + catalog: &NetworkDevicesCatalog, + circuit_hash: i64, +) -> Option { + let device = catalog.device_by_hashes(None, Some(circuit_hash))?; + Some(CircuitDescriptor { + circuit_id: device.circuit_id.clone(), + circuit_name: device.circuit_name.clone(), + parent_node: device.parent_node.clone(), + parent_node_id: device.parent_node_id.clone(), + }) +} + /// Builds a cumulative byte counter snapshot for the bus. /// -/// Side effects: acquires the counter read lock and the runtime network tree -/// read lock. +/// Side effects: acquires the counter lock and the runtime network tree read +/// lock. Descriptors are resolved before the tree lock is taken so the lock +/// order stays `CIRCUIT_BYTES` then `NETWORK_JSON`, matching the tracker's +/// `NETWORK_JSON` write followed by `CIRCUIT_BYTES` write. pub(crate) fn snapshot() -> ByteCountersSnapshot { if !is_enabled() { return ByteCountersSnapshot { @@ -70,65 +122,70 @@ pub(crate) fn snapshot() -> ByteCountersSnapshot { }; } - let circuit_bytes: Vec<(i64, DownUpOrder)> = CIRCUIT_BYTES - .read() - .iter() - .map(|(circuit_hash, bytes)| (*circuit_hash, *bytes)) - .collect(); + fill_missing_descriptors(); - let catalog = lqos_network_devices::network_devices_catalog(); - lqos_network_devices::with_network_json_read(|tree| { - rollup(tree, &circuit_bytes, |circuit_hash| { - let device = catalog.device_by_hashes(None, Some(circuit_hash))?; - Some(CircuitDescriptor { - circuit_id: device.circuit_id.clone(), - circuit_name: device.circuit_name.clone(), - parent_node: device.parent_node.clone(), - }) - }) - }) + let counters: Vec = CIRCUIT_BYTES.read().values().cloned().collect(); + + lqos_network_devices::with_network_json_read(|tree| rollup(tree, &counters)) +} + +/// Cumulative bytes plus the identity captured when the circuit was first seen. +#[derive(Clone, Default)] +struct CircuitCounter { + bytes: DownUpOrder, + descriptor: Option, } -/// Identity fields for one circuit, resolved from the shaped-devices catalog. +/// Identity fields for one circuit, captured from the device catalog. +#[derive(Clone)] struct CircuitDescriptor { circuit_id: String, circuit_name: String, parent_node: String, + parent_node_id: Option, } /// Rolls circuit totals up the network tree and formats a bus snapshot. /// -/// Node totals include every descendant circuit. Circuits whose device or -/// parent node cannot be resolved are omitted from both lists. -fn rollup( - tree: &NetworkJson, - circuits: &[(i64, DownUpOrder)], - mut lookup: impl FnMut(i64) -> Option, -) -> ByteCountersSnapshot { +/// Node totals include every descendant circuit. Circuits keep a row even when +/// their parent node can no longer be resolved, but those bytes contribute to +/// no node total until the parent resolves again. +fn rollup(tree: &NetworkJson, counters: &[CircuitCounter]) -> ByteCountersSnapshot { let mut node_totals = vec![DownUpOrder::zeroed(); tree.nodes.len()]; - let mut node_index: FxHashMap<&str, usize> = FxHashMap::default(); + let mut node_by_name: FxHashMap<&str, usize> = FxHashMap::default(); + let mut node_by_id: FxHashMap<&str, usize> = FxHashMap::default(); for (index, node) in tree.nodes.iter().enumerate() { - node_index.entry(node.name.as_str()).or_insert(index); + node_by_name.entry(node.name.as_str()).or_insert(index); + if let Some(id) = node.id.as_deref() { + node_by_id.entry(id).or_insert(index); + } } let mut circuit_rows = Vec::new(); - for (circuit_hash, bytes) in circuits { - let Some(descriptor) = lookup(*circuit_hash) else { + for counter in counters { + let Some(descriptor) = counter.descriptor.as_ref() else { continue; }; - let Some(&parent_index) = node_index.get(descriptor.parent_node.as_str()) else { - continue; - }; - for &index in &tree.nodes[parent_index].parents { - if let Some(total) = node_totals.get_mut(index) { - total.checked_add(*bytes); + if let Some(parent_index) = resolve_parent_node(descriptor, &node_by_id, &node_by_name) { + let parent_node = &tree.nodes[parent_index]; + if parent_node.parents.is_empty() { + // The root node carries no parent list, so add its own traffic. + if let Some(total) = node_totals.get_mut(parent_index) { + total.checked_add(counter.bytes); + } + } else { + for &index in &parent_node.parents { + if let Some(total) = node_totals.get_mut(index) { + total.checked_add(counter.bytes); + } + } } } circuit_rows.push(CircuitByteCounters { - circuit_id: descriptor.circuit_id, - circuit_name: descriptor.circuit_name, - parent_node: descriptor.parent_node, - bytes: *bytes, + circuit_id: descriptor.circuit_id.clone(), + circuit_name: descriptor.circuit_name.clone(), + parent_node: descriptor.parent_node.clone(), + bytes: counter.bytes, }); } circuit_rows.sort_by(|a, b| a.circuit_id.cmp(&b.circuit_id)); @@ -151,6 +208,19 @@ fn rollup( } } +/// Resolves a circuit's parent node, preferring the stable node identifier. +fn resolve_parent_node( + descriptor: &CircuitDescriptor, + node_by_id: &FxHashMap<&str, usize>, + node_by_name: &FxHashMap<&str, usize>, +) -> Option { + descriptor + .parent_node_id + .as_deref() + .and_then(|id| node_by_id.get(id).copied()) + .or_else(|| node_by_name.get(descriptor.parent_node.as_str()).copied()) +} + #[cfg(test)] mod tests { use super::*; @@ -190,18 +260,26 @@ mod tests { } } - fn descriptor(circuit_id: &str, parent_node: &str) -> Option { - Some(CircuitDescriptor { + fn descriptor(circuit_id: &str, parent_node: &str) -> CircuitDescriptor { + CircuitDescriptor { circuit_id: circuit_id.to_string(), circuit_name: format!("{circuit_id} name"), parent_node: parent_node.to_string(), - }) + parent_node_id: None, + } + } + + fn counter(descriptor: CircuitDescriptor, bytes: DownUpOrder) -> CircuitCounter { + CircuitCounter { + bytes, + descriptor: Some(descriptor), + } } fn test_tree() -> NetworkJson { NetworkJson { nodes: vec![ - node("Root", None, vec![0], None), + node("Root", None, vec![], None), node("Site A", Some("site-a"), vec![0, 1], Some(0)), node("Site A1", None, vec![0, 1, 2], Some(1)), node("Site B", None, vec![0, 3], Some(0)), @@ -210,28 +288,34 @@ mod tests { } #[test] - fn merge_accumulates_repeated_circuit_deltas() { + fn apply_deltas_accumulates_repeated_circuit_deltas() { let mut counters = FxHashMap::default(); - merge( + apply_deltas( &mut counters, FxHashMap::from_iter([(7, DownUpOrder::new(100, 40))]), + |_| Some(descriptor("circuit-7", "Site A")), ); - merge( + apply_deltas( &mut counters, FxHashMap::from_iter([(7, DownUpOrder::new(10, 5))]), + |_| None, ); - assert_eq!(counters.get(&7), Some(&DownUpOrder::new(110, 45))); + let counter = counters.get(&7).expect("counter should exist"); + assert_eq!(counter.bytes, DownUpOrder::new(110, 45)); + assert_eq!( + counter.descriptor.as_ref().map(|d| d.circuit_id.as_str()), + Some("circuit-7") + ); } #[test] fn rollup_includes_descendant_bytes_in_ancestor_totals() { - let circuits = vec![(1, DownUpOrder::new(100, 0)), (2, DownUpOrder::new(0, 50))]; - let snapshot = rollup(&test_tree(), &circuits, |circuit_hash| match circuit_hash { - 1 => descriptor("circuit-1", "Site A1"), - 2 => descriptor("circuit-2", "Site A"), - _ => None, - }); + let counters = vec![ + counter(descriptor("circuit-1", "Site A1"), DownUpOrder::new(100, 0)), + counter(descriptor("circuit-2", "Site A"), DownUpOrder::new(0, 50)), + ]; + let snapshot = rollup(&test_tree(), &counters); assert!(snapshot.enabled); assert_eq!(snapshot.nodes[0].bytes, DownUpOrder::new(100, 50)); @@ -246,21 +330,86 @@ mod tests { } #[test] - fn rollup_skips_unresolved_circuits_and_parents() { - let circuits = vec![ - (1, DownUpOrder::new(100, 0)), - (2, DownUpOrder::new(10, 10)), - (3, DownUpOrder::new(5, 5)), + fn rollup_keeps_circuit_rows_when_the_parent_node_is_missing() { + let counters = vec![ + counter(descriptor("circuit-1", "Site B"), DownUpOrder::new(100, 0)), + counter( + descriptor("circuit-2", "Missing Node"), + DownUpOrder::new(10, 10), + ), ]; - let snapshot = rollup(&test_tree(), &circuits, |circuit_hash| match circuit_hash { - 1 => descriptor("circuit-1", "Site B"), - 2 => None, - _ => descriptor("circuit-3", "Missing Node"), - }); + let snapshot = rollup(&test_tree(), &counters); - assert_eq!(snapshot.circuits.len(), 1); + assert_eq!(snapshot.circuits.len(), 2); assert_eq!(snapshot.circuits[0].circuit_id, "circuit-1"); + assert_eq!(snapshot.circuits[1].circuit_id, "circuit-2"); assert_eq!(snapshot.nodes[0].bytes, DownUpOrder::new(100, 0)); assert_eq!(snapshot.nodes[3].bytes, DownUpOrder::new(100, 0)); } + + #[test] + fn rollup_skips_counters_without_identity() { + let counters = vec![ + counter(descriptor("circuit-1", "Site B"), DownUpOrder::new(100, 0)), + CircuitCounter::default(), + ]; + let snapshot = rollup(&test_tree(), &counters); + + assert_eq!(snapshot.circuits.len(), 1); + assert_eq!(snapshot.circuits[0].circuit_id, "circuit-1"); + } + + #[test] + fn rollup_prefers_stable_node_ids_over_names() { + let mut tree = test_tree(); + tree.nodes + .push(node("Site B", Some("site-b-2"), vec![0, 4], Some(0))); + let mut identified = descriptor("circuit-1", "Site B"); + identified.parent_node_id = Some("site-b-2".to_string()); + + let snapshot = rollup(&tree, &[counter(identified, DownUpOrder::new(5, 5))]); + + assert_eq!(snapshot.nodes[0].bytes, DownUpOrder::new(5, 5)); + assert_eq!(snapshot.nodes[3].bytes, DownUpOrder::new(0, 0)); + assert_eq!(snapshot.nodes[4].bytes, DownUpOrder::new(5, 5)); + } + + #[test] + fn rollup_counts_circuits_attached_to_root() { + let counters = vec![counter( + descriptor("circuit-1", "Root"), + DownUpOrder::new(7, 3), + )]; + let snapshot = rollup(&test_tree(), &counters); + + assert_eq!(snapshot.nodes[0].bytes, DownUpOrder::new(7, 3)); + } + + #[test] + fn rollup_sorts_circuit_rows_by_circuit_id() { + let counters = vec![ + counter(descriptor("circuit-b", "Site A"), DownUpOrder::new(1, 0)), + counter(descriptor("circuit-a", "Site A"), DownUpOrder::new(1, 0)), + ]; + let snapshot = rollup(&test_tree(), &counters); + + let ids: Vec<&str> = snapshot + .circuits + .iter() + .map(|row| row.circuit_id.as_str()) + .collect(); + assert_eq!(ids, vec!["circuit-a", "circuit-b"]); + } + + #[test] + fn disabled_snapshot_reports_empty_lists() { + let previous = is_enabled(); + set_enabled(false); + let snapshot = snapshot(); + set_enabled(previous); + + assert!(!snapshot.enabled); + assert!(snapshot.nodes.is_empty()); + assert!(snapshot.circuits.is_empty()); + } } diff --git a/src/rust/lqosd/src/throughput_tracker/tracking_data.rs b/src/rust/lqosd/src/throughput_tracker/tracking_data.rs index 364c4956..96cd76be 100644 --- a/src/rust/lqosd/src/throughput_tracker/tracking_data.rs +++ b/src/rust/lqosd/src/throughput_tracker/tracking_data.rs @@ -771,20 +771,12 @@ impl ThroughputTracker { } if entry.packets != entry.prev_packets { entry.most_recent_cycle = self_cycle; - let actual_bytes_delta = DownUpOrder::new( - entry - .actual_bytes - .down - .saturating_sub(entry.prev_actual_bytes.down), - entry - .actual_bytes - .up - .saturating_sub(entry.prev_actual_bytes.up), - ); + let actual_bytes_delta = + entry.actual_bytes.checked_sub_or_zero(entry.prev_actual_bytes); // Call to Bakery Update for existing traffic if let Some(circuit_hash) = entry.circuit_hash { changed_circuits.insert(circuit_hash); - if byte_counters_enabled { + if byte_counters_enabled && actual_bytes_delta.not_zero() { byte_counter_deltas .entry(circuit_hash) .or_default() @@ -945,7 +937,7 @@ impl ThroughputTracker { }); if byte_counters_enabled { - crate::byte_counters::add_batch(byte_counter_deltas); + crate::byte_counters::add_batch(byte_counter_deltas, &catalog); } if !observations.is_empty() { -- knotmirror 0.0.1 From 2a022c0e0613f6540a6dca389694a8b58b36ed28 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Wed, 7 Oct 2026 13:00:57 -0500 Subject: [PATCH 09/17] Fix: resolve byte counter parents through the canonical topology lookup Reuses ParentNodeLookup so node attribution follows the same id, name, and attachment-alias precedence as the rest of the runtime, and prefers the published effective parent when capturing circuit identity. Adds an alias-resolution test and clarifies the snapshot lock-order comment. --- src/rust/lqosd/src/byte_counters.rs | 78 ++++++++++++++++++++++------- 1 file changed, 60 insertions(+), 18 deletions(-) diff --git a/src/rust/lqosd/src/byte_counters.rs b/src/rust/lqosd/src/byte_counters.rs index 347fbbf7..42bd5edb 100644 --- a/src/rust/lqosd/src/byte_counters.rs +++ b/src/rust/lqosd/src/byte_counters.rs @@ -15,7 +15,7 @@ use fxhash::FxHashMap; use lqos_bus::{ByteCountersSnapshot, CircuitByteCounters, NodeByteCounters}; use lqos_config::NetworkJson; -use lqos_network_devices::NetworkDevicesCatalog; +use lqos_network_devices::{NetworkDevicesCatalog, ParentNodeLookup}; use lqos_utils::units::DownUpOrder; use once_cell::sync::Lazy; use parking_lot::RwLock; @@ -64,13 +64,23 @@ fn apply_deltas( ) { for (circuit_hash, bytes) in deltas { let counter = counters.entry(circuit_hash).or_default(); - if counter.descriptor.is_none() { - counter.descriptor = describe(circuit_hash); - } + ensure_descriptor(counter, circuit_hash, &describe); counter.bytes.checked_add(bytes); } } +/// Captures a counter's identity on first sight or when it could not be +/// resolved previously. +fn ensure_descriptor( + counter: &mut CircuitCounter, + circuit_hash: i64, + describe: &impl Fn(i64) -> Option, +) { + if counter.descriptor.is_none() { + counter.descriptor = describe(circuit_hash); + } +} + /// Fills descriptors for counters that could not resolve identity when they /// were first recorded, for example because the catalog snapshot was stale. /// @@ -87,32 +97,40 @@ fn fill_missing_descriptors() { let catalog = lqos_network_devices::network_devices_catalog(); let mut counters = CIRCUIT_BYTES.write(); for (circuit_hash, counter) in counters.iter_mut() { - if counter.descriptor.is_none() { - counter.descriptor = describe_circuit(&catalog, *circuit_hash); - } + ensure_descriptor(counter, *circuit_hash, &|circuit_hash| { + describe_circuit(&catalog, circuit_hash) + }); } } /// Resolves one circuit's identity fields from the combined device catalog. +/// +/// The runtime effective parent wins when one is published, so accounting +/// follows the same tree as the rest of the runtime. fn describe_circuit( catalog: &NetworkDevicesCatalog, circuit_hash: i64, ) -> Option { let device = catalog.device_by_hashes(None, Some(circuit_hash))?; + let (parent_node, parent_node_id) = + match crate::shaped_devices_tracker::effective_parent_for_circuit(&device.circuit_id) { + Some(parent) => (parent.name, parent.id), + None => (device.parent_node.clone(), device.parent_node_id.clone()), + }; Some(CircuitDescriptor { circuit_id: device.circuit_id.clone(), circuit_name: device.circuit_name.clone(), - parent_node: device.parent_node.clone(), - parent_node_id: device.parent_node_id.clone(), + parent_node, + parent_node_id, }) } /// Builds a cumulative byte counter snapshot for the bus. /// /// Side effects: acquires the counter lock and the runtime network tree read -/// lock. Descriptors are resolved before the tree lock is taken so the lock -/// order stays `CIRCUIT_BYTES` then `NETWORK_JSON`, matching the tracker's -/// `NETWORK_JSON` write followed by `CIRCUIT_BYTES` write. +/// lock. Descriptors are resolved and the counter lock is released before the +/// tree lock is taken, so the two locks are never held at the same time and +/// cannot invert the tracker's `NETWORK_JSON` then `CIRCUIT_BYTES` order. pub(crate) fn snapshot() -> ByteCountersSnapshot { if !is_enabled() { return ByteCountersSnapshot { @@ -160,13 +178,16 @@ fn rollup(tree: &NetworkJson, counters: &[CircuitCounter]) -> ByteCountersSnapsh node_by_id.entry(id).or_insert(index); } } + let parent_lookup = ParentNodeLookup::from_nodes(&tree.nodes); let mut circuit_rows = Vec::new(); for counter in counters { let Some(descriptor) = counter.descriptor.as_ref() else { continue; }; - if let Some(parent_index) = resolve_parent_node(descriptor, &node_by_id, &node_by_name) { + if let Some(parent_index) = + resolve_parent_index(&parent_lookup, descriptor, &node_by_id, &node_by_name) + { let parent_node = &tree.nodes[parent_index]; if parent_node.parents.is_empty() { // The root node carries no parent list, so add its own traffic. @@ -208,17 +229,23 @@ fn rollup(tree: &NetworkJson, counters: &[CircuitCounter]) -> ByteCountersSnapsh } } -/// Resolves a circuit's parent node, preferring the stable node identifier. -fn resolve_parent_node( +/// Resolves a circuit's parent node with the canonical id, name, and alias +/// precedence used by the rest of the runtime. +fn resolve_parent_index( + parent_lookup: &ParentNodeLookup<'_>, descriptor: &CircuitDescriptor, node_by_id: &FxHashMap<&str, usize>, node_by_name: &FxHashMap<&str, usize>, ) -> Option { - descriptor - .parent_node_id + let parent = parent_lookup.resolve( + &descriptor.parent_node, + descriptor.parent_node_id.as_deref(), + )?; + parent + .id .as_deref() .and_then(|id| node_by_id.get(id).copied()) - .or_else(|| node_by_name.get(descriptor.parent_node.as_str()).copied()) + .or_else(|| node_by_name.get(parent.name.as_str()).copied()) } #[cfg(test)] @@ -374,6 +401,21 @@ mod tests { assert_eq!(snapshot.nodes[4].bytes, DownUpOrder::new(5, 5)); } + #[test] + fn rollup_resolves_parent_aliases() { + let mut tree = test_tree(); + tree.nodes[2].active_attachment_name = Some("Site A1 Alias".to_string()); + let counters = vec![counter( + descriptor("circuit-1", "Site A1 Alias"), + DownUpOrder::new(4, 2), + )]; + let snapshot = rollup(&tree, &counters); + + assert_eq!(snapshot.nodes[0].bytes, DownUpOrder::new(4, 2)); + assert_eq!(snapshot.nodes[1].bytes, DownUpOrder::new(4, 2)); + assert_eq!(snapshot.nodes[2].bytes, DownUpOrder::new(4, 2)); + } + #[test] fn rollup_counts_circuits_attached_to_root() { let counters = vec![counter( -- knotmirror 0.0.1 From 3f00f1059391f9914800e648dde2684de965a95d Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Wed, 7 Oct 2026 13:20:03 -0500 Subject: [PATCH 10/17] Fix: refresh byte counter identity for configured circuits Live circuits now follow renames and re-parenting because descriptors refresh from the catalog on each snapshot, while circuits removed from configuration keep their last-known descriptor and continue contributing to their last known parent. Documents the tracker-side lock constraint, releases the throughput table lock before the counter merge, adds a first-miss descriptor recovery test, and applies rustfmt to the new hunk. --- src/rust/lqosd/src/byte_counters.rs | 56 +++++++++++++------ .../src/throughput_tracker/tracking_data.rs | 7 ++- 2 files changed, 43 insertions(+), 20 deletions(-) diff --git a/src/rust/lqosd/src/byte_counters.rs b/src/rust/lqosd/src/byte_counters.rs index 42bd5edb..570f1844 100644 --- a/src/rust/lqosd/src/byte_counters.rs +++ b/src/rust/lqosd/src/byte_counters.rs @@ -45,7 +45,9 @@ pub(crate) fn is_enabled() -> bool { /// /// New circuits capture their identity from `catalog` on first sight. /// -/// Side effects: mutates the shared cumulative counter map. +/// Side effects: mutates the shared cumulative counter map. Callers may +/// already hold the network tree write lock, so this function must never +/// acquire a network tree lock. pub(crate) fn add_batch(deltas: FxHashMap>, catalog: &NetworkDevicesCatalog) { if deltas.is_empty() { return; @@ -81,32 +83,28 @@ fn ensure_descriptor( } } -/// Fills descriptors for counters that could not resolve identity when they -/// were first recorded, for example because the catalog snapshot was stale. +/// Refreshes descriptors for circuits that still resolve in the device +/// catalog, so live circuits follow renames and re-parenting. Circuits that no +/// longer resolve keep their last-known descriptor and continue contributing +/// to their last known parent. /// /// Side effects: mutates the shared cumulative counter map. -fn fill_missing_descriptors() { - if CIRCUIT_BYTES - .read() - .values() - .all(|counter| counter.descriptor.is_some()) - { - return; - } - +fn refresh_descriptors() { let catalog = lqos_network_devices::network_devices_catalog(); let mut counters = CIRCUIT_BYTES.write(); for (circuit_hash, counter) in counters.iter_mut() { - ensure_descriptor(counter, *circuit_hash, &|circuit_hash| { - describe_circuit(&catalog, circuit_hash) - }); + if let Some(descriptor) = describe_circuit(&catalog, *circuit_hash) { + counter.descriptor = Some(descriptor); + } } } /// Resolves one circuit's identity fields from the combined device catalog. /// /// The runtime effective parent wins when one is published, so accounting -/// follows the same tree as the rest of the runtime. +/// follows the same tree as the rest of the runtime. This function must never +/// acquire a network tree lock, because callers may already hold the tree +/// write lock. fn describe_circuit( catalog: &NetworkDevicesCatalog, circuit_hash: i64, @@ -128,7 +126,7 @@ fn describe_circuit( /// Builds a cumulative byte counter snapshot for the bus. /// /// Side effects: acquires the counter lock and the runtime network tree read -/// lock. Descriptors are resolved and the counter lock is released before the +/// lock. Descriptors are refreshed and the counter lock is released before the /// tree lock is taken, so the two locks are never held at the same time and /// cannot invert the tracker's `NETWORK_JSON` then `CIRCUIT_BYTES` order. pub(crate) fn snapshot() -> ByteCountersSnapshot { @@ -140,7 +138,7 @@ pub(crate) fn snapshot() -> ByteCountersSnapshot { }; } - fill_missing_descriptors(); + refresh_descriptors(); let counters: Vec = CIRCUIT_BYTES.read().values().cloned().collect(); @@ -336,6 +334,28 @@ mod tests { ); } + #[test] + fn apply_deltas_fills_descriptor_when_first_lookup_missed() { + let mut counters = FxHashMap::default(); + apply_deltas( + &mut counters, + FxHashMap::from_iter([(7, DownUpOrder::new(1, 0))]), + |_| None, + ); + apply_deltas( + &mut counters, + FxHashMap::from_iter([(7, DownUpOrder::new(2, 0))]), + |_| Some(descriptor("circuit-7", "Site A")), + ); + + let counter = counters.get(&7).expect("counter should exist"); + assert_eq!(counter.bytes, DownUpOrder::new(3, 0)); + assert_eq!( + counter.descriptor.as_ref().map(|d| d.circuit_id.as_str()), + Some("circuit-7") + ); + } + #[test] fn rollup_includes_descendant_bytes_in_ancestor_totals() { let counters = vec![ diff --git a/src/rust/lqosd/src/throughput_tracker/tracking_data.rs b/src/rust/lqosd/src/throughput_tracker/tracking_data.rs index 96cd76be..cab6cc4c 100644 --- a/src/rust/lqosd/src/throughput_tracker/tracking_data.rs +++ b/src/rust/lqosd/src/throughput_tracker/tracking_data.rs @@ -771,8 +771,9 @@ impl ThroughputTracker { } if entry.packets != entry.prev_packets { entry.most_recent_cycle = self_cycle; - let actual_bytes_delta = - entry.actual_bytes.checked_sub_or_zero(entry.prev_actual_bytes); + let actual_bytes_delta = entry + .actual_bytes + .checked_sub_or_zero(entry.prev_actual_bytes); // Call to Bakery Update for existing traffic if let Some(circuit_hash) = entry.circuit_hash { changed_circuits.insert(circuit_hash); @@ -936,6 +937,8 @@ impl ThroughputTracker { } }); + drop(raw_data); + if byte_counters_enabled { crate::byte_counters::add_batch(byte_counter_deltas, &catalog); } -- knotmirror 0.0.1 From 18cde06b3583b10c324115f50d5390a13b0f51bd Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Wed, 7 Oct 2026 13:35:08 -0500 Subject: [PATCH 11/17] Fix: index the device catalog once per byte counter refresh Builds a circuit-hash index from the combined catalog before refreshing descriptors, so dynamic and removed circuits cannot trigger per-circuit fallback scans while the counter lock is held. Clarifies the module documentation and fixes the Spanish parent-node wording. --- docs-es/v2.0/configuration-advanced-es.md | 2 +- src/rust/lqosd/src/byte_counters.rs | 50 +++++++++++++++-------- 2 files changed, 35 insertions(+), 17 deletions(-) diff --git a/docs-es/v2.0/configuration-advanced-es.md b/docs-es/v2.0/configuration-advanced-es.md index 6f26f0ab..1ad43dbd 100644 --- a/docs-es/v2.0/configuration-advanced-es.md +++ b/docs-es/v2.0/configuration-advanced-es.md @@ -75,7 +75,7 @@ enabled = true - Los valores se acumulan mientras `lqosd` se ejecuta y se reinician cuando `lqosd` se reinicia. - Los valores de un nodo incluyen el tráfico de todos sus nodos descendientes. - Solo se listan los circuitos con tráfico registrado. -- Los circuitos eliminados de `ShapedDevices.csv` siguen aportando sus bytes acumulados a su último nodo principal conocido mientras `lqosd` se ejecuta. +- Los circuitos eliminados de `ShapedDevices.csv` siguen aportando sus bytes acumulados a su último nodo padre conocido mientras `lqosd` se ejecuta. Con los contadores habilitados, `GET /byte_counters` en la API del nodo devuelve los valores actuales. Consulte [API del nodo LibreQoS](api-es.md). diff --git a/src/rust/lqosd/src/byte_counters.rs b/src/rust/lqosd/src/byte_counters.rs index 570f1844..66108e82 100644 --- a/src/rust/lqosd/src/byte_counters.rs +++ b/src/rust/lqosd/src/byte_counters.rs @@ -5,16 +5,16 @@ //! module. Counters are cumulative since `lqosd` started and are not //! persisted across restarts. //! -//! Only per-circuit totals and their last-known identity are stored. Node -//! totals are derived when a snapshot is requested by walking each circuit's -//! parent node through the runtime network tree, so node totals include -//! descendants. Circuit identity is captured when a counter first receives -//! traffic, so circuits removed from configuration keep contributing their -//! accumulated bytes to their last known parent while `lqosd` runs. +//! Only per-circuit totals and their identity are stored. Node totals are +//! derived when a snapshot is requested by walking each circuit's parent node +//! through the runtime network tree, so node totals include descendants. +//! Configured circuits follow the current device catalog, and circuits removed +//! from configuration keep their last known identity, so their accumulated +//! bytes continue to contribute to their last known parent while `lqosd` runs. use fxhash::FxHashMap; use lqos_bus::{ByteCountersSnapshot, CircuitByteCounters, NodeByteCounters}; -use lqos_config::NetworkJson; +use lqos_config::{NetworkJson, ShapedDevice}; use lqos_network_devices::{NetworkDevicesCatalog, ParentNodeLookup}; use lqos_utils::units::DownUpOrder; use once_cell::sync::Lazy; @@ -58,7 +58,7 @@ pub(crate) fn add_batch(deltas: FxHashMap>, catalog: &Netw } /// Merges per-circuit deltas into a cumulative counter map, capturing identity -/// through `describe` when a circuit is first seen. +/// through `describe` when a circuit is first seen or has none captured yet. fn apply_deltas( counters: &mut FxHashMap, deltas: FxHashMap>, @@ -88,39 +88,57 @@ fn ensure_descriptor( /// longer resolve keep their last-known descriptor and continue contributing /// to their last known parent. /// +/// The catalog is indexed once per refresh so circuits missing from +/// `ShapedDevices.csv` cannot trigger per-circuit fallback scans. +/// /// Side effects: mutates the shared cumulative counter map. fn refresh_descriptors() { let catalog = lqos_network_devices::network_devices_catalog(); + let mut devices_by_circuit_hash: FxHashMap = FxHashMap::default(); + for device in catalog.iter_all_devices() { + devices_by_circuit_hash + .entry(device.circuit_hash) + .or_insert(device); + } + let mut counters = CIRCUIT_BYTES.write(); for (circuit_hash, counter) in counters.iter_mut() { - if let Some(descriptor) = describe_circuit(&catalog, *circuit_hash) { - counter.descriptor = Some(descriptor); + if let Some(device) = devices_by_circuit_hash.get(circuit_hash) { + counter.descriptor = Some(describe_device(device)); } } } /// Resolves one circuit's identity fields from the combined device catalog. /// -/// The runtime effective parent wins when one is published, so accounting -/// follows the same tree as the rest of the runtime. This function must never -/// acquire a network tree lock, because callers may already hold the tree -/// write lock. +/// This function must never acquire a network tree lock, because callers may +/// already hold the tree write lock. fn describe_circuit( catalog: &NetworkDevicesCatalog, circuit_hash: i64, ) -> Option { let device = catalog.device_by_hashes(None, Some(circuit_hash))?; + Some(describe_device(device)) +} + +/// Builds identity fields for one device. +/// +/// The runtime effective parent wins when one is published, so accounting +/// follows the same tree as the rest of the runtime. This function must never +/// acquire a network tree lock, because callers may already hold the tree +/// write lock. +fn describe_device(device: &ShapedDevice) -> CircuitDescriptor { let (parent_node, parent_node_id) = match crate::shaped_devices_tracker::effective_parent_for_circuit(&device.circuit_id) { Some(parent) => (parent.name, parent.id), None => (device.parent_node.clone(), device.parent_node_id.clone()), }; - Some(CircuitDescriptor { + CircuitDescriptor { circuit_id: device.circuit_id.clone(), circuit_name: device.circuit_name.clone(), parent_node, parent_node_id, - }) + } } /// Builds a cumulative byte counter snapshot for the bus. -- knotmirror 0.0.1 From 49024d065caa7da082c14caf6c4638acbd77529e Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Wed, 7 Oct 2026 13:43:48 -0500 Subject: [PATCH 12/17] Docs: tighten byte counters API wording Uses active phrasing in the Spanish API note and aligns the English wording with the configuration page. --- docs-es/v2.0/api-es.md | 2 +- docs/v2.0/api.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs-es/v2.0/api-es.md b/docs-es/v2.0/api-es.md index 65600d8c..80fbef84 100644 --- a/docs-es/v2.0/api-es.md +++ b/docs-es/v2.0/api-es.md @@ -125,7 +125,7 @@ Endpoints representativos: - `GET /warnings` - `GET /urgent`, `GET /urgent/status` -`GET /byte_counters` devuelve contadores de bytes acumulados por nodo y por circuito cuando `[byte_counters] enabled = true` está configurado en `/etc/lqos.conf`. Los valores son acumulados desde que `lqosd` inició, incluyen el tráfico descendiente en los nodos y se reinician cuando `lqosd` se reinicia. Consulte [Configuración avanzada](configuration-advanced-es.md). +`GET /byte_counters` devuelve contadores de bytes acumulados por nodo y por circuito cuando `[byte_counters] enabled = true` está configurado en `/etc/lqos.conf`. Los valores se acumulan desde que `lqosd` inició, incluyen el tráfico de los nodos descendientes y se reinician cuando `lqosd` se reinicia. Consulte [Configuración avanzada](configuration-advanced-es.md). ### 5) Operaciones de control y reload diff --git a/docs/v2.0/api.md b/docs/v2.0/api.md index dfc33982..10638acd 100644 --- a/docs/v2.0/api.md +++ b/docs/v2.0/api.md @@ -125,7 +125,7 @@ Representative endpoints: - `GET /warnings` - `GET /urgent`, `GET /urgent/status` -`GET /byte_counters` returns cumulative per-node and per-circuit byte counters when `[byte_counters] enabled = true` is set in `/etc/lqos.conf`. Values are cumulative since `lqosd` started, include descendant traffic for nodes, and reset when `lqosd` restarts. See [Advanced Configuration](configuration-advanced.md). +`GET /byte_counters` returns cumulative per-node and per-circuit byte counters when `[byte_counters] enabled = true` is set in `/etc/lqos.conf`. Values accumulate since `lqosd` started, node values include traffic from descendant nodes, and values reset when `lqosd` restarts. See [Advanced Configuration](configuration-advanced.md). ### 5) Control and Reload Operations -- knotmirror 0.0.1 From 4577b9b5b1a42f8be87bb55883dcf174c6288104 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Wed, 14 Oct 2026 14:42:41 -0500 Subject: [PATCH 13/17] CI: gate Python and Rust jobs on changed paths Both workflows ran their full pipelines on every push, including docs-only and opposite-language changes, which wasted runner time and reported failures unrelated to the change under test. Add a shared detect-changes workflow that diffs the pushed or PR range against per-group patterns and exposes a matched output. The heavy jobs run only when their group changed, or when detection itself fails, so a broken detector cannot silently skip checks. Tag pushes and unknown events fall back to running everything. Include .github/scripts/test-changed-files.sh, a manual harness for the detection logic that follows the repo's existing shell self-tests. --- .github/scripts/changed-files.sh | 132 ++++++++++++++++ .github/scripts/test-changed-files.sh | 209 ++++++++++++++++++++++++++ .github/workflows/detect-changes.yml | 31 ++++ .github/workflows/lint_python.yml | 10 ++ .github/workflows/rust.yml | 12 ++ 5 files changed, 394 insertions(+) create mode 100755 .github/scripts/changed-files.sh create mode 100755 .github/scripts/test-changed-files.sh create mode 100644 .github/workflows/detect-changes.yml diff --git a/.github/scripts/changed-files.sh b/.github/scripts/changed-files.sh new file mode 100755 index 00000000..0f75b525 --- /dev/null +++ b/.github/scripts/changed-files.sh @@ -0,0 +1,132 @@ +#!/usr/bin/env bash +# +# Decide whether files relevant to a CI job changed in the current run. +# +# Usage: changed-files.sh +# +# Reads the standard GITHUB_* environment plus EVENT_BEFORE and DEFAULT_BRANCH +# (supplied by the calling workflow) and writes "matched=true|false" to +# $GITHUB_OUTPUT. Matching files are listed on stdout for the workflow log. +# If the change range cannot be determined, the group is reported as matched +# so that a CI job is never silently skipped. +set -euo pipefail + +group="${1:-}" +case "$group" in + python) + patterns=( + '*.py' + 'requirements*.txt' + '.github/workflows/lint_python.yml' + '.github/workflows/detect-changes.yml' + '.github/scripts/*' + ) + ;; + rust) + # The Rust workspace plus the build scripts the Rust workflow executes. + # Files that are only copied into the .deb (Python sources, service + # examples) do not trigger this group. + patterns=( + 'src/rust/*' + 'src/build_dpkg.sh' + 'src/build_rust.sh' + 'src/VERSION_STRING' + '.github/workflows/rust.yml' + '.github/workflows/detect-changes.yml' + '.github/scripts/*' + ) + ;; + *) + echo "usage: $0 " >&2 + exit 2 + ;; +esac + +# Report every tracked file as changed; used when no change range is available. +all_tracked_files() { + echo "Treating every tracked file as changed." >&2 + git -c core.quotePath=false ls-files +} + +# Files touched by this run, one per line. +changed_files() { + local base_ref="" + local merge_base + + # Tag pushes have no meaningful change range; run everything. + if [[ "${GITHUB_REF:-}" == refs/tags/* ]]; then + all_tracked_files + return + fi + + case "${GITHUB_EVENT_NAME:-}" in + pull_request) + # Pull requests check out a merge commit; diff against the merge base + # so files that only changed on the base branch are not reported. + if [[ -n "${GITHUB_BASE_REF:-}" ]]; then + base_ref="origin/${GITHUB_BASE_REF}" + fi + ;; + push) + # github.event.before is the previously pushed commit; a new branch + # pushes the all-zero object id and falls back to the default branch. + if [[ -n "${EVENT_BEFORE:-}" && ! "${EVENT_BEFORE}" =~ ^0+$ ]] && + git rev-parse --verify --quiet "${EVENT_BEFORE}^{commit}" >/dev/null; then + git -c core.quotePath=false diff --name-only "${EVENT_BEFORE}" "${GITHUB_SHA:-HEAD}" + return + fi + if [[ -n "${DEFAULT_BRANCH:-}" ]]; then + base_ref="origin/${DEFAULT_BRANCH}" + fi + ;; + *) + all_tracked_files + return + ;; + esac + + if [[ -n "$base_ref" ]] && git rev-parse --verify --quiet "$base_ref" >/dev/null; then + merge_base="$(git merge-base "$base_ref" HEAD)" + git -c core.quotePath=false diff --name-only "$merge_base" HEAD + return + fi + + all_tracked_files +} + +# Does a changed file belong to the requested group? +matches_group() { + local pattern + for pattern in "${patterns[@]}"; do + if [[ "$1" == $pattern ]]; then + return 0 + fi + done + return 1 +} + +if ! changed="$(changed_files)"; then + changed="$(all_tracked_files)" +fi + +matching_files=() +while IFS= read -r file; do + if [[ -n "$file" ]] && matches_group "$file"; then + matching_files+=("$file") + fi +done <<< "$changed" + +if (( ${#matching_files[@]} > 0 )); then + echo "Change group '$group': matching files changed:" + printf ' %s\n' "${matching_files[@]}" +else + echo "Change group '$group': no matching files changed." +fi + +if [[ -n "${GITHUB_OUTPUT:-}" ]]; then + if (( ${#matching_files[@]} > 0 )); then + echo "matched=true" >> "$GITHUB_OUTPUT" + else + echo "matched=false" >> "$GITHUB_OUTPUT" + fi +fi diff --git a/.github/scripts/test-changed-files.sh b/.github/scripts/test-changed-files.sh new file mode 100755 index 00000000..e4596974 --- /dev/null +++ b/.github/scripts/test-changed-files.sh @@ -0,0 +1,209 @@ +#!/usr/bin/env bash +# +# Self-test for changed-files.sh. Run it after editing the detection logic or +# the pattern lists: +# +# ./.github/scripts/test-changed-files.sh +# +set -euo pipefail + +script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +detect="$script_dir/changed-files.sh" +workdir="$(mktemp -d)" +trap 'rm -rf "$workdir"' EXIT + +checks=0 +failures=0 + +check() { + local label="$1" expect="$2" group="$3" + local out="$workdir/out.txt" log got + rm -f "$out" + checks=$((checks + 1)) + if ! log="$(GITHUB_OUTPUT="$out" bash "$detect" "$group" 2>&1)"; then + echo "FAILED [$label] $group: script exited non-zero" + echo "$log" | sed 's/^/ | /' + failures=$((failures + 1)) + return + fi + got="$(grep -E '^matched=' "$out" | cut -d= -f2)" + if [[ "$got" == "$expect" ]]; then + echo "ok [$label] $group -> matched=$got" + else + echo "FAILED [$label] $group: expected $expect, got '$got'" + echo "$log" | sed 's/^/ | /' + failures=$((failures + 1)) + fi +} + +cd "$workdir" +git init -q --bare origin.git +git clone -q origin.git work +cd work +git config user.email ci@test.invalid +git config user.name "CI Test" +git symbolic-ref HEAD refs/heads/develop + +mkdir -p src/rust/lqosd .github/workflows .github/scripts +printf 'base\n' > README.md +printf 'shaper\n' > src/LibreQoS.py +printf 'fn main() {}\n' > src/rust/lqosd/main.rs +printf '2.0\n' > src/VERSION_STRING +printf 'binpacking\n' > requirements.txt +printf 'pytest\n' > requirements_dev.txt +printf '# package\n' > src/build_dpkg.sh +printf '# build rust\n' > src/build_rust.sh +printf 'name: Rust\n' > .github/workflows/rust.yml +printf 'name: lint_python\n' > .github/workflows/lint_python.yml +printf 'name: detect-changes\n' > .github/workflows/detect-changes.yml +printf '# helper\n' > .github/scripts/other.sh +git add -A +git commit -qm base +git push -q origin develop + +new_branch() { + git checkout -q -b "$1" develop +} + +commit_file() { + printf '%s\n' "$2" > "$1" + git add -A + git commit -qm "change $1" +} + +export GITHUB_REF=refs/heads/test +export GITHUB_EVENT_NAME=push +export DEFAULT_BRANCH=develop +export GITHUB_BASE_REF="" + +# --- push: one file per group --- +new_branch python-change +commit_file src/LibreQoS.py '# python change' +export GITHUB_SHA="$(git rev-parse HEAD)" EVENT_BEFORE="$(git rev-parse HEAD~1)" +check "push/python" true python +check "push/python" false rust + +new_branch rust-change +commit_file src/rust/lqosd/main.rs '// rust change' +export GITHUB_SHA="$(git rev-parse HEAD)" EVENT_BEFORE="$(git rev-parse HEAD~1)" +check "push/rust" true rust +check "push/rust" false python + +new_branch docs-change +commit_file README.md 'more docs' +export GITHUB_SHA="$(git rev-parse HEAD)" EVENT_BEFORE="$(git rev-parse HEAD~1)" +check "push/docs" false python +check "push/docs" false rust + +# --- push: pattern coverage --- +new_branch requirements-change +commit_file requirements_dev.txt 'coverage' +export GITHUB_SHA="$(git rev-parse HEAD)" EVENT_BEFORE="$(git rev-parse HEAD~1)" +check "push/requirements" true python +check "push/requirements" false rust + +new_branch version-change +commit_file src/VERSION_STRING '2.1' +export GITHUB_SHA="$(git rev-parse HEAD)" EVENT_BEFORE="$(git rev-parse HEAD~1)" +check "push/version" true rust +check "push/version" false python + +new_branch build-script-change +commit_file src/build_rust.sh '# tweak' +export GITHUB_SHA="$(git rev-parse HEAD)" EVENT_BEFORE="$(git rev-parse HEAD~1)" +check "push/build-script" true rust +check "push/build-script" false python + +new_branch package-script-change +commit_file src/build_dpkg.sh '# tweak' +export GITHUB_SHA="$(git rev-parse HEAD)" EVENT_BEFORE="$(git rev-parse HEAD~1)" +check "push/package-script" true rust +check "push/package-script" false python + +new_branch rust-workflow-change +commit_file .github/workflows/rust.yml 'name: Rust # tweak' +export GITHUB_SHA="$(git rev-parse HEAD)" EVENT_BEFORE="$(git rev-parse HEAD~1)" +check "push/rust-workflow" true rust +check "push/rust-workflow" false python + +new_branch python-workflow-change +commit_file .github/workflows/lint_python.yml 'name: lint_python # tweak' +export GITHUB_SHA="$(git rev-parse HEAD)" EVENT_BEFORE="$(git rev-parse HEAD~1)" +check "push/python-workflow" true python +check "push/python-workflow" false rust + +new_branch shared-workflow-change +commit_file .github/workflows/detect-changes.yml 'name: detect-changes # tweak' +export GITHUB_SHA="$(git rev-parse HEAD)" EVENT_BEFORE="$(git rev-parse HEAD~1)" +check "push/shared-workflow" true python +check "push/shared-workflow" true rust + +new_branch shared-script-change +commit_file .github/scripts/other.sh '# tweak' +export GITHUB_SHA="$(git rev-parse HEAD)" EVENT_BEFORE="$(git rev-parse HEAD~1)" +check "push/shared-script" true python +check "push/shared-script" true rust + +# --- push: new branch with the all-zero before --- +new_branch new-branch +commit_file src/LibreQoS.py '# new branch change' +export GITHUB_SHA="$(git rev-parse HEAD)" +export EVENT_BEFORE=0000000000000000000000000000000000000000 +check "push/new-branch" true python +check "push/new-branch" false rust + +# --- push: before no longer exists (force push) --- +export EVENT_BEFORE=1111111111111111111111111111111111111111 +check "push/gone-before" true python +check "push/gone-before" false rust + +# --- push: no before at all, falls back to the default branch --- +export EVENT_BEFORE="" +check "push/no-before" true python +check "push/no-before" false rust + +# --- push: tag on an already-pushed commit --- +git checkout -q develop +export GITHUB_SHA="$(git rev-parse HEAD)" +export EVENT_BEFORE=0000000000000000000000000000000000000000 +export GITHUB_REF=refs/tags/v2.0.0 +check "push/tag" true python +check "push/tag" true rust +export GITHUB_REF=refs/heads/test + +# --- push: non-ASCII filename --- +new_branch unicode-change +commit_file "src/café.py" '# unicode' +export GITHUB_SHA="$(git rev-parse HEAD)" EVENT_BEFORE="$(git rev-parse HEAD~1)" +check "push/unicode" true python +check "push/unicode" false rust + +# --- pull_request: only the branch's own changes count --- +new_branch pr-branch +commit_file src/LibreQoS.py '# pr change' +git checkout -q develop +commit_file src/rust/lqosd/main.rs '// develop advances' +git push -q origin develop +git checkout -q pr-branch +export GITHUB_EVENT_NAME=pull_request +export GITHUB_BASE_REF=develop +export GITHUB_SHA="$(git rev-parse HEAD)" +check "pr/python-only" true python +check "pr/python-only" false rust + +export GITHUB_BASE_REF=does-not-exist +check "pr/unknown-base" true python +check "pr/unknown-base" true rust + +# --- unknown event: everything counts as changed --- +export GITHUB_EVENT_NAME=workflow_dispatch +export GITHUB_BASE_REF="" +check "workflow_dispatch" true python +check "workflow_dispatch" true rust + +echo +if (( failures > 0 )); then + echo "$checks checks, $failures failures" + exit 1 +fi +echo "$checks checks, 0 failures" diff --git a/.github/workflows/detect-changes.yml b/.github/workflows/detect-changes.yml new file mode 100644 index 00000000..42a8cef5 --- /dev/null +++ b/.github/workflows/detect-changes.yml @@ -0,0 +1,31 @@ +name: detect-changes + +# Shared change detection for lint_python.yml and rust.yml. Callers gate their +# heavy jobs on the `matched` output; see .github/scripts/changed-files.sh. +on: + workflow_call: + inputs: + group: + description: File group to detect (python or rust) + required: true + type: string + outputs: + matched: + description: "true when files in the group changed" + value: ${{ jobs.detect.outputs.matched }} + +jobs: + detect: + runs-on: lq_run + outputs: + matched: ${{ steps.filter.outputs.matched }} + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - name: Detect ${{ inputs.group }} changes + id: filter + env: + EVENT_BEFORE: ${{ github.event.before }} + DEFAULT_BRANCH: ${{ github.event.repository.default_branch }} + run: bash .github/scripts/changed-files.sh "${{ inputs.group }}" diff --git a/.github/workflows/lint_python.yml b/.github/workflows/lint_python.yml index b3851394..1727a4c9 100644 --- a/.github/workflows/lint_python.yml +++ b/.github/workflows/lint_python.yml @@ -1,7 +1,17 @@ name: lint_python on: [pull_request, push] jobs: + changes: + uses: ./.github/workflows/detect-changes.yml + with: + group: python + + # Python checks only run when Python sources or dependencies changed. + # Skipped jobs report success, so required status checks stay compatible; + # if change detection fails, the checks run anyway. lint_python: + needs: changes + if: needs.changes.result != 'success' || needs.changes.outputs.matched == 'true' runs-on: lq_run steps: - uses: actions/checkout@v4 diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 7ee3c842..0a73a35b 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -3,7 +3,17 @@ name: Rust on: [push] jobs: + changes: + uses: ./.github/workflows/detect-changes.yml + with: + group: rust + + # The Rust build and audit only run when the Rust workspace or its build + # scripts changed. Skipped jobs report success; if change detection fails, + # they run anyway. build: + needs: changes + if: needs.changes.result != 'success' || needs.changes.outputs.matched == 'true' runs-on: [ lq_run ] steps: @@ -41,6 +51,8 @@ jobs: path: src/dist/libreqos_${{ env.VERSION }}.-1_amd64.deb audit: + needs: changes + if: needs.changes.result != 'success' || needs.changes.outputs.matched == 'true' runs-on: ubuntu-latest steps: -- knotmirror 0.0.1 From 4c643dc62f99081c67c6a124df26a8975acff14e Mon Sep 17 00:00:00 2001 From: rchac Date: Sat, 24 Oct 2026 15:58:30 -0600 Subject: [PATCH 14/17] fix(uisp_integration): harden full2 directionality for mutual AP references Based on PR #1183 (trendal), locally hardened for the v2.2 line. A mutual `apDevice` reference is not evidence of orientation: UISP also fills it on the AP end of PtP/bridge links. Trust the reference only when one end is positively labelled as AP/station, and decline both-AP, both-station or unlabelled mutual references so the result does not depend on argument order. Adds 9 regression tests (13 directionality tests total). Credit: PR #1183 (trendal). Backport target: public v2.2 line (develop). --- .../src/strategies/full2/directionality.rs | 202 +++++++++++++++++- 1 file changed, 199 insertions(+), 3 deletions(-) diff --git a/src/rust/uisp_integration/src/strategies/full2/directionality.rs b/src/rust/uisp_integration/src/strategies/full2/directionality.rs index 3a63491e..76aaaf21 100644 --- a/src/rust/uisp_integration/src/strategies/full2/directionality.rs +++ b/src/rust/uisp_integration/src/strategies/full2/directionality.rs @@ -82,11 +82,47 @@ pub(crate) fn classify_ap_station( let meta_a = meta_by_id.get(id_a)?; let meta_b = meta_by_id.get(id_b)?; - // Highest confidence: the station references its AP by device ID. - if meta_a.ap_device_id.as_deref() == Some(id_b) { + // UISP (devices?withInterfaces=true) also fills `attributes.apDevice` on the AP + // end of PtP/bridge links, pointing back at the station, so a mutual reference + // is not evidence of orientation on its own. Use the reference only when one + // end is positively labelled: trust a positively-labelled AP end, or a + // positively-labelled station end (the other end is then the AP). If both are + // AP, both are station, or neither is labelled, decline instead of making the + // answer depend on argument order. + let a_refs_b = meta_a.ap_device_id.as_deref() == Some(id_b); + let b_refs_a = meta_b.ap_device_id.as_deref() == Some(id_a); + let a_is_ap = role_kind(meta_a.role.as_deref()) == Some(RadioRole::Ap) + || wireless_mode_kind(meta_a.wireless_mode.as_deref()) == Some(RadioRole::Ap); + let b_is_ap = role_kind(meta_b.role.as_deref()) == Some(RadioRole::Ap) + || wireless_mode_kind(meta_b.wireless_mode.as_deref()) == Some(RadioRole::Ap); + let a_is_station = role_kind(meta_a.role.as_deref()) == Some(RadioRole::Station) + || wireless_mode_kind(meta_a.wireless_mode.as_deref()) == Some(RadioRole::Station); + let b_is_station = role_kind(meta_b.role.as_deref()) == Some(RadioRole::Station) + || wireless_mode_kind(meta_b.wireless_mode.as_deref()) == Some(RadioRole::Station); + if a_refs_b && b_refs_a { + if a_is_ap && !b_is_ap { + return Some(LinkOrientation::AIsAp); + } + if b_is_ap && !a_is_ap { + return Some(LinkOrientation::BIsAp); + } + if a_is_ap && b_is_ap { + return None; + } + if a_is_station && !b_is_station { + return Some(LinkOrientation::BIsAp); + } + if b_is_station && !a_is_station { + return Some(LinkOrientation::AIsAp); + } + return None; + } + // A one-way reference keeps the historical behavior: the referencing end is + // the station unless it is itself positively an AP. + if a_refs_b && !a_is_ap { return Some(LinkOrientation::BIsAp); } - if meta_b.ap_device_id.as_deref() == Some(id_a) { + if b_refs_a && !b_is_ap { return Some(LinkOrientation::AIsAp); } @@ -251,4 +287,164 @@ mod tests { assert!(directed_caps_mbps(&meta, &caps, &cfg, "a", "b").is_none()); } + + #[test] + fn mutual_ap_device_references_do_not_flip_orientation() { + // UISP devices?withInterfaces=true reports apDevice on both ends of 1:1 + // PtP links; the labelled AP end must decide the orientation for both + // argument orders. + let ap = mk_raw_device("ap", Some("ap"), Some("ap-ptp"), Some("sta")); + let sta = mk_raw_device("sta", Some("station"), Some("sta-ptp"), Some("ap")); + let meta = build_device_link_meta_map(&[ap, sta]); + let cfg = Config::default(); + let caps = caps_map(&[("ap", 193, 61), ("sta", 193, 61)]); + assert_eq!( + directed_caps_mbps(&meta, &caps, &cfg, "ap", "sta"), + Some((193, 61)) + ); + assert_eq!( + directed_caps_mbps(&meta, &caps, &cfg, "sta", "ap"), + Some((61, 193)) + ); + } + + #[test] + fn mutual_references_without_labels_are_order_independent() { + // Both ends reference each other but neither has usable role/wireless + // metadata. Decline in both argument orders instead of picking a side. + let a = mk_raw_device("a", None, None, Some("b")); + let b = mk_raw_device("b", None, None, Some("a")); + let meta = build_device_link_meta_map(&[a, b]); + let cfg = Config::default(); + let caps = caps_map(&[("a", 193, 61), ("b", 193, 61)]); + assert!(classify_ap_station(&meta, "a", "b").is_none()); + assert!(classify_ap_station(&meta, "b", "a").is_none()); + assert!(directed_caps_mbps(&meta, &caps, &cfg, "a", "b").is_none()); + assert!(directed_caps_mbps(&meta, &caps, &cfg, "b", "a").is_none()); + } + + #[test] + fn mutual_references_with_a_labelled_station_still_resolve() { + // The AP end may have no role/wireless metadata; a positively-labelled + // station end is enough to identify the other end as the AP. + let ap = mk_raw_device("ap", None, None, Some("sta")); + let sta = mk_raw_device("sta", Some("station"), Some("sta-ptp"), Some("ap")); + let meta = build_device_link_meta_map(&[ap, sta]); + let cfg = Config::default(); + let caps = caps_map(&[("ap", 193, 61), ("sta", 193, 61)]); + assert_eq!( + classify_ap_station(&meta, "ap", "sta"), + Some(LinkOrientation::AIsAp) + ); + assert_eq!( + classify_ap_station(&meta, "sta", "ap"), + Some(LinkOrientation::BIsAp) + ); + assert_eq!( + directed_caps_mbps(&meta, &caps, &cfg, "ap", "sta"), + Some((193, 61)) + ); + assert_eq!( + directed_caps_mbps(&meta, &caps, &cfg, "sta", "ap"), + Some((61, 193)) + ); + } + + #[test] + fn both_ap_ends_are_ambiguous() { + let ap1 = mk_raw_device("ap1", Some("ap"), Some("ap-ptp"), Some("ap2")); + let ap2 = mk_raw_device("ap2", Some("ap"), Some("ap-ptp"), Some("ap1")); + let meta = build_device_link_meta_map(&[ap1, ap2]); + let cfg = Config::default(); + let caps = caps_map(&[("ap1", 193, 61), ("ap2", 193, 61)]); + assert!(classify_ap_station(&meta, "ap1", "ap2").is_none()); + assert!(classify_ap_station(&meta, "ap2", "ap1").is_none()); + assert!(directed_caps_mbps(&meta, &caps, &cfg, "ap1", "ap2").is_none()); + assert!(directed_caps_mbps(&meta, &caps, &cfg, "ap2", "ap1").is_none()); + } + + #[test] + fn one_way_ap_device_from_an_ap_uses_role_fallback() { + let ap = mk_raw_device("ap", Some("ap"), Some("ap-ptp"), Some("sta")); + let sta = mk_raw_device("sta", Some("station"), Some("sta-ptp"), None); + let meta = build_device_link_meta_map(&[ap, sta]); + assert_eq!( + classify_ap_station(&meta, "ap", "sta"), + Some(LinkOrientation::AIsAp) + ); + assert_eq!( + classify_ap_station(&meta, "sta", "ap"), + Some(LinkOrientation::BIsAp) + ); + } + + #[test] + fn mixed_role_and_wireless_uses_wireless_when_both_roles_are_station() { + // Pre-existing fallback policy: when both explicit roles say station, the + // wirelessMode pair decides. This is not a role-first precedence test. + let a = mk_raw_device("a", Some("station"), Some("ap-ptp"), None); + let b = mk_raw_device("b", Some("station"), Some("sta-ptp"), None); + let meta = build_device_link_meta_map(&[a, b]); + assert_eq!( + classify_ap_station(&meta, "a", "b"), + Some(LinkOrientation::AIsAp) + ); + } + + #[test] + fn mutual_references_with_both_ends_station_are_ambiguous() { + let a = mk_raw_device("a", Some("station"), Some("sta-ptp"), Some("b")); + let b = mk_raw_device("b", Some("station"), Some("sta-ptp"), Some("a")); + let meta = build_device_link_meta_map(&[a, b]); + let cfg = Config::default(); + let caps = caps_map(&[("a", 193, 61), ("b", 193, 61)]); + assert!(classify_ap_station(&meta, "a", "b").is_none()); + assert!(classify_ap_station(&meta, "b", "a").is_none()); + assert!(directed_caps_mbps(&meta, &caps, &cfg, "a", "b").is_none()); + assert!(directed_caps_mbps(&meta, &caps, &cfg, "b", "a").is_none()); + } + + #[test] + fn mutual_conflicting_labels_still_orient_by_the_ap_label() { + // A positive AP label (wirelessMode here) wins even when the role says + // station; the pair is still order-independent. + let a = mk_raw_device("a", Some("station"), Some("ap-ptp"), Some("b")); + let b = mk_raw_device("b", Some("station"), Some("sta-ptp"), Some("a")); + let meta = build_device_link_meta_map(&[a, b]); + let cfg = Config::default(); + let caps = caps_map(&[("a", 193, 61), ("b", 193, 61)]); + assert_eq!( + classify_ap_station(&meta, "a", "b"), + Some(LinkOrientation::AIsAp) + ); + assert_eq!( + classify_ap_station(&meta, "b", "a"), + Some(LinkOrientation::BIsAp) + ); + assert_eq!( + directed_caps_mbps(&meta, &caps, &cfg, "a", "b"), + Some((193, 61)) + ); + assert_eq!( + directed_caps_mbps(&meta, &caps, &cfg, "b", "a"), + Some((61, 193)) + ); + } + + #[test] + fn role_pair_wins_over_conflicting_wireless_labels() { + // No apDevice: the explicit role pair (ap,station) wins over the + // conflicting wireless pair (sta,ap); this is the role-first policy. + let a = mk_raw_device("a", Some("ap"), Some("sta-ptp"), None); + let b = mk_raw_device("b", Some("station"), Some("ap-ptp"), None); + let meta = build_device_link_meta_map(&[a, b]); + assert_eq!( + classify_ap_station(&meta, "a", "b"), + Some(LinkOrientation::AIsAp) + ); + assert_eq!( + classify_ap_station(&meta, "b", "a"), + Some(LinkOrientation::BIsAp) + ); + } } -- knotmirror 0.0.1 From e6162ac18a5427aeb0d5ade4c4b7c1bee6a4e865 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20Chac=C3=B3n?= Date: Sun, 25 Oct 2026 15:54:38 -0600 Subject: [PATCH 15/17] fix(uisp_integration): prefer site topology over radio labels Use UISP site assignment as the primary full2 orientation signal: a parent/upstream site wins, then the northern site for a real latitude delta. Keep apDevice/role/wirelessMode as the fallback for east/west and missing topology, with the mutual-reference guard from #1184. Adds topology tests for north/south, parent/child, east/west, missing data, and argument-order stability. --- .../uisp_integration/src/strategies/full2.rs | 17 +- .../src/strategies/full2/directionality.rs | 300 +++++++++++++++++- 2 files changed, 310 insertions(+), 7 deletions(-) diff --git a/src/rust/uisp_integration/src/strategies/full2.rs b/src/rust/uisp_integration/src/strategies/full2.rs index df4d51bc..af71ee53 100644 --- a/src/rust/uisp_integration/src/strategies/full2.rs +++ b/src/rust/uisp_integration/src/strategies/full2.rs @@ -9,7 +9,8 @@ use crate::ethernet_advisory::apply_ethernet_rate_cap; use crate::ip_ranges::IpRanges; use crate::strategies::common::UispData; use crate::strategies::full2::directionality::{ - build_device_capacity_map, build_device_link_meta_map, directed_caps_mbps, + LinkTopology, build_device_capacity_map, build_device_link_meta_map, + directed_caps_mbps_with_topology, }; use crate::strategies::full2::graph_mapping::GraphMapping; use crate::strategies::full2::link_mapping::LinkMapping; @@ -1018,6 +1019,9 @@ fn add_device_links_to_graph( ) { let meta_by_id = build_device_link_meta_map(&uisp_data.devices_raw); let caps_by_id = build_device_capacity_map(&uisp_data.devices); + // Build once per import: the site assignment is the primary orientation + // signal; labels remain the fallback for east/west and missing topology. + let topology = LinkTopology::from_uisp_data(&uisp_data.sites, &uisp_data.devices); for link in uisp_data.data_links_raw.iter() { let Some(from_device) = &link.from.device else { @@ -1054,9 +1058,14 @@ fn add_device_links_to_graph( let id_a = from_device.identification.id.as_str(); let id_b = to_device.identification.id.as_str(); - let (cap_ab, cap_ba) = if let Some((cap_ab, cap_ba)) = - directed_caps_mbps(&meta_by_id, &caps_by_id, config, id_a, id_b) - { + let (cap_ab, cap_ba) = if let Some((cap_ab, cap_ba)) = directed_caps_mbps_with_topology( + &meta_by_id, + Some(&topology), + &caps_by_id, + config, + id_a, + id_b, + ) { (cap_ab, cap_ba) } else { warn!( diff --git a/src/rust/uisp_integration/src/strategies/full2/directionality.rs b/src/rust/uisp_integration/src/strategies/full2/directionality.rs index 76aaaf21..d0a0e274 100644 --- a/src/rust/uisp_integration/src/strategies/full2/directionality.rs +++ b/src/rust/uisp_integration/src/strategies/full2/directionality.rs @@ -1,8 +1,126 @@ -use crate::uisp_types::UispDevice; +use crate::uisp_types::{UispDevice, UispSite}; use lqos_config::Config; -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use uisp::Device; +/// Site latitude differences below this are treated as east/west (no +/// north/south winner). ~1e-5 degrees is about one metre, so ordinary +/// geocoding noise does not flip a link. +const LATITUDE_EPSILON: f32 = 1e-5; + +#[derive(Debug, Clone)] +struct SiteTopology { + latitude: Option, + parent_id: Option, +} + +/// The UISP site assignment is the orientation signal we trust first. +#[derive(Debug, Clone, Default)] +pub(crate) struct LinkTopology { + site_by_id: HashMap, + site_id_by_device_id: HashMap, +} + +impl LinkTopology { + pub(crate) fn from_uisp_data(sites: &[UispSite], devices: &[UispDevice]) -> Self { + let site_by_id = sites + .iter() + .map(|site| { + ( + site.id.clone(), + SiteTopology { + latitude: site.latitude, + parent_id: site.uisp_parent_id.clone(), + }, + ) + }) + .collect(); + let site_id_by_device_id = devices + .iter() + .filter(|device| !device.site_id.is_empty()) + .map(|device| (device.id.clone(), device.site_id.clone())) + .collect(); + Self { + site_by_id, + site_id_by_device_id, + } + } + + /// Topology-first orientation: + /// 1. parent/upstream site wins; + /// 2. otherwise the northern site wins when there is a real latitude delta; + /// 3. otherwise None, letting the label-based fallback decide. + fn orientation(&self, id_a: &str, id_b: &str) -> Option { + let site_a = self.site_id_by_device_id.get(id_a)?; + let site_b = self.site_id_by_device_id.get(id_b)?; + if site_a == site_b { + return None; + } + if self.is_ancestor(site_a, site_b) { + return Some(LinkOrientation::AIsAp); + } + if self.is_ancestor(site_b, site_a) { + return Some(LinkOrientation::BIsAp); + } + + let lat_a = self.site_by_id.get(site_a)?.latitude?; + let lat_b = self.site_by_id.get(site_b)?.latitude?; + if (lat_a - lat_b).abs() <= LATITUDE_EPSILON { + return None; + } + if lat_a > lat_b { + Some(LinkOrientation::AIsAp) + } else { + Some(LinkOrientation::BIsAp) + } + } + + fn is_ancestor(&self, ancestor: &str, descendant: &str) -> bool { + let mut current = descendant; + let mut seen = HashSet::new(); + loop { + if !seen.insert(current.to_string()) { + return false; + } + let Some(site) = self.site_by_id.get(current) else { + return false; + }; + let Some(parent) = site.parent_id.as_deref() else { + return false; + }; + if parent == ancestor { + return true; + } + current = parent; + } + } + + #[cfg(test)] + fn from_test_sites( + sites: &[(&str, Option, Option<&str>)], + device_sites: &[(&str, &str)], + ) -> Self { + Self { + site_by_id: sites + .iter() + .map(|(id, latitude, parent_id)| { + ( + (*id).to_string(), + SiteTopology { + latitude: *latitude, + parent_id: parent_id.map(str::to_string), + }, + ) + }) + .collect(), + site_id_by_device_id: device_sites + .iter() + .map(|(device, site)| ((*device).to_string(), (*site).to_string())) + .collect(), + } + } +} + #[derive(Debug, Clone)] pub(crate) struct DeviceLinkMeta { pub(crate) ap_device_id: Option, @@ -79,6 +197,21 @@ pub(crate) fn classify_ap_station( id_a: &str, id_b: &str, ) -> Option { + classify_ap_station_with_topology(meta_by_id, None, id_a, id_b) +} + +pub(crate) fn classify_ap_station_with_topology( + meta_by_id: &HashMap, + topology: Option<&LinkTopology>, + id_a: &str, + id_b: &str, +) -> Option { + if let Some(topology) = topology + && let Some(orientation) = topology.orientation(id_a, id_b) + { + return Some(orientation); + } + let meta_a = meta_by_id.get(id_a)?; let meta_b = meta_by_id.get(id_b)?; @@ -154,7 +287,18 @@ pub(crate) fn directed_caps_mbps( id_a: &str, id_b: &str, ) -> Option<(u64, u64)> { - let orientation = classify_ap_station(meta_by_id, id_a, id_b)?; + directed_caps_mbps_with_topology(meta_by_id, None, caps_by_id, config, id_a, id_b) +} + +pub(crate) fn directed_caps_mbps_with_topology( + meta_by_id: &HashMap, + topology: Option<&LinkTopology>, + caps_by_id: &HashMap, + config: &Config, + id_a: &str, + id_b: &str, +) -> Option<(u64, u64)> { + let orientation = classify_ap_station_with_topology(meta_by_id, topology, id_a, id_b)?; let (a_down, a_up) = caps_by_id.get(id_a).copied().unwrap_or(( config.queues.generated_pn_download_mbps, @@ -447,4 +591,154 @@ mod tests { Some(LinkOrientation::BIsAp) ); } + + #[test] + fn topology_north_site_wins_over_inverted_labels() { + // The radio at the northern site is the AP even when both ends carry + // misleading station/AP labels. This is the ISP-reported Wave case. + let a = mk_raw_device("a", Some("station"), Some("sta-ptp"), Some("b")); + let b = mk_raw_device("b", Some("ap"), Some("ap-ptp"), Some("a")); + let meta = build_device_link_meta_map(&[a, b]); + let topology = LinkTopology::from_test_sites( + &[("north", Some(40.0), None), ("south", Some(39.0), None)], + &[("a", "north"), ("b", "south")], + ); + let cfg = Config::default(); + let caps = caps_map(&[("a", 193, 61), ("b", 193, 61)]); + + assert_eq!( + classify_ap_station_with_topology(&meta, Some(&topology), "a", "b"), + Some(LinkOrientation::AIsAp) + ); + assert_eq!( + classify_ap_station_with_topology(&meta, Some(&topology), "b", "a"), + Some(LinkOrientation::BIsAp) + ); + assert_eq!( + directed_caps_mbps_with_topology(&meta, Some(&topology), &caps, &cfg, "a", "b"), + Some((193, 61)) + ); + assert_eq!( + directed_caps_mbps_with_topology(&meta, Some(&topology), &caps, &cfg, "b", "a"), + Some((61, 193)) + ); + } + + #[test] + fn topology_parent_site_wins_over_north_site_and_labels() { + // Site hierarchy is stronger than latitude: the upstream/parent site is + // the AP even if the child site is further north. + let a = mk_raw_device("a", Some("ap"), Some("ap-ptp"), None); + let b = mk_raw_device("b", Some("station"), Some("sta-ptp"), None); + let meta = build_device_link_meta_map(&[a, b]); + let topology = LinkTopology::from_test_sites( + &[ + ("parent", Some(39.0), None), + ("child", Some(40.0), Some("parent")), + ], + &[("a", "child"), ("b", "parent")], + ); + let cfg = Config::default(); + let caps = caps_map(&[("a", 193, 61), ("b", 193, 61)]); + + assert_eq!( + classify_ap_station_with_topology(&meta, Some(&topology), "a", "b"), + Some(LinkOrientation::BIsAp) + ); + assert_eq!( + classify_ap_station_with_topology(&meta, Some(&topology), "b", "a"), + Some(LinkOrientation::AIsAp) + ); + assert_eq!( + directed_caps_mbps_with_topology(&meta, Some(&topology), &caps, &cfg, "a", "b"), + Some((61, 193)) + ); + } + + #[test] + fn east_west_link_falls_back_to_labels() { + // Same latitude (within the epsilon): there is no north/south winner, + // so the existing label policy decides. + let a = mk_raw_device("a", Some("ap"), Some("ap-ptp"), None); + let b = mk_raw_device("b", Some("station"), Some("sta-ptp"), None); + let meta = build_device_link_meta_map(&[a, b]); + let topology = LinkTopology::from_test_sites( + &[("east", Some(40.0), None), ("west", Some(40.0), None)], + &[("a", "east"), ("b", "west")], + ); + assert_eq!( + classify_ap_station_with_topology(&meta, Some(&topology), "a", "b"), + Some(LinkOrientation::AIsAp) + ); + assert_eq!( + classify_ap_station_with_topology(&meta, Some(&topology), "b", "a"), + Some(LinkOrientation::BIsAp) + ); + } + + #[test] + fn latitude_noise_does_not_override_labels() { + let a = mk_raw_device("a", Some("ap"), Some("ap-ptp"), None); + let b = mk_raw_device("b", Some("station"), Some("sta-ptp"), None); + let meta = build_device_link_meta_map(&[a, b]); + let topology = LinkTopology::from_test_sites( + &[ + ("a-site", Some(40.0), None), + ("b-site", Some(40.000001), None), + ], + &[("a", "a-site"), ("b", "b-site")], + ); + assert_eq!( + classify_ap_station_with_topology(&meta, Some(&topology), "a", "b"), + Some(LinkOrientation::AIsAp) + ); + } + + #[test] + fn missing_site_coordinates_fall_back_to_labels() { + let a = mk_raw_device("a", Some("ap"), Some("ap-ptp"), None); + let b = mk_raw_device("b", Some("station"), Some("sta-ptp"), None); + let meta = build_device_link_meta_map(&[a, b]); + let topology = LinkTopology::from_test_sites( + &[("a-site", None, None), ("b-site", None, None)], + &[("a", "a-site"), ("b", "b-site")], + ); + assert_eq!( + classify_ap_station_with_topology(&meta, Some(&topology), "a", "b"), + Some(LinkOrientation::AIsAp) + ); + } + + #[test] + fn missing_device_site_assignment_falls_back_to_labels() { + let a = mk_raw_device("a", Some("ap"), Some("ap-ptp"), None); + let b = mk_raw_device("b", Some("station"), Some("sta-ptp"), None); + let meta = build_device_link_meta_map(&[a, b]); + let topology = + LinkTopology::from_test_sites(&[("a-site", Some(40.0), None)], &[("a", "a-site")]); + assert_eq!( + classify_ap_station_with_topology(&meta, Some(&topology), "a", "b"), + Some(LinkOrientation::AIsAp) + ); + } + + #[test] + fn parent_cycle_does_not_hang_topology_resolution() { + // Invalid UISP data: both sites point at each other. The visited set + // must break the walk; the first parent edge still gives a stable answer. + let a = mk_raw_device("a", Some("ap"), Some("ap-ptp"), None); + let b = mk_raw_device("b", Some("station"), Some("sta-ptp"), None); + let meta = build_device_link_meta_map(&[a, b]); + let topology = LinkTopology::from_test_sites( + &[ + ("a-site", Some(39.0), Some("b-site")), + ("b-site", Some(40.0), Some("a-site")), + ], + &[("a", "a-site"), ("b", "b-site")], + ); + assert_eq!( + classify_ap_station_with_topology(&meta, Some(&topology), "a", "b"), + Some(LinkOrientation::AIsAp) + ); + } } -- knotmirror 0.0.1 From 8a108d09a31cc1d6dc3b33c1f7c5b0ee7551d7c4 Mon Sep 17 00:00:00 2001 From: rchac Date: Sun, 25 Oct 2026 18:55:18 -0600 Subject: [PATCH 16/17] fix(uisp): remove latitude tiebreak and decline invalid cycles Final topology-first orientation: upstream/ancestor wins; peer/same-site falls back to the #1184 labels; both-ancestor (cycle) returns Invalid independent of argument order. Content is the reviewed v3 implementation (directionality.rs sha256 f2d39fc9). --- .../src/strategies/full2/directionality.rs | 191 +++++++----------- 1 file changed, 78 insertions(+), 113 deletions(-) diff --git a/src/rust/uisp_integration/src/strategies/full2/directionality.rs b/src/rust/uisp_integration/src/strategies/full2/directionality.rs index d0a0e274..16418289 100644 --- a/src/rust/uisp_integration/src/strategies/full2/directionality.rs +++ b/src/rust/uisp_integration/src/strategies/full2/directionality.rs @@ -3,14 +3,8 @@ use lqos_config::Config; use std::collections::{HashMap, HashSet}; use uisp::Device; -/// Site latitude differences below this are treated as east/west (no -/// north/south winner). ~1e-5 degrees is about one metre, so ordinary -/// geocoding noise does not flip a link. -const LATITUDE_EPSILON: f32 = 1e-5; - #[derive(Debug, Clone)] struct SiteTopology { - latitude: Option, parent_id: Option, } @@ -29,7 +23,6 @@ impl LinkTopology { ( site.id.clone(), SiteTopology { - latitude: site.latitude, parent_id: site.uisp_parent_id.clone(), }, ) @@ -46,32 +39,30 @@ impl LinkTopology { } } - /// Topology-first orientation: - /// 1. parent/upstream site wins; - /// 2. otherwise the northern site wins when there is a real latitude delta; - /// 3. otherwise None, letting the label-based fallback decide. - fn orientation(&self, id_a: &str, id_b: &str) -> Option { - let site_a = self.site_id_by_device_id.get(id_a)?; - let site_b = self.site_id_by_device_id.get(id_b)?; + /// Topology-first orientation: only the upstream/parent site wins. + /// Peer and same-site links return None so the label-based fallback + /// (#1184) decides. Invalid data with both ancestry directions true also + /// returns None, independent of argument order. + fn orientation(&self, id_a: &str, id_b: &str) -> TopologyDecision { + let Some(site_a) = self.site_id_by_device_id.get(id_a) else { + return TopologyDecision::Fallback; + }; + let Some(site_b) = self.site_id_by_device_id.get(id_b) else { + return TopologyDecision::Fallback; + }; if site_a == site_b { - return None; - } - if self.is_ancestor(site_a, site_b) { - return Some(LinkOrientation::AIsAp); + return TopologyDecision::Fallback; } - if self.is_ancestor(site_b, site_a) { - return Some(LinkOrientation::BIsAp); - } - - let lat_a = self.site_by_id.get(site_a)?.latitude?; - let lat_b = self.site_by_id.get(site_b)?.latitude?; - if (lat_a - lat_b).abs() <= LATITUDE_EPSILON { - return None; - } - if lat_a > lat_b { - Some(LinkOrientation::AIsAp) - } else { - Some(LinkOrientation::BIsAp) + match ( + self.is_ancestor(site_a, site_b), + self.is_ancestor(site_b, site_a), + ) { + (true, false) => TopologyDecision::Resolved(LinkOrientation::AIsAp), + (false, true) => TopologyDecision::Resolved(LinkOrientation::BIsAp), + // Both directions true is invalid UISP data; declining keeps the + // answer independent of argument order. + (true, true) => TopologyDecision::Invalid, + (false, false) => TopologyDecision::Fallback, } } @@ -96,18 +87,14 @@ impl LinkTopology { } #[cfg(test)] - fn from_test_sites( - sites: &[(&str, Option, Option<&str>)], - device_sites: &[(&str, &str)], - ) -> Self { + fn from_test_sites(sites: &[(&str, Option<&str>)], device_sites: &[(&str, &str)]) -> Self { Self { site_by_id: sites .iter() - .map(|(id, latitude, parent_id)| { + .map(|(id, parent_id)| { ( (*id).to_string(), SiteTopology { - latitude: *latitude, parent_id: parent_id.map(str::to_string), }, ) @@ -134,6 +121,15 @@ pub(crate) enum LinkOrientation { BIsAp, } +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum TopologyDecision { + Resolved(LinkOrientation), + /// No topology answer; let the #1184 label classifier decide. + Fallback, + /// Invalid/ambiguous topology; decline rather than fall through to labels. + Invalid, +} + #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum RadioRole { Ap, @@ -206,10 +202,12 @@ pub(crate) fn classify_ap_station_with_topology( id_a: &str, id_b: &str, ) -> Option { - if let Some(topology) = topology - && let Some(orientation) = topology.orientation(id_a, id_b) - { - return Some(orientation); + if let Some(topology) = topology { + match topology.orientation(id_a, id_b) { + TopologyDecision::Resolved(orientation) => return Some(orientation), + TopologyDecision::Invalid => return None, + TopologyDecision::Fallback => {} + } } let meta_a = meta_by_id.get(id_a)?; @@ -593,53 +591,19 @@ mod tests { } #[test] - fn topology_north_site_wins_over_inverted_labels() { - // The radio at the northern site is the AP even when both ends carry - // misleading station/AP labels. This is the ISP-reported Wave case. - let a = mk_raw_device("a", Some("station"), Some("sta-ptp"), Some("b")); - let b = mk_raw_device("b", Some("ap"), Some("ap-ptp"), Some("a")); - let meta = build_device_link_meta_map(&[a, b]); - let topology = LinkTopology::from_test_sites( - &[("north", Some(40.0), None), ("south", Some(39.0), None)], - &[("a", "north"), ("b", "south")], - ); - let cfg = Config::default(); - let caps = caps_map(&[("a", 193, 61), ("b", 193, 61)]); - - assert_eq!( - classify_ap_station_with_topology(&meta, Some(&topology), "a", "b"), - Some(LinkOrientation::AIsAp) - ); - assert_eq!( - classify_ap_station_with_topology(&meta, Some(&topology), "b", "a"), - Some(LinkOrientation::BIsAp) - ); - assert_eq!( - directed_caps_mbps_with_topology(&meta, Some(&topology), &caps, &cfg, "a", "b"), - Some((193, 61)) - ); - assert_eq!( - directed_caps_mbps_with_topology(&meta, Some(&topology), &caps, &cfg, "b", "a"), - Some((61, 193)) - ); - } - - #[test] - fn topology_parent_site_wins_over_north_site_and_labels() { - // Site hierarchy is stronger than latitude: the upstream/parent site is - // the AP even if the child site is further north. + fn upstream_site_wins_over_conflicting_labels() { + // The parent/upstream site is the AP even when its device is labelled + // station and the child device is labelled AP. Asymmetric capacities + // prove that the selected end's capacity tuple is used. let a = mk_raw_device("a", Some("ap"), Some("ap-ptp"), None); let b = mk_raw_device("b", Some("station"), Some("sta-ptp"), None); let meta = build_device_link_meta_map(&[a, b]); let topology = LinkTopology::from_test_sites( - &[ - ("parent", Some(39.0), None), - ("child", Some(40.0), Some("parent")), - ], + &[("parent", None), ("child", Some("parent"))], &[("a", "child"), ("b", "parent")], ); let cfg = Config::default(); - let caps = caps_map(&[("a", 193, 61), ("b", 193, 61)]); + let caps = caps_map(&[("a", 50, 20), ("b", 193, 61)]); assert_eq!( classify_ap_station_with_topology(&meta, Some(&topology), "a", "b"), @@ -651,20 +615,24 @@ mod tests { ); assert_eq!( directed_caps_mbps_with_topology(&meta, Some(&topology), &caps, &cfg, "a", "b"), - Some((61, 193)) + Some((20, 50)) + ); + assert_eq!( + directed_caps_mbps_with_topology(&meta, Some(&topology), &caps, &cfg, "b", "a"), + Some((50, 20)) ); } #[test] - fn east_west_link_falls_back_to_labels() { - // Same latitude (within the epsilon): there is no north/south winner, - // so the existing label policy decides. + fn peer_sites_fall_back_to_labels() { + // Neither site is upstream. Site assignment alone must not orient the + // link; the #1184 label classifier decides. let a = mk_raw_device("a", Some("ap"), Some("ap-ptp"), None); let b = mk_raw_device("b", Some("station"), Some("sta-ptp"), None); let meta = build_device_link_meta_map(&[a, b]); let topology = LinkTopology::from_test_sites( - &[("east", Some(40.0), None), ("west", Some(40.0), None)], - &[("a", "east"), ("b", "west")], + &[("north-site", None), ("south-site", None)], + &[("a", "north-site"), ("b", "south-site")], ); assert_eq!( classify_ap_station_with_topology(&meta, Some(&topology), "a", "b"), @@ -677,16 +645,13 @@ mod tests { } #[test] - fn latitude_noise_does_not_override_labels() { + fn same_site_assignment_falls_back_to_labels() { let a = mk_raw_device("a", Some("ap"), Some("ap-ptp"), None); let b = mk_raw_device("b", Some("station"), Some("sta-ptp"), None); let meta = build_device_link_meta_map(&[a, b]); let topology = LinkTopology::from_test_sites( - &[ - ("a-site", Some(40.0), None), - ("b-site", Some(40.000001), None), - ], - &[("a", "a-site"), ("b", "b-site")], + &[("same-site", None)], + &[("a", "same-site"), ("b", "same-site")], ); assert_eq!( classify_ap_station_with_topology(&meta, Some(&topology), "a", "b"), @@ -695,16 +660,22 @@ mod tests { } #[test] - fn missing_site_coordinates_fall_back_to_labels() { - let a = mk_raw_device("a", Some("ap"), Some("ap-ptp"), None); - let b = mk_raw_device("b", Some("station"), Some("sta-ptp"), None); - let meta = build_device_link_meta_map(&[a, b]); + fn ap_south_of_station_resolves_by_labels() { + // Regression for the removed geographic rule: the southern peer is the + // AP here, and labels must resolve it in both argument orders. + let station = mk_raw_device("station", Some("station"), Some("sta-ptp"), None); + let ap = mk_raw_device("ap", Some("ap"), Some("ap-ptp"), None); + let meta = build_device_link_meta_map(&[station, ap]); let topology = LinkTopology::from_test_sites( - &[("a-site", None, None), ("b-site", None, None)], - &[("a", "a-site"), ("b", "b-site")], + &[("north-site", None), ("south-site", None)], + &[("station", "north-site"), ("ap", "south-site")], ); assert_eq!( - classify_ap_station_with_topology(&meta, Some(&topology), "a", "b"), + classify_ap_station_with_topology(&meta, Some(&topology), "station", "ap"), + Some(LinkOrientation::BIsAp) + ); + assert_eq!( + classify_ap_station_with_topology(&meta, Some(&topology), "ap", "station"), Some(LinkOrientation::AIsAp) ); } @@ -714,8 +685,7 @@ mod tests { let a = mk_raw_device("a", Some("ap"), Some("ap-ptp"), None); let b = mk_raw_device("b", Some("station"), Some("sta-ptp"), None); let meta = build_device_link_meta_map(&[a, b]); - let topology = - LinkTopology::from_test_sites(&[("a-site", Some(40.0), None)], &[("a", "a-site")]); + let topology = LinkTopology::from_test_sites(&[("a-site", None)], &[("a", "a-site")]); assert_eq!( classify_ap_station_with_topology(&meta, Some(&topology), "a", "b"), Some(LinkOrientation::AIsAp) @@ -723,22 +693,17 @@ mod tests { } #[test] - fn parent_cycle_does_not_hang_topology_resolution() { - // Invalid UISP data: both sites point at each other. The visited set - // must break the walk; the first parent edge still gives a stable answer. + fn parent_cycle_returns_none_both_orders() { + // Invalid UISP data: both sites point at each other. Topology must + // decline rather than let argument order choose a winner. let a = mk_raw_device("a", Some("ap"), Some("ap-ptp"), None); let b = mk_raw_device("b", Some("station"), Some("sta-ptp"), None); let meta = build_device_link_meta_map(&[a, b]); let topology = LinkTopology::from_test_sites( - &[ - ("a-site", Some(39.0), Some("b-site")), - ("b-site", Some(40.0), Some("a-site")), - ], + &[("a-site", Some("b-site")), ("b-site", Some("a-site"))], &[("a", "a-site"), ("b", "b-site")], ); - assert_eq!( - classify_ap_station_with_topology(&meta, Some(&topology), "a", "b"), - Some(LinkOrientation::AIsAp) - ); + assert!(classify_ap_station_with_topology(&meta, Some(&topology), "a", "b").is_none()); + assert!(classify_ap_station_with_topology(&meta, Some(&topology), "b", "a").is_none()); } } -- knotmirror 0.0.1 From 0e1514c020dd39602e3d3bd4b10112362f3f4370 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20Chac=C3=B3n?= Date: Tue, 27 Oct 2026 04:11:47 -0600 Subject: [PATCH 17/17] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d7e05ad1..0d667421 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ LibreQoS

-# LibreQoS v2.0 +# LibreQoS v2.2 LibreQoS is a self-hosted traffic management and network operations platform for Internet Service Providers and enterprise networks. It improves subscriber experience by reducing latency under load while giving operators a local, topology-aware view of network health, subscriber behavior, queue conditions, and traffic patterns.