From 454a681a50c4c34414ed958277ea582b7fb7fffa Mon Sep 17 00:00:00 2001 From: Dobromir Popov Date: Tue, 14 Jul 2026 14:17:23 +0300 Subject: [PATCH] feat: MAINT-001 - Fix Ruff violations across all Python source --- packages/gateway/meshnet_gateway/server.py | 3 +-- packages/node/meshnet_node/cli.py | 4 ++-- packages/node/meshnet_node/dashboard.py | 8 +++----- packages/node/meshnet_node/server.py | 2 +- packages/node/meshnet_node/torch_server.py | 5 ++--- packages/node/meshnet_node/wizard.py | 1 - packages/p2p/meshnet_p2p/mdns.py | 1 - packages/p2p/meshnet_p2p/tls.py | 2 -- packages/relay/meshnet_relay/cli.py | 1 - packages/tracker/meshnet_tracker/raft.py | 4 ++-- .../tracker/meshnet_tracker/routing_stats.py | 2 +- packages/tracker/meshnet_tracker/server.py | 16 ++++------------ packages/validator/meshnet_validator/__init__.py | 2 ++ pyproject.toml | 5 +++++ tests/test_gossip_and_relay.py | 7 ++----- tests/test_mining_cli.py | 5 ----- tests/test_openai_gateway.py | 2 +- tests/test_real_model_backend.py | 1 - tests/test_settlement_loop.py | 4 +--- tests/test_tracker_consensus.py | 4 ++-- tests/test_tracker_routing.py | 3 +-- 21 files changed, 30 insertions(+), 52 deletions(-) diff --git a/packages/gateway/meshnet_gateway/server.py b/packages/gateway/meshnet_gateway/server.py index 2426fb5..8958c08 100644 --- a/packages/gateway/meshnet_gateway/server.py +++ b/packages/gateway/meshnet_gateway/server.py @@ -3,7 +3,6 @@ import http.server import hashlib import json -import os from collections import Counter from dataclasses import dataclass import threading @@ -62,7 +61,7 @@ class _GatewayHTTPServer(http.server.HTTPServer): class _GatewayHandler(http.server.BaseHTTPRequestHandler): - def log_message(self, fmt, *args): # noqa: suppress request logs in tests + def log_message(self, fmt, *args): # suppress request logs in tests pass def do_GET(self): diff --git a/packages/node/meshnet_node/cli.py b/packages/node/meshnet_node/cli.py index a986276..ec68717 100644 --- a/packages/node/meshnet_node/cli.py +++ b/packages/node/meshnet_node/cli.py @@ -144,7 +144,7 @@ def _cmd_default(args) -> int: print("\nSetup cancelled.") return 1 save_config(cfg) - print(f"\nConfig saved to ~/.config/meshnet/config.json\n") + print("\nConfig saved to ~/.config/meshnet/config.json\n") # Apply CLI overrides on top of saved config overrides: dict = {} @@ -198,7 +198,7 @@ def _cmd_default(args) -> int: def _cmd_models(args) -> int: """List curated models (with optional HF Hub browse).""" - from .wizard import print_models_table, _browse_hf_interactive + from .wizard import print_models_table if args.browse: from .model_catalog import browse_hf_hub diff --git a/packages/node/meshnet_node/dashboard.py b/packages/node/meshnet_node/dashboard.py index a12ab05..23e9d9f 100644 --- a/packages/node/meshnet_node/dashboard.py +++ b/packages/node/meshnet_node/dashboard.py @@ -5,7 +5,6 @@ from __future__ import annotations import os import sys import time -from collections import deque from typing import TYPE_CHECKING if TYPE_CHECKING: @@ -114,7 +113,7 @@ def run_dashboard(node, config: dict, start_time: float) -> None: return try: - from rich.live import Live # type: ignore[import] + from rich.live import Live # type: ignore[import] # noqa: F401 _run_rich_dashboard(node, config, start_time) except ImportError: @@ -126,7 +125,6 @@ def _build_rich_renderable( ): from rich.table import Table # type: ignore[import] from rich.panel import Panel # type: ignore[import] - from rich.columns import Columns # type: ignore[import] from rich.text import Text # type: ignore[import] uptime = time.monotonic() - start_time @@ -178,8 +176,8 @@ def _build_rich_renderable( f"Tokens/sec {tps_bar} {tps:.1f} t/s (EMA)", f"Requests {req_count:,} served", f"Success {stats['success_rate']:.1f}% failed {stats['failed_requests']:,} queue {stats['queue_depth']}", - f"Peers 0 connected (gossip: US-017)", - f"TAI earned 0.00 TAI (payments: US-006)", + "Peers 0 connected (gossip: US-017)", + "TAI earned 0.00 TAI (payments: US-006)", f"Uptime {_format_uptime(uptime)}", "", "[q] quit [c] compact view", diff --git a/packages/node/meshnet_node/server.py b/packages/node/meshnet_node/server.py index 236d66b..d3ebf7e 100644 --- a/packages/node/meshnet_node/server.py +++ b/packages/node/meshnet_node/server.py @@ -105,7 +105,7 @@ class _StubHTTPServer(http.server.HTTPServer): class _StubHandler(http.server.BaseHTTPRequestHandler): - def log_message(self, fmt, *args): # noqa: suppress request logs in tests + def log_message(self, fmt, *args): # suppress request logs in tests pass def do_POST(self): diff --git a/packages/node/meshnet_node/torch_server.py b/packages/node/meshnet_node/torch_server.py index e58cf6d..d6c058d 100644 --- a/packages/node/meshnet_node/torch_server.py +++ b/packages/node/meshnet_node/torch_server.py @@ -19,7 +19,6 @@ from .model_backend import ( InsufficientVRAMError, KVCacheMiss, MissingModelDependencyError, - Quantization, TailTokenResult, TorchModelShard, _tensor_from_bfloat16_bytes, @@ -46,7 +45,7 @@ class _DirectRequestUncertainError(ConnectionError): """A direct request may have reached the downstream node but did not finish.""" -from .server import ( +from .server import ( # noqa: E402 _WIRE_VERSION, _parse_shape, _validate_activation_body, @@ -399,7 +398,7 @@ class _TorchHandler(http.server.BaseHTTPRequestHandler): # Finite responses below provide Content-Length; streams are chunked. protocol_version = "HTTP/1.1" - def log_message(self, fmt, *args): # noqa: suppress request logs in tests + def log_message(self, fmt, *args): # suppress request logs in tests pass def _request_id(self) -> str: diff --git a/packages/node/meshnet_node/wizard.py b/packages/node/meshnet_node/wizard.py index 5edf1d3..1ce4f3c 100644 --- a/packages/node/meshnet_node/wizard.py +++ b/packages/node/meshnet_node/wizard.py @@ -2,7 +2,6 @@ from __future__ import annotations -import sys import urllib.error import urllib.request from pathlib import Path diff --git a/packages/p2p/meshnet_p2p/mdns.py b/packages/p2p/meshnet_p2p/mdns.py index edd38d2..713f651 100644 --- a/packages/p2p/meshnet_p2p/mdns.py +++ b/packages/p2p/meshnet_p2p/mdns.py @@ -7,7 +7,6 @@ from __future__ import annotations import logging import socket -import threading from typing import Callable log = logging.getLogger(__name__) diff --git a/packages/p2p/meshnet_p2p/tls.py b/packages/p2p/meshnet_p2p/tls.py index 4f5f1d6..b05148d 100644 --- a/packages/p2p/meshnet_p2p/tls.py +++ b/packages/p2p/meshnet_p2p/tls.py @@ -3,9 +3,7 @@ from __future__ import annotations import datetime -import hashlib import ipaddress -import json import os import socket import ssl diff --git a/packages/relay/meshnet_relay/cli.py b/packages/relay/meshnet_relay/cli.py index 23a0912..0c969dd 100644 --- a/packages/relay/meshnet_relay/cli.py +++ b/packages/relay/meshnet_relay/cli.py @@ -4,7 +4,6 @@ from __future__ import annotations import argparse import logging -import sys import time from pathlib import Path diff --git a/packages/tracker/meshnet_tracker/raft.py b/packages/tracker/meshnet_tracker/raft.py index bad3c97..26b9307 100644 --- a/packages/tracker/meshnet_tracker/raft.py +++ b/packages/tracker/meshnet_tracker/raft.py @@ -16,8 +16,8 @@ import threading import time import urllib.error import urllib.request -from dataclasses import dataclass, field -from typing import Any, Callable +from dataclasses import dataclass +from typing import Callable @dataclass diff --git a/packages/tracker/meshnet_tracker/routing_stats.py b/packages/tracker/meshnet_tracker/routing_stats.py index 4b24a71..1ee606e 100644 --- a/packages/tracker/meshnet_tracker/routing_stats.py +++ b/packages/tracker/meshnet_tracker/routing_stats.py @@ -26,7 +26,7 @@ import random import sqlite3 import threading import time -from dataclasses import dataclass, field +from dataclasses import dataclass from typing import Any, Iterable diff --git a/packages/tracker/meshnet_tracker/server.py b/packages/tracker/meshnet_tracker/server.py index 117de71..737e249 100644 --- a/packages/tracker/meshnet_tracker/server.py +++ b/packages/tracker/meshnet_tracker/server.py @@ -53,10 +53,6 @@ from typing import Any from .accounts import DEFAULT_ACCOUNTS_DB_PATH, AccountStore from .auth import is_validator_token, sign_hive_request, verify_hive_request from .capability import ( - DEFAULT_POLICY as DEFAULT_CAPABILITY_POLICY, - POLICY_COMPAT, - POLICY_ENFORCE, - STATE_ABSENT, STATE_ADMITTED, STATE_MODEL_MISMATCH, STATE_SHARD_MISMATCH, @@ -69,7 +65,7 @@ from .capability import ( ) from .wallet_proof import binding_message, verify_wallet_signature from .billing import DEFAULT_BILLING_DB_PATH, BillingLedger -from .calibration import DEFAULT_CALIBRATION_DB_PATH, ToplocCalibrationStore +from .calibration import ToplocCalibrationStore from .hf_pricing import DEFAULT_HF_PRICING_LOG_DB_PATH, HfPricingLog, refresh_preset_price from .gossip import NodeGossip from .logging_setup import tracker_logger @@ -2566,8 +2562,8 @@ def _estimate_prompt_tokens(body: dict) -> int | None: def _requested_completion_token_limit(body: dict) -> int | None: - for field in ("max_completion_tokens", "max_tokens"): - value = body.get(field) + for key in ("max_completion_tokens", "max_tokens"): + value = body.get(key) if isinstance(value, bool): return None if isinstance(value, (int, float)): @@ -2948,7 +2944,7 @@ class _TrackerHTTPServer(socketserver.ThreadingMixIn, http.server.HTTPServer): class _TrackerHandler(http.server.BaseHTTPRequestHandler): - def log_message(self, fmt, *args): # noqa: suppress request logs in tests + def log_message(self, fmt, *args): # suppress request logs in tests pass def _send_json(self, status: int, data: dict, headers: dict[str, str] | None = None) -> None: @@ -7069,10 +7065,6 @@ class TrackerServer: shard_end = int(payload["shard_end"]) if payload.get("shard_end") is not None else None except (TypeError, ValueError): return - try: - friendly_name = _normalize_friendly_name(payload.get("friendly_name")) - except ValueError: - friendly_name = None # The replicated payload is the raw registration body, so the follower can # resolve precision exactly as the leader did -- including telling a legacy # absent `quantization` from a declared one. Dropping these fields here diff --git a/packages/validator/meshnet_validator/__init__.py b/packages/validator/meshnet_validator/__init__.py index b55b104..a87dae3 100644 --- a/packages/validator/meshnet_validator/__init__.py +++ b/packages/validator/meshnet_validator/__init__.py @@ -545,6 +545,8 @@ def _post_json(url: str, payload: dict, timeout: float = 5.0) -> dict: __all__ = [ "ToplocAuditConfig", "ToplocProofClaim", + "ToplocVerificationResult", + "verify_activation_proofs_detailed", "ValidatorProcess", "AdaptiveAuditSampler", "AuditRateConfig", diff --git a/pyproject.toml b/pyproject.toml index 2bf488a..b0fbbcb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -14,6 +14,11 @@ dev = ["pytest>=8", "openai>=1", "langchain-openai>=0.1", "cryptography>=41"] [tool.setuptools] packages = [] +[tool.ruff] +# Protobuf/gRPC stubs are regenerated by scripts/generate_native_protocol.py; +# linting them would drift the checked-in files from the generator's output. +extend-exclude = ["packages/node/meshnet_node/native_protocol/generated"] + [tool.pytest.ini_options] testpaths = ["tests"] markers = [ diff --git a/tests/test_gossip_and_relay.py b/tests/test_gossip_and_relay.py index 38ab46c..1ea501a 100644 --- a/tests/test_gossip_and_relay.py +++ b/tests/test_gossip_and_relay.py @@ -5,8 +5,7 @@ from __future__ import annotations import json import threading import time -from pathlib import Path -from unittest.mock import MagicMock, patch +from unittest.mock import MagicMock # --------------------------------------------------------------------------- @@ -277,7 +276,6 @@ def test_relay_server_peer_list_grows_on_connect(): def test_relay_circuit_relay_proxies_message(): "A node behind NAT (client_a) receives a message via circuit relay from client_b.\n\nTags: gossip, network, relay" - import websockets.sync.client # type: ignore[import] from meshnet_relay.server import RelayServer relay = RelayServer(host="127.0.0.1", port=0) @@ -755,7 +753,6 @@ def test_node_relay_bridge_reconnects_after_failed_connection(monkeypatch): def _start_tracker_and_register(extra_fields: dict) -> dict: """Helper: start tracker, register node with extra gossip fields, return response.""" - import http.server import json as _json import urllib.request @@ -766,7 +763,7 @@ def _start_tracker_and_register(extra_fields: dict) -> dict: url = f"http://127.0.0.1:{port}" payload = { - "endpoint": f"http://127.0.0.1:8001", + "endpoint": "http://127.0.0.1:8001", "shard_start": 0, "shard_end": 7, "model": "stub-model", diff --git a/tests/test_mining_cli.py b/tests/test_mining_cli.py index 22b9b61..85cfd05 100644 --- a/tests/test_mining_cli.py +++ b/tests/test_mining_cli.py @@ -5,8 +5,6 @@ from __future__ import annotations import json import socket import sys -import types -from pathlib import Path from unittest.mock import MagicMock, patch # A fake node server has no real backend to prove capability with; say so @@ -134,7 +132,6 @@ def test_print_models_table_runs_without_error(capsys, monkeypatch): def test_wizard_writes_config_on_happy_path(tmp_path, monkeypatch): "Wizard writes config on happy path\n\nTags: general" from meshnet_node import wizard as wiz - from meshnet_node.config import load_config, save_config # Fake GPU gpus = [{"index": 0, "name": "RTX 4090", "vram_gb": 24.0, "backend": "cuda"}] @@ -265,7 +262,6 @@ def test_config_command_no_config_exits_1(tmp_path, monkeypatch): def test_config_command_prints_saved_config(tmp_path, monkeypatch, capsys): "Config command prints saved config\n\nTags: general" - from meshnet_node import config as cfg_mod from meshnet_node.config import save_config from meshnet_node.cli import main @@ -309,7 +305,6 @@ def test_detect_num_layers_returns_none_on_error(monkeypatch): def test_startup_auto_detects_shard_range(monkeypatch, tmp_path): "When shard_start/end are None, startup reads layer count from catalog.\n\nTags: general" from meshnet_node import startup as su - from meshnet_node.model_catalog import detect_num_layers calls = [] diff --git a/tests/test_openai_gateway.py b/tests/test_openai_gateway.py index e6e15c2..7389122 100644 --- a/tests/test_openai_gateway.py +++ b/tests/test_openai_gateway.py @@ -162,7 +162,7 @@ def test_streaming_end_to_end_http(two_node_setup): assert "text/event-stream" in content_type raw = resp.read().decode() - data_lines = [l for l in raw.strip().splitlines() if l.startswith("data: ")] + data_lines = [line for line in raw.strip().splitlines() if line.startswith("data: ")] assert data_lines, "No SSE data lines found" assert data_lines[-1] == "data: [DONE]" diff --git a/tests/test_real_model_backend.py b/tests/test_real_model_backend.py index 6f533b3..697cf46 100644 --- a/tests/test_real_model_backend.py +++ b/tests/test_real_model_backend.py @@ -13,7 +13,6 @@ import urllib.request import pytest from meshnet_node.model_backend import ( - InsufficientVRAMError, PartialModelLoadUnsupported, KVCacheMiss, TensorPayload, diff --git a/tests/test_settlement_loop.py b/tests/test_settlement_loop.py index 443ee64..fb1e8b6 100644 --- a/tests/test_settlement_loop.py +++ b/tests/test_settlement_loop.py @@ -5,9 +5,7 @@ before the transaction is sent, unconfirmed batches resent by settlement id (never double-paying), banned wallets skipped, history queryable over HTTP. """ -import json import time -import urllib.request import pytest @@ -68,7 +66,7 @@ def test_threshold_triggers_payout_and_zeroes_pending(): ledger.charge_request("client", MODEL, 1000, [("wallet-a", 12)]) # 0.018 pending treasury = _FakePayoutTreasury() tracker = _make_tracker(ledger, treasury, threshold=0.01) - port = tracker.start() + tracker.start() try: assert _wait_for(lambda: treasury.batches) assert treasury.batches[0] == [("wallet-a", pytest.approx(0.018))] diff --git a/tests/test_tracker_consensus.py b/tests/test_tracker_consensus.py index c537450..0dbc5dc 100644 --- a/tests/test_tracker_consensus.py +++ b/tests/test_tracker_consensus.py @@ -157,7 +157,7 @@ def test_registration_on_follower_visible_on_all_nodes(three_tracker_cluster): _wait_until_follower_knows_leader(follower, timeout=2.0) # Register via a follower - node_id = _register_node(follower, port_hint=19999) + _register_node(follower, port_hint=19999) # Allow replication to propagate (Raft heartbeat interval is 50ms) time.sleep(0.5) @@ -223,7 +223,7 @@ def test_registration_on_leader_visible_to_all(three_tracker_cluster): urls = list(urls) leader_url, followers = _wait_for_leader(urls, timeout=1.0) - node_id = _register_node(leader_url, port_hint=19996) + _register_node(leader_url, port_hint=19996) # Allow Raft heartbeat to replicate the entry time.sleep(0.3) diff --git a/tests/test_tracker_routing.py b/tests/test_tracker_routing.py index 853ef6e..42754a1 100644 --- a/tests/test_tracker_routing.py +++ b/tests/test_tracker_routing.py @@ -19,7 +19,6 @@ from meshnet_tracker.server import ( TrackerServer, _NodeEntry, _available_quantizations, - _memory_pool_map, _rebalance_all_locked, _registration_ban_error, _scale_demanded_models_locked, @@ -1448,7 +1447,7 @@ def test_tracker_pool_join_adds_redundant_copy_without_splitting_incumbent(): "vram_bytes": 10_000, "ram_bytes": 10_000, "quantizations": ["bfloat16"], "benchmark_tokens_per_sec": 1.0, "hardware_profile": {}, "score": 1.0}, ) - second = _post_json( + _post_json( f"http://127.0.0.1:{tracker_port}/v1/nodes/register", {"endpoint": "http://127.0.0.1:9016", "model": "tiny-model", "vram_bytes": 10_000, "ram_bytes": 10_000, "quantizations": ["bfloat16"],