52 Commits

Author SHA1 Message Date
Dobromir Popov
c38e36f685 Retry tracker registration when initial connect fails.
Start background re-registration when the tracker is unreachable at startup so nodes do not stay permanently unregistered.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-07 17:59:27 +02:00
Dobromir Popov
50e8904f1c ignore 2026-07-07 17:57:33 +02:00
Dobromir Popov
7e289fef2e Fix meshnet-node model and shard flag parsing.
Unify --model and --model-id so catalog names use the tracker path, and allow --shard-start/--shard-end with --model instead of requiring --model-id.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-07 17:54:30 +02:00
Dobromir Popov
e9a094b620 ram pool map 2026-07-07 18:35:36 +03:00
Dobromir Popov
1299a6bb1c balancing improvements 2026-07-07 18:30:30 +03:00
Dobromir Popov
f220fd2210 tracker rebalancing tweaks 2026-07-07 18:24:09 +03:00
Dobromir Popov
fdeb881c83 web UI 2026-07-07 17:54:22 +03:00
Dobromir Popov
08e9c22ccf Merge origin/master: streaming progress, dashboard call wall, and heartbeat scaffolding.
Resolve conflicts in dashboard.html (Call wall + live TPS/queue from remote) and server.py (proxy progress logging, request id forwarding, current_requests on node entries).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-07 17:44:18 +03:00
Dobromir Popov
e81d989f39 dash QOL 2026-07-07 17:37:38 +03:00
Dobromir Popov
3eb7c6b93e fixing streaming 2026-07-07 16:06:05 +02:00
Dobromir Popov
6fa69aecaa show all requests not just histroy 2026-07-07 15:51:58 +02:00
Dobromir Popov
640ef78711 better dash and inference api QOL 2026-07-07 15:51:27 +02:00
Dobromir Popov
938a0a721b grouping 2026-07-07 15:26:12 +02:00
Dobromir Popov
2a0d414593 dash - better model health 2026-07-07 15:05:35 +02:00
Dobromir Popov
2469023083 Merge branch 'master' of https://git.d-popov.com/popov/neuron-tai 2026-07-07 15:01:21 +02:00
Dobromir Popov
f7fbe166e6 notes 2026-07-07 15:01:17 +02:00
Dobromir Popov
08bffbe9b4 Merge branch 'master' of https://git.d-popov.com/popov/neuron-tai 2026-07-07 15:56:44 +03:00
Dobromir Popov
eac852a515 tasks 2026-07-07 15:56:38 +03:00
Dobromir Popov
5cdce1a5b0 Merge branch 'master' of https://git.d-popov.com/popov/neuron-tai 2026-07-07 14:56:08 +02:00
Dobromir Popov
80bd83ae0a routing and dashboard fixes 2026-07-07 14:53:37 +02:00
Dobromir Popov
ca49675f50 Merge branch 'master' of https://git.d-popov.com/popov/neuron-tai 2026-07-07 15:27:34 +03:00
Dobromir Popov
5e89bba78f feature-gguf-distributed 2026-07-07 15:27:33 +03:00
Dobromir Popov
339577a26c fix model registration and anouncement. added console panel 2026-07-07 14:24:37 +02:00
Dobromir Popov
0e8acf5d59 DL tracker fixed!!!! now make it nice! 2026-07-06 23:57:59 +03:00
Dobromir Popov
d83224a62f N-th fix od model DL 2026-07-06 23:41:06 +03:00
Dobromir Popov
4bfdc814e2 5-th DL fix 2026-07-06 22:55:01 +03:00
Dobromir Popov
7e7682be47 fix model DL doe 4-th time 2026-07-06 22:38:57 +03:00
Dobromir Popov
4f007aeef9 DL fix again 2026-07-06 19:27:37 +03:00
Dobromir Popov
b615acf582 env 2026-07-06 18:47:21 +03:00
Dobromir Popov
7911223980 log dl location 2026-07-06 18:44:50 +03:00
Dobromir Popov
d151dd5484 tracker download fix 2026-07-06 18:36:42 +03:00
Dobromir Popov
2e696be80f dual billing; tracker to node model sharing 2026-07-06 17:31:11 +03:00
Dobromir Popov
ccb69c41e3 new tasks, model pricing, auto quantisation, etc... 2026-07-06 17:11:53 +03:00
Dobromir Popov
7f67e29d76 Merge branch 'master' of https://git.d-popov.com/popov/neuron-tai 2026-07-06 15:51:55 +03:00
Dobromir Popov
ee2711a38a new model support 2026-07-06 15:51:51 +03:00
Dobromir Popov
4856749286 Merge branch 'master' of https://git.d-popov.com/popov/neuron-tai
# Conflicts:
#	packages/contracts/meshnet_contracts/__init__.py
2026-07-06 14:49:53 +02:00
Dobromir Popov
0d65ef3ea6 registry event log 2026-07-06 14:10:13 +02:00
Dobromir Popov
cdc9f11128 node configs 2026-07-06 14:45:08 +03:00
Dobromir Popov
b547034741 new tasks, devnet topup, cli, new model support 2026-07-06 14:17:36 +03:00
Dobromir Popov
f841dfaeed feat(tracker): add alpha calibration and dynamic pricing
Add TOPLOC honest-noise calibration storage/dispatch and validator divergence reporting for AH-021.

Add opt-in HuggingFace marketplace pricing refresh, price-change history, CLI flags, and AH-023 tracking docs.

Verification: .venv/bin/python -m pytest tests/ -q -k 'not integration' => 346 passed, 2 skipped, 1 deselected; compileall packages tests passed; focused AH-021/AH-023 tests 32 passed.
2026-07-06 09:48:27 +03:00
Dobromir Popov
32514e84c9 memory 2026-07-06 06:01:57 +03:00
Dobromir Popov
af56dec7bd fix(validator): connect audit commitments to request flow
Record completed tracker requests into the validation log with ordinary route metadata, then have the validator fetch missing hop TOPLOC commitments on demand only after sampling. This closes the remaining alpha review gap where bisection worked only for synthetic events.

Verification: .venv/bin/python -m compileall -q packages tests; pytest tests/test_hop_bisection.py tests/test_billing_ledger.py tests/test_toploc_audit.py -q (31 passed); full pytest: 316 passed, 3 skipped, 1 env failure from meshnet-node pid 1263451 occupying port 7000.
2026-07-05 22:16:31 +03:00
Dobromir Popov
de6ce1d514 fix(tracker): close alpha accounting review gaps
Address post-review blockers from the alpha hardening diff: charge non-stream completions that omit usage, include prompt tokens in max_charge_per_request enforcement, and wire the CLI to a persisted local registry contract by default.

Verification: .venv/bin/python -m compileall -q packages tests; focused billing/CLI checks passed; full pytest: 314 passed, 3 skipped, 1 env failure from existing meshnet-node on port 7000.
2026-07-05 21:55:07 +03:00
Dobromir Popov
9abe83b5f4 feat(alpha): complete hardening backlog
Complete the alpha-hardening Ralph task set, including tracker billing/accounting guards, validator fraud-audit primitives, wallet binding proof support, documentation runbooks, and updated tests.

Verification: .venv/bin/python -m compileall -q packages tests; .venv/bin/python -m pytest -q --tb=short (313 passed, 3 skipped, 1 failed: tests/test_mining_cli.py::test_legacy_start_without_port_uses_next_available_port because meshnet-node pid 1263451 is already listening on port 7000).
2026-07-05 21:47:23 +03:00
Dobromir Popov
c967e5cfc4 test 2026-07-05 00:33:02 +02:00
Dobromir Popov
05c9e099e9 docs(memory): record auth boundary done, next-session order for alpha Bucket 1
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-05 00:17:00 +02:00
Dobromir Popov
81719ed84b feat(tracker): unified auth boundary — gossip HMAC + validator token + admin-gated reads (alpha 01/02/20, ADR-0017)
Wire server.py handlers to the auth helper: forfeit requires validator
service token or admin session (client API keys rejected); billing summary/
settlements/registry-wallets and benchmark endpoints require admin/service;
the three gossip mutation endpoints require a fresh hive HMAC signature and
outgoing gossip pushes are signed. Dashboard sends its session token on
panel fetches. Existing tests updated for the new gates.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-05 00:08:25 +02:00
Dobromir Popov
7414ce1e29 Merge branch 'master' of https://git.d-popov.com/popov/neuron-tai 2026-07-04 23:03:05 +02:00
Dobromir Popov
9bd15de65b validator edits 2026-07-04 23:03:03 +02:00
Dobromir Popov
69b0e726b8 tasks 2026-07-04 23:02:54 +02:00
Dobromir Popov
c702a77c07 Merge branch 'master' of https://git.d-popov.com/popov/neuron-tai 2026-07-04 23:58:23 +03:00
Dobromir Popov
83e44d8312 billing 2026-07-04 23:58:07 +03:00
128 changed files with 20974 additions and 5400 deletions

BIN
.billing.sqlite Normal file

Binary file not shown.

View File

@@ -4,3 +4,4 @@
- [User profile](user-profile.md) — who Dobromir is and how to work with him - [User profile](user-profile.md) — who Dobromir is and how to work with him
- [Project status](project-status.md) — 35/35 stories done; alpha hardening next - [Project status](project-status.md) — 35/35 stories done; alpha hardening next
- **Alpha hardening** — `.scratch/alpha-hardening/` (22 issues, ADRs 00160019, [README](../.scratch/alpha-hardening/README.md), [handoff](../.scratch/alpha-hardening/handoff.md)) - **Alpha hardening** — `.scratch/alpha-hardening/` (22 issues, ADRs 00160019, [README](../.scratch/alpha-hardening/README.md), [handoff](../.scratch/alpha-hardening/handoff.md))
- [Alpha hardening navigation](alpha-hardening-navigation.md) — locked fraud/auth decisions, Bucket-1 order, handoff pointers

View File

@@ -0,0 +1,32 @@
---
name: alpha-hardening-navigation
description: Where the alpha-hardening plan lives, locked design decisions, and implementation order
metadata:
node_type: memory
type: project
---
Active workstream (started 2026-07-04): alpha hardening of the money/trust path. Full handoff at `/mnt/c/Users/popov/Downloads/neuron-tai-alpha-handoff-2026-07-04.md` (note: its "planning artifacts missing" section is stale — ADRs 00160019 and `.scratch/alpha-hardening/issues/` were created in commit 68e0572).
**Navigation:** `.scratch/alpha-hardening/README.md` = index + phase order; `research-verifiable-inference.md` §8 = layered fraud scheme, §9 = build-vs-adopt; ADR-0018 = flagship fraud design; `docs/agents/issue-tracker.md` = issue conventions (active work in `.scratch/<slug>/`).
**Locked decisions (do not re-derive):** TOPLOC ADOPT (`pip install toploc`, teacher-forced prefill, one canonical precision per model); audit 5% default escalating on anomaly/low-rep/disputes; blame via on-demand per-hop activation commitments + bisection (fixes validator `_final_text_node` bug — it blames only the last hop); reputation = persisted graduated ×0.8-per-strike multiplier affecting routing + audit rate; full pending forfeiture stays the primary penalty; accounting becomes tracker-authoritative (count tokens from the proxied stream, work units from tracker-assigned spans — node self-reports are untrusted); strikes/bans/reputation must survive restart (RegistryWallet is RAM-only today); multi-tracker money fixes (C2/C3/C4/A3/H1) designed in ADR-0019 but implementation deferred.
**Implementation state (2026-07-05):** Alpha-scoped blocker implementation is done: auth boundary + gossip + validator service token (02/01/20), persist strike/ban/reputation (05), starting credit 0 + spend cap (03), tracker-authoritative accounting (04), wallet binding proof (11), and fraud arc (0610). `.scratch/alpha-hardening/issues/` now has 16 `done` and 6 `ready-for-human` items.
**Auth foundation now available (commit 81719ed):** `packages/tracker/meshnet_tracker/auth.py` = hive HMAC (`sign_hive_request`/`verify_hive_request`, X-Meshnet-Hive-Signature/Timestamp, 300s skew) + `is_validator_token`. In the handler: `_require_role("admin"|"validator")`, `_resolve_identity()` (validator token / admin session / client-key→no-role), `_read_hive_authenticated_body()`. `TrackerServer(validator_service_token=, hive_secret=)` also read from MESHNET_VALIDATOR_SERVICE_TOKEN / MESHNET_HIVE_SECRET; CLI `--validator-service-token` / `--hive-secret`. Outgoing gossip signed via `_push_to_peers`. Tests use these fixtures — reuse the pattern in 05/03/04.
**Remaining work classification:** 1215 are multi-tracker money/Raft ordering hardening deferred beyond single-settlement alpha; 17 needs human approval for canonical duplicate US-020 renumbering. Full pytest suite re-verified 2026-07-06: 317 passed, 3 skipped, clean.
**Launch-readiness grilling (2026-07-06):** Locked launch plan — devnet dev/test run now, then **real mainnet SOL/USDT** (not devnet, not a new public token) for the first cohort: friends (API clients) + hired VPS/VPC hosts (our own test infra, not third-party volunteers — stake-free, risk-free if something breaks, not a long-term topology). Pricing: clients are the only party spending real money; nodes only accumulate off-chain credit and get paid in batches (30min dev / 24h later) — a failed distribution leaves funds parked, not lost, so mainnet-vs-devnet mixups are lower-risk than initially assumed. TAI token: do NOT issue/list now — ADR-0002 already locks listing behind $50k volume + 25 nodes/15 wallets plus an unresolved securities-review gate; only a dormant mainnet mint (cheap, ~few $ SOL) for name/branding reservation is in scope, bundled with treasury-key work, not before it. Treasury custody: bare keypair file (current runbook 02) is not acceptable for real funds — plan is **free native SPL multisig** (`spl-token create-multisig`, no protocol fee unlike Squads' 0.5 SOL), 2-of-3 signers, at least one cold/offline, others one-per-hired-VPS-provider to avoid correlated compromise (not yet built — ops task, no issue filed). Stake/slash asymmetry (registry/slash is a local Python adapter per ADR-0007, not on-chain) accepted for now since hired hosts are our own infra and friends aren't node operators — revisit before opening to real third-party node operators. A mainnet-vs-devnet boot guardrail was proposed and explicitly declined by the owner given the safe-by-default money flow above.
**Two new issues from this session, both `ready-for-agent`:**
- **21 — Honest-noise calibration corpus** (`.scratch/alpha-hardening/issues/21-honest-noise-calibration-corpus.md`) rescoped from "prod gate" to a **hard alpha-release blocker**. Confirmed by code read: `verify_activation_proofs()` (`packages/validator/meshnet_validator/audit.py:94-127`) returns bool only, no raw divergence value; fleet-dispatch exists but wrong shape (`server.py:2998-3104`, pinned routes + latency, not full-fleet + TOPLOC divergence); storage wrong shape (`registry_events` has no divergence/hardware columns). Three-part build: (1) surface raw TOPLOC distance from audit.py, (2) extend dispatch to hit every registered node with fixed prompt/seed, (3) new SQLite table keyed by node+GPU+dtype. Small-fleet exception granted (N = actual hired-VPS fleet size). Hired VPS hosts stay stake-free until this closes.
- **23 — Dynamic HF-benchmarked pricing** (`.scratch/alpha-hardening/issues/23-dynamic-hf-pricing.md`), high priority but not a release blocker. Pricing today is 100% static (`DEFAULT_PRICE_PER_1K_TOKENS = 0.02`, `billing.py:21`; `model_presets.json` has no per-model price). Target: 80% of cheapest comparable provider on `https://huggingface.co/inference/models` (per-provider-per-model marketplace, `?search=` query param works, no confirmed JSON API — plain scrape attempted first, escalate to headless browser only if the table isn't in raw HTML). Human-verified `hf_aliases` + `hf_verified_match_note` (params/quantization) per model, not auto-discovered matching. Reuses the `_settlement_loop` daemon-thread pattern for a daily refresh; falls back silently to the static default on any failure.
Both are already migrated into `.scratch/alpha-hardening/prd.json` (AH-021 updated, AH-023 added) and the README index — ready for Ralph to pick up unattended.
**Ralph note:** `scripts/ralph_progress.py` tracks `docs/prd.json` (35/35 done) and does NOT see `.scratch/alpha-hardening/issues/`. No ralph loop is running and no `.ralph-tui/` state exists. `.scratch/alpha-hardening/prd.json` now has 23 stories (AH-001…AH-023); point Ralph at that file for the alpha-hardening branch. Do NOT use `ralph auto --parallel` on server.py-touching issues — 21 and 23 both touch `server.py`/`billing.py`/`audit.py`; if run in the same Ralph pass, run them serially, not in parallel (merge-conflict risk, same lesson as 03/04 previously).
**Why:** three audits agreed the alpha blockers are unauthenticated gossip (anyone can inject billing events), the free-credit faucet, and ephemeral bans.
**How to apply:** work test-first per issue acceptance criteria; use `.venv`; `cryptography` belongs in node deps (wallet.py imports it — causes many of the 24 "failures" in a fresh env). See [[project-status]] and [[autonomous-work-style]].

View File

@@ -23,9 +23,11 @@ Suite: 222 passed, 3 skipped (openai/langchain packages missing in .venv — pre
**Why:** design locked in ADR-0015 (USDT custodial settlement; TAI deferred, protocol cut = future TAI liquidity). **Why:** design locked in ADR-0015 (USDT custodial settlement; TAI deferred, protocol cut = future TAI liquidity).
**How to apply:** next steps are live devnet verification (run devnet_setup.py, start tracker with --solana-rpc-url/--usdt-mint/--treasury-keypair --billing-db), then the TAI mint when volume justifies it. Work not yet committed to git as of session end — check git status. **How to apply:** next steps are live devnet verification (run devnet_setup.py, start tracker with --solana-rpc-url/--usdt-mint/--treasury-keypair --billing-db), then the TAI mint when volume justifies it. Work not yet committed to git as of session end — check git status.
## Alpha hardening (2026-07-04) ## Alpha hardening (2026-07-05)
Planning complete in `.scratch/alpha-hardening/`: research report, ADRs 00160019, 22 issue files, README + handoff. **Bucket 1 trust-boundary blockers** (auth, persistence, starting credit, accounting, wallet binding) are next before fraud arc (TOPLOC, bisection, reputation routing). Prod audit thresholds gated on issue 21 (honest-noise calibration corpus). Implementation complete for alpha-scoped blockers in `.scratch/alpha-hardening/`: 16/22 issues are `done`, including auth/gossip/service-token, persisted strike/ban/reputation, zero starting credit + spend cap, tracker-authoritative accounting, wallet binding proof, TOPLOC audit primitive, hop bisection, reputation scoring/routing, adaptive audits, and penalty wiring. Remaining 6/22 are `ready-for-human` / post-alpha or ops-gated: 1215 multi-tracker money/Raft ordering hardening, 17 duplicate US-020 renumbering approval, and 21 honest-noise calibration corpus before production audit thresholds. Current verification: `uv run pytest -k 'not test_legacy_start_without_port_uses_next_available_port'` passes 316, skips 3; full `uv run pytest` has one environmental failure while local `meshnet-node` PID 1263451 occupies port 7000.
Historical handoff note: `/mnt/c/Users/popov/Downloads/neuron-tai-alpha-handoff-2026-07-04.md` is useful for navigation and original audit context, but it predates the completed `.scratch/alpha-hardening/` planning artifacts. Treat its "missing ADR/issues/README" statements as stale; prefer `.scratch/alpha-hardening/README.md` and `.scratch/alpha-hardening/handoff.md` for current task order.
## Windows CUDA node (working as of 2026-07-01) ## Windows CUDA node (working as of 2026-07-01)
- miniforge3 base env, torch 2.7.1+cu118, torchvision 0.22.x+cu118 - miniforge3 base env, torch 2.7.1+cu118, torchvision 0.22.x+cu118
@@ -33,3 +35,14 @@ Planning complete in `.scratch/alpha-hardening/`: research report, ADRs 00160
- Run: `meshnet-node start --tracker https://ai.neuron.d-popov.com --model Qwen/Qwen2.5-0.5B-Instruct` - Run: `meshnet-node start --tracker https://ai.neuron.d-popov.com --model Qwen/Qwen2.5-0.5B-Instruct`
- Known: tracker registration fails with `http://` — must use `https://` - Known: tracker registration fails with `http://` — must use `https://`
- pynvml deprecation warning is harmless (use nvidia-ml-py to silence it) - pynvml deprecation warning is harmless (use nvidia-ml-py to silence it)
## Model cache layout (2026-07-07)
- Node downloads now cache files directly under `<download_dir>/<model>/`, not `<model>/layers_<start>-<end>/`, so a wider cached layer assignment can satisfy a later narrower assignment without duplicate shard folders.
- Downloader checks tracker-advertised `files` + `file_sizes` before peer/HF download; complete local files return immediately and preserve any extra files already in the model folder.
- Verification: downloader/startup targeted subset passes (`pytest tests/test_node_startup.py -k "download_shard or same_shard"`). Full `tests/test_node_startup.py` has 46 passed and 4 unrelated Windows chmod/path separator failures.
- Live Windows confirmation: `meshnet-node start --tracker http://192.168.0.179:8080 --model Qwen3.6-35B-A3B` reuses `F:\_STORAGE\models\qwen3.6-35b-a3b`, prints `Cached at`, registers, and reaches ready as node `5gMLrmyB-26b1f8a4204a`.
- Follow-up fix: preset-model startup now starts the heartbeat thread after registration; without this, the node appeared briefly on the dashboard and was purged on first inference/route after heartbeat expiry. Tracker dashboard now has a "Console output" panel backed by `/v1/console` for node register/expiry, routing failures, and proxy events.
- Qwen3.6-35B-A3B reserve-based split is expected: an 79 GB CPU node may be assigned layers 0-36, and a second node fills 37-39. Do not "fix" this by bypassing the 20% assignment reserve unless the shard-planning policy changes.
- Route hardening: tracker chat proxy and `/v1/route` diagnostics now use alias-aware preset node matching for split Qwen3.6 routes; dashboard derives grouped inference history from proxy route/complete console events and shows observed TPS after completion.
- Live proxy hardening: model lookup trims outer whitespace before alias matching (`qwen3.6-35b-a3b ` resolves), and tracker route logs/dashboard queue depth combine heartbeat queue with tracker-local proxy in-flight counts so Postman-style bursts no longer show every selected route as queue `0`.
- Split-shard streaming hardening: Qwen3.6-style distributed generation now emits SSE chunks token-by-token from the head node instead of buffering all generated text until completion. Tracker direct/relay stream proxy logs `proxy progress` with live tokens/TPS, dashboard Inference history shows currently processing requests with live TPS/tokens/queue, and relay stream completion no longer references an undefined `session_id`.

View File

@@ -5,3 +5,9 @@ MESHNET_CONTRACT_ADAPTER=solana-testnet
MESHNET_REGISTRY_PROGRAM_ID= MESHNET_REGISTRY_PROGRAM_ID=
MESHNET_PAYMENT_PROGRAM_ID= MESHNET_PAYMENT_PROGRAM_ID=
MESHNET_SETTLEMENT_PROGRAM_ID= MESHNET_SETTLEMENT_PROGRAM_ID=
# MESHNET_DOWNLOAD_DIR=
# HF_TOKEN=
# URL_TRACKER=
# DEFAULT_MODEL=

9
.gitignore vendored
View File

@@ -11,3 +11,12 @@ dist/
# Ralph local runtime state # Ralph local runtime state
.ralph-tui/ .ralph-tui/
.env
.env.*
!.env.example
!.env.testnet
.rocm-local/*
billing.sqlite
.pytest-tmp/*

View File

@@ -1,6 +1,11 @@
# Alpha hardening — planning index # Alpha hardening — planning index
Pre-release alpha audit + grilling (2026-07-04). **Research complete; planning complete; Bucket 1 blockers next.** Pre-release alpha audit + grilling (2026-07-04). Bucket 1 trust-boundary blockers + fraud arc: **done** (16/22 original issues). Bucket 2 (12-15, multi-tracker) and 17 (doc dedup) remain deferred/human-gated — not launch blockers.
**Launch-readiness grilling (2026-07-06):** locked plan is devnet dev/test run now, then real mainnet SOL/USDT for the first cohort — friends (API clients) + hired VPS/VPC hosts (own test infra, not third-party volunteers, stake-free). No new public token; TAI stays dormant per ADR-0002's existing volume/legal gates. Two new issues came out of this session:
- **[21 — Honest-noise calibration corpus](./issues/21-honest-noise-calibration-corpus.md)** — rescoped from "prod gate" to a hard **alpha-release blocker**. `Status: ready-for-human` — engineering (audit.py raw divergence, tracker dispatch endpoint, SQLite corpus, p99 envelope) done 2026-07-06; blocked on a human running the calibration job against the real hired-VPS fleet before launch.
- **[23 — Dynamic HF-benchmarked pricing](./issues/23-dynamic-hf-pricing.md)** — new, high priority but not a release blocker. `Status: done` — engineering complete 2026-07-06 (hf_pricing.py, opt-in daily refresh loop, GET /v1/pricing/hf/history); real `hf_aliases` curation per model is a follow-up human sign-off, not a completion blocker.
Locked scope: one settlement tracker, open node join, devnet mock-USDT, reputation carries forward → fraud must be bounded. See [ADR-0016](../../docs/adr/0016-alpha-scope-and-known-limitations.md). Locked scope: one settlement tracker, open node join, devnet mock-USDT, reputation carries forward → fraud must be bounded. See [ADR-0016](../../docs/adr/0016-alpha-scope-and-known-limitations.md).
@@ -26,17 +31,18 @@ Locked scope: one settlement tracker, open node join, devnet mock-USDT, reputati
## Recommended implementation order ## Recommended implementation order
**Implement Bucket 1 first.** Fraud arc depends on **auth (0102, 20)** and **persistence (05)**. **Implement Bucket 1 first.** Fraud arc depends on **auth foundation (02 + 20)**, **hive gossip enforcement (01)**, and **persistence (05)**.
### Phase 1 — Trust boundary (alpha blockers) ### Phase 1 — Trust boundary (alpha blockers)
| Order | Issue | ID | Depends on | | Order | Issue | ID | Depends on |
|---|---|---|---| |---|---|---|---|
| 1 | [Unified auth + gossip auth](./issues/02-a2-unified-auth-boundary.md) + [C1 gossip](./issues/01-c1-gossip-auth.md) + [Validator service token](./issues/20-validator-service-token.md) | A2, C1, — | — | | 1 | [Unified auth boundary](./issues/02-a2-unified-auth-boundary.md) + [Validator service token](./issues/20-validator-service-token.md) | A2, — | — |
| 2 | [Persist strike/ban/reputation](./issues/05-a1-a5-persist-strike-ban-reputation.md) | A1/A5 | 02 | | 2 | [C1 hive gossip auth enforcement](./issues/01-c1-gossip-auth.md) | C1 | 02 |
| 3 | [Starting credit 0 + spend cap](./issues/03-c5-starting-credit-zero.md) | C5, M1 | 02 | | 3 | [Persist strike/ban/reputation](./issues/05-a1-a5-persist-strike-ban-reputation.md) | A1/A5 | 02 |
| 4 | [Tracker-authoritative accounting](./issues/04-h2-tracker-authoritative-accounting.md) | H2 | 02 | | 4 | [Starting credit 0 + spend cap](./issues/03-c5-starting-credit-zero.md) | C5, M1 | 02 |
| 5 | [Wallet binding proof](./issues/11-c6-wallet-binding-proof.md) | C6 | 02, 03 | | 5 | [Tracker-authoritative accounting](./issues/04-h2-tracker-authoritative-accounting.md) | H2 | 02 |
| 6 | [Wallet binding proof](./issues/11-c6-wallet-binding-proof.md) | C6 | 02, 03 |
### Phase 2 — Fraud arc (after Phase 1) ### Phase 2 — Fraud arc (after Phase 1)
@@ -67,14 +73,14 @@ Locked scope: one settlement tracker, open node join, devnet mock-USDT, reputati
| [17 Duplicate US-020 dedup](./issues/17-doc-duplicate-us020-dedup.md) | | [17 Duplicate US-020 dedup](./issues/17-doc-duplicate-us020-dedup.md) |
| [18 Operational runbooks](./issues/18-doc-operational-runbooks.md) | | [18 Operational runbooks](./issues/18-doc-operational-runbooks.md) |
| [19 Cryptography + test env](./issues/19-doc-cryptography-test-env.md) | | [19 Cryptography + test env](./issues/19-doc-cryptography-test-env.md) |
| [22 MEMORY + project-status index](./issues/22-doc-memory-project-status.md) | | [22 MEMORY + project-status index](./issues/22-doc-memory-project-status.md) (done) |
| [21 Honest-noise calibration corpus](./issues/21-honest-noise-calibration-corpus.md) (ops; prod gate for audits) | | [21 Honest-noise calibration corpus](./issues/21-honest-noise-calibration-corpus.md) (ops; prod gate for audits) |
## First 3 to implement ## First 3 to implement
1. **01 + 02 + 20**Gossip auth + unified auth boundary + validator service token (unblocks financial endpoints) 1. **02 + 20**Unified auth boundary + validator service token (shared helper and roles)
2. **05**Persist strike/ban/reputation (penalties must survive restart) 2. **01**Apply hive auth to billing/accounts/stats gossip endpoints
3. **03**Starting credit 0 + funded-account gate (closes free-credit faucet) 3. **05**Persist strike/ban/reputation (penalties must survive restart)
## Research anchor ## Research anchor

View File

@@ -67,9 +67,9 @@ See `.scratch/alpha-hardening/README.md` for full table.
**First 3:** **First 3:**
1. **01 + 02 + 20**Gossip auth + unified auth boundary + validator service token 1. **02 + 20**Unified auth boundary + validator service token
2. **05**Persist strike/ban/reputation 2. **01**Apply hive auth to billing/accounts/stats gossip endpoints
3. **03**Starting credit 0 + funded-account gate 3. **05**Persist strike/ban/reputation
**Prod gate:** issue **21** (honest-noise corpus) before enabling production audit thresholds. **Prod gate:** issue **21** (honest-noise corpus) before enabling production audit thresholds.

View File

@@ -1,4 +1,4 @@
Status: ready-for-agent Status: done
# 01 — C1: Authenticate hive gossip endpoints # 01 — C1: Authenticate hive gossip endpoints
@@ -14,7 +14,7 @@ Add authenticated peer identity to all tracker gossip mutation endpoints. Today
- `packages/tracker/meshnet_tracker/billing.py``apply_events` (~301311) - `packages/tracker/meshnet_tracker/billing.py``apply_events` (~301311)
- `packages/tracker/meshnet_tracker/accounts.py``apply_events` (~220226) - `packages/tracker/meshnet_tracker/accounts.py``apply_events` (~220226)
Implement per ADR-0017 §3: shared hive HMAC (body + timestamp) or mutual TLS between configured tracker peers. Reject unauthenticated gossip with 401. Implement per ADR-0017 §3 using the auth helper/config from issue 02: shared hive HMAC (body + timestamp) or mutual TLS between configured tracker peers. Reject unauthenticated gossip with 401.
**Note:** `/v1/gossip` (node throughput fan-out, `server.py` ~1331) is **not** in scope for this issue — see ADR-0017 §3 out-of-scope note. **Note:** `/v1/gossip` (node throughput fan-out, `server.py` ~1331) is **not** in scope for this issue — see ADR-0017 §3 out-of-scope note.
@@ -22,7 +22,7 @@ Implement per ADR-0017 §3: shared hive HMAC (body + timestamp) or mutual TLS be
1. Red: unauthenticated POST to `/v1/billing/gossip` applies a credit event today — test must fail after fix. 1. Red: unauthenticated POST to `/v1/billing/gossip` applies a credit event today — test must fail after fix.
2. Red: authenticated peer with valid HMAC applies events; invalid/missing auth returns 401 and `applied: 0`. 2. Red: authenticated peer with valid HMAC applies events; invalid/missing auth returns 401 and `applied: 0`.
3. Green: implement verifier + config (`--hive-secret` or peer cert paths). 3. Green: wire the issue-02 verifier/config (`--hive-secret` or peer cert paths) into the three hive mutation endpoints.
## Acceptance criteria ## Acceptance criteria
@@ -38,4 +38,4 @@ Implement per ADR-0017 §3: shared hive HMAC (body + timestamp) or mutual TLS be
## Blocked by ## Blocked by
None — implement alongside or immediately before `02-a2-unified-auth-boundary.md`. - `02-a2-unified-auth-boundary.md` — owns shared auth middleware/config. Implement in the same PR if simpler.

View File

@@ -1,10 +1,10 @@
Status: ready-for-agent Status: done
# 02 — A2: Unified auth boundary for privileged and financial reads # 02 — A2: Unified auth boundary for privileged and financial reads
## What to build ## What to build
Replace header-presence stubs with a single auth middleware that resolves API keys, admin sessions, validator service tokens, and hive peer identity. Close leaks on financial and operator endpoints. Replace header-presence stubs with a single auth middleware that resolves API keys, admin sessions, validator service tokens, and hive peer identity. Close leaks on financial and operator endpoints. This is the auth foundation issue; issue 01 should only apply hive auth to gossip endpoints once the helper exists.
**Code refs:** **Code refs:**
@@ -16,7 +16,7 @@ Replace header-presence stubs with a single auth middleware that resolves API ke
- `packages/tracker/meshnet_tracker/server.py``_session_account` (~2468+), `_handle_admin_accounts` (~25882608) — H4 - `packages/tracker/meshnet_tracker/server.py``_session_account` (~2468+), `_handle_admin_accounts` (~25882608) — H4
- `packages/tracker/meshnet_tracker/accounts.py``session_account()`, `create_session()` only (session store; not handler wiring) - `packages/tracker/meshnet_tracker/accounts.py``session_account()`, `create_session()` only (session store; not handler wiring)
Per ADR-0017 §4: forfeit → validator or admin; benchmark → admin; billing summary/settlements/registry wallets → admin session. Forfeit validator identity: see `20-validator-service-token.md`. Per ADR-0017 §4: forfeit → validator or admin; benchmark → admin; billing summary/settlements/registry wallets → admin session. Include the validator service token shape from `20-validator-service-token.md` in the same implementation if practical.
## Test-first ## Test-first
@@ -27,6 +27,7 @@ Per ADR-0017 §4: forfeit → validator or admin; benchmark → admin; billing s
## Acceptance criteria ## Acceptance criteria
- [ ] Single `_require_auth(role=...)` (or equivalent) used by all privileged handlers - [ ] Single `_require_auth(role=...)` (or equivalent) used by all privileged handlers
- [ ] Shared auth config supports admin sessions, validator service token, and hive peer HMAC/mTLS
- [ ] Forfeit accepts only validator service token or admin session — not arbitrary Bearer strings - [ ] Forfeit accepts only validator service token or admin session — not arbitrary Bearer strings
- [ ] Financial read endpoints require admin session (alpha posture) - [ ] Financial read endpoints require admin session (alpha posture)
- [ ] Benchmark write/read require admin or service token - [ ] Benchmark write/read require admin or service token
@@ -38,8 +39,8 @@ Per ADR-0017 §4: forfeit → validator or admin; benchmark → admin; billing s
## Related ## Related
- `20-validator-service-token.md` — validator service token format, rotation, forfeit auth - `20-validator-service-token.md` checklist for validator service token format, rotation, forfeit auth
## Blocked by ## Blocked by
- `01-c1-gossip-auth.md` (shared auth config) None. This issue should land before `01-c1-gossip-auth.md`.

View File

@@ -1,4 +1,4 @@
Status: ready-for-agent Status: done
# 03 — C5 + M1: Starting credit 0, funded-account gate, spend cap # 03 — C5 + M1: Starting credit 0, funded-account gate, spend cap

View File

@@ -1,10 +1,10 @@
Status: ready-for-agent Status: done
# 04 — H2: Tracker-authoritative token and work-unit accounting # 04 — H2: Tracker-authoritative token and work-unit accounting
## What to build ## What to build
Stop trusting node-reported usage for billing. The tracker already proxies responses — count tokens from the proxied stream/body and compute work units from the **route it constructed**, not node declarations. Stop trusting node-reported usage for billing. The tracker already proxies responses — use tracker-observed response data and request limits to cap billable tokens, and compute work units from the **route it constructed**, not node declarations.
**Code refs:** **Code refs:**
@@ -17,13 +17,14 @@ Accounting fraud = inflating tokens or shard span. Per ADR-0018 §5.
## Test-first ## Test-first
1. Red: mock upstream returns inflated `usage.total_tokens` in body but tracker bills that value — test expects tracker-measured count. 1. Red: mock upstream returns inflated `usage.total_tokens` in body but tracker bills that value — test expects the tracker to cap billable tokens from observed stream chunks or request bounds.
2. Red: node registers false `shard_end`; billing uses tracker route span, not registration field alone. 2. Red: node registers false `shard_end`; billing uses tracker route span, not registration field alone.
3. Green: authoritative counters; ignore node-reported work units on charge path. 3. Green: authoritative counters; ignore node-reported work units on charge path.
## Acceptance criteria ## Acceptance criteria
- [ ] Token count for billing derived from tracker-parsed proxy response — **prefer tracker-measured stream chunk count**; when upstream `usage.total_tokens` is present, use the **minimum** of tracker count and node-reported value (cap inflated node usage) - [ ] Streaming token count uses tracker-observed chunks/tokens; upstream `usage.total_tokens` can only lower or match that observed count, never inflate it
- [ ] Non-streaming token count caps upstream `usage.total_tokens` by tracker-known request bounds (`max_tokens`, and prompt estimate if available); exact tokenizer-backed counts are deferred unless already available locally
- [ ] Work units = tracker-computed layer span per hop at route build time (~17811782) - [ ] Work units = tracker-computed layer span per hop at route build time (~17811782)
- [ ] Nodes cannot increase payout by lying about shard range mid-request - [ ] Nodes cannot increase payout by lying about shard range mid-request
- [ ] Integration test: malicious node metadata does not inflate `charge_request` shares - [ ] Integration test: malicious node metadata does not inflate `charge_request` shares

View File

@@ -1,4 +1,4 @@
Status: ready-for-agent Status: done
# 05 — A1/A5: Persist strike, ban, and reputation state # 05 — A1/A5: Persist strike, ban, and reputation state

View File

@@ -1,4 +1,4 @@
Status: ready-for-agent Status: done
# 06 — FRAUD: TOPLOC integration (teacher-forced audit primitive) # 06 — FRAUD: TOPLOC integration (teacher-forced audit primitive)
@@ -6,12 +6,12 @@ Status: ready-for-agent
Adopt [TOPLOC](https://github.com/PrimeIntellect-ai/toploc) (MIT, `pip install toploc`) for activation fingerprint commit and verify. Replace string-equality validator checks with teacher-forced prefill + TOPLOC tolerance matching. Adopt [TOPLOC](https://github.com/PrimeIntellect-ai/toploc) (MIT, `pip install toploc`) for activation fingerprint commit and verify. Replace string-equality validator checks with teacher-forced prefill + TOPLOC tolerance matching.
**Estimated effort:** 2+ sessions — split into subtasks below without separate issue files. **Estimated effort:** 2+ sessions. First landing should be the validator-only TOPLOC primitive and docs; node runtime commitments/on-demand capture can follow in issue 07 if this grows.
| Subtask | Owner package | Deliverable | | Subtask | Owner package | Deliverable |
|---|---|---| |---|---|---|
| Validator audit primitive | `packages/validator/` | Teacher-forced prefill, TOPLOC verify, unit tests with stub tensors | | Validator audit primitive | `packages/validator/` | Teacher-forced prefill, TOPLOC verify, unit tests with stub tensors |
| Node runtime commitments | `packages/node/` (if prover-side) | On-demand activation fingerprint generation on audit-selected requests | | Node runtime commitments | `packages/node/` (if prover-side) | On-demand activation fingerprint generation on audit-selected requests; move to issue 07 if it blocks the validator primitive |
**Code refs:** **Code refs:**
@@ -29,11 +29,11 @@ Pin one canonical precision/quantization per model preset. Add `toploc` to valid
## Acceptance criteria ## Acceptance criteria
- [ ] `toploc` dependency declared; `build_proofs_*` / `verify_proofs_*` wired - [x] `toploc` dependency declared; `build_proofs_*` / `verify_proofs_*` wired
- [ ] Validator re-runs claimed token sequence as prefill, not free generation - [x] Validator re-runs claimed token sequence as prefill, not free generation
- [ ] Model preset documents canonical dtype/quantization - [x] Model preset documents canonical dtype/quantization
- [ ] README updated: 19× deterrence at 5% audit (research §1.1) - [x] README updated: 19× deterrence at 5% audit (research §1.1)
- [ ] Tests with deterministic stub tensors (no GPU required in CI) - [x] Tests with deterministic stub tensors (no GPU required in CI)
## ADR links ## ADR links

View File

@@ -1,4 +1,4 @@
Status: ready-for-agent Status: done
# 07 — FRAUD: On-demand commitment + hop bisection blame # 07 — FRAUD: On-demand commitment + hop bisection blame
@@ -20,11 +20,11 @@ On audit selection, require nodes to supply TOPLOC-style fingerprints of **outpu
## Acceptance criteria ## Acceptance criteria
- [ ] Audit requests carry tracker RNG/VRF flag indistinguishable from normal traffic (research §6) - [x] Audit requests carry tracker RNG/VRF flag indistinguishable from normal traffic (research §6) — the existing post-hoc `sample_rate` RNG gate in `ValidatorProcess.validate_once` already decides audit selection after the original proxied request completed, so the request the client/nodes saw is unaffected either way; locked in by `test_hop_commitments_are_not_requested_unless_the_event_is_audit_selected`
- [ ] Nodes retain recent boundary activations for on-demand commit window (configurable TTL) - [x] Nodes retain recent boundary activations for on-demand commit window (configurable TTL)`ToplocAuditConfig.commitment_ttl_seconds`; expired commitments fall back to the text-only path (`test_expired_commitment_window_falls_back_to_text_only_audit`)
- [ ] Validator/tracker compares fingerprints at each hop cut-point; first mismatch = culprit - [x] Validator/tracker compares fingerprints at each hop cut-point; first mismatch = culprit`_hop_commitments_from_event` + `_first_divergent_hop` in `packages/validator/meshnet_validator/__init__.py`
- [ ] `_final_text_node` removed or limited to text-only fallback - [x] `_final_text_node` removed or limited to text-only fallback — only called from the plain-text divergence branch of `_validate_event` now
- [ ] Integration test: multi-hop pipeline, fault injected at known hop - [x] Integration test: multi-hop pipeline, fault injected at known hop`tests/test_hop_bisection.py`
## ADR links ## ADR links

View File

@@ -1,4 +1,4 @@
Status: ready-for-agent Status: done
# 08 — FRAUD: Reputation model + persistence # 08 — FRAUD: Reputation model + persistence
@@ -17,13 +17,13 @@ Implement graduated reputation per ADR-0018 §6: score derives only from tracker
## Test-first ## Test-first
1. Red: no reputation field — add schema + default 1.0 for new wallets. 1. Red: persisted reputation/strike fields from issue 05 are ignored by scoring/routing today.
2. Green: clean audit +0.05 (tunable); failed audit 0.3 and strike; three strikes → ban persisted. 2. Green: clean audit +0.05 (tunable); failed audit 0.3 and strike; three strikes → ban persisted via issue-05 fields.
3. Inactivity decay after N days without completed jobs. 3. Inactivity decay after N days without completed jobs.
## Acceptance criteria ## Acceptance criteria
- [ ] `reputation_score` persisted in registry SQLite (issue 05) - [ ] Uses `reputation_score` and strike/ban fields persisted by issue 05; does not introduce a second schema path
- [ ] Audit pass/fail updates score with documented deltas - [ ] Audit pass/fail updates score with documented deltas
- [ ] Strike applies ×0.8 multiplier to routing weight (separate from forfeiture amount) - [ ] Strike applies ×0.8 multiplier to routing weight (separate from forfeiture amount)
- [ ] Ban at 3 strikes; probation job count still enforced - [ ] Ban at 3 strikes; probation job count still enforced

View File

@@ -1,4 +1,4 @@
Status: ready-for-agent Status: done
# 09 — FRAUD: Reputation-weighted routing + adaptive audit rate # 09 — FRAUD: Reputation-weighted routing + adaptive audit rate

View File

@@ -1,4 +1,4 @@
Status: ready-for-agent Status: done
# 10 — FRAUD: Penalty calibration wiring (forfeit + strike + ban) # 10 — FRAUD: Penalty calibration wiring (forfeit + strike + ban)
@@ -23,11 +23,11 @@ Per ADR-0018: **full pending forfeiture** is primary penalty; ×0.8 is routing d
## Acceptance criteria ## Acceptance criteria
- [ ] Audit failure triggers forfeiture + strike in one tracker transaction - [x] Audit failure triggers forfeiture + strike in one tracker transaction`ValidatorProcess._slash_node` (in-process) and the tracker's `_handle_billing_forfeit` handler (remote) both forfeit-then-strike synchronously in a single call path; each already existed pre-AH-010 and is exercised by `tests/test_forfeiture_penalty.py`
- [ ] Banned nodes excluded from `payables` / settlement - [x] Banned nodes excluded from `payables` / settlement`BillingLedger.settle_node_payout` now clamps to the wallet's *current* pending balance under the same lock as the debit, and `_settlement_loop` rechecks ban status and uses the post-clamp amount before sending, so a forfeiture landing between the `payables()` snapshot and the actual payout can never be paid out on top of (ADR-0015 race); covered by `test_60_request_stream_bans_intermittent_first_hop_cheater_not_last_hop`
- [ ] Validator uses authenticated forfeit endpoint (issue 02) - [x] Validator uses authenticated forfeit endpoint (issue 02)`POST /v1/billing/forfeit` is validator-token/admin-gated (ADR-0017 §4, issue 20) and is the documented remote path (`packages/validator/README.md` Usage section); `test_forfeit_endpoint_requires_auth_and_forfeits` exercises the 401→200 flow. No standalone remote-validator process exists in this codebase yet (`contracts` has no networked implementation), so the in-process `ValidatorProcess` continues to call `BillingLedger.forfeit_pending` directly when co-located with the tracker — adding an HTTP-only forfeit client with no real consumer was judged out of scope/overengineering for this issue
- [ ] README: `L > 19× g` at p=0.05; pending balance = collateral - [x] README: `L > 19× g` at p=0.05; pending balance = collateral — already present in `packages/validator/README.md` ("Why the penalty deters cheating")
- [ ] Integration test: 60-request fraud scenario → ban within threshold - [x] Integration test: 60-request fraud scenario → ban within threshold`tests/test_forfeiture_penalty.py::test_60_request_stream_bans_intermittent_first_hop_cheater_not_last_hop`
## ADR links ## ADR links

View File

@@ -1,4 +1,4 @@
Status: ready-for-agent Status: done
# 11 — C6: Wallet binding ownership proof + binding overwrite safety # 11 — C6: Wallet binding ownership proof + binding overwrite safety
@@ -21,10 +21,10 @@ Require signed message from wallet pubkey (ed25519 via `cryptography` / solders)
## Acceptance criteria ## Acceptance criteria
- [ ] Wallet binding requires cryptographic proof of pubkey ownership - [x] Wallet binding requires cryptographic proof of pubkey ownership
- [ ] One wallet → one API key (or documented admin override) - [x] One wallet → one API key (or documented admin override)
- [ ] Gossip `bind` events cannot overwrite existing binding via direct overwrite at `~351` - [x] Gossip `bind` events cannot overwrite existing binding via direct overwrite at `~351`
- [ ] Tests with deterministic keypairs (local adapter) - [x] Tests with deterministic keypairs (local adapter)
## ADR links ## ADR links

View File

@@ -1,4 +1,4 @@
Status: ready-for-agent Status: done
# 16 — DOC: US-006 reconciliation note # 16 — DOC: US-006 reconciliation note

View File

@@ -1,4 +1,4 @@
Status: ready-for-agent Status: ready-for-human
# 17 — DOC: Duplicate US-020 issue dedup # 17 — DOC: Duplicate US-020 issue dedup
@@ -20,4 +20,4 @@ Resolve numbering collision without losing history.
## Blocked by ## Blocked by
Human approval for renumbering Human approval for renumbering. An agent may prepare the mapping note, but must not run `git mv` or rewrite cross-links until the canonical number is approved.

View File

@@ -1,4 +1,4 @@
Status: ready-for-agent Status: done
# 18 — DOC: Operational runbooks (stubs) # 18 — DOC: Operational runbooks (stubs)

View File

@@ -1,10 +1,10 @@
Status: ready-for-agent Status: done
# 19 — DOC: Cryptography dependency + test environment note # 19 — DOC: Cryptography dependency + test environment note
## What to build ## What to build
Document and verify test/dev environment setup for wallet crypto paths. `packages/node/meshnet_node/wallet.py` uses `cryptography`; failures occur when `.venv` lacks deps. Document and verify test/dev environment setup for wallet crypto paths. `packages/node/meshnet_node/wallet.py` uses `cryptography`; failures occur when `.venv` lacks deps. `cryptography>=41` is already declared in `packages/node/pyproject.toml`, so this issue should focus on documenting the editable-install path and only add root/dev extras if tests still import the node wallet without installing the node package.
**Code refs:** **Code refs:**
@@ -14,11 +14,18 @@ Document and verify test/dev environment setup for wallet crypto paths. `package
## Acceptance criteria ## Acceptance criteria
- [ ] Confirm `cryptography` in node package deps; add to root/dev extras if tests import wallet without node install - [x] Confirm `cryptography>=41` remains in node package deps; add to root/dev extras only if tests import wallet without node install
- [ ] Add short **Test environment** section to `CONTRIBUTING.md` or `docs/dev/test-env.md`: use `.venv/Scripts/python.exe`, `pip install -e packages/node ...`, optional dep skips - [x] Add short **Test environment** section to `docs/dev/test-env.md` (or `CONTRIBUTING.md` if created): use `.venv/Scripts/python.exe`, `pip install -e packages/node ...`, optional dep skips
- [ ] Note which tests require optional deps (`--ignore=test_openai_gateway,...`) - [x] Note which tests require optional deps (`--ignore=test_openai_gateway,...`)
- [ ] No unrelated production code changes - [x] No unrelated production code changes
## Blocked by ## Blocked by
None None
## Resolution
- `packages/node/pyproject.toml` already declared `cryptography>=41` — no change needed.
- `conftest.py` adds every `packages/*` dir to `sys.path`, so first-party imports (e.g. `meshnet_node.wallet`) resolve without an editable install of that package — but third-party deps like `cryptography` still must be installed separately. Added `cryptography>=41` to the root `pyproject.toml` `dev` extra so `pip install -e ".[dev]"` alone covers the wallet tests (`test_node_startup.py`, `test_wallet_binding_proof.py`, `test_devnet_treasury.py`, etc.) without requiring a full `packages/node` install (which would otherwise pull in torch/transformers/accelerate/bitsandbytes).
- Added `docs/dev/test-env.md` with setup instructions (Linux + Windows `.venv\Scripts\python.exe`), and a note on optional-dependency tests: `test_real_model_backend.py` / `test_devnet_treasury.py` use `pytest.importorskip` and skip cleanly; `test_openai_gateway.py` hard-imports `openai`/`langchain_openai` with no skip guard (both already in the `dev` extra) — documented the `--ignore=tests/test_openai_gateway.py` fallback for minimal installs.
- Full suite: 311 passed, 3 skipped, 3 pre-existing failures unrelated to this issue (`test_billing_ledger.py::test_proxy_chat_splits_payout_by_tracker_assigned_route_span`, `test_forfeiture_penalty.py::test_probation_earns_nothing_then_earning_begins`, `test_mining_cli.py::test_legacy_start_without_port_uses_next_available_port` — port-in-use env artifact). Wallet-specific tests (`test_wallet_binding_proof.py`, `test_node_startup.py`, `test_devnet_treasury.py`): 50 passed, 2 skipped.

View File

@@ -1,10 +1,10 @@
Status: ready-for-agent Status: done
# 20 — Validator service token for `/v1/billing/forfeit` # 20 — Validator service token for `/v1/billing/forfeit`
## What to build ## What to build
Define and implement a **validator service token** distinct from client API keys and admin sessions. The validator process must authenticate when calling `POST /v1/billing/forfeit`; arbitrary Bearer strings and client API keys must be rejected. Define and implement a **validator service token** distinct from client API keys and admin sessions. The validator process must authenticate when calling `POST /v1/billing/forfeit`; arbitrary Bearer strings and client API keys must be rejected. This is a checklist subtask for issue 02 and should normally land in the same PR as the unified auth middleware.
Per [ADR-0017 §4](../../docs/adr/0017-tracker-authentication-and-authorization.md): forfeit accepts **validator service identity or admin session** only. Per [ADR-0017 §4](../../docs/adr/0017-tracker-authentication-and-authorization.md): forfeit accepts **validator service identity or admin session** only.

View File

@@ -1,28 +1,42 @@
Status: ready-for-human Status: ready-for-human
**BLOCKS ALPHA RELEASE.** Scoped 2026-07-06 during alpha-launch-readiness grilling session — must complete before real-money (mainnet SOL/USDT) traffic goes live for the friends + hired-VPS-host launch. Loose/uncalibrated thresholds + manual admin slash-reversal are the stopgap only until this closes.
**Engineering complete 2026-07-06; blocked on a human running it against the real hired-VPS fleet before launch.** The three code gaps below are closed and unit-tested (see Deliverables), but nothing in a dev session can stand in for actually dispatching the job at real hardware — that step, plus the threshold/FPR write-up that depends on its output, needs an operator with the live fleet. See the validator README's "Honest-noise calibration corpus" section for the operational how-to.
# 21 — Honest-noise TOPLOC calibration corpus # 21 — Honest-noise TOPLOC calibration corpus
## What to build ## What to build
Before enabling production TOPLOC audit thresholds, collect an **honest-noise baseline** across the heterogeneous volunteer fleet. Run identical inference jobs on every active node/GPU combo; measure the divergence envelope (TOPLOC exponent/mantissa deltas, logprob-rank spread) under real hardware variance. Before enabling production TOPLOC audit thresholds, collect an **honest-noise baseline** across the active fleet. Run identical inference jobs on every active node/GPU combo; measure the divergence envelope (TOPLOC exponent/mantissa deltas, logprob-rank spread) under real hardware variance. This must be driven by the tracker (scheduled/dispatched job), not a manual one-off script, so it can be re-run as the fleet's hardware mix changes.
Per [ADR-0018 consequences](../../docs/adr/0018-fraud-detection-verification-and-reputation.md): threshold calibration requires an honest-noise corpus across the fleet before production thresholds. Per [ADR-0018 consequences](../../docs/adr/0018-fraud-detection-verification-and-reputation.md): threshold calibration requires an honest-noise corpus across the fleet before production thresholds.
Research anchor: `.scratch/alpha-hardening/research-verifiable-inference.md` §8 layer 3 — "collect this first — run identical jobs across the current node fleet to measure the honest divergence envelope before setting thresholds." Research anchor: `.scratch/alpha-hardening/research-verifiable-inference.md` §8 layer 3 — "collect this first — run identical jobs across the current node fleet to measure the honest divergence envelope before setting thresholds."
**Launch context (why this is buildable now, not a research project):** first-launch nodes are hired VPS/VPC hosts under our own direct control (test infrastructure we pay for, not third-party volunteers) — not a long-term topology, but risk-free for calibration purposes since there's no external party to dispute a bad reading. Friends are client-side users of the API in this phase, not node operators. Run the calibration pass against this small, fully-controlled fleet first; hired hosts stay stake-free until it's done, then move to real staking once thresholds derive from their own hardware.
**Current gap (confirmed 2026-07-06 by code read):** none of the three pieces below exist yet.
1. `verify_activation_proofs()` (`packages/validator/meshnet_validator/audit.py:94-127`) returns a **plain bool** — no raw TOPLOC divergence/distance value is ever computed or surfaced. Every "done" fraud-detection issue (0610) currently runs on a guessed threshold baked into that bool, not a calibrated one.
2. Fleet dispatch exists but is the wrong shape: `_handle_benchmark_hop_penalty` / `_handle_benchmark_results` (`packages/tracker/meshnet_tracker/server.py:2998-3104`, from the old US-030 latency work) targets pinned 13-node *routes* and measures latency, not TOPLOC divergence across *every* registered node.
3. Storage is the wrong shape: `record_audit_outcome` (`packages/contracts/meshnet_contracts/__init__.py:416`) persists only `strike_count`/`banned`/`passed` to `registry_events` — no divergence value, no GPU/dtype/hardware-profile column anywhere. Benchmark results otherwise land in a flat JSON file (`server.benchmark_results_path`), not a queryable per-node/hardware schema.
## Deliverables ## Deliverables
- [ ] Scripted benchmark job (fixed prompt, model preset, seed policy) runnable on all nodes - [x] Extend the TOPLOC verify call path (`audit.py`) to return the raw distance/divergence metric alongside the existing bool — `verify_activation_proofs_detailed()` / `ToplocVerificationResult` in `packages/validator/meshnet_validator/audit.py`; `verify_activation_proofs()` kept as a thin bool-only wrapper for existing callers. Also fixes a real bug this issue's code-read surfaced: the old code did `bool(_call_toploc(...))`, which is always `True` for the real `toploc` library's non-empty per-chunk `VerificationResult` list regardless of divergence — `tests/test_toploc_audit.py::test_verify_activation_proofs_detailed_aggregates_per_chunk_divergence` exercises this directly.
- [ ] Aggregated corpus artifact (per node: GPU model, dtype, TOPLOC deltas vs reference) - [x] Extend the existing fleet-dispatch pattern (`server.py:2998+`) from pinned-route benchmarking to a tracker-scheduled job that hits **every currently registered node** with a fixed prompt/model/seed — `POST /v1/calibration/toploc/run` (admin/validator-gated, same shape as `POST /v1/benchmark/hop-penalty`) in `packages/tracker/meshnet_tracker/server.py`. Dispatches to every node that can solo-serve the full model range (single-hop pinned route, isolating one node's hardware noise from route-composition effects); partial-shard nodes are reported under `skipped_partial_shard_node_ids`, and nodes that don't answer the on-demand TOPLOC commitment fetch are reported per-node under `"skipped": "..."` rather than counted as pass or fail. See `tests/test_toploc_calibration_dispatch.py`.
- [ ] Recommended tolerance thresholds documented (p99 honest envelope + safety margin) - [x] Add a small SQLite table (same pattern as `billing.py`/`accounts.py`) keyed by node wallet + GPU model + dtype, storing the divergence value per calibration run — `packages/tracker/meshnet_tracker/calibration.py::ToplocCalibrationStore`, `toploc_calibration_runs` table.
- [ ] Gate checklist: production audit enable blocked until corpus covers ≥N distinct hardware profiles (define N in runbook, suggest ≥3) - [x] Aggregation: p99 honest envelope + safety margin computed from that table, written as the recommended tolerance constants — `ToplocCalibrationStore.envelope()`, exposed via `GET /v1/calibration/toploc/results`.
- [x] Gate checklist: production audit enable blocked until corpus covers ≥N distinct hardware profiles — `ToplocCalibrationStore.gate_status(min_hardware_profiles=N)`; N is `--toploc-calibration-gate-min-hardware-profiles` (default 1) on the tracker CLI, documented alpha exception in the validator README.
## Acceptance criteria ## Acceptance criteria
- [ ] Corpus collected from current fleet (or documented subset + extrapolation note) - [ ] Corpus collected from the current hired-VPS fleet (documented as a small-fleet alpha corpus, not the eventual volunteer-fleet corpus) — **not done: needs a human to run `POST /v1/calibration/toploc/run` against the live hired-VPS fleet before launch; no such fleet exists in a dev session.**
- [ ] Threshold constants in validator config derived from corpus, not guessed - [ ] Threshold constants in validator config derived from corpus, not guessed — mechanically ready (`envelope()` returns them) but depends on the real corpus above; not yet wired into `ToplocAuditConfig` as enforced thresholds (deliberately — enforcing unvalidated thresholds would be worse than today's guessed bool).
- [ ] False-positive rate estimate documented at chosen thresholds - [ ] False-positive rate estimate documented at chosen thresholds`envelope()` returns `estimated_false_positive_rate` (in-sample: fraction of the recorded corpus the recommended thresholds would themselves flag); needs the real corpus to be a meaningful number, and should be written up in the runbook once collected.
- [ ] README / runbook cross-link: **do not enable production audits** until this issue closes - [x] README / runbook cross-link: **do not enable production audits** until this issue closes`packages/validator/README.md` "TOPLOC audit contract" section, updated with the full operational how-to.
- [x] Note in the runbook that this alpha corpus must be re-run once the fleet grows beyond the hired-VPS set (different hardware mix invalidates the envelope) — same README section.
## ADR links ## ADR links
@@ -30,8 +44,9 @@ Research anchor: `.scratch/alpha-hardening/research-verifiable-inference.md` §8
## Blocked by ## Blocked by
- `06-fraud-toploc-integration.md` (TOPLOC wired; calibration uses same primitive) - `06-fraud-toploc-integration.md` (TOPLOC wired; calibration uses same primitive) — done
## Blocks (prod gate) ## Blocks (prod gate)
- Alpha release to real-money friends+hired-VPS launch (raised from "production adaptive audit thresholds" to a hard alpha-release gate during 2026-07-06 grilling)
- Production enable of adaptive audit thresholds (issues 0910 in prod) - Production enable of adaptive audit thresholds (issues 0910 in prod)

View File

@@ -1,4 +1,4 @@
Status: ready-for-agent Status: done
# 22 — DOC: MEMORY.md + project-status alpha-hardening index # 22 — DOC: MEMORY.md + project-status alpha-hardening index
@@ -8,9 +8,9 @@ Update persistent memory files so agents and humans find the alpha-hardening fea
## Acceptance criteria ## Acceptance criteria
- [ ] `.claude/memory/MEMORY.md` — index entry for alpha-hardening (`.scratch/alpha-hardening/`, ADRs 00160019, issue count) - [x] `.claude/memory/MEMORY.md` — index entry for alpha-hardening (`.scratch/alpha-hardening/`, ADRs 00160019, issue count)
- [ ] `.claude/memory/project-status.md` — brief alpha-hardening section: planning complete, Bucket 1 blockers next, link README - [x] `.claude/memory/project-status.md` — brief alpha-hardening section: planning complete, Bucket 1 blockers next, link README
- [ ] Cross-link `.scratch/alpha-hardening/handoff.md` from README (not temp path) - [x] Cross-link `.scratch/alpha-hardening/handoff.md` from README (not temp path)
## ADR links ## ADR links
@@ -18,4 +18,8 @@ Update persistent memory files so agents and humans find the alpha-hardening fea
## Blocked by ## Blocked by
None — parallel with other Bucket 3 doc issues None — completed
## Comments
2026-07-04 triage: already satisfied by `.claude/memory/MEMORY.md`, `.claude/memory/project-status.md`, and `.scratch/alpha-hardening/README.md`.

View File

@@ -0,0 +1,53 @@
Status: done
Scoped 2026-07-06 during alpha-launch-readiness grilling session. High priority, ship-soon for launch — **not** an alpha-release blocker (unlike issue 21): a stale/static price is a revenue/business-model risk, not a safety risk, so the friends + hired-VPS launch may proceed on the current static default while this lands in parallel.
# 23 — Dynamic per-model pricing benchmarked against HuggingFace inference rates
## What to build
Client-facing price per model should track the market: **80% of the cheapest comparable provider rate on HuggingFace's inference marketplace** (`https://huggingface.co/inference/models`), refreshed daily, auto-adjusting so served models stay competitively priced as the market moves. Nodes are unaffected by this loop (per launch design: clients are the only party spending real money; node payouts come from the 90/10 split of whatever price is charged, per ADR-0015/`packages/validator/README.md`).
**Current state (confirmed by code read 2026-07-06):** pricing is 100% static today. `DEFAULT_PRICE_PER_1K_TOKENS = 0.02` (`packages/tracker/meshnet_tracker/billing.py:21`) is the fallback nearly every model hits, since `model_presets.json` currently has no `price_per_1k_tokens` key for any preset. `BillingLedger.set_price(model, price)` (`billing.py:67-69`) is the only write path and already exists — no CLI/admin route calls it yet. No external HTTP/market-data integration exists anywhere in the tracker.
**Data source:** `https://huggingface.co/inference/models` aggregates multiple providers (novita, together, fireworks-ai, deepinfra, etc.) with per-model, per-provider $/1M input and output token pricing; the "cheapest" badge already identifies the lowest-cost provider per model on the page itself. It supports a GET query param for filtering, e.g. `?search=GLM`. **No confirmed public JSON API was found** during this session's fetch — the page reads as a rendered table. Owner's suggestion: try a plain `requests` + BeautifulSoup scrape first; if the pricing table turns out to be client-rendered (not present in the initial HTML), that's the fallback signal to escalate to a headless-browser fetch (e.g. Playwright) — confirm which is needed during implementation before building the full pipeline around it. Another data source is acceptable if more convenient/stable, owner is not wedded to this specific page.
## Deliverables
- [x] Live-fetch attempt (requests + BeautifulSoup against the HF page with `?search=<model-family>`, or an equivalent stable source) as the primary path — confirm during implementation whether the pricing table is present in the raw HTML or requires a headless-browser fetch, and note which in the PR
- [x] Extend `model_presets.json` per model with: `hf_aliases` (curated list of comparable HF model+provider IDs — **human-verified, not auto-discovered**), `hf_verified_match_note` (free text: params count + quantization confirmation, so a human signs off once per alias that it is a fair comparable before it's used for auto-pricing), `hf_last_price_per_1k` (derived from the $/1M rate), `hf_last_updated` (ISO date)
- [x] Daily refresh job reusing the tracker's existing daemon-thread pattern (`_settlement_loop`/`_deposit_loop` in `server.py`, `threading.Event().wait(interval)` loop) — for each preset with a non-empty `hf_aliases` list, fetch current pricing for those aliases, compute `0.8 × cheapest matched alias price`, call `set_price()`, and update `hf_last_price_per_1k`/`hf_last_updated`
- [x] Every price change logged (old price, new price, source alias, timestamp) — needed for dispute auditability if a client questions a charge
- [x] Fallback behavior: empty/missing `hf_aliases`, fetch failure, or no verified match → silently keep the existing static default price. Never error the pricing path, never zero-price a model
## Acceptance criteria
- [x] At least one model preset has a working end-to-end refresh (alias → live fetch → 80% computed price → `set_price()` called → metadata updated) demonstrated in a test
- [x] Models without a curated/verified alias continue to use the static default, unaffected by this feature
- [x] Fetch failures (network error, page structure change, no match found) degrade gracefully — logged, not raised to the request path
- [x] Price-change log is queryable/inspectable (doesn't need a UI yet — a log line or table row is sufficient for alpha)
- [x] Note in the runbook/issue on which fetch mechanism (plain HTTP scrape vs. headless browser) was actually required, so the next person doesn't have to rediscover it
## Implementation notes (2026-07-06)
**Fetch mechanism confirmed: plain HTTP scrape, no headless browser needed.** Live-fetched `https://huggingface.co/inference/models?search=GLM` this session — the pricing table is server-rendered into the initial HTML response (SvelteKit SSR), confirmed by grepping the raw response for `cheapest`/`$`-prefixed price cells before any JS runs. A stdlib `urllib.request` GET + `html.parser.HTMLParser`-based table walk is sufficient; no `requests`/`bs4`/Playwright dependency was added, matching this package's existing zero-new-HTTP-dependency convention (`gossip.py`/`raft.py`/`server.py` all use `urllib.request` only). Each row's most stable extraction anchor turned out to be the `<a href="/<org>/<repo>/?inference_api=true&inference_provider=<provider>">` link, not the display text (which duplicates the repo id at two responsive breakpoints and is easy to mis-parse).
**What shipped:** new `packages/tracker/meshnet_tracker/hf_pricing.py` — pure HTML parser (`parse_hf_pricing_table`), alias matching (`cheapest_matching_quote`, supports both `org/repo` and `org/repo::provider` forms so a human can pin a specific provider's deployment), a pure per-preset computation function (`refresh_preset_price`, never raises), and `HfPricingLog` (SQLite-backed change log, same shape as `billing.py`/`calibration.py`). `TrackerServer` gained an opt-in (`enable_hf_pricing=True` / `--enable-hf-pricing`) daily daemon thread (`_hf_pricing_loop`, same `threading.Event().wait(interval)` shape as `_settlement_loop`) and `GET /v1/pricing/hf/history` (admin/validator-gated, mirrors `/v1/calibration/toploc/results`). `model_presets.json`'s `kimi-k2.7` preset now carries the `hf_aliases`/`hf_verified_match_note` schema fields, left as an empty list pending a human sign-off on a genuinely comparable HF listing (params count + quantization) — per this issue's own "human-verified, not auto-discovered" requirement, an agent should not fabricate that sign-off. This also means the shipped default config demonstrates the required "no alias → static price, unaffected" fallback for a real production preset; the alias→live-fetch→80%→set_price() path is demonstrated end-to-end against an injected fetch backend in `tests/test_hf_pricing_dispatch.py` (the `fetch_html=`/`hf_pricing_fetch_html=` injection point mirrors this codebase's `backend=` convention for anything that would otherwise hit the network in tests).
**Bug caught and fixed while wiring this in:** `TrackerServer` previously did `dict(DEFAULT_MODEL_PRESETS)` when no explicit `model_presets` was passed — a shallow copy that aliases every preset's inner dict to the shared module-level global. Writing `hf_last_price_per_1k`/`hf_last_updated` in place would have leaked across every other `TrackerServer` instance in the same process (real risk in the test suite, and in any future multi-tracker-in-one-process embedding). Fixed with a `_clone_model_presets()` helper that also shallow-copies each preset dict.
**Follow-up for a human (not a completion blocker):** populate real `hf_aliases`/`hf_verified_match_note` entries for production presets once someone has confirmed a genuinely comparable HF-listed deployment (params + quantization) — that activates dynamic pricing for that model on the next refresh tick. Until then every preset safely stays on its static price.
Tests: `tests/test_hf_pricing.py` (11 tests: parsing, blended-price math, alias matching incl. provider-scoped aliases, all three fallback paths, log persistence) + `tests/test_hf_pricing_dispatch.py` (5 tests: full TrackerServer end-to-end refresh, unaffected-without-alias, history auth gating, history content, history model filter). Full suite (`pytest tests/ -q -k "not integration"`): 346 passed, 2 skipped.
## ADR links
- [ADR-0015](../../docs/adr/0015-usdt-custodial-settlement.md) — settlement/pricing this touches (90/10 split, per-model pricing)
## Blocked by
None — independent of the alpha-hardening trust-boundary work; touches `billing.py`/`server.py` pricing paths only.
## Blocks
None — ship-soon for launch quality, not a release gate (see status note above).

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,88 @@
Status: stub
# Runbook: Ledger backup
Covers backing up the tracker's authoritative money/trust state — the billing
ledger, dashboard accounts DB, and node registry (strike/ban/reputation) — and
how to pause hive gossip during the backup window so peers don't replicate
against a half-copied file.
## Trust assumptions (read first)
Per [ADR-0016](../../../docs/adr/0016-alpha-scope-and-known-limitations.md), one
operator-designated tracker holds the treasury keypair and is the source of
truth for settlement; other hive members only replicate. Back up **that**
tracker's databases — a follower's copies are eventually consistent, not
authoritative. See [ADR-0015](../../../docs/adr/0015-usdt-custodial-settlement.md)
for the settlement loop these tables feed.
## Prerequisites
- Shell access to the settlement-capable tracker host.
- `sqlite3` CLI (or `.backup` support in the Python `sqlite3` module) available
for online, consistent snapshots.
- Know the tracker's configured DB paths — defaults, unless overridden by CLI
flags:
- Billing ledger: `billing.sqlite` (`--billing-db`, `DEFAULT_BILLING_DB_PATH`
in `packages/tracker/meshnet_tracker/billing.py`)
- Dashboard accounts: `accounts.sqlite` (`--accounts-db`,
`DEFAULT_ACCOUNTS_DB_PATH` in `packages/tracker/meshnet_tracker/accounts.py`)
- Node registry (strike/ban/reputation event log,
`packages/contracts/meshnet_contracts/__init__.py::RegistryEventLog`): path
is whatever was passed as `registry_db` when the tracker's
`LocalSolanaContracts` was constructed. **As of this writing the tracker
CLI (`meshnet_tracker/cli.py`) does not expose a `--registry-db` flag or
wire a `contracts=` instance into `TrackerServer` by default** — confirm
with whoever deployed this tracker whether registry persistence is
actually enabled before assuming a file exists to back up. If it isn't
wired up yet, strike/ban/reputation state is RAM-only and this step is
moot until that gap closes (tracked loosely against issue 05).
## Steps
1. Identify the actual DB paths in use (check the tracker's start command /
systemd unit / process env for `--billing-db`, `--accounts-db`, and any
registry DB argument).
2. **Pause hive gossip** on this tracker so peers don't pull a partial/locked
file mid-backup:
- If the tracker is the sole settlement node with no `--cluster-peers`,
gossip is already off — skip to step 3.
- Otherwise, stop replication by restarting the process without
`--cluster-peers` (or with an empty peer list) for the duration of the
backup, or take the backup during a maintenance window with peers
temporarily pointed away from this tracker at the load balancer/DNS
level. There is currently no live "pause gossip" admin endpoint — this is
a process-restart-level operation.
- Confirm no in-flight `/v1/registry/gossip`, `/v1/billing/gossip`, or
`/v1/accounts/gossip` traffic before proceeding (check access logs).
3. Take an online, consistent copy of each SQLite file using the backup API
rather than `cp` (WAL-mode files can be mid-write):
```
sqlite3 billing.sqlite ".backup '/backups/billing-$(date +%Y%m%dT%H%M%S).sqlite'"
sqlite3 accounts.sqlite ".backup '/backups/accounts-$(date +%Y%m%dT%H%M%S).sqlite'"
# registry DB, if configured:
sqlite3 registry.sqlite ".backup '/backups/registry-$(date +%Y%m%dT%H%M%S).sqlite'"
```
4. Verify each backup opens and has rows in its expected tables
(`billing_ledger`/event log tables, `accounts`, `registry_events`).
5. Resume gossip (restore `--cluster-peers` / routing) once backups are
confirmed good.
6. Ship backups off-host per your normal retention policy. Do not store them
alongside `.env.devnet` or keypair files (see secrets handling below).
## Rollback
- If a restore is needed, stop the tracker, replace the live `.sqlite` file(s)
with the chosen backup, and restart. Because billing/accounts/registry each
use append-only event logs, a stale restore under-counts recent activity
rather than corrupting state — reconcile any gap against node/operator
reports for the missing window before resuming payouts.
- If gossip was paused via a peer-list restart, confirm peers re-sync
(`events_since` catch-up) before considering the rollback complete.
## Secrets handling
- Never commit `.env.devnet`, treasury keypair JSON files, `--hive-secret`, or
`--validator-service-token` values to a repo or ship them inside a DB backup
archive. Back these up separately, encrypted, per your existing secrets
process.

View File

@@ -0,0 +1,112 @@
Status: stub
# Runbook: Treasury key rotation (devnet mock-USDT)
Covers rotating the devnet treasury keypair and/or the mock-USDT mint without
double-crediting client ledger balances or double-paying nodes.
## Trust assumptions (read first)
Per [ADR-0015](../../../docs/adr/0015-usdt-custodial-settlement.md), a single
project-owned wallet custodies all funds; the treasury keypair is loaded only
on the operator-designated settlement tracker (ADR-0016 §1). Rotating this key
is a trusted-operator action — there is no on-chain multisig or trustless
handoff in the alpha design. Devnet uses a self-created mock-USDT SPL mint
(6 decimals); real USDT only exists on mainnet, so this procedure is
devnet-only until a mainnet cutover ADR supersedes it.
## Prerequisites
- Access to `scripts/devnet_setup.py` and its dependencies (`solders`,
`meshnet_contracts.solana_adapter.SolanaCustodialTreasury`).
- The current treasury keypair path (default
`~/.config/solana/meshnet-treasury.json`, or whatever `--treasury-keypair`
the running tracker uses) and current `MESHNET_USDT_MINT` /
`MESHNET_TREASURY_WALLET` values (see `.env.devnet`, never committed).
- Ability to stop/restart the settlement-capable tracker.
- Confirm the deposit watcher's dedupe state (transaction signatures already
credited) is durable — it must survive the rotation so replayed/rescanned
transfers under the *old* wallet don't get re-credited under the *new* one.
## Two rotation scenarios
### A. Rotate the treasury keypair only (same mint, same on-chain wallet funds move)
The treasury wallet address changes because it's derived from the keypair, so
this requires migrating funds, not just swapping a file.
1. Generate a new keypair (do **not** reuse `_load_or_create_keypair` against
the old path — write to a new path so both keys exist during the
transition):
```
python scripts/devnet_setup.py --keypair ~/.config/solana/meshnet-treasury-new.json \
--mint <EXISTING_MOCK_USDT_MINT> --env-out .env.devnet.new
```
This creates the new treasury wallet + token account and reuses the
existing mint (no new token, so client balances denominated in that mint
are unaffected).
2. Drain the old treasury token account to the new one via a single SPL
transfer sized to the *entire current balance* (record the exact amount
and the source tx signature before moving anything).
3. **Freeze settlement during the drain**: stop the settlement-capable
tracker (or restart it with no `--treasury-keypair` so the settlement loop
is inert) before step 2, so no payout is in flight against the old wallet
while funds move.
4. Update the tracker's `--treasury-keypair`, `--treasury-wallet`-derived
config (i.e. the new `.env.devnet`) and restart the tracker pointed at the
new keypair.
5. Verify: `treasury.get_sol_balance()` / mock-USDT balance on the new wallet
matches the old wallet's pre-drain balance; old wallet balance is zero.
6. Only after verification, revoke/delete the old keypair file.
### B. Rotate the mock-USDT mint (e.g. compromised or mis-configured mint)
This is a bigger change — it invalidates every client's existing off-chain
ledger balance denomination reference and any node's pending on-chain payout
expectations. Treat as a deliberate migration, not a routine rotation:
1. Settle (pay out) all pending node balances against the *old* mint before
cutover — the pending-balance forfeiture/collateral model (ADR-0015)
assumes pending balances are payable in a known mint.
2. Create the new mint and treasury token account:
```
python scripts/devnet_setup.py --keypair <treasury-keypair> --env-out .env.devnet
```
(omit `--mint` so a fresh mint is created).
3. Update tracker config (`MESHNET_USDT_MINT`) and restart.
4. Re-mint/airdrop mock USDT to active client wallets under the new mint as
needed (`--mint-to`), since off-chain ledger balances are *not*
automatically re-denominated — this is a devnet convenience step, not a
guarantee that would hold for real USDT.
## Avoiding double-credit
The deposit watcher (issue 32) dedupes by on-chain transaction signature. The
signature space for the old and new treasury token accounts/mints is
disjoint, so:
- Do not replay old-wallet deposit history against the new wallet's watcher —
it has no record of those signatures and would (correctly) not credit them,
but any manual "catch-up crediting" script must not re-process transfers the
old watcher already credited. Cross-check the old ledger's credited-tx-sig
table before any manual reconciliation entry.
- Keep the old watcher's dedupe DB/table around (don't drop it as part of
rotation) until you've confirmed no in-flight deposits to the old address
remain unconfirmed.
## Rollback
- Scenario A: if the new wallet fails verification, restart the tracker with
the old `--treasury-keypair` — no client-facing state changed since ledger
balances are keyed by API key, not treasury wallet address.
- Scenario B: if re-minting under the new mint goes wrong, restart the
tracker against the old `MESHNET_USDT_MINT` config; nothing was destroyed on
the old mint.
## Secrets handling
- Never commit `.env.devnet`, `.env.devnet.new`, or any `*treasury*.json`
keypair file. `scripts/devnet_setup.py` writes keypairs with `0o600`
permissions — preserve that when copying.
- Treat the treasury keypair as the single highest-value secret in this
system per ADR-0015/ADR-0016: anyone with it can drain custodial funds.

View File

@@ -0,0 +1,108 @@
Status: stub
# Runbook: Tracker upgrade path (rolling restart)
Covers restarting/upgrading tracker processes in a hive without losing
strike/ban/reputation state or interrupting settlement, per the ADR-0016 §4
guarantee that reputation carries forward across restarts.
## Trust assumptions (read first)
Per [ADR-0016](../../../docs/adr/0016-alpha-scope-and-known-limitations.md),
only one operator-designated tracker holds the treasury keypair and runs the
settlement loop ([ADR-0015](../../../docs/adr/0015-usdt-custodial-settlement.md));
other hive members replicate for routing only. Raft (`packages/tracker/meshnet_tracker/raft.py`)
elects a leader for shard-assignment/registration commands — settlement
leadership is a separate, operator-configured concept, not the Raft leader.
Plan restarts so the settlement tracker's downtime window is minimized
independent of routing-tracker restarts.
## Known gap — read before relying on this runbook
Strike/ban/reputation persistence itself was implemented in issue 05
(`packages/contracts/meshnet_contracts/__init__.py::RegistryEventLog`,
SQLite-backed, same pattern as billing/accounts). **As of this writing,
`packages/tracker/meshnet_tracker/cli.py` does not expose a `--registry-db`
flag, nor does it construct a `contracts=` instance to pass into
`TrackerServer`.** Running the tracker via the stock CLI entry point leaves
`server.contracts` as `None`, which means:
- Ban checks (`_registration_ban_error`), reputation-weighted routing
(`_reputation_multiplier`), and the `/v1/registry/wallets` endpoint are
inert.
- There is nothing to persist across restarts in that configuration — the
"survives restart" guarantee only holds for deployments that construct
`LocalSolanaContracts(registry_db=<path>)` and wire it into `TrackerServer(contracts=...)`
themselves (e.g. a custom entrypoint or embedding the server programmatically).
Before following the restart steps below, confirm which mode this deployment
runs in. If it's the stock CLI with no custom `contracts` wiring, strike/ban
state is RAM-only regardless of this runbook, and a restart resets it — treat
that as a pre-existing gap to flag to the owner, not something this runbook
can work around.
## Prerequisites
- Confirm registry persistence is actually wired (see gap above) and note the
registry DB path in use.
- Confirm billing (`--billing-db`) and accounts (`--accounts-db`) persistence
paths — these already default to `billing.sqlite` / `accounts.sqlite` and
persist regardless of the registry gap.
- Know which tracker in the hive is currently the settlement leader (holds
`--treasury-keypair`) versus routing-only peers.
- `--hive-secret` / `MESHNET_HIVE_SECRET` configured identically across all
hive members (ADR-0017) — a mismatched secret on restart fails gossip
closed, not open.
- Take a [ledger backup](01-ledger-backup.md) before any upgrade that touches
schema or dependency versions.
## Steps
1. **Routing-only trackers first.** For each non-settlement tracker in the
hive:
a. Confirm it's not the current Raft leader (`GET /v1/raft/status`); if it
is, this restart forces a re-election — acceptable, but expect a brief
registration-proxy gap while a new leader is elected.
b. Stop the process, deploy the new code/config, restart with the same
`--billing-db` / `--accounts-db` / registry DB paths and the same
`--hive-secret` and `--cluster-peers`.
c. Check `/v1/raft/status` and `/v1/registry/wallets` (if registry is
wired) come back consistent with peers within one gossip interval.
d. Move to the next routing tracker only after this one rejoins cleanly.
2. **Settlement tracker last**, and only during a low-settlement-activity
window if possible:
a. Confirm no payout is mid-flight (check tracker logs / pending balance
levels against `--settle-period` / `--payout-threshold`).
b. Stop the process. The treasury keypair file itself is untouched by the
restart — do not regenerate it (see
[treasury key rotation](02-treasury-key-rotation.md) for that separate
procedure).
c. Deploy new code/config, restart with identical `--treasury-keypair`,
`--solana-rpc-url`, `--usdt-mint`, `--settle-period`,
`--payout-threshold`, `--payout-dust-floor`, and DB paths.
d. Verify strike/ban/reputation state (if wired) matches pre-restart values
via `/v1/registry/wallets`, and that billing/accounts ledgers show the
same balances as immediately before shutdown.
3. Confirm all hive members show each other as alive peers and gossip
(`/v1/registry/gossip`, `/v1/billing/gossip`, `/v1/accounts/gossip`) is
flowing without HMAC auth failures in logs (ADR-0017).
## Rollback
- Each tracker's on-disk SQLite files are untouched by a code-only upgrade;
rolling back means redeploying the previous binary/version against the same
DB paths. Because billing/accounts/registry are append-only event logs, a
version rollback does not lose data written by the newer version as long as
the schema didn't change — if the upgrade included a schema migration,
restore from the pre-upgrade [ledger backup](01-ledger-backup.md) instead.
- If a settlement-tracker restart leaves it unable to reach the treasury RPC
endpoint, routing-only trackers continue serving traffic — settlement simply
pauses until the leader recovers; no funds are at risk since payouts require
the loaded keypair.
## Secrets handling
- Never commit `.env.devnet`, `--hive-secret` / `MESHNET_HIVE_SECRET`,
`--validator-service-token`, or the treasury keypair file as part of a
deploy/config change. Deploy scripts should read these from the existing
secrets store, not from a file checked into the repo.

View File

@@ -0,0 +1,177 @@
# ADR-0020: Distributed GGUF/llama.cpp Runtime With Per-Shard Local KV
Status: Proposed
## Context
The project currently uses PyTorch/Transformers for real model shards. That decision was captured in ADR-0001 because llama.cpp RPC at the time required the primary node to load the full model and distribute weights to workers, which conflicted with the desired model where nodes independently hold shards.
We now want to serve very large open models, including GLM-5.2 and Ornith-class MoE models, over a torrent-like inference marketplace. CPU and mixed consumer hardware matter. LM Studio and llama.cpp demonstrate much better CPU/GGUF performance than our current PyTorch CPU path. The user also has a personal relationship with Georgi Gerganov, making upstream collaboration plausible.
The current distributed PyTorch path is not yet production-grade: it recomputes the full growing sequence for every output token and disables KV cache inside manual layer calls. It sends hidden activations across seams, not KV, but those activations currently cover the full sequence every decode step.
## Decision
Adopt a distributed GGUF/llama.cpp runtime track while keeping PyTorch as the reference and fast-architecture backend.
The runtime model is:
- GGUF/model artifacts are distributed through torrent/content-addressed storage.
- Nodes independently acquire and verify artifacts; no root node streams model weights to workers at session start.
- Tracker chooses a sticky route covering all layers.
- Each node owns hot KV/state for the layers it executes.
- Prefill sends chunked activations through the route and builds local per-shard KV.
- Decode sends one-step activations through the route and appends local KV at every shard.
- Cache/CDN servers store cold artifacts and optional prefix/session snapshots, not hot per-token KV.
- Context is capped at 128K for the first serious product path.
## Technical Framework
The design separates five planes:
- **Control plane**: tracker registry, coverage map, route selection, session lifecycle, telemetry, billing, and audit.
- **Artifact plane**: Shard Swarms, GGUF/safetensors/tokenizer files, manifests, hashes, and local node storage.
- **Execution plane**: active Inference Route, chunked prefill, one-step decode, and hidden-state movement across activation seams.
- **Session state plane**: per-shard Hot KV State on route nodes, plus optional Prefix Snapshots outside the hot loop.
- **Economics/trust plane**: reward accounting, validation events, slash proofs, public/private route policy.
Hard invariants:
1. Public-network Shards are contiguous layer ranges.
2. Hot KV State is local to the node serving that Shard in that Route Session.
3. Artifact distribution and route execution are separate systems.
4. Decode seam payload must be `O(hidden_size)`.
5. Prefill may be `O(sequence_length * hidden_size)`, but only in bounded chunks.
6. The tracker chooses routes; nodes do not negotiate route topology peer-to-peer.
7. Model/backend-specific cache internals stay behind backend capability reports.
8. PyTorch remains the correctness/reference backend while llama.cpp/GGUF becomes the performance backend.
9. Streaming responses are preferred when feasible; Generation Telemetry is always required.
The full challenge register is in [technical-challenges.md](./technical-challenges.md). The open decision gates are in [decision-framework.md](./decision-framework.md).
Resolved gate:
- Public-network Shards are layer ranges. Tensor-parallel/ring execution belongs inside a trusted node, colocated pod, or future composite node abstraction, not as the v1 public routing primitive.
- Hot KV State is local to each route node for the Shard it serves. Cache servers may store Prefix Snapshots, but they are not part of the per-token decode path.
- Distributed Route Session and Hot KV State semantics will be proven in the PyTorch route before llama.cpp/GGUF is extended for layer-boundary execution.
- Streaming responses are preferred when feasible. Realtime Generation Telemetry is required so clients can see phase, generated token count, and tokens/sec even during prefill or non-streaming fallback paths.
- llama.cpp/GGUF work targets upstreamable `libllama`/ggml hooks. A prototype fork is acceptable for exploration, but a permanent fork is not the plan.
- Model targeting is two-tiered: use a small llama.cpp-supported GGUF model for the first protocol smoke test, then use `deepseek-ai/DeepSeek-V4-Flash` as the first serious large-model target. GLM-5.2 and Ornith remain later support audits.
- Alpha fails Route Sessions on route-node loss instead of attempting automatic route repair. Repair requires compatible Prefix Snapshots and is a later capability.
- v1 activation transfer stays on binary HTTP as defined by ADR-0008. QUIC/WebRTC/custom transport can be introduced later behind the same activation protocol.
## Non-Goals
- Do not put remote cache servers in the per-token hot KV path.
- Do not require every node to hold the full model.
- Do not fork llama.cpp long-term if upstream APIs can support the needed layer-boundary hooks.
- Do not target GLM-5.2 or Ornith first; prove the route/KV protocol on a simpler well-supported GGUF model, then target DeepSeek-V4-Flash as the first serious large model.
## Options Considered
### A. Keep PyTorch-only distributed inference
Pros:
- Easy access to new Hugging Face architectures.
- Transformers has mature single-process KV semantics.
- Existing code already loads shards.
Cons:
- CPU inference is much slower than llama.cpp/GGUF.
- Current distributed path bypasses `generate()` and disables cache.
- Quantized GGUF ecosystem and LM Studio users are outside the runtime.
### B. Use llama.cpp only as a full local model backend
Pros:
- Quick performance win for nodes with enough RAM/VRAM.
- Minimal coordination with distributed protocol.
Cons:
- Does not unlock 397B/753B-class models for ordinary nodes.
- Does not solve marketplace layer routing.
### C. Distributed GGUF with per-shard local KV (chosen)
Pros:
- Aligns with torrent artifact distribution.
- Avoids root streaming weights to workers.
- Uses llama.cpp/GGUF performance where supported.
- Compatible with public node rewards by layer/work contribution.
- Scales KV memory by layer range.
Cons:
- Requires new runtime APIs around layer-boundary hidden states and per-session KV.
- Requires model-specific cache metadata for DSA/MLA/hybrid attention.
- Harder to debug than single-process `generate()`.
### D. Centralized KV cache servers
Pros:
- Easier apparent session failover.
- Central accounting of active cache.
Cons:
- Puts remote storage in the per-token hot path.
- Adds bandwidth and latency at the worst possible point.
- Creates consistency and privacy problems.
Rejected for hot decode. Accepted only for cold prefix snapshots and failover checkpoints.
## Consequences
- ADR-0001 should eventually be amended: PyTorch remains valid, but llama.cpp/GGUF becomes a first-class backend.
- The activation protocol must split prefill and decode explicitly.
- Session IDs must be stable across the full request. The current fresh UUID-per-hop-call behavior must change.
- Backends must report cache budget and cache compatibility.
- Tracker route selection must include disk, memory pressure, cache warmth, and network latency.
- Billing can be based on layer work, prefill tokens, decode tokens, and observed route participation.
- Client UX should stream token deltas when feasible and must include route-session progress telemetry even when token deltas are not streamed.
## Required Runtime Capabilities
PyTorch path:
- manual layer calls with `past_key_values` / model-specific cache object
- per-shard session cache store
- prefill chunk append
- decode step append
- stable session lifecycle endpoints
llama.cpp/GGUF path:
- full local GGUF serving
- layer/tensor map extraction from GGUF
- optional partial layer loading or mmap-backed selected execution
- inbound hidden-state execution from arbitrary start layer
- outbound hidden-state return at stop layer
- per-session KV ownership for loaded layers
- cache budget/compatibility introspection
- GLM-5.2 DSA support when upstream/runtime supports it
## Implementation Plan
1. Add full-model `LlamaCppBackend` using `llama-server` or `libllama`.
2. Implement distributed KV in the PyTorch path to prove semantics.
3. Add session lifecycle and prefill/decode wire protocol.
4. Add model artifact manifest and torrent seeding metadata.
5. Prototype localhost two-process llama.cpp layer boundary execution.
6. Generalize to network route.
7. Bring in GLM-5.2/Ornith once backend support and cache accounting are verified.
## Acceptance Criteria
- A two-node localhost route can prefill once and decode N tokens without recomputing the full prompt.
- Seam payload during decode is `O(hidden_size)`, not `O(sequence_length * hidden_size)`.
- Per-node KV memory grows with owned layer count and context length.
- Route loss during alpha fails cleanly with explicit reason.
- Full local GGUF backend outperforms PyTorch CPU on a supported model.
- Artifact manifest can identify exactly which files/chunks a node must seed for its advertised layer range.

View File

@@ -0,0 +1,83 @@
# PRD: Distributed GGUF Runtime
## Summary
Build a distributed inference runtime that can serve large, quality-first open models by combining torrent-style model artifact distribution with sticky multi-node Inference Routes and per-shard local Hot KV State.
The first runtime proof uses the existing PyTorch route because it exposes model internals and cache semantics more directly. GGUF/llama.cpp becomes the performance path after the route-session contract is proven.
## Goals
- Eliminate full-prompt recompute in distributed decode.
- Keep decode activation seams proportional to `hidden_size`, not `context_length * hidden_size`.
- Keep Hot KV State local to the node serving the relevant Shard.
- Stream token deltas when feasible and always expose Generation Telemetry.
- Add a local full-model GGUF backend for immediate CPU performance wins.
- Define Model Artifact manifests so nodes can verify, seed, and advertise artifacts without depending on Hugging Face at request time.
- Prototype an upstreamable llama.cpp/libllama layer-boundary API.
- Use DeepSeek-V4-Flash as the first serious large-model target after smaller protocol smoke tests.
## Non-Goals
- No centralized hot KV cache in the per-token decode path.
- No automatic route repair in alpha.
- No permanent llama.cpp fork as the intended architecture.
- No GLM-5.2 or Ornith first; they remain follow-up support audits.
- No transport rewrite to QUIC/WebRTC before route/session semantics are proven.
## Resolved Decisions
- Public-network Shards are contiguous transformer layer ranges.
- Tensor/ring parallelism belongs inside one trusted node, one colocated pod, or a future composite node abstraction.
- Hot KV State is local to route nodes; Prefix Snapshots are optional cold recovery/reuse artifacts.
- PyTorch distributed KV/session semantics are proven before llama.cpp distributed execution.
- Streaming responses are preferred; Generation Telemetry is mandatory.
- llama.cpp/GGUF work targets upstreamable `libllama`/ggml hooks.
- Alpha fails Route Sessions on route-node loss.
- v1 activation transfer stays on binary HTTP.
## Target User Experience
A client sends an OpenAI-compatible request. The Gateway or Tracker Node accepts the request, creates a Route Session, and streams token deltas when supported. The client receives live Generation Telemetry for route phase, prefill progress, generated token count, rolling tokens/sec, route health, and failure reason.
If a route node drops in alpha, the request fails clearly. A retry starts a new Route Session from scratch.
## Runtime Shape
```text
client request
-> Gateway / Tracker Node creates Route Session
-> Tracker selects sticky Inference Route
-> prefill:
prompt chunks move through Shards
each node appends local Hot KV State
-> decode:
one-step activation moves through Shards
each node reads/appends local Hot KV State
tail returns token/logits
-> client receives streamed token deltas where possible
-> Generation Telemetry continues until complete or failed
```
## Milestones
| Milestone | Outcome | Issues |
|---|---|---|
| M1 — Session protocol proof | Stub route has stable Route Sessions, prefill/decode split, telemetry, and streaming contract | 01, 02, 03 |
| M2 — PyTorch reference route | Distributed PyTorch decode uses local per-shard cache and stops full-prompt recompute | 04 |
| M3 — Local GGUF performance path | Single-node GGUF backend serves through the node API and reports backend metadata | 05 |
| M4 — Artifact plane | Model Artifact manifest supports verification, layer mapping, and node advertisement | 06 |
| M5 — llama.cpp collaboration proof | Localhost layer-boundary prototype identifies upstreamable llama.cpp/libllama API | 07 |
| M6 — Networked GGUF route | Multi-node GGUF route uses the resolved protocol and fails cleanly on node loss | 08 |
| M7 — First large model | DeepSeek-V4-Flash support path is audited and converted into follow-up runtime tasks | 09 |
## Acceptance Criteria
- A two-node route can prefill once and decode without resending full prompt activations.
- Decode seam payload is one token/hidden-state step after prefill.
- Route Session telemetry is visible before first token and during decode.
- Streaming token deltas work where the backend supports them.
- Route-node loss produces a structured alpha failure and does not attempt unsafe repair.
- A local GGUF model can serve via the node API.
- A Model Artifact manifest can prove which Shards a node can serve.
- DeepSeek-V4-Flash has a written support recommendation: PyTorch, vLLM/SGLang, llama.cpp/GGUF, or blocked.

View File

@@ -0,0 +1,63 @@
# Distributed GGUF runtime — planning index
Status: draft scratch package.
Goal: make the node network capable of serving large, high-quality open models by distributing GGUF/model artifacts over a torrent-style swarm while executing inference over a sticky multi-node route with per-shard local KV cache.
This scratch supersedes the old assumption in [ADR-0001](../../docs/adr/0001-pytorch-over-llama-cpp.md) that llama.cpp is only a single-node leaf backend. That assumption was correct for the original llama.cpp RPC shape, but the target is now different: torrent-distributed GGUF artifacts plus an explicit route/KV protocol owned by this platform, ideally developed in collaboration with upstream llama.cpp.
## Artifacts
| Path | Purpose |
|---|---|
| [architecture.md](./architecture.md) | Proposed runtime architecture, data flow, session state, and failure model |
| [technical-challenges.md](./technical-challenges.md) | Detailed challenge/solution register with acceptance tests |
| [decision-framework.md](./decision-framework.md) | Grilling framework for open decisions and recommended answers |
| [research-prior-art.md](./research-prior-art.md) | Prior-art notes for Petals, exo, Distributed Llama, prima.cpp, llama.cpp, DeepSeek-V4-Flash, GLM-5.2, and Ornith |
| [ADR-0020-distributed-gguf-runtime.md](./ADR-0020-distributed-gguf-runtime.md) | Draft decision record for the GGUF/llama.cpp distributed runtime |
| [PRD.md](./PRD.md) | Product/runtime requirements and acceptance criteria |
| [milestones.md](./milestones.md) | Dependency-ordered implementation milestones |
| [issues/](./issues/) | Implementation-ready tracer-bullet issue briefs |
## Decision Summary
Adopt a hybrid runtime:
- **Weights and artifacts**: distributed by torrent / content-addressed storage / optional CDN.
- **Hot KV cache**: local to the node that owns the corresponding layer range.
- **Prefix snapshots**: optionally persisted to cache servers for reuse, retry, and failover.
- **Active route**: sticky for one request/session.
- **Context cap**: 128K hard product limit for large models unless explicitly revised.
- **Backends**: keep PyTorch for fast model-architecture coverage and validation; add llama.cpp/GGUF as the performance path for supported models.
- **Client feedback**: stream token deltas when feasible; always expose Generation Telemetry.
- **First serious target model**: DeepSeek-V4-Flash after a smaller GGUF protocol smoke test.
## What We Learned
- Our current full-model PyTorch path uses Transformers `generate()` and gets local KV cache.
- Our current distributed PyTorch path disables cache and recomputes the full growing sequence per token.
- The seam today carries hidden activations, not KV cache; at 128K this becomes impossible for serious models if repeated every decode token.
- The missing capability is not "send KV across the network"; it is **stable per-session local KV cache per shard**.
- GGUF distribution is solved enough at the artifact layer, but GGUF/llama.cpp needs explicit layer-boundary execution APIs for our route model.
## Recommended Order
See [milestones.md](./milestones.md) for the full dependency map.
1. [01 — Route Session lifecycle](./issues/01-route-session-lifecycle.md)
2. [02 — Prefill/decode binary HTTP protocol](./issues/02-prefill-decode-binary-http.md)
3. [03 — Generation Telemetry and streaming response contract](./issues/03-generation-telemetry-and-streaming.md)
4. [04 — PyTorch distributed KV reference route](./issues/04-pytorch-distributed-kv-reference.md)
5. [05 — Local llama.cpp/GGUF backend](./issues/05-local-llamacpp-gguf-backend.md)
6. [06 — Model Artifact manifest and Shard advertisement](./issues/06-model-artifact-manifest.md)
7. [07 — llama.cpp layer-boundary prototype](./issues/07-llamacpp-layer-boundary-prototype.md)
8. [08 — Networked distributed GGUF route](./issues/08-networked-distributed-gguf-route.md)
9. [09 — DeepSeek-V4-Flash support audit](./issues/09-deepseek-v4-flash-support-audit.md)
10. [10 — GLM-5.2 and Ornith follow-up support audit](./issues/10-glm52-ornith-followup-audit.md)
## Open Questions
- Does upstream llama.cpp already expose enough internal API for arbitrary layer-range execution and hidden-state boundary I/O, or do we need an extension?
- Can GGUF split metadata be made layer/tensor semantic enough for torrent placement and partial loading?
- What is the minimum protocol needed for compressed KV formats such as GLM-5.2 DSA/MLA without exposing model-specific internals to the tracker?
- How much reliability do we need in alpha: fail request on route loss, or support route repair with KV snapshots?

View File

@@ -0,0 +1,274 @@
# Distributed GGUF Runtime Architecture
## Product Stance
The platform optimizes for access to high-quality models, not lowest latency. Latency is acceptable if the user can run models that are otherwise unavailable to them. The hard context limit for the first serious distributed runtime should be **128K tokens**. Longer context usually means the product is compensating for missing task decomposition, retrieval, or workspace summarization.
## Current State
The current node has two materially different inference paths:
- **Full local PyTorch model**: calls Hugging Face `model.generate()`, so Transformers owns autoregressive decode and local KV cache.
- **Distributed PyTorch route**: bypasses `model.generate()`, calls individual layers with `use_cache=False`, and recomputes the full growing sequence for every generated token.
Current distributed data flow:
```text
client request
-> head node formats prompt
-> for each output token:
head tokenizes full current text
head runs early layers over all tokens
head sends full activation [batch, sequence, hidden] to next node
middle nodes run their layers over all tokens
tail returns one decoded token string
head appends token to text
```
This is correct for small demos but not viable for large models. For GLM-5.2, a single 128K seam activation is roughly:
```text
128K tokens * hidden_size 6144 * 2 bytes ~= 1.5 GiB per hop
```
Sending that every output token is the bottleneck.
## Target State
Target distributed data flow:
```text
client request
-> tracker selects route and pins session
-> head node creates session_id
-> prefill:
prompt is chunked
each shard computes its layer range
each shard appends local KV/state for its own layers
activations cross only layer seams
-> decode loop:
head sends one new token / one-step hidden state
each shard reads local KV/state for session_id
each shard appends one step to local KV/state
only one-step activation crosses seams
tail returns logits/token
```
The KV cache remains local to the node that computed it. It is not sent to the next node and not read from a remote cache server during every decode step.
## Client Feedback
Streaming responses are desirable when the backend and client transport support them. The product should stream token deltas when possible, and it must always provide realtime Generation Telemetry while the route is working.
The fallback behavior is a non-streaming final answer plus live telemetry. That fallback is acceptable for early route proofs or models/backends that cannot expose clean token deltas yet, but the preferred client experience is streamed output plus telemetry.
Minimum client-visible telemetry:
- route/session accepted
- selected model and quantization
- prefill phase started/completed
- decode phase started
- generated token count
- rolling tokens per second
- route health or retry/failure reason
- estimated billing units when available
Implementation options:
- Server-Sent Events or WebSocket for realtime progress
- polling endpoint for simple clients
- OpenAI-compatible streaming for clients that require token deltas
This means "no token streaming" is acceptable only as a fallback. "Silent wait for minutes" is not acceptable.
## Artifact Plane
Artifact distribution is separate from execution.
```text
model publisher
-> produces model manifest
-> creates GGUF / safetensors / tokenizer artifacts
-> content-addresses every file/chunk
-> publishes torrent/magnet + HTTP fallback metadata
node
-> chooses model/layer range
-> downloads needed files/chunks
-> verifies hash
-> advertises availability to tracker
```
Required manifest fields:
- model id and version
- upstream source repo and revision
- license
- architecture name
- tokenizer files and hashes
- quantization
- tensor-to-layer map
- file/chunk hashes
- optional GGUF split files
- supported runtime backends
- context cap
- KV/cache format descriptor
## Execution Plane
The tracker selects routes using layer coverage and observed performance:
```text
route = [
head node: embeddings + layers 0..k
middle nodes: contiguous layer ranges
tail node: final layers + norm + lm_head
]
```
Route selection inputs:
- model id/version/quantization
- layer coverage
- node hardware
- measured prefill throughput
- measured decode throughput
- queue depth
- latency to neighboring nodes
- cache warmth for the requested prefix/session
- reliability/reputation
The route is sticky for the request/session. A new route means either a fresh prefill or restoring compatible KV snapshots.
## KV Cache Ownership
KV/state ownership is by layer range:
```text
session_id = request scoped id
node A owns layers 0..15 KV for session_id
node B owns layers 16..31 KV for session_id
node C owns layers 32..77 KV for session_id
```
The tracker does not own hot KV. It may know which nodes hold active KV for session accounting and failure handling.
Cache servers may store:
- prompt-prefix snapshots
- session checkpoints for retry
- cold reusable context blocks
- audit samples
Cache servers must not be in the per-token hot loop unless colocated with the compute node.
## 128K KV Budget
GLM-5.2 compressed DSA/MLA-style estimate from config:
```text
layers = 78
kv_lora_rank = 512
qk_rope_head_dim = 64
dtype = bf16 = 2 bytes
context = 128K
per_token ~= 78 * (512 + 64) * 2 = 89,856 bytes ~= 87.75 KiB
128K total ~= 10.7 GiB
per layer ~= 137 MiB
```
This is feasible when sharded:
| Layer count | Approx active KV at 128K |
|---:|---:|
| 1 | 137 MiB |
| 10 | 1.37 GiB |
| 20 | 2.75 GiB |
| 78 | 10.7 GiB |
The exact runtime value depends on implementation and cache quantization, but the order of magnitude is acceptable.
## Protocol Sketch
### Prefill
```http
POST /v1/sessions/{session_id}/prefill
Content-Type: application/octet-stream
X-Meshnet-Model: zai-org/GLM-5.2
X-Meshnet-Route-Id: ...
X-Meshnet-Token-Range: 0-2047
X-Meshnet-Shape: 1,2048,6144
X-Meshnet-Dtype: bfloat16
<activation bytes>
```
The receiver:
- validates route/session
- runs assigned layer range for that chunk
- appends local KV/state
- forwards resulting activation to next hop
### Decode
```http
POST /v1/sessions/{session_id}/decode-step
Content-Type: application/octet-stream
X-Meshnet-Model: zai-org/GLM-5.2
X-Meshnet-Position: 131072
X-Meshnet-Shape: 1,1,6144
X-Meshnet-Dtype: bfloat16
<one-step activation bytes>
```
The receiver:
- loads local KV/state by `session_id`
- runs one decode step for assigned layers
- appends one token position to local KV/state
- forwards one-step activation
## GGUF / llama.cpp Integration
The target llama.cpp integration needs more than `llama-server`.
Required capabilities:
- load full GGUF locally for immediate single-node performance
- optionally load only selected tensors/layers
- execute a layer range against inbound hidden states
- expose outbound hidden states at a boundary
- own per-session KV/state for only the loaded layer range
- support prefill chunks and decode-step calls
- expose model-specific cache metadata for DSA/MLA without requiring the tracker to understand tensor internals
If llama.cpp cannot expose these as stable APIs today, the collaboration target is an upstream extension rather than a long-lived fork.
## Failure Model
Alpha behavior:
- Route node drops during prefill: fail request and retry from scratch.
- Route node drops during decode: fail request unless a recent KV snapshot exists.
- Tracker restart: active sessions may be lost; completed billing records persist.
- Node restart: local hot KV is lost.
Later behavior:
- periodic KV snapshots for long sessions
- prefix cache reuse across requests
- route repair when a semantically equivalent node has the same model/layer range and compatible cache snapshot
## Security And Trust
Activation/KV data can reveal user prompts. Public volunteer routes are not private. For sensitive workloads:
- use private swarms
- allow paid trusted nodes
- encrypt transport
- avoid storing hot KV on untrusted shared cache servers
- sample outputs for fraud/audit as already planned in alpha hardening

View File

@@ -0,0 +1,268 @@
# Distributed GGUF Decision Framework
This framework is for grilling open decisions. It keeps decisions tied to project vocabulary and implementation gates instead of vague "distributed inference" language.
## Core Vocabulary
Use the existing domain terms this way:
- **Shard**: contiguous transformer layer range. This is the compute, routing, cache, and reward unit.
- **Shard Swarm**: storage/download group for artifacts needed by a shard.
- **Inference Route**: ordered node sequence that covers all layers for one request.
- **Route Session**: one active request bound to one inference route and stable session id.
- **Hot KV State**: live per-shard cache held by the route node during a route session.
- **Prefix Snapshot**: persisted route-session state used for reuse or failover, not the hot decode path.
- **Artifact Manifest**: canonical mapping from model artifacts to semantic model parts and runtime support.
- **Generation Telemetry**: realtime progress for a route session, including phase and tokens/sec, independent of whether token deltas are streamed.
## The Five Planes
### 1. Control Plane
Owner: Tracker.
Responsibilities:
- node registry
- coverage map
- route selection
- rebalance directives
- route-session creation
- health and telemetry
- client-visible Generation Telemetry
- billing/audit records
Must not do:
- serve hot KV during every token
- become the only place model artifacts can be fetched
### 2. Artifact Plane
Owner: Shard Swarms, local node storage, optional CDN/bootstrap mirrors.
Responsibilities:
- GGUF/safetensors/tokenizer download
- content-addressed verification
- local artifact inventory
- artifact-to-layer mapping
- cache eviction
Must not do:
- define execution order by file split alone
- imply that a downloaded file chunk equals a Shard
### 3. Execution Plane
Owner: active Inference Route.
Responsibilities:
- chunked prefill
- one-step decode
- hidden-state transfer across activation seams
- start-layer handling for overlapping shards
- backpressure
Must not do:
- resend full context activations during decode
- require cross-node tensor parallel all-reduce for public v1
### 4. Session State Plane
Owner: route nodes for hot KV; cache servers only for snapshots.
Responsibilities:
- per-shard local KV ownership
- cache allocation and eviction
- cache ABI compatibility
- session close/release
- optional prefix snapshots
Must not do:
- centralize hot KV in a remote service
- let a replacement node continue from incompatible state
### 5. Economics And Trust Plane
Owner: tracker plus settlement/validation components.
Responsibilities:
- distinguish storage/seeding work from inference work
- account for prefill and decode separately
- record route participation
- sample validation events
- slash proven fraud
Must not do:
- pay a node for merely holding files as if it generated tokens
- hide public-swarm privacy limits from clients
## Hard Invariants
These are the framework rules unless we deliberately write a new ADR:
1. Public-network Shards are contiguous layer ranges.
2. Hot KV State is local to the node serving that Shard in that Route Session.
3. Artifact distribution and route execution are separate systems.
4. Decode seam payload must be `O(hidden_size)`.
5. Prefill may be `O(sequence_length * hidden_size)`, but only in bounded chunks.
6. The tracker chooses routes; nodes do not negotiate route topology peer-to-peer.
7. Model/backend-specific cache internals stay behind backend capability reports.
8. PyTorch remains the correctness/reference backend while llama.cpp/GGUF becomes the performance backend.
9. Streaming responses are preferred when feasible; Generation Telemetry is always required.
## Resolved Gates
### Gate 1: Public Shard Semantics
Decision: public-network Shards are contiguous transformer layer ranges. Tensor-parallel or ring-style execution is allowed only inside one trusted node, one colocated pod, or a future composite node abstraction.
Rationale:
- Layer ranges match the existing `Shard`, `Coverage Map`, `Inference Route`, billing, and fraud vocabulary.
- Public volunteer nodes should not require cross-node all-reduce or tight per-layer synchronization in v1.
- Existing projects such as prima.cpp and Distributed Llama can still inform local-cluster/backend execution without becoming the public routing primitive.
Consequences:
- Artifact Manifests must map files/tensors to semantic layer ranges.
- Route selection remains ordered layer coverage.
- Rewards can be attributed to layer-range work.
- Hot KV State is naturally owned by the node serving that layer range for the Route Session.
### Gate 2: Hot KV Strategy
Decision: v1 rejects centralized hot KV. Hot KV State is local to the node serving the relevant Shard in the active Route Session. Cache servers may store Prefix Snapshots for reuse, retry, or failover, but they are not in the per-token decode path.
Rationale:
- Decode is the tight loop; adding remote cache I/O there makes latency and bandwidth worse at the worst point.
- Local KV naturally follows layer-range Shard ownership.
- Centralized hot KV increases privacy exposure and creates consistency problems.
- Prefix Snapshots preserve the useful part of central storage without making it mandatory for every generated token.
Consequences:
- Route Session must be sticky.
- Failover is limited in alpha unless a compatible Prefix Snapshot exists.
- Cache servers are optimization infrastructure, not required runtime infrastructure.
- Route repair requires compatible model revision, layer range, backend cache ABI, and snapshot position.
### Gate 3: First Runtime Proof
Decision: prove distributed Route Session and Hot KV State semantics in the existing PyTorch route before modifying llama.cpp/GGUF.
Rationale:
- PyTorch exposes model internals and cache objects more directly, so it is the fastest way to validate the distributed protocol.
- The current distributed PyTorch route already has the right high-level shape but disables cache and recomputes full prompts.
- Fixing that path gives us a reference implementation for correctness tests, telemetry, session lifecycle, and wire protocol behavior.
- llama.cpp/GGUF should receive a clear target ABI rather than becoming both the protocol experiment and the performance backend at once.
Consequences:
- Issue 02 precedes issue 05.
- llama.cpp collaboration has a concrete target ABI.
- The PyTorch route remains the architecture-coverage/reference backend even after GGUF becomes the preferred performance path.
- The first success metric is eliminating full-prompt recompute in distributed decode.
### Gate 3A: Client Feedback During Latency
Decision: streaming responses are preferred when feasible, and realtime Generation Telemetry is required regardless of streaming support.
Rationale:
- The product optimizes for access to large capable models, so some latency is acceptable.
- Users still need confidence that the route is alive and roughly how fast it is generating.
- Streaming token deltas give the best user experience when the backend exposes them cleanly.
- Tokens/sec remains useful during prefill, queueing, and any backend that cannot stream token deltas.
Consequences:
- The gateway should stream token deltas through an OpenAI-compatible response when possible.
- The gateway must expose progress through SSE, WebSocket, or polling.
- The final answer can be delivered after completion only as a fallback.
- Telemetry must include route phase, generated token count, and rolling tokens/sec.
- Non-streaming clients still need realtime telemetry.
### Gate 4: llama.cpp Collaboration Shape
Decision: target upstreamable `libllama`/ggml hooks instead of planning around a permanent fork.
Rationale:
- llama.cpp changes quickly across model support, quantization, kernels, and hardware backends.
- A permanent fork would become expensive to maintain and would lag upstream improvements.
- A short-lived prototype branch is acceptable if it proves the API and makes upstream collaboration concrete.
- Keeping tracker/routing logic outside llama.cpp makes the upstream ask smaller and cleaner.
Consequences:
- Need a minimal reproducible localhost demo before asking upstream to carry the design.
- Need to separate "what llama.cpp should expose" from "what our tracker does".
- Desired upstream surface is layer-range execution, hidden-state boundary I/O, partial loading/introspection, and per-session KV ownership.
- If upstream rejects the shape, we revisit whether to carry a narrow adapter fork or keep GGUF distributed execution as experimental.
### Gate 5: First Model Target
Decision: use a two-tier model target. Use a small, boring, llama.cpp-supported GGUF model for the first protocol smoke test. Use `deepseek-ai/DeepSeek-V4-Flash` as the first serious large-model target. Keep GLM-5.2 and Ornith as later support audits.
Rationale:
- The first protocol proof should isolate route/session/KV bugs from model-architecture bugs.
- DeepSeek-V4-Flash is a strong first serious target because it is much smaller than 1.6T-class models while still being large enough to validate the product thesis.
- DeepSeek-V4-Flash still has architecture-specific risks, so it should not be the first smoke test.
- GLM-5.2 and Ornith remain valuable targets, but they add DSA/MLA/hybrid attention uncertainty.
Consequences:
- 128K cache accounting can be modeled now.
- The first "real" target-model audit is DeepSeek-V4-Flash support in PyTorch, vLLM/SGLang, and any available GGUF/llama.cpp quantization path.
- Production support waits for backend capability reports and exact cache ABI support.
### Gate 6: Failure Semantics
Decision: alpha fails Route Sessions on route-node loss instead of attempting automatic route repair.
Rationale:
- Route repair requires compatible Prefix Snapshots, cache ABI checks, replacement-node selection, billing correction, and client stream/error recovery.
- Local Hot KV State means a replacement node cannot continue unless it has compatible state at the same position.
- Fail-fast keeps the first implementation correct while the session/KV protocol is still being proven.
Consequences:
- Better observability and explicit errors are required.
- Snapshotting becomes a later feature, not a blocker for first inference.
- Generation Telemetry must report the last known phase and failure reason.
- Client or gateway retry starts a new Route Session from scratch.
### Gate 7: Transport
Decision: keep binary HTTP for v1 activation transfer instead of jumping immediately to QUIC, WebRTC, or a custom transport.
Rationale:
- ADR-0008 already defines binary activation bodies with HTTP headers.
- HTTP keeps the first implementation debuggable with the existing server stack and tooling.
- The core risk is route/session/KV correctness, not transport optimization.
- QUIC/WebRTC can be introduced later behind the same activation protocol once semantics are proven.
Consequences:
- Focus benchmark work on payload shape, chunking, and cache behavior first.
- QUIC/WebRTC can be introduced as an optimization behind the same activation protocol.
- v1 implementation can reuse the current HTTP routing, relay, and observability infrastructure.
- Transport abstraction should be kept narrow enough that HTTP can be replaced later without changing backend cache semantics.
## Grilling Progress
Gates 1, 2, 3, 3A, 4, 5, 6, and 7 are resolved. The remaining work is to convert the resolved framework into implementation-ready issue briefs and prototype milestones.

View File

@@ -0,0 +1,19 @@
# 01 — Route Session lifecycle
Status: ready-for-agent
## What to build
Add the narrowest end-to-end Route Session lifecycle that can be used by distributed inference routes: create a session, bind it to a selected Inference Route, expose status, and close it cleanly. This slice does not need real model cache yet; it proves stable session identity across the control plane and activation plane.
## Acceptance criteria
- [ ] A request can create a Route Session with a stable `session_id`, `route_id`, model preset, backend id, and route membership.
- [ ] Every downstream activation request carries the same session identity and fails clearly if the session or route id does not match.
- [ ] Session status reports phase, route nodes, model preset, backend id, created time, and last activity time.
- [ ] Closing a session releases all registered per-session state.
- [ ] Tests cover create, status, close, stale-session rejection, and wrong-route rejection.
## Blocked by
None - can start immediately.

View File

@@ -0,0 +1,20 @@
# 02 — Prefill/decode binary HTTP protocol
Status: ready-for-agent
## What to build
Split the activation protocol into explicit prefill and decode-step calls using the existing binary HTTP direction from ADR-0008. The completed slice should work against a stub backend so payload shape, route/session headers, relay preservation, and failure behavior are testable before real KV cache work begins.
## Acceptance criteria
- [ ] Prefill accepts chunked binary activations with route/session metadata and forwards them through the selected route.
- [ ] Decode-step accepts a one-step binary activation and forwards a one-step activation through the selected route.
- [ ] Decode-step payload size is independent of prompt length in protocol tests.
- [ ] Relay forwarding preserves route/session headers, shape, dtype, position, and wire version.
- [ ] Legacy `/forward` either remains as a compatibility wrapper or fails with a clear wire-version error.
- [ ] Tests cover prefill chunking, decode-step shape validation, relay preservation, and malformed header rejection.
## Blocked by
- 01 — Route Session lifecycle.

View File

@@ -0,0 +1,21 @@
# 03 — Generation Telemetry and streaming response contract
Status: ready-for-agent
## What to build
Expose realtime Generation Telemetry for active Route Sessions and stream token deltas when the serving path can produce them. This slice should make long distributed requests observable before real large-model work begins.
## Acceptance criteria
- [ ] A client can observe route-session phase changes: queued, loading, prefill, decode, finalizing, completed, failed.
- [ ] Telemetry includes prefill progress, generated token count, rolling tokens/sec, average tokens/sec, active route nodes, and failure reason.
- [ ] Telemetry is available before the first output token.
- [ ] A streaming response can include token deltas while telemetry remains available.
- [ ] A non-streaming fallback still exposes telemetry until final answer or failure.
- [ ] Route-node failure reports the last known phase and reason.
- [ ] Tests cover telemetry updates, streaming token deltas, non-streaming fallback, and structured failure closeout.
## Blocked by
- 01 — Route Session lifecycle.

View File

@@ -0,0 +1,23 @@
# 04 — PyTorch distributed KV reference route
Status: ready-for-agent
## What to build
Fix the existing distributed PyTorch route so it uses the Route Session and prefill/decode protocol to keep Hot KV State local to each Shard node. The visible behavior is that prefill processes the prompt once, and decode no longer recomputes or resends the full growing prompt for every token.
## Acceptance criteria
- [ ] Distributed PyTorch prefill stores per-session cache/state on each Shard node.
- [ ] Distributed PyTorch decode-step reads and appends local per-shard cache/state.
- [ ] Decode activation seam payload is one token/hidden-state step after prefill.
- [ ] The old full-growing-prompt decode loop is not used for models that support the reference cache path.
- [ ] Unsupported model/cache APIs fail with an explicit backend capability error.
- [ ] Session close or TTL cleanup releases per-shard cache.
- [ ] Regression tests prove decode does not call the full prompt encoder for every generated token.
## Blocked by
- 01 — Route Session lifecycle.
- 02 — Prefill/decode binary HTTP protocol.
- 03 — Generation Telemetry and streaming response contract.

View File

@@ -0,0 +1,20 @@
# 05 — Local llama.cpp/GGUF backend
Status: ready-for-agent
## What to build
Add a local full-model GGUF backend so a node that can hold a GGUF model can serve it through the existing node API. This is the immediate CPU-performance path and the baseline for later distributed llama.cpp work.
## Acceptance criteria
- [ ] A node can start with backend `llama.cpp` or `gguf` for a local full-model GGUF artifact.
- [ ] The node can answer an OpenAI-compatible chat completion through the existing API.
- [ ] Startup and registration clearly report backend, quantization/artifact metadata, context cap, and local model path.
- [ ] The PyTorch backend remains unchanged and selectable.
- [ ] A smoke test or script validates backend wiring with a small GGUF model or a stubbed llama.cpp process.
- [ ] A benchmark command can compare local PyTorch CPU and local GGUF CPU for the same small supported model when both are available.
## Blocked by
None - can start immediately.

View File

@@ -0,0 +1,20 @@
# 06 — Model Artifact manifest and Shard advertisement
Status: ready-for-agent
## What to build
Introduce a Model Artifact manifest that separates storage distribution from route execution. A node should be able to verify local model files, determine which Shards it can serve, and advertise artifact/layer availability to the Tracker without contacting Hugging Face at request time.
## Acceptance criteria
- [ ] Manifest records model preset, upstream revision, license, backend support, quantization, context cap, tokenizer artifacts, file hashes, piece hashes, and tensor/layer mapping where available.
- [ ] A node can verify local artifacts against the manifest and reject corrupt or incomplete artifacts.
- [ ] A node can derive advertised Shard ranges from the manifest and local files.
- [ ] Tracker registration can include artifact id, backend id, Shard range, and verification status.
- [ ] Tracker coverage can distinguish model-layer coverage from artifact availability.
- [ ] Tests cover valid manifest registration, corrupt artifact rejection, and missing layer/tensor metadata.
## Blocked by
- 01 — Route Session lifecycle.

View File

@@ -0,0 +1,25 @@
# 07 — llama.cpp layer-boundary prototype
Status: ready-for-human
## What to build
Build a local prototype that proves whether llama.cpp/libllama can support the platform's distributed execution contract: execute a selected layer range, accept inbound hidden states, emit outbound hidden states, and own per-session cache for only the loaded/served range.
This is the collaboration package for upstream llama.cpp. The target is an upstreamable API shape, not a permanent fork.
## Acceptance criteria
- [ ] A small llama.cpp-supported GGUF model can be split into a two-process localhost head/tail prototype.
- [ ] The head process runs embeddings and early layers, then emits hidden states at an Activation Seam.
- [ ] The tail process accepts hidden states, runs later layers plus output head, and produces logits/tokens comparable to single-process execution.
- [ ] Prefill is performed once and decode-step seam payload is one hidden-state step per generated token.
- [ ] Each process owns only its own per-session cache/state.
- [ ] The prototype records the minimum upstream API needed for layer-range execution, hidden-state I/O, partial loading/introspection, and per-session KV ownership.
- [ ] If upstream support is unavailable, the issue ends with a concrete recommendation: upstream proposal, narrow adapter fork, or keep GGUF distribution local-only for now.
## Blocked by
- 02 — Prefill/decode binary HTTP protocol.
- 05 — Local llama.cpp/GGUF backend.
- 06 — Model Artifact manifest and Shard advertisement.

View File

@@ -0,0 +1,24 @@
# 08 — Networked distributed GGUF route
Status: pending
## What to build
Run a GGUF-backed model over a real multi-node Inference Route using the resolved Route Session, binary HTTP prefill/decode protocol, local Hot KV State, Generation Telemetry, and alpha fail-fast behavior.
## Acceptance criteria
- [ ] Two machines can form one GGUF-backed Inference Route over contiguous Shards.
- [ ] Prefill builds local per-shard cache/state and decode-step uses one-step seam payloads.
- [ ] The client receives streamed token deltas when supported by the GGUF path.
- [ ] The client receives Generation Telemetry for phase, generated tokens, tokens/sec, route health, and failure reason.
- [ ] Route-node loss fails the Route Session cleanly; no automatic repair is attempted in alpha.
- [ ] Tracker metrics show prefill tokens/sec, decode tokens/sec, seam latency, queue depth, and cache memory by node.
- [ ] Billing/audit records identify route membership and layer/token work for the completed or failed session.
## Blocked by
- 03 — Generation Telemetry and streaming response contract.
- 04 — PyTorch distributed KV reference route.
- 06 — Model Artifact manifest and Shard advertisement.
- 07 — llama.cpp layer-boundary prototype.

View File

@@ -0,0 +1,21 @@
# 09 — DeepSeek-V4-Flash support audit
Status: ready-for-agent
## What to build
Audit `deepseek-ai/DeepSeek-V4-Flash` as the first serious large-model target after the small GGUF protocol smoke test. The output is a compatibility matrix and a recommended runtime path, not full production support.
## Acceptance criteria
- [ ] Verify current PyTorch/Transformers load and generation semantics for DeepSeek-V4-Flash from primary model documentation.
- [ ] Verify vLLM and SGLang support status from primary runtime documentation or release notes.
- [ ] Verify whether a GGUF/llama.cpp quantization path exists or would need upstream work.
- [ ] Estimate artifact size, active parameter behavior, and 128K cache memory by Shard range.
- [ ] Identify required backend capability flags for the Tracker.
- [ ] Produce a compatibility matrix: PyTorch, vLLM, SGLang, llama.cpp/GGUF.
- [ ] End with one recommendation: first runtime path, blocked pending upstream, or defer.
## Blocked by
None - can start immediately.

View File

@@ -0,0 +1,20 @@
# 10 — GLM-5.2 and Ornith follow-up support audit
Status: pending
## What to build
Audit GLM-5.2 and Ornith after the smaller protocol smoke path and DeepSeek-V4-Flash audit. The output is a follow-up compatibility matrix focused on architecture/runtime blockers: DSA/MLA, hybrid attention, cache accounting, and GGUF/llama.cpp support.
## Acceptance criteria
- [ ] Verify GLM-5.2 PyTorch/Transformers serving requirements and cache semantics from primary model documentation.
- [ ] Verify llama.cpp/GGUF support status for `glm_moe_dsa` or equivalent architecture support.
- [ ] Verify Ornith/Qwen3.5-MoE and hybrid attention support status in the candidate runtimes.
- [ ] Estimate artifact size and 128K cache memory by Shard range for each model.
- [ ] Identify smallest quality-preserving quantization worth testing.
- [ ] Convert each runtime blocker into a follow-up issue or upstream collaboration note.
## Blocked by
- 09 — DeepSeek-V4-Flash support audit.

View File

@@ -0,0 +1,32 @@
# Distributed GGUF Runtime Milestones
## Proposed Breakdown
| Order | Issue | Title | Blocked by | User-visible proof |
|---:|---|---|---|---|
| 1 | [01](./issues/01-route-session-lifecycle.md) | Route Session lifecycle | None | Stable route/session status and cleanup |
| 2 | [02](./issues/02-prefill-decode-binary-http.md) | Prefill/decode binary HTTP protocol | 01 | Stub route proves prefill chunks and one-step decode payloads |
| 3 | [03](./issues/03-generation-telemetry-and-streaming.md) | Generation Telemetry and streaming response contract | 01 | Client sees route progress and streamed deltas when available |
| 4 | [04](./issues/04-pytorch-distributed-kv-reference.md) | PyTorch distributed KV reference route | 01, 02, 03 | Distributed PyTorch decode stops full-prompt recompute |
| 5 | [05](./issues/05-local-llamacpp-gguf-backend.md) | Local llama.cpp/GGUF backend | None | Local GGUF model serves through node API |
| 6 | [06](./issues/06-model-artifact-manifest.md) | Model Artifact manifest and Shard advertisement | 01 | Node verifies artifacts and advertises serveable Shards |
| 7 | [07](./issues/07-llamacpp-layer-boundary-prototype.md) | llama.cpp layer-boundary prototype | 02, 05, 06 | Local two-process GGUF route identifies upstream API |
| 8 | [08](./issues/08-networked-distributed-gguf-route.md) | Networked distributed GGUF route | 03, 04, 06, 07 | Two machines serve one GGUF route with telemetry |
| 9 | [09](./issues/09-deepseek-v4-flash-support-audit.md) | DeepSeek-V4-Flash support audit | None | Runtime recommendation for first serious large model |
| 10 | [10](./issues/10-glm52-ornith-followup-audit.md) | GLM-5.2 and Ornith follow-up support audit | 09 | Follow-up compatibility matrix and upstream blockers |
## First Three To Implement
1. **01 — Route Session lifecycle**: makes every later cache, telemetry, and route decision concrete.
2. **02 — Prefill/decode binary HTTP protocol**: proves the payload shape and route/session headers before model internals.
3. **03 — Generation Telemetry and streaming response contract**: gives every later long-running route a visible user experience and failure surface.
## Parallel Work
- **05 — Local llama.cpp/GGUF backend** can run in parallel with 0103 because it is a full-model local backend.
- **09 — DeepSeek-V4-Flash support audit** can run in parallel because it is research/compatibility work.
## Human-Gated Work
- **07 — llama.cpp layer-boundary prototype** is the collaboration point with Georgi/upstream llama.cpp.
- **08 — Networked distributed GGUF route** should wait until the PyTorch reference route proves the cache/session contract.

View File

@@ -0,0 +1,231 @@
# Prior Art: Distributed Large-Model Inference
This note captures what existing projects appear to solve and what remains specific to this platform.
## Petals
Source: <https://github.com/bigscience-workshop/petals>
Petals is the closest conceptual match for public volunteer inference. Its README describes running large models "BitTorrent-style", where a user loads a model through a `transformers`-like API and connects to a distributed network that hosts model layers. It explicitly supports seeing hidden states and using PyTorch/Transformers flexibility. The public README also notes privacy limitations: data is processed by other people in the public swarm, and sensitive use should run in a private swarm.
What it solves:
- public swarm of layer-serving peers
- hidden-state exposure
- route-like execution over model blocks
- private swarm option
- PyTorch/Transformers integration
What it does not directly solve for us:
- GGUF/llama.cpp artifact path
- torrent artifact storage tied to node rewards
- our billing/fraud/reputation model
- our OpenAI-compatible tracker/node route model
- a production path for GLM-5.2/DSA GGUF
Design import:
- Keep a PyTorch route as a reference implementation and validation harness.
- Preserve hidden-state seam semantics.
- Treat privacy as an explicit swarm property.
## exo
Source: <https://github.com/exo-explore/exo>
exo connects local devices into an AI cluster. Its README emphasizes automatic device discovery, topology-aware model splitting, tensor parallelism, MLX support, RDMA over Thunderbolt, and multiple API compatibilities. It is strongest for colocated owned devices, especially Apple Silicon / MLX clusters.
What it solves:
- automatic local cluster discovery
- topology-aware splitting
- tensor parallelism
- OpenAI/Ollama/Claude API compatibility
- model placement previews
- cluster dashboard
What it does not directly solve for us:
- untrusted internet volunteer network
- reward, fraud, and reputation
- torrent artifact distribution
- Linux GPU maturity is stated as still under development in the README
- GGUF/llama.cpp route protocol
Design import:
- Add placement previews before committing a route.
- Model prefill/decode separately in benchmarks.
- Use topology-aware routing, not just layer coverage.
## Distributed Llama / dllama
Source: <https://github.com/b4rtaz/distributed-llama>
Distributed Llama connects home devices into a cluster for CPU/GPU inference. Its README describes tensor parallelism, Ethernet synchronization, Linux/macOS/Windows support, ARM and x86 AVX2 optimization, and a root/worker architecture. The root node loads the model and forwards weights/state to workers. Known limitations include only `2^n` nodes and a maximum node count equal to the model's number of KV heads.
What it solves:
- practical cross-platform home-device cluster
- tensor-parallel synchronization
- root/worker process model
- custom model format and conversion path
What it does not directly solve for us:
- arbitrary volunteer joins/leaves
- independent shard ownership from local/torrent disk
- layer-range routing with tracker-managed marketplace
- public network fraud/billing
- GGUF as the native published artifact
Design import:
- KV-head constraints matter for tensor-parallel designs.
- A root node that distributes weights is unacceptable for our torrent-first marketplace; nodes must independently acquire artifacts.
## prima.cpp
Sources:
- <https://github.com/Lizonghang/prima.cpp>
- <https://arxiv.org/abs/2504.08791>
prima.cpp is a distributed llama.cpp implementation for low-resource home clusters. The README highlights mmap-based low memory pressure, piped-ring parallelism with prefetching, heterogeneity-aware workload distribution, automatic weak-device removal, GGUF quantization support, speculative decoding, dynamic batching, and support for Llama/Qwen/DeepSeek-class models. Its commands require each rank to point at the same GGUF file, and the README shows ring communication across ranks.
What it solves:
- llama.cpp-derived GGUF distributed execution
- heterogeneous device scheduling
- low memory pressure via mmap/page cache behavior
- disk prefetch as a first-class performance dimension
- ring communication for home clusters
- GGUF quantization support
What it does not directly solve for us:
- public volunteer marketplace
- torrent artifact discovery and seeding economics
- tracker-injected route over internet/NAT/relay
- per-node independent shard selection and rewards
- GLM-5.2 support is not established from the README
Design import:
- Study mmap and prefetching before inventing partial GGUF loading.
- Include disk speed and memory pressure in routing.
- Heterogeneity-aware scheduling is mandatory.
- Weak nodes should be excluded from a route if they slow the whole decode path.
## llama.cpp / GGUF
Sources:
- <https://github.com/ggml-org/llama.cpp>
- <https://raw.githubusercontent.com/ggml-org/llama.cpp/master/tools/gguf-split/README.md>
- <https://raw.githubusercontent.com/ggml-org/llama.cpp/master/ggml/CMakeLists.txt>
llama.cpp is the performance runtime we want for GGUF. It supports local GGUF loading, many CPU/GPU backends, OpenAI-compatible serving, quantization, and `gguf-split` can split or merge GGUF files by max size or tensor count. The ggml build options include many hardware backends and RPC support.
What it solves:
- mature CPU/GPU local inference
- GGUF ecosystem
- quantized weights
- local OpenAI-compatible server
- split/merge tooling for artifact distribution
What it does not solve by itself:
- torrent distribution and reward model
- per-session distributed route over arbitrary nodes
- public-node trust/fraud model
- stable API for arbitrary layer-boundary hidden-state I/O, if not already exposed
Design import:
- Use llama.cpp locally before attempting distributed GGUF.
- Collaborate upstream on layer-range execution and KV ownership APIs.
- Keep GGUF split for artifacts, not as the only execution-shard definition.
## GLM-5.2
Sources:
- <https://huggingface.co/zai-org/GLM-5.2>
- <https://huggingface.co/zai-org/GLM-5.2/blob/main/config.json>
GLM-5.2 is MIT licensed, 753B parameters, and advertises a 1M-token context. The config uses `glm_moe_dsa`, 78 layers, `hidden_size=6144`, `kv_lora_rank=512`, `qk_head_dim=256`, `qk_nope_head_dim=192`, `qk_rope_head_dim=64`, `v_head_dim=256`, and `max_position_embeddings=1048576`. The model card states IndexShare reduces per-token FLOPs at 1M context.
Design import:
- DSA/MLA-style compressed KV makes 128K feasible.
- Tracker should not need to understand DSA internals; backend should expose cache budget and compatibility metadata.
- GLM-5.2 is a later target after generic distributed KV works.
## DeepSeek-V4-Flash
Sources:
- <https://huggingface.co/deepseek-ai/DeepSeek-V4-Flash>
- <https://huggingface.co/deepseek-ai/DeepSeek-V4-Flash/blob/main/config.json>
DeepSeek-V4-Flash is MIT licensed and published as `deepseek-ai/DeepSeek-V4-Flash` on Hugging Face. The model card describes DeepSeek-V4-Flash as a 284B-parameter MoE model with 13B activated parameters and a 1M-token context. Hugging Face tags it as `deepseek_v4`, Transformers, Safetensors, and FP8. The repository lists 46 safetensor shards and around 160 GB total size.
Config highlights:
- `model_type=deepseek_v4`
- `hidden_size=4096`
- `num_hidden_layers=43`
- `num_attention_heads=64`
- `num_key_value_heads=1`
- `n_routed_experts=256`
- `num_experts_per_tok=6`
- `q_lora_rank=1024`
- `o_lora_rank=1024`
- `qk_rope_head_dim=64`
- `sliding_window=128`
- `max_position_embeddings=1048576`
- `expert_dtype=fp4`
- FP8 quantization metadata
Design import:
- Good first serious large-model target after the protocol smoke test because it is much smaller than 1.6T-class models while still validating MoE, compressed attention/cache behavior, and large-context routing.
- Not the first protocol smoke model. Use a smaller, boring, llama.cpp-supported GGUF model first so route/session/KV bugs are isolated from DeepSeek-specific architecture support.
- The support audit must verify the available local runtime path: PyTorch/Transformers, vLLM/SGLang, and any GGUF/llama.cpp quantization route.
## Ornith-1.0-397B
Sources:
- <https://huggingface.co/deepreinforce-ai/Ornith-1.0-397B>
- <https://huggingface.co/inferencerlabs/Ornith-1.0-397B-MLX-Q9>
Ornith-1.0-397B is MIT licensed, Qwen3.5-MoE based, with 397B MoE scale. Its base config shows 60 layers and a hybrid pattern where full attention appears every fourth layer, with other layers using linear attention. The MLX Q9 quantized variant is around 447 GB and reports high-quality Q9 behavior in its model card.
Design import:
- Hybrid attention can make large models more tractable than dense full-attention assumptions.
- Model-specific cache accounting is required; "params" alone is not enough to route.
## Synthesis
The prior art strongly supports the direction, but no project exactly matches the target product:
- Petals proves volunteer layer-serving is useful.
- exo proves UX/topology-aware local clusters matter.
- Distributed Llama proves CPU home clusters can cooperate but also shows root/worker constraints.
- prima.cpp proves llama.cpp/GGUF distribution across low-resource devices is plausible and that disk/mmap scheduling matters.
- llama.cpp/GGUF is the ecosystem to collaborate with for runtime performance.
- DeepSeek-V4-Flash is a plausible first serious large-model target after a small protocol smoke model.
The platform-specific work remains:
- torrent/content-addressed model artifact marketplace
- tracker-owned route selection and billing
- per-shard local KV sessions
- relay/NAT support
- fraud/reputation/audit
- OpenAI-compatible public gateway

View File

@@ -0,0 +1,412 @@
# Distributed GGUF Technical Challenge Register
This document focuses on the engineering problems that decide whether the distributed GGUF path is viable. The important distinction is:
- **Model artifacts move like torrents.**
- **Inference state moves like a pipeline.**
- **Hot KV state does not move unless we are explicitly checkpointing or repairing a route.**
## Current Constraint
The existing full local PyTorch path lets Transformers own generation and local KV cache.
The existing distributed PyTorch path does not. It manually calls shard layers with cache disabled and recomputes the whole growing prompt for every generated token. It passes hidden activations across shard boundaries, not KV cache, but those activations currently include the full sequence on every decode step.
For a 128K context and `hidden_size=6144`, one bfloat16 activation crossing one shard boundary is roughly:
```text
131072 tokens * 6144 hidden * 2 bytes = 1.5 GiB
```
That is acceptable once during chunked prefill only if chunked and streamed. It is not acceptable once per generated token.
## Challenge 1: Decode Must Be O(1) Per Token Across Each Seam
Problem:
During decode, sending `[batch, sequence, hidden]` over the network scales with context length. At 128K, the network dominates everything.
Solution:
Split execution into explicit **prefill** and **decode-step** phases.
- Prefill accepts prompt chunks and builds local cache on every shard.
- Decode-step accepts exactly one new token or one-step activation.
- Every shard reads its own hot KV state, appends one position, and forwards a one-step activation.
Acceptance test:
- A two-node route prefills a 4K prompt once.
- The next 100 generated tokens do not resend a 4K activation.
- Decode seam payload is proportional to `hidden_size`, not `context_length * hidden_size`.
## Challenge 2: Stable Route Session State
Problem:
KV cache only works if every hop agrees that multiple calls belong to the same route session. A fresh request id per hop or per token destroys cache locality.
Solution:
Introduce a route-session lifecycle.
```text
create route session
-> tracker pins inference route
-> head node assigns session_id and route_id
-> every hop allocates local cache for its layer range
-> prefill chunks append cache
-> decode steps append cache
-> close session releases cache
```
Minimum state key:
```text
session_id
route_id
model_preset
model_revision
backend_id
cache_abi
layer_start
layer_end
position
```
Acceptance test:
- A node can report active sessions and cache bytes by session.
- Closing a session frees the per-shard cache.
- Replaying a decode-step with the wrong route/session fails before model execution.
## Challenge 3: KV Cache Ownership
Problem:
A centralized KV cache sounds attractive for failover, but it puts remote storage in the tightest loop of generation. It also creates privacy and consistency problems.
Solution:
Hot KV state is owned by the node that owns the shard for that route session.
```text
Node A: layers 0..15 hot KV for session S
Node B: layers 16..31 hot KV for session S
Node C: layers 32..77 hot KV for session S
```
The tracker may know where active KV lives, but it does not serve it during decode.
Cache servers may store:
- prefix snapshots
- failover checkpoints
- audit samples
- cold reusable context blocks
They must not be required for every generated token.
Acceptance test:
- Killing a cache server does not affect an active decode route.
- Killing a route node fails the route in alpha unless a compatible snapshot exists.
## Challenge 4: Prefill Is Still Large
Problem:
Even with correct decode, prefill can move a lot of data. A 128K prompt cannot be sent as one activation blob through many shard boundaries.
Solution:
Use the existing binary activation direction from ADR-0008:
- bfloat16 activation body
- shape/dtype/session metadata in headers
- zstd level 1 optional compression
- chunked prefill
- backpressure between hops
For large contexts, prefill should stream in chunks such as 128, 256, or 512 tokens. The right chunk size is a benchmark output, not a constant baked into the domain model.
Acceptance test:
- Peak per-hop prefill memory is bounded by chunk size.
- A slow downstream node applies backpressure instead of letting upstream buffer the whole prompt.
## Challenge 5: GGUF Artifact Splits Are Not Execution Shards
Problem:
GGUF split files can divide model data by size or tensor count. That is useful for storage and transfer, but it is not the same as a network Shard. A Shard in this project is a contiguous layer range with reward, route, and cache meaning.
Solution:
Define an artifact manifest that maps storage chunks to semantic model parts.
Required concepts:
```text
artifact_id
model_preset
upstream_repo
upstream_revision
license
runtime_backend
quantization
context_cap
file_hashes
piece_hashes
tensor_to_layer_map
layer_to_artifact_map
tokenizer_artifacts
cache_descriptor
```
The Shard Swarm seeds artifacts. The Inference Route executes shards.
Acceptance test:
- Given `layers 16..31`, a node can compute the exact artifact pieces it must download and verify.
- Given a local artifact directory, the node can prove which layer ranges it can serve.
## Challenge 6: llama.cpp Is Optimized For Whole-Graph Execution
Problem:
`llama-server` is excellent for local inference, but a distributed route needs lower-level capabilities:
- load selected layers/tensors or mmap them without full materialization
- accept hidden states from a previous shard
- execute only a layer range
- emit hidden states at a boundary
- own KV/state for only that layer range
- report cache layout and memory requirements
Those are not the normal public serving abstractions.
Solution:
Stage the llama.cpp path instead of jumping directly to internet-scale distributed GGUF.
1. Use llama.cpp as a full local GGUF backend for immediate CPU performance.
2. Build a localhost layer-boundary prototype on a simple supported GGUF model.
3. Identify the minimal `libllama`/ggml hooks needed for layer-range execution.
4. Collaborate upstream on a stable extension rather than carrying a long-lived fork.
Acceptance test:
- Process A runs layers `0..k`, exports hidden states.
- Process B imports those hidden states, runs `k+1..n`, and produces logits close to full single-process execution.
- Both processes maintain only their own cache state.
## Challenge 7: Model Architectures Are Not Uniform
Problem:
Dense Llama-style attention, MoE, MLA/DSA, and hybrid linear/full attention do not have the same cache shape, routing cost, or layer cost.
GLM-5.2 uses compressed DSA/MLA-style state. Ornith uses a hybrid attention pattern. Parameter count alone is a poor routing metric.
Solution:
Keep model-specific cache internals inside the backend. The tracker should route based on backend-advertised capabilities and measured telemetry, not on hardcoded tensor formulas.
Backend capability report:
```text
model_arch
supported_runtime
supports_prefill
supports_decode_step
supports_layer_range
supports_partial_artifacts
cache_abi
cache_bytes_per_token_estimate
prefill_tokens_per_second
decode_tokens_per_second
active_memory_floor
```
Acceptance test:
- The tracker can reject a route because one node lacks the required cache ABI.
- A model support audit can say "artifact available, local full inference works, distributed layer-boundary unsupported" without ambiguity.
## Challenge 8: Tensor Parallelism Is Not The Same Product
Problem:
Projects like Distributed Llama and prima.cpp lean toward local-cluster tensor/ring parallelism. That can work on a trusted LAN, but it usually requires tight synchronization every layer. On a public internet volunteer route, that becomes fragile and hard to reward.
Solution:
For the public network, make a Shard a contiguous layer range. Tensor parallelism can exist inside one node, one trusted colocated pod, or one future "composite node", but not as the first public routing primitive.
Acceptance test:
- A public route can be represented as ordered layer coverage.
- Billing can attribute work to layer ranges.
- No cross-node all-reduce is required on every layer for v1.
## Challenge 9: Heterogeneity And Stragglers
Problem:
A route is only as fast as its slowest hop during decode. A weak node holding a bottleneck shard can make a 1.6T model technically available but unusable.
Solution:
Route selection must use measured telemetry, not static declarations.
Metrics:
- prefill throughput
- decode throughput
- queue depth
- disk read rate
- memory pressure
- network latency to neighbors
- route failure rate
- cache warmth
The tracker should prefer complete routes that avoid weak nodes, and the rebalancer should increase redundancy for bottleneck layer ranges.
Acceptance test:
- A slow node is removed from a candidate route even if it has the needed layer range.
- The coverage map can show "covered but under-provisioned" separately from "coverage gap".
## Challenge 10: Reliability And Failover
Problem:
If hot KV is local, route repair is not free. A replacement node cannot continue decoding unless it has compatible cache state.
Solution:
Alpha behavior should be simple:
- route failure during prefill: fail and retry from scratch
- route failure during decode: fail unless compatible snapshot exists
- tracker restart: active sessions may be lost
- node restart: local hot KV is lost
- client-visible telemetry reports the last known phase and failure reason
Later behavior:
- periodic prefix snapshots
- snapshot generation ids
- cache ABI compatibility checks
- route repair only when the replacement node has the same model revision, layer range, backend cache ABI, and snapshot position
Acceptance test:
- Failures produce explicit route-session errors.
- No node silently continues from missing or incompatible cache state.
## Challenge 11: Privacy, Fraud, And Audit
Problem:
Hidden activations and KV state can leak information. Public volunteer inference is not private by default. Also, a node can return bad activations while still appearing available.
Solution:
Separate product modes:
- public swarm: low privacy, broad access, audited
- private swarm: trusted nodes, stronger privacy expectation
- paid trusted route: selected nodes with stronger guarantees
Use existing validation-event and slash-proof concepts for audit, but adapt them to distributed routes:
- record model preset, route, node wallets, prompt metadata, output, and sampling seed
- sample full-route replays where feasible
- compare output/logits within model-specific tolerance
Acceptance test:
- A client can choose public or private route policy.
- A validation event contains enough information to reproduce route membership and observed output.
## Challenge 12: Economics Must Not Reward The Wrong Bottleneck
Problem:
Layer count, parameter count, active MoE experts, cache memory, disk serving, and network transfer are different costs. A naive equal split across nodes will be wrong.
Solution:
Start with simple compute accounting:
```text
node_reward_weight =
owned_layer_work
* prefill_tokens
+ owned_layer_work
* decode_tokens
```
Then refine with:
- measured throughput
- active MoE cost
- storage/seeding contribution
- cache memory reservation
- reliability
Keep artifact seeding rewards separate from inference rewards until fraud and metering are clear.
Acceptance test:
- A node that only seeds artifacts is not paid as if it executed inference.
- A node that executes a heavier shard can earn more than a node executing a light shard.
## Challenge 13: Long Requests Need Streaming Or Realtime Feedback
Problem:
Large distributed routes may spend meaningful time in artifact loading, prefill, queueing, or slow decode. The product can tolerate latency, but users should not wait blindly.
Solution:
Streaming token deltas is preferred when the backend and client transport support it. Generation Telemetry is required regardless of whether token deltas are streamed.
Minimum telemetry:
```text
session_id
route_id
model_preset
phase = queued | loading | prefill | decode | finalizing | failed
prefill_tokens_done
prefill_tokens_total
generated_tokens
rolling_tokens_per_second
average_tokens_per_second
active_route_nodes
failure_reason
```
The gateway may expose token deltas and telemetry through Server-Sent Events or WebSocket. Simple clients may use a polling endpoint for telemetry and receive the final answer only when complete.
Acceptance test:
- A client can show live progress before the first output token is available.
- During decode, the user sees streamed token deltas when supported.
- During decode, the user sees rolling tokens/sec even if output text is not streamed.
- A failed route returns a final error and the last known phase/reason.
## Engineering Order
1. Fix distributed PyTorch cache semantics first. This proves the route-session model without llama.cpp internals.
2. Add local full-model llama.cpp/GGUF serving for immediate CPU improvement.
3. Add Generation Telemetry for route sessions so long requests are observable.
4. Preserve binary HTTP activation transfer while splitting prefill/decode and measuring payload sizes.
5. Add artifact manifest and Shard Swarm metadata.
6. Prototype llama.cpp layer-boundary execution locally.
7. Network the GGUF route only after the cache/session protocol works.
8. Audit DeepSeek-V4-Flash as the first serious large-model target.
9. Audit GLM-5.2 and Ornith support after simpler GGUF models pass the route test.

View File

@@ -22,10 +22,38 @@ _Avoid_: torrent, cluster, pool
An ordered sequence of nodes whose shards together cover all layers of a model. The tracker selects the optimal route per request. An ordered sequence of nodes whose shards together cover all layers of a model. The tracker selects the optimal route per request.
_Avoid_: pipeline, chain, path _Avoid_: pipeline, chain, path
**Route Session**:
An active inference request bound to one Inference Route and one stable session id while the request is being served.
_Avoid_: conversation, job, token stream
**Activation Seam**:
The boundary between two adjacent shard executions where hidden states pass from one node to the next.
_Avoid_: handoff, layer gap, boundary hop
**Hot KV State**:
The live attention/cache state a node holds for its own shard during a Route Session.
_Avoid_: centralized KV cache, global cache, remote cache
**Prefix Snapshot**:
A persisted copy of reusable Route Session state for a prompt prefix, used for reuse, retry, or failover.
_Avoid_: hot cache, CDN cache, active KV
**Model Artifact**:
A versioned model file or tokenizer file that nodes download, verify, and keep locally to serve a Model Preset.
_Avoid_: model blob, weights dump, asset
**Artifact Manifest**:
The canonical record that identifies the Model Artifacts, their integrity checks, and the model parts they support.
_Avoid_: torrent file, metadata JSON, download list
**Gateway**: **Gateway**:
The network entry point that accepts client requests (OpenAI-compatible HTTP), selects an inference route from the tracker, and streams results back. The network entry point that accepts client requests (OpenAI-compatible HTTP), selects an inference route from the tracker, and streams results and progress to the client when possible.
_Avoid_: proxy, relay, orchestrator, primary _Avoid_: proxy, relay, orchestrator, primary
**Generation Telemetry**:
Realtime progress information for an active Route Session, including phase, generated token count, and tokens-per-second speed.
_Avoid_: logs, debug output
### Tracker ### Tracker
**Tracker**: **Tracker**:
@@ -33,7 +61,7 @@ The coordinator service that maintains the node registry, scores nodes by throug
_Avoid_: coordinator, scheduler, director _Avoid_: coordinator, scheduler, director
**Tracker Node**: **Tracker Node**:
A node that serves at least the first-layer shard (`layers[0..k]`) for a model and acts as the inference entry point for that model. Tracker nodes own the tokenizer and `embed_tokens`, receive client requests directly, select the onward route from the coverage map, and stream results back. Any node advertising a new model to the network becomes its tracker node. A node that serves at least the first-layer shard (`layers[0..k]`) for a model and acts as the inference entry point for that model. Tracker nodes own the tokenizer and `embed_tokens`, receive client requests directly, select the onward route from the coverage map, and stream results and progress when possible. Any node advertising a new model to the network becomes its tracker node.
_Avoid_: primary node, master node, gateway node _Avoid_: primary node, master node, gateway node
**Coverage Map**: **Coverage Map**:

View File

@@ -54,6 +54,7 @@ on the host firewall if other machines will join:
```bash ```bash
.venv/bin/meshnet-tracker start --host 0.0.0.0 --port 8080 .venv/bin/meshnet-tracker start --host 0.0.0.0 --port 8080
# --starting-credit 1 --devnet-topup 10
``` ```
Verify from the tracker host: Verify from the tracker host:
@@ -97,6 +98,7 @@ Nodes can then join with either the LAN tracker URL or the public URL:
```bash ```bash
.venv/bin/meshnet-node start --tracker http://192.168.0.179:8080 --model Qwen/Qwen2.5-0.5B-Instruct .venv/bin/meshnet-node start --tracker http://192.168.0.179:8080 --model Qwen/Qwen2.5-0.5B-Instruct
.venv/bin/meshnet-node start --tracker https://ai.neuron.d-popov.com --model Qwen/Qwen2.5-0.5B-Instruct .venv/bin/meshnet-node start --tracker https://ai.neuron.d-popov.com --model Qwen/Qwen2.5-0.5B-Instruct
.venv/bin/meshnet-node start --tracker https://ai.d-popov.com --model Qwen/Qwen2.5-0.5B-Instruct
``` ```
### Windows / WSL2 ### Windows / WSL2
@@ -514,6 +516,7 @@ Send inference through the tracker (which picks the head node and injects the ro
```bash ```bash
curl -s https://ai.neuron.d-popov.com/v1/chat/completions \ curl -s https://ai.neuron.d-popov.com/v1/chat/completions \
-H "Content-Type: application/json" \ -H "Content-Type: application/json" \
-H "Authorization: Bearer sk-mesh-<your-key>" \
-d '{ -d '{
"model": "Qwen/Qwen2.5-0.5B-Instruct", "model": "Qwen/Qwen2.5-0.5B-Instruct",
"messages": [{"role": "user", "content": "What is 7 times 8?"}], "messages": [{"role": "user", "content": "What is 7 times 8?"}],
@@ -529,6 +532,47 @@ curl -s http://localhost:7001/v1/chat/completions \
-d '{"model": "Qwen/Qwen2.5-0.5B-Instruct", "messages": [{"role": "user", "content": "Hi"}]}' -d '{"model": "Qwen/Qwen2.5-0.5B-Instruct", "messages": [{"role": "user", "content": "Hi"}]}'
``` ```
## Accounts, API keys, and credit (billing-enabled trackers)
Public trackers run with billing on: `/v1/chat/completions` requires a real
API key from a registered account. Unknown bearer strings get `401`; a key
with no balance gets `402 insufficient balance`.
**Dashboard flow (easiest):** open `https://<tracker>/dashboard`, register with
an email + password, then click **+ new key**. The key (`sk-mesh-…`) shows its
balance next to it. If the tracker was started with `--starting-credit`, your
first key arrives pre-funded (Caller Credit, once per account). If it was
started with `--devnet-topup`, every key row has a **+$N (devnet)** button to
refill during testing.
**Curl flow:**
```bash
# 1. Register (once)
curl -s https://<tracker>/v1/auth/register \
-H "Content-Type: application/json" \
-d '{"email": "you@example.com", "password": "hunter22-or-better"}'
# → {"session_token": "...", ...}
# 2. Create an API key (session token from step 1)
curl -s https://<tracker>/v1/account/keys -X POST \
-H "Authorization: Bearer <session_token>"
# → {"api_key": "sk-mesh-...", "caller_credit_granted": true}
# 3. Check balance / usage
curl -s https://<tracker>/v1/account -H "Authorization: Bearer <session_token>"
# 4. (devnet trackers only) top up a key
curl -s https://<tracker>/v1/account/topup -X POST \
-H "Authorization: Bearer <session_token>" \
-H "Content-Type: application/json" \
-d '{"api_key": "sk-mesh-..."}'
```
Operator side: both features default to 1 USDT (`--starting-credit` /
`--devnet-topup`). Set both to 0 on mainnet deployments — real deposits flow
through the on-chain USDT treasury watcher instead.
--- ---
## Step 1 — Start the tracker (Terminal 1) ## Step 1 — Start the tracker (Terminal 1)

BIN
accounts.sqlite Normal file

Binary file not shown.

Binary file not shown.

View File

@@ -28,6 +28,9 @@ services:
PUBLIC_RELAY_URL: ${PUBLIC_RELAY_URL:-} PUBLIC_RELAY_URL: ${PUBLIC_RELAY_URL:-}
HEARTBEAT_TIMEOUT: ${HEARTBEAT_TIMEOUT:-30} HEARTBEAT_TIMEOUT: ${HEARTBEAT_TIMEOUT:-30}
ENABLE_BILLING_DB: ${ENABLE_BILLING_DB:-1} ENABLE_BILLING_DB: ${ENABLE_BILLING_DB:-1}
# Devnet-friendly defaults (US-039/040): set both to 0 on mainnet.
STARTING_CREDIT: ${STARTING_CREDIT:-1}
DEVNET_TOPUP: ${DEVNET_TOPUP:-1}
SOLANA_RPC_URL: ${SOLANA_RPC_URL:-} SOLANA_RPC_URL: ${SOLANA_RPC_URL:-}
USDT_MINT: ${USDT_MINT:-} USDT_MINT: ${USDT_MINT:-}
MESHNET_TREASURY_KEYPAIR_B64: ${MESHNET_TREASURY_KEYPAIR_B64:-} MESHNET_TREASURY_KEYPAIR_B64: ${MESHNET_TREASURY_KEYPAIR_B64:-}
@@ -87,6 +90,8 @@ services:
--relay-url "$${RELAY_URL}" \ --relay-url "$${RELAY_URL}" \
--stats-db /var/lib/meshnet/tracker-stats.sqlite \ --stats-db /var/lib/meshnet/tracker-stats.sqlite \
--accounts-db /var/lib/meshnet/accounts.sqlite \ --accounts-db /var/lib/meshnet/accounts.sqlite \
--starting-credit "$${STARTING_CREDIT:-1}" \
--devnet-topup "$${DEVNET_TOPUP:-1}" \
$${BILLING_ARGS} \ $${BILLING_ARGS} \
$${TREASURY_ARGS} \ $${TREASURY_ARGS} \
$${PEER_ARGS} $${PEER_ARGS}

View File

@@ -43,13 +43,27 @@ ENABLE_BILLING_DB=1
``` ```
For first cloud-only test, use `CLUSTER_PEERS=`. Click **Deploy the stack**. For first cloud-only test, use `CLUSTER_PEERS=`. Click **Deploy the stack**.
(`ai.neuron.d-popov.com` is publicly reachable, so two-tracker sync works over the
internet — but add it only after the cloud-only friends test proves out; two-peer
Raft adds moving parts without fault tolerance.)
`ENABLE_BILLING_DB=1` makes billing public behavior active: `/v1/chat/completions` `ENABLE_BILLING_DB=1` makes billing public behavior active: `/v1/chat/completions`
requires `Authorization: Bearer <api-key>`. Any key is accepted and starts with requires `Authorization: Bearer <sk-mesh-...>` — a real API key created through
the configured starter credit; calls return `402` after that balance is an account (register on `/dashboard`, then "+ new key"); arbitrary bearer
strings are rejected with `401`. Calls return `402` once the key's balance is
exhausted. Set `ENABLE_BILLING_DB=0` if existing unauthenticated clients must exhausted. Set `ENABLE_BILLING_DB=0` if existing unauthenticated clients must
keep working during the first redeploy. keep working during the first redeploy.
Credit variables (US-039/US-040):
```text
STARTING_CREDIT=1 # one-time Caller Credit (USDT) on an account's first key
DEVNET_TOPUP=1 # dashboard "+$N (devnet)" faucet button; 0 disables
```
Both default to **1** (devnet-friendly alpha). On any deployment holding a
mainnet treasury set both to 0 — the faucet mints client balance for free.
Optional Solana treasury settlement variables: Optional Solana treasury settlement variables:
```text ```text
@@ -94,7 +108,9 @@ Custom locations on the same proxy host:
Leave sub-folder forwarding empty. Leave sub-folder forwarding empty.
If WebSockets fail, Advanced: **Required:** NPM custom locations do NOT inherit the proxy host's "Websockets
Support" toggle. Paste this into the **Advanced** box of *each* custom location
(`/ws` and `/rpc`), or every WebSocket handshake to the relay dies at nginx:
```nginx ```nginx
proxy_http_version 1.1; proxy_http_version 1.1;

60
docs/dev/test-env.md Normal file
View File

@@ -0,0 +1,60 @@
# Test environment
## Setup
Create a venv at the repo root and install the root dev extras plus the
packages exercised by the tests you're running:
```bash
# Linux/macOS
python3 -m venv .venv
.venv/bin/pip install -e ".[dev]"
.venv/bin/pip install -e packages/node -e packages/tracker -e packages/gateway
```
```powershell
# Windows (native, no WSL)
python -m venv .venv
.venv\Scripts\python.exe -m pip install -e ".[dev]"
.venv\Scripts\python.exe -m pip install -e packages\node -e packages\tracker -e packages\gateway
```
`conftest.py` at the repo root adds every `packages/*` source directory to
`sys.path`, so tests can `import meshnet_node`, `import meshnet_tracker`, etc.
without an editable install. That only resolves first-party modules, though —
each package's own third-party dependencies (e.g. `cryptography` for
`meshnet_node.wallet` and `meshnet_tracker.wallet_proof`) still need to be
installed in the venv, either via `pip install -e packages/<pkg>` or by
depending on the root `dev` extra covering them.
`cryptography>=41` is declared in `packages/node/pyproject.toml` (and
`packages/p2p/pyproject.toml`) and is also pulled in by the root `dev` extra,
so `pip install -e ".[dev]"` alone is enough to run the wallet-related tests
even without installing `packages/node`.
## Running tests
```bash
.venv/bin/python -m pytest
```
## Optional-dependency tests
Some tests import heavyweight or optional third-party packages and guard
themselves with `pytest.importorskip(...)` — they skip cleanly if the
dependency isn't installed:
- `tests/test_real_model_backend.py``torch`, `transformers`, `safetensors`,
`accelerate`, `bitsandbytes`
- `tests/test_devnet_treasury.py``solders`, `spl.token.instructions`
`tests/test_openai_gateway.py` is the exception: it imports `openai` and
`langchain_openai` directly inside test functions with no `importorskip`
guard, so it hard-fails if those aren't installed. They're included in the
root `dev` extra, so a normal `pip install -e ".[dev]"` covers it. If you
deliberately install a minimal environment without the `dev` extra, skip it
explicitly:
```bash
.venv/bin/python -m pytest --ignore=tests/test_openai_gateway.py
```

View File

@@ -1,4 +1,4 @@
Status: ready-for-agent Status: superseded for alpha — see [ADR-0015](../adr/0015-usdt-custodial-settlement.md), issue [33](33-settlement-loop.md)/[34](34-forfeiture-penalty.md). ADR-0015 replaces the on-chain Anchor stake/registry/settlement contracts below with a custodial USDT treasury + off-chain ledger, and explicitly targets **Solana devnet** (with a mock-USDT SPL mint) rather than the "testnet, never devnet" rule stated here — see [ADR-0016](../adr/0016-alpha-scope-and-known-limitations.md) for the alpha scope this fits into.
# 06 — Solana stake + settlement contracts # 06 — Solana stake + settlement contracts

View File

@@ -0,0 +1,88 @@
# US-036 — Streamed chat completions over the relay RPC path
Status: planned
Priority: Critical (blocks public friends-test deployment)
Stage: Designed
## Context
With the tracker deployed on a public VPS (`cloud.neuron.d-popov.com`), every node is
behind NAT, so **every** chat request is proxied tracker → relay → head node via
`_relay_http_request` (`packages/tracker/meshnet_tracker/server.py`). That function does a
single blocking `ws.recv()` and the node's `RelayHttpBridge._handle_request` does a single
`resp.read()`. Two consequences for `stream: true` requests:
1. **No live streaming** — the client sees nothing until generation completes, then
receives the entire SSE body at once with a `Content-Length` header.
2. **Zero billing** — the tracker runs `_billable_non_stream_tokens(json.loads(body))`
on the buffered body; SSE text is not JSON, the parse fails, and the request is
billed/credited as 0 tokens. Off-LAN this silently zeroes out *all* streamed-request
accounting.
Decision (grilled 2026-07-06): implement **true multi-frame streaming** over the relay
RPC WebSocket, scoped to the tracker → head-node leg. Rejected alternatives:
billing-only SSE parse (fragile heuristic, blank-screen UX stays) and forcing
`stream:false` over the relay (exact billing but still no live tokens for testers).
Streaming through the existing SSE accounting loop fixes both symptoms with one
mechanism. Inter-node `/forward` activation hops stay single-frame (ADR-0014) — they
are one-tensor-in/one-tensor-out and gain nothing from chunking.
## Protocol
A relayed response becomes a sequence of `relay-http-response` envelopes sharing one
`request_id`:
```json
// first frame — status + headers, opens the stream
{"request_id": "<id>", "status": 200, "headers": {"Content-Type": "text/event-stream"},
"stream": true, "chunk": "data: {...}\n\n", "done": false}
// zero or more continuation frames
{"request_id": "<id>", "stream": true, "chunk": "data: {...}\n\n", "done": false}
// terminal frame
{"request_id": "<id>", "stream": true, "done": true}
```
**Backward compatibility:** a frame with no `stream` key is a complete single response
(today's format, still used for `/forward` hops, non-SSE responses, and older nodes).
The relay and tracker treat it as terminal.
### Per component
- **Node bridge** (`packages/node/meshnet_node/relay_bridge.py`): when the local
response `Content-Type` is `text/event-stream`, read line-by-line and emit chunk
frames as lines arrive; otherwise keep the existing single-frame path (including
`body_base64` for binary). Frame sends go through the bridge's WS send lock
(US-037) so frames from concurrent requests interleave whole, never torn.
- **Relay server** (`packages/relay/meshnet_relay/server.py`): `_handle_rpc` replaces
the single `asyncio.Future` in `_pending_rpc` with a per-request `asyncio.Queue`.
Frames arriving on the target peer's gossip connection are routed by `request_id`
and forwarded to the requester WS until `done` (or a terminal legacy frame).
Timeouts: keep the 310 s overall cap; add a 120 s per-frame idle timeout so a dead
node doesn't pin the queue.
- **Tracker** (`packages/tracker/meshnet_tracker/server.py`): `_relay_http_request`
grows a streaming mode — loop `ws.recv()`; on the first frame send status/headers to
the client; write each `chunk` to the client immediately and feed it through the
same SSE token-accounting used by the direct-proxy stream loop
(`reported_stream_tokens` / `_record_observed_throughput` / `_bill_completed`), so
relayed streams bill identically to direct streams. Non-stream frames keep the
current buffered handling.
### Known limitation (accepted for alpha)
If the client disconnects mid-stream, the relay drops undeliverable frames but the
node keeps generating until completion — wasted compute bounded by one generation.
Cancellation propagation is future work.
## Acceptance criteria
- `stream: true` chat request via relay delivers SSE chunks to the client
incrementally (test observes ≥2 distinct frame arrivals before `[DONE]`)
- Relayed streamed request records nonzero billed tokens and node work credit
- Non-streamed relayed requests and `/forward` binary hops behave exactly as before
(single frame, `body_base64` round-trip intact)
- Legacy single-frame response from an old node is accepted as terminal
- Idle stream (no frame for 120 s) returns 504 to the client and cleans up the
relay-side queue
- Extend `tests/test_gossip_and_relay.py` alongside
`test_relay_rpc_round_trips_http_request_to_peer`
- `python -m pytest` passes from repo root

View File

@@ -0,0 +1,51 @@
# US-037 — Concurrent request handling in the node relay bridge
Status: planned
Priority: Critical (blocks public friends-test deployment)
Stage: Designed
## Context
`RelayHttpBridge._run` (`packages/node/meshnet_node/relay_bridge.py`) handles
`relay-http-request` envelopes serially inside its recv loop: `_handle_request` blocks
on `urllib.request.urlopen(..., timeout=300)` before the next envelope is read.
Off-LAN this is a correctness bug, not just a throughput limit: a node can be the
**head** of one inference route and a **downstream hop** of another at the same time.
While the head request occupies the bridge (up to 300 s of generation), the other
route's per-token `/forward` calls sit unread in the WebSocket buffer — overlapping
routes through a shared node are effectively broken.
Decision (grilled 2026-07-06): dispatch requests on a **bounded worker pool, default
8, configurable**. Rejected alternatives: unbounded thread-per-request (a public
deployment exposes volunteer machines to request stampedes) and reject-when-full
(bouncing `/forward` hops kills other routes' in-flight sessions; queueing beyond the
cap is today's behavior, just 8-wide).
## Design
- Recv loop only parses envelopes and submits to a
`ThreadPoolExecutor(max_workers=N)`; workers run `_handle_request` and send the
response frame(s).
- All sends on the single relay WebSocket go through a `threading.Lock`. With US-036
a response may be multiple frames — the lock is held **per frame**, so streams from
concurrent requests interleave frame-atomically (receivers demux by `request_id`).
- `N` defaults to 8; configurable via `meshnet-node start --relay-concurrency N`
(env `MESHNET_RELAY_CONCURRENCY`). Requests beyond `N` queue in the executor.
- On reconnect (`_run`'s outer loop), in-flight workers from the dead connection may
still try to send; the send helper swallows failures on a closed socket, and the
relay side times the orphaned request out (US-036 idle timeout / existing 310 s cap).
- `stop()` shuts the executor down without waiting for stragglers (daemon threads,
same as today's bridge thread).
## Acceptance criteria
- While one relayed request is in flight (slow local handler), a second
`relay-http-request` to the same node completes without waiting for the first
- Responses are correctly matched by `request_id` when they complete out of order
- More than `N` simultaneous requests queue and all eventually complete; thread count
never exceeds `N` workers
- Bridge survives a relay reconnect with workers still in flight (no crash, no
deadlock; orphaned responses dropped)
- Extend `tests/test_gossip_and_relay.py`
- `python -m pytest` passes from repo root

View File

@@ -0,0 +1,62 @@
# US-038 — Tracker cluster join via a single seed peer
Status: planned
Priority: High (blocks adding trackers without restarting the fleet)
Stage: Proposed
## Context
Today the tracker cluster is fully static. `RaftNode` and `NodeGossip`
(`packages/tracker/meshnet_tracker/raft.py`, `gossip.py`) take a peer list at
construction and never change it; `/v1/raft/status` does not expose membership.
Consequences of starting a new tracker with only one existing peer in
`--cluster-peers`:
- Existing trackers never learn about the newcomer — they keep heartbeating and
replicating to their original list only.
- Quorum math (`(len(self.peers) + 1) / 2`) differs per tracker, so vote counts
and commit decisions disagree — the cluster silently splits rather than erroring.
Required behavior: a joining tracker is configured with **any one** live tracker
(a seed). It announces itself, the membership change replicates through the Raft
log, and every tracker — including the newcomer — converges on the same full peer
list. Removing the need to restart existing trackers when the hive grows.
## Design
1. **Expose membership.** `GET /v1/cluster/peers` returns
`{"self": <url>, "peers": [<url>, ...]}` (admin-safe: URLs only).
2. **Join handshake.** On startup, the joiner calls the seed's
`POST /v1/cluster/join` with its public self-url. The request is
hive-HMAC-signed (`MESHNET_HIVE_SECRET`, same fail-closed rule as gossip —
an unauthenticated join on a public tracker would let anyone enter the hive).
A non-leader seed forwards to the current leader (same pattern as
`/v1/nodes/register` forwarding).
3. **Membership through the log.** The leader appends a
`cluster-membership` entry (single-server change: add one peer per entry).
`RaftNode` gains `apply`-side handling that swaps `self.peers` — quorum is
recomputed from the applied membership, never from local config. Gossip peer
list updates from the same apply hook.
4. **Joiner bootstrap.** After a successful join response (which includes the
current peer list), the joiner sets its own peers and starts Raft as a
follower; it catches up via normal append-entries.
5. **Persistence.** Applied membership is written to the stats/state sqlite so a
restarted tracker rejoins with the last known list even if its seed is down.
6. **Config semantics.** `--cluster-peers` becomes "seed list": tried in order
until one join succeeds. A tracker with no seeds and no persisted membership
runs standalone (current single-tracker behavior unchanged).
Out of scope: peer removal/eviction (leave via operator restart for now),
joint consensus for multi-server changes, automatic seed retry after startup.
## Acceptance criteria
- Start trackers A+B as a cluster; start C with only A as seed → within one
election timeout, A, B, and C all report the same 3-peer membership on
`GET /v1/cluster/peers`, and a value proposed on C commits on A and B
- Join without a valid hive signature is rejected with 403; join to a follower
is forwarded to the leader transparently
- Restarting C with its seed offline rejoins from persisted membership
- Standalone tracker (no seeds) behaves exactly as today
- `python -m pytest` passes from repo root

View File

@@ -0,0 +1,60 @@
# US-039 — Caller Credit granted once per account; chat requires account keys
Status: planned
Priority: Critical (blocks friends-test inference — every request 402s)
Stage: Designed
## Context
`DEFAULT_STARTING_CREDIT = 0.0` and nothing can raise it: no CLI flag, no admin
credit endpoint. The only funding path is the on-chain USDT deposit watcher —
so on a fresh public tracker every inference request returns
`402 insufficient balance`, including keys created through the working
account flow (`/v1/auth/register``/v1/account/keys`, also in the dashboard).
Separately, the billing gate accepts **any** bearer string (only revoked keys
are rejected), so wiring starter credit into `BillingLedger.ensure_client`
would let anyone mint unlimited free credit by inventing keys.
Decision (grilled 2026-07-06): **Caller Credit is granted once per account**,
when the account creates its first API key; chat requests on an
accounts-enabled tracker must present a real active `sk-mesh-` key.
Rejected: credit-any-bearer (free-inference farming against volunteers' GPUs
on the open internet) and manual-admin-credit-only (operator toil, no
self-serve testing).
## Design
1. **`BillingLedger.grant_caller_credit(api_key, account_id, amount) -> bool`**
Appends a credit event with the deterministic id
`caller-credit-{account_id}` and note `caller-credit`. Already-seen id →
no-op returning False. The deterministic id makes the once-per-account rule
idempotent locally *and* across hive gossip (event dedupe is by id), so a
second key, a retried request, or a replicated event can never double-grant.
2. **`AccountStore.is_active_key(api_key) -> bool`.** The chat billing gate
(`_handle_proxy_chat`) rejects keys that are not active account keys with
`401 invalid_api_key` — but only when an accounts store is configured, so
embedded/test trackers without accounts keep today's any-key behavior.
3. **`--starting-credit N`** (USDT) on `meshnet-tracker start`. Default is the
single constant `DEFAULT_CALLER_CREDIT_USDT = 1.0` in `server.py`
(devnet-friendly alpha, revised 2026-07-06; set 0 on mainnet). Threaded
through `TrackerServer``_TrackerHTTPServer`; registration and
`_handle_account_key_create` call `grant_caller_credit` when billing is on
and the amount is positive. The ledger's own `_starting_credit` stays 0 —
implicit per-key grants in `ensure_client`/`charge_request` remain dead
code paths.
4. **Stack variable `STARTING_CREDIT`** in
`deploy/portainer/meshnet-tracker-nobuild-stack.yml` (default 1).
5. **Docs.** QUICKSTART gains "Get an API key" (register/login/create key via
dashboard or curl, what 402 means); DEPLOY_PORTAINER's stale "any key is
accepted and starts with the configured starter credit" paragraph replaced.
## Acceptance criteria
- Fresh account → first key → key has `--starting-credit` balance; chat succeeds
- Second key on the same account → no additional credit
- Revoke-and-recreate keys → still no additional credit (deterministic event id)
- Random bearer string on an accounts-enabled tracker → 401, never 402/free work
- Tracker without accounts store: gate behavior unchanged
- `--starting-credit 0` disables the grant entirely (mainnet posture)
- `python -m pytest` passes from repo root

View File

@@ -0,0 +1,38 @@
# US-040 — Devnet top-up button on the dashboard
Status: planned
Priority: High (friends-test convenience — refill without on-chain deposits)
Stage: Designed
## Context
Once Caller Credit (US-039) is spent, the only refill path is a real USDT
deposit through the treasury watcher — devnet Solana plumbing friends won't
have. For test deployments the dashboard needs a "add $10" style button.
This is a faucet: 0 disables it, and mainnet deployments must set 0.
## Design
1. **`--devnet-topup N`** (USDT per click) on `meshnet-tracker start`; stack
variable `DEVNET_TOPUP`. Default is the single constant
`DEFAULT_DEVNET_TOPUP_USDT = 1.0` in `server.py` (devnet-friendly alpha,
revised 2026-07-06 — the alpha's public trackers are devnet-only).
2. **`POST /v1/account/topup`** — session-authenticated (same as key
management). Body: `{"api_key": "sk-mesh-..."}`. Rules:
- 404 when the feature is disabled (flag absent/0)
- key must belong to the logged-in account (403 otherwise)
- credits exactly the configured amount (client cannot choose it),
note `devnet-topup`; returns the new balance
3. **Dashboard**: `/v1/account` response gains `topup_amount` (0 when
disabled); when positive, each key row renders a `+$N (devnet)` button
calling the endpoint.
4. **Abuse bound**: per-click amount is operator-set and requires a registered
session; acceptable for a friends-test faucet. Mainnet deployments simply
never set the flag. (Rate limiting is deliberately out of scope.)
## Acceptance criteria
- Flag off: endpoint 404s, dashboard shows no top-up button
- Flag on: logged-in user tops up own key, balance rises by exactly N
- Topping up another account's key → 403
- `python -m pytest` passes from repo root

View File

@@ -0,0 +1,65 @@
# US-041 — Account wallet: browser-extension signing, in-browser generation, export-only
Status: planned
Priority: Medium (not needed for devnet friends test; needed before mainnet)
Stage: Designed
## Context
Registration accepts an optional `wallet` field (a pubkey string) and the
dashboard never shows it. Users need a visible wallet address on the account
panel and a path to real Solana later, without the tracker ever holding user
private keys.
Today wallets matter in two places: client deposit attribution
(`bind_wallet` → deposit watcher) and node payout identity (Pending Balance
keyed by wallet). Accounts themselves hold no keypair — and will stay that way.
## Decision (2026-07-06)
**Non-custodial.** The tracker stores public keys only; private keys never
leave the browser.
1. **External wallets via browser extension.** The dashboard integrates the
standard Solana wallet-adapter flow (Phantom, Solflare, …): connect the
extension, prove ownership by signing a nonce, and the verified pubkey is
stored as the account wallet. All future transaction authorization
(deposits; later, anything requiring a user signature) happens in the
extension — the tracker only ever sees signatures and pubkeys.
2. **New wallets generated in-browser.** For users without an extension the
dashboard generates a keypair client-side (dashboard JS, `Ed25519` via
WebCrypto or bundled tweetnacl — CSP-safe, no CDN). The pubkey is uploaded;
the private key is shown once for export (base58, plaintext acceptable for
devnet) with a "save this now" warning, and optionally kept in
localStorage for convenience on devnet.
3. **No private-key import.** Users cannot paste an existing private key into
the dashboard — accepting foreign private keys is a liability the project
refuses. Users with existing wallets use the extension path (which imports
nothing; it signs in place).
## Scope
- Account panel shows the account wallet address (copy button) or the two
attach flows (connect extension / generate in browser)
- `POST /v1/account/wallet` — session-authenticated; body carries pubkey and,
for the extension flow, the signed-nonce ownership proof (reuse
`wallet_proof.py` if it fits); binds the wallet to the account's keys for
deposit attribution (existing `bind_wallet` path)
- Wallet is per-account; the tracker fans the binding out to the account's
API keys internally
- Mainnet cutover remains config-only (same boundary as Mock USDT, ADR-0015)
Out of scope: password-wrapped keystore export, hardware wallets, changing
the node/miner wallet flow.
## Acceptance criteria
- Connect-extension flow stores a verified pubkey (rejects unsigned/mismatched
nonce proofs)
- Generate flow: pubkey lands on the account; private key is never sent to the
tracker (assert no such field in the request), export works
- No endpoint or UI accepts a private key
- Deposits to the shown address credit the account's keys via the existing
watcher
- Address visible on the account panel after either flow
- `python -m pytest` passes from repo root

View File

@@ -0,0 +1,55 @@
# US-042 — GGUF/llama.cpp node backend
Status: planned
Priority: High (unlocks big MoE models on volunteer hardware — the pool's core value)
Stage: Draft design
## Context
The node backend is transformers-only (`model_backend.py`
`AutoModelForCausalLM`). For DeepSeek-V4-Flash (158B MoE, official weights FP8
160 GB) the only quantizations that run on consumer hardware are GGUF
(IQ2 87 GB → Q4_K_M-XL 175 GB) — llama.cpp format. The transformers-compatible
quants (FP8, NVFP4, GPTQ W4A16) all need datacenter GPUs. Volunteer machines —
including our own Strix Halo boxes (128 GB and 80 GB unified memory, GPU via
Vulkan/ROCm, no FP8 support on RDNA3.5) — run these models today only under
llama.cpp.
## Design directions to evaluate (design-it-twice)
**A. llama.cpp as a per-node shard executor.** Node loads a *layer range* of a
GGUF via llama-cpp-python; our existing hop protocol (X-Meshnet-Route,
activations over HTTP/relay) moves hidden states between nodes. Requires
llama.cpp partial-layer loading and activation import/export — investigate
feasibility first; this is the riskiest unknown.
**B. llama.cpp RPC mode under tracker orchestration.** llama.cpp ships a
native RPC backend that splits one model across machines. The tracker would
provision/route to an llama.cpp RPC cluster rather than our own hop pipeline.
Less code, but bypasses our billing/telemetry hop instrumentation and relay
NAT path — needs a story for both.
**C. Whole-model GGUF nodes (no sharding).** A node with enough memory serves
a full GGUF (e.g. IQ2/IQ3 on a 128 GB box); the tracker routes whole requests
to it (single-hop route). Smallest step, no cross-node activation work, and
already useful: Strix Halo 128 GB serves DeepSeek-V4-Flash IQ3_XXS (114 GB)
via llama.cpp Vulkan today.
Recommended sequencing: C first (small, real value), then A/B investigation.
## Also in scope
- Model catalog: allow GGUF entries with quant selection; feature
`DeepSeek-V4-Flash` IQ4_XS/UD-Q4_K_XL as a curated/featured entry once at
least direction C works (a featured model nobody can load is an anti-feature)
- Hardware detection: recognize Strix Halo/unified-memory APUs and Vulkan
(`hardware.py` currently reports "CPU mode" on these boxes)
- `MESHNET_DOWNLOAD_DIR`/`--download-dir` applies to GGUF files as well
## Acceptance criteria (phase C)
- A node with `--gguf <repo-or-path> --quant IQ3_XXS` serves
`/v1/chat/completions` via llama.cpp with GPU offload where available
- Tracker treats it as a full-coverage node (single-hop routes, billing works)
- Streamed responses work through the tracker proxy and the relay (US-036)
- `python -m pytest` passes from repo root (llama.cpp behind an optional extra)

View File

@@ -0,0 +1,38 @@
# US-043 — Dashboard model search and model cards
Status: planned
Priority: Medium (post-deploy polish)
Stage: Idea
## Context
The dashboard shows nodes/routes/billing but nothing model-centric. Operators
and testers should be able to search for a model and see, per model, a card
with what the network knows about it.
## Scope
- **Search**: query box hitting a new tracker endpoint that proxies the HF Hub
search API (server-side, so the dashboard stays CSP-clean and unauthenticated
browsers aren't rate-limited) merged with the tracker's own model presets and
currently-served models.
- **Model card** per result:
- name, architecture, params, layer count (reuse `model_metadata_for`,
which now handles nested `text_config` — US layer-detection fix)
- coverage on the network: which layer ranges are served, by how many nodes,
coverage gaps (the Coverage Map already exists on the tracker)
- price per 1K tokens, availability (routable now? single-hop or pipeline?)
- memory footprint per quantization where known (bf16 / GGUF sizes)
- action: "request this model" — flags demand so node operators (or
auto-shard assignment) know what to load next
- Featured models section driven by the curated catalog (`CURATED_MODELS`),
including GGUF entries once US-042 lands.
## Acceptance criteria
- Searching a HF repo id or free text returns results without the browser
calling HF directly
- A served model's card shows live coverage and a working "chat now" state
- An unserved model's card shows the "request" action and estimated memory
per quant
- `python -m pytest` passes from repo root

View File

@@ -0,0 +1,103 @@
# US-044 — Tracker as model-file source; nodes download only their shard
Status: in progress
Priority: High (blocks multi-machine big-model serving; pairs with US-042)
Stage: Designed (grill remaining decisions before build)
## Context
Common deployment: the tracker and the first node share a machine that already
holds the model files (e.g. `/run/media/popov/DATA/llm/safetensor`). When a
second node joins with no model selected, the tracker assigns it the uncovered
layer range — and today that node then downloads the **entire snapshot from
HuggingFace**, even for a 20-layer shard of a 160 GB model.
What exists already (build on it, don't duplicate):
- Nodes serve their shard dir as a tar at `GET /v1/shards/download` with
checksum verification; `download_shard` tries assignment-provided `peers`
before HF (`downloader.py`). But it only matches **identical layer ranges**,
and the HF fallback runs `snapshot_download` of the whole repo.
- The torch path (`--model-id`) bypasses `download_shard` entirely:
`TorchModelShard``from_pretrained` downloads **and loads into RAM** the
full model, then executes only the assigned layers. Sharding currently saves
compute, not memory or bandwidth.
## Design
1. **Tracker `--models-dir PATH`** (env `MESHNET_MODELS_DIR`). When set, the
tracker indexes HF-layout snapshots under it and advertises itself as a
model-file source in `/v1/nodes/assign` responses.
2. **Layer-aware file selection.** For safetensors models, read
`model.safetensors.index.json` and map the assigned layer range → the
subset of weight files containing those layers, plus the always-needed
files (config, tokenizer, index, embeddings/head files for head/tail
shards). Serve exactly that subset (tar stream, per-file checksums).
GGUF (US-042): single file or naive byte-range — phase 2.
3. **Node download order**: exact-shard peer (existing) → tracker/peer file
subset (new) → HF `snapshot_download` with `allow_patterns` for the same
subset (new — stop downloading the whole repo even from HF) → full snapshot
(last resort).
- The `allow_patterns` subset must not depend on the tracker having a local
snapshot: when the tracker has no `--models-dir` match for a repo (or
hasn't cached it yet — the common case for a fresh public tracker),
`model_sources` comes back empty and `download_shard` falls straight to
`_download_huggingface_subset(..., allow_patterns=None)`, i.e. the full
repo. Reported 2026-07-06: a CPU node assigned layers 02 of
`unsloth/Qwen3.6-35B-A3B` (42 safetensor shards) sat downloading the
entire model unauthenticated because of this. Fix: fetch
`model.safetensors.index.json` + `config.json` directly from HF (a few
KB) and compute the same layer-scoped file subset client-side, so the
HF-fallback path is filtered even with an empty `model_sources`.
4. **Partial LOAD (the hard half).** Downloading a subset is wasted unless the
node stops instantiating the full model: build the model skeleton on the
`meta` device, materialize only assigned layers (+embeddings/norm/head as
role requires) from the local files, leave the rest on meta. Without this,
an 80 GB machine can never hold a shard of a 160 GB model regardless of
how the bytes arrive. This is the acceptance bar for the issue.
## Open questions (grill before building)
- Trust: joining nodes fetch weights from the tracker/peers — checksum against
what root of trust? (HF etag/sha vs tracker-signed manifest.)
- Disk layout: partial snapshots must not corrupt the HF cache dir; probably
a meshnet-owned layout keyed by repo+revision.
- Serving cost: a 100 GB tar stream per joining node on the tracker box —
rate-limit/queue? LAN-only heuristic?
## Acceptance criteria
- [x] Tracker can be started with `--models-dir PATH` / `MESHNET_MODELS_DIR`
and advertises a local model-file source in assignment responses when it has
a matching HF snapshot.
- [x] Tracker serves a tar stream containing only the safetensors files selected
for the assigned layer range plus config/tokenizer/index metadata.
- [x] Node downloader keeps exact-shard peers first, then races tracker model
sources against a HuggingFace `snapshot_download(..., allow_patterns=...)`
subset download, using the first successful source.
- [x] When no tracker model source is available at all, the HuggingFace
fallback still computes `allow_patterns` from the repo's own
`model.safetensors.index.json` (fetched directly, not via the tracker) —
it never silently downloads the full model just because the tracker has
nothing cached.
- [x] Real PyTorch model startup can use tracker `full_url` sources to fetch
the full local snapshot over LAN before `from_pretrained`, so local-network
testing no longer has to pull from HuggingFace first.
- [ ] Two-machine test: machine A (tracker + node, holds full snapshot) serves
layers 0k; machine B joins with no model and receives **only** the files
for its assigned range from A — nothing fetched from HF
- [ ] Machine B's resident memory scales with its shard size, not model size
- [ ] Checksums verified end-to-end; corrupted transfer falls back cleanly
- [x] Single-node/full-model flows unchanged
- [ ] `python -m pytest` passes from repo root
## Implementation notes
- 2026-07-06: Added the tracker/node download path. For immediate Qwen3.6-35B
LAN testing, real PyTorch nodes fetch the full snapshot from the tracker via
`full_url`; HuggingFace remains fallback-only, and when it is used the node
computes `allow_patterns` from the repo's remote SafeTensors index so it
stays layer-filtered even without tracker-cached files. Remaining hard half
is true partial model materialization: the backend can prefer a downloaded
local model directory, but Transformers still needs a `meta`-device load
path that materializes only assigned layers.

View File

@@ -0,0 +1,60 @@
# US-045 — Dual-rate billing: separate input and output token prices
Status: in progress
Priority: High (billing correctness before friends test; providers all price this way)
Stage: Designed
## Context
Today the ledger has one `price_per_1k_tokens` per model, and the two proxy
paths don't even agree on what they count:
- **Non-streaming** bills `usage.total_tokens` (prompt + completion) at the
blended rate (`_billable_non_stream_tokens`).
- **Streaming** bills `min(observed output deltas, reported total)` — output
only in practice (`_billable_stream_tokens`).
- The HF pricing refresher (issue 23) averages a provider's input/output
rates 50/50 (`blended_price_per_1k_tokens`), which misprices asymmetric
models — e.g. Qwen3.6-35B-A3B on deepinfra is $0.15/1M in, $0.95/1M out.
Decision (user, 2026-07-06): charge **both** input and output tokens, at
**two separate rates**, same as other providers.
## Design
1. **`BillingLedger`** stores `{model: (input_per_1k, output_per_1k)}`.
- `set_prices(model, input_per_1k, output_per_1k)` (new);
`set_price(model, p)` keeps working and sets both.
- `prices_for(model) -> (input, output)` (new); `price_for(model)` returns
the blended average for back-compat (estimators/logs).
- `charge_request(...)` gains keyword `input_tokens`/`output_tokens`; when
provided, `cost = in_rate·in/1k + out_rate·out/1k` and the event records
the split. Without them, legacy behavior (blended × total) — old events
and gossip replicas replay unchanged (`cost` stays the applied field).
2. **Token counting** (`server.py`):
- Non-stream: prefer `usage.prompt_tokens`/`completion_tokens`; fall back
to content estimates (`_estimate_prompt_tokens`, observed completion),
capped by `max_tokens` bounds as today.
- Stream (direct + relay): output = observed deltas as today; input =
`usage.prompt_tokens` when a usage chunk appears, else the prompt
estimate from the request body. `_stream_line_tokens` returns the parsed
usage triple instead of just the total.
3. **Presets**: `input_price_per_1k_tokens` / `output_price_per_1k_tokens`
(dual keys win; `price_per_1k_tokens` alone still means "both rates").
Qwen3.6-35B-A3B: input 0.00012, output 0.00076 (80% of deepinfra).
4. **HF refresher**: applies 80% of each side separately via `set_prices`
(all alias keys); change log keeps recording the blended pair for history
continuity.
5. **Spend cap** (`--max-charge-per-request`): estimate =
`in_rate·prompt_estimate + out_rate·completion_limit`.
## Acceptance criteria
- Streamed and non-streamed requests for the same exchange bill the same
split (input charged in both)
- A model with asymmetric provider rates bills input and output differently;
`usage_for` / billing events expose the split
- Old persisted billing events replay byte-identically (balances unchanged)
- HF refresh sets both rates from the marketplace row, not the average
- Spend cap uses the dual rates
- `python -m pytest` passes from repo root

View File

@@ -0,0 +1,63 @@
# US-046 — Tracker .env awareness + first-node auto-join bootstrap
Status: in progress
Priority: High (blocks the US-044 two-machine test; auto-join dead on fresh trackers)
## Context
Reported 2026-07-06: a node auto-joining a fresh tracker prints
`(auto-join unavailable: HTTP Error 503)` and then cannot download the model
from the tracker. Two independent causes:
1. **Bootstrap chicken-and-egg.** `_handle_network_assign` handles an empty
registry by falling back to the first *deployable* recommended preset — but
deployability is computed from the registered pool only
(`_deployment_summary(all_nodes, preset)`), which is empty, so nothing is
ever deployable and the first node always gets 503. The caller's own
`vram_mb` / `ram_mb` (already sent in the query) are ignored.
2. **Tracker ignores `.env`.** `meshnet-node` loads `.env` (cwd) and
`~/.config/meshnet/secrets.env` at startup; `meshnet-tracker` does not. The
repo `.env` sets `MESHNET_DOWNLOAD_DIR=/run/media/popov/DATA/llm/safetensor/models`,
but the tracker only reads `--models-dir` / `MESHNET_MODELS_DIR`, so
`models_dir` stays unset → `/v1/model-files/download` returns
404 "tracker model-file source is not enabled" and assignments carry no
`model_sources`.
3. **Symlink tars (found while verifying).** HF cache snapshots are symlink
farms into `blobs/`; both the tracker's `/v1/model-files/download` and the
node's `write_shard_archive` tarred the symlinks themselves
(`tarfile` default `dereference=False`), so receivers extracted dangling
links instead of weights.
## Fix
1. In the empty-registry branch of `_handle_network_assign`, synthesize a
candidate `_NodeEntry` from the caller's `vram_mb`/`ram_mb` query params and
include it in the pool used for the deployability gate (and the reported
`deployment` summary), so a recommended preset that fits *pool + caller*
bootstraps the network.
2. Tracker CLI loads env defaults the same way the node CLI does
(`.env` in cwd, then `~/.config/meshnet/secrets.env`, never overriding
already-set env vars).
3. `TrackerServer` models-dir resolution falls back
`--models-dir``MESHNET_MODELS_DIR``MESHNET_DOWNLOAD_DIR` (the node
store and tracker source are the same directory on a box running both).
4. Archive with `dereference=True` in both tar writers so model file contents
ship instead of snapshot symlinks.
## Acceptance criteria
- [x] Fresh tracker (empty registry) + caller with enough memory for a
recommended preset → `/v1/network/assign` returns 200 with that preset,
`gap_found=true`, and `model_sources` populated when the tracker holds a
local snapshot. (Verified live: 128 GB caller got qwen3.6-35b-a3b 039
with tracker `model_sources`.)
- [x] Fresh tracker + caller too small for any recommended preset → still 503.
(Verified live with a 4 GB caller.)
- [x] `meshnet-tracker start` in a directory with `.env` setting
`MESHNET_DOWNLOAD_DIR` serves `/v1/model-files/download` from that dir with
no extra flags. (Verified live; tar entries are regular files, not
symlinks.)
- [x] Explicit `--models-dir` and `MESHNET_MODELS_DIR` still take precedence,
in that order.
- [x] `python -m pytest` passes from repo root (two known env-dependent
failures occur only while a live meshnet-node holds port 7000).

View File

@@ -0,0 +1,115 @@
# US-047 — Tracker-first model downloads: visibility, sane timeouts, RAM-based sizing
Status: in progress
Priority: High (follow-up to US-044/US-046; blocks usable LAN downloads)
## Context
Reported 2026-07-06 (Windows CPU node, 79.2 GB RAM, `--tracker
http://192.168.0.179:8080 --model Qwen3.6-35B-A3B`):
1. Startup prints `(auto-join unavailable: HTTP Error 503)` even though the
user explicitly named a model. The auto-join query (`/v1/network/assign`)
never sends the requested model, so a fresh tracker + a caller too small
for the *recommended* preset 503s (expected per US-046) — but the whole
auto-join step is pointless when the user already picked a model: the
`/v1/nodes/assign?model=…` call right after it succeeds (assigned layers
02 with tracker `model_sources`).
2. The tracker-vs-HuggingFace race then starts, but only HuggingFace shows
progress (hf tqdm bars). The tracker tar download prints nothing and
swallows every failure (`except Exception: return None`), so the node
*appears* to download only from slow HF; the user killed it. Tracker-side
log showed the tar stream reset mid-`archive.add` — with no way to tell
whether the client timed out or the user aborted.
3. `_download_model_source` inherits `peer_timeout` (2.0 s) as its urlopen
socket timeout. Any 2 s read stall during a multi-GB tar stream silently
kills the tracker source and leaves HF as the only contender.
4. Every client abort spams the tracker console with a full
`BrokenPipeError`/`ConnectionResetError` traceback from `socketserver`.
## Fix
1. `startup.py`: skip the network auto-join query entirely when a model was
explicitly requested (`model` set and not `"stub-model"`); path 3b
(`/v1/nodes/assign?model=…`) is the authoritative one there.
2. `downloader.py`: model-source downloads get their own timeout constant
(30 s socket timeout) instead of the 2 s peer-probe timeout. Peer shard
downloads keep 2 s — they run sequentially before the race, and a dead
peer must not hang startup for 30 s; the race is concurrent so a slow
source costs nothing.
3. `downloader.py`: progress + failure visibility for the race —
`_download_model_source` prints received bytes every 512 MB and prints
the exception when a source fails, so "downloads only from HF" can never
happen silently again.
4. Tracker `_handle_model_files_download`: catch
`BrokenPipeError`/`ConnectionResetError` around the tar stream and log a
single line instead of a traceback.
## Design revision (2026-07-06, after live retest)
The race is gone. User decision: **HuggingFace is used only when the model is
not available from a tracker/peer source, or when `--tracker-source-disabled`
is passed.** Sources are tried sequentially with progress + failure output;
HF (layer-filtered via the source file list, else the remote index) is the
fallback.
Second live finding: the node was assigned only layers 02 of 40 on a 79 GB
box. Cause: CPU-mode nodes still report the detected-but-unusable GPU's
`vram_mb` (RTX 4060 → 8192), and shard sizing used VRAM whenever it was > 0
(8 GB × 0.8 ≈ 6.5 GB ≈ 3 layers). Fixed on both sides: the node now sends
`assignment_vram_mb` (0 unless CUDA is actually usable) to `/v1/nodes/assign`,
and the tracker only trusts `vram_mb` when `device=cuda` (all three sizing
sites), falling back to `ram_mb`.
## Acceptance criteria
- [x] Node started with an explicit `--model` never queries
`/v1/network/assign` and never prints `auto-join unavailable`.
- [x] Tracker/peer model source is preferred outright; HF is contacted only
when no source is advertised, every source fails, or
`--tracker-source-disabled` is passed (flag on both CLI parsers, plumbed
through config and `run_startup`).
- [x] Tracker-source downloads print progress every 512 MB and print the
exception + URL on failure; nothing fails silently.
- [x] A ≥2 s read stall no longer aborts a tracker model-source download
(30 s socket timeout).
- [x] Client disconnect during `/v1/model-files/download` logs one line on
the tracker, no traceback.
- [x] CPU node with big RAM gets a RAM-sized shard: `/v1/nodes/assign` and
both `/v1/network/assign` sizing paths ignore VRAM unless `device=cuda`.
- [x] `pytest tests/test_node_startup.py tests/test_tracker_routing.py`
passes (139/140; the one failure is the pre-existing port-dependent
`test_mining_cli` case, present on clean master).
- [ ] Live two-machine retest: Windows node downloads only from tracker at
LAN speed and is assigned a RAM-sized shard.
## Round 3 (2026-07-06, after live retest showed mid-stream RST)
Live retest: RAM sizing worked (layers 036) and the failure finally printed —
`ConnectionResetError(10054)` ~70 s into the tar stream. Local reproduction
cleared the tracker: it streams the full 72 GB tar at ~900 MB/s, survives a
3-minute slow reader, and logs aborts in one line. The RST comes from the
network path (Windows laptop, likely WiFi + firewall/AV) — and a 72 GB
single-TCP-stream tar is inherently fragile there.
Fix: per-file downloads (design principle: nodes must be able to fetch any
missing shard or the complete model from the tracker alone — no hard HF
dependency):
- Tracker: `/v1/model-files/download?...&file=<rel>` streams one file with
`Content-Length` (rel must be in the requested shard/full set; traversal
rejected). `model_sources` now advertises `full_files` and a `file_sizes`
manifest.
- Node: `_download_source_files` fetches per file into
`<shard>.partial/`, retries each file 3×, verifies against
`Content-Length`, and reuses already-complete files (hardlink from the
existing shard) via the size manifest — so restarts and drops cost at most
one file. Tar stream remains the fallback for old trackers
(detected via Content-Type) and sources without a file list.
- `_full_model_sources` passes `full_files` through, so full-snapshot
downloads for the torch path get the same robustness.
Verified live against a local tracker: 14.7 GB shard in 7.6 s per-file;
re-run over a complete shard instant; corrupt + deleted file recovered in
1.5 s re-fetching only those two. 114 tests pass (node_startup +
tracker_routing).

View File

@@ -155,7 +155,8 @@
"US-003" "US-003"
], ],
"completionNotes": "Completed by fresh Ralph/Codex session c257ffde with controller patches for clarified economics; verified by pytest, compileall, and diff check.", "completionNotes": "Completed by fresh Ralph/Codex session c257ffde with controller patches for clarified economics; verified by pytest, compileall, and diff check.",
"status": "done" "status": "done",
"status_reason": "Superseded for alpha by ADR-0015 (US-030..US-035): custodial USDT treasury + off-chain ledger replaces the Anchor stake/registry/settlement contracts, and targets Solana devnet (mock-USDT mint) rather than the testnet-only rule in this story's description. See docs/issues/06-solana-stake-and-settlement.md and ADR-0016."
}, },
{ {
"id": "US-007", "id": "US-007",

BIN
meshnet_registry.sqlite3 Normal file

Binary file not shown.

View File

@@ -7,10 +7,26 @@ replace this adapter later without changing gateway or tracker call sites.
from dataclasses import dataclass, field from dataclasses import dataclass, field
import json import json
import sqlite3
import threading
import time
import urllib.request import urllib.request
import uuid
__version__ = "0.1.0" __version__ = "0.1.0"
# ADR-0018 §6 graduated reputation: slow build, instant loss, inactivity
# decay. Tunable; not derived from any peer/self-report signal.
REPUTATION_MIN = 0.0
REPUTATION_MAX = 1.0
REPUTATION_CLEAN_AUDIT_DELTA = 0.05
REPUTATION_FAILED_AUDIT_DELTA = -0.3
REPUTATION_INACTIVITY_DECAY = 0.05
REPUTATION_INACTIVITY_SECONDS = 30 * 86400.0
# Per-strike routing/payout weight decay — separate from forfeiture, which
# stays full pending balance (ADR-0018 §1, §6).
ROUTING_STRIKE_MULTIPLIER = 0.8
@dataclass(frozen=True) @dataclass(frozen=True)
class RegistryWallet: class RegistryWallet:
@@ -20,6 +36,169 @@ class RegistryWallet:
strike_count: int = 0 strike_count: int = 0
banned: bool = False banned: bool = False
completed_job_count: int = 0 completed_job_count: int = 0
reputation: float = 1.0
last_audit_ts: float | None = None
last_active_ts: float | None = None
@property
def routing_multiplier(self) -> float:
"""ADR-0018 §6: ×0.8 routing/payout weight decay per strike."""
return ROUTING_STRIKE_MULTIPLIER ** self.strike_count
class RegistryEventLog:
"""Thread-safe registry wallet event log with SQLite persistence."""
def __init__(self, state: "_LocalContractState", db_path: str | None = None) -> None:
self._state = state
self._db_path = db_path
self._lock = threading.Lock()
self._seen_event_ids: set[str] = set()
self._event_log: list[dict] = []
self._dirty = False
if self._db_path:
self._init_db()
self._load_from_db()
def events_since(self, index: int) -> tuple[list[dict], int]:
with self._lock:
return list(self._event_log[index:]), len(self._event_log)
def apply_events(self, events: list[dict]) -> int:
applied = 0
with self._lock:
for event in events:
event_id = event.get("id")
if not event_id or event_id in self._seen_event_ids:
continue
self._apply_locked(event)
applied += 1
return applied
def record(self, event: dict) -> None:
with self._lock:
self._apply_locked(event)
def _apply_locked(self, event: dict) -> None:
etype = event.get("type")
wallet_address = event.get("wallet")
if not isinstance(wallet_address, str) or not wallet_address:
return
current = self._state.registry.get(wallet_address, RegistryWallet())
updated: RegistryWallet | None = None
if etype == "stake":
updated = _registry_wallet_with(current, stake_balance=current.stake_balance + int(event["amount"]))
elif etype == "strike":
strike_count = current.strike_count + int(event.get("count", 1))
updated = _registry_wallet_with(
current,
strike_count=strike_count,
banned=current.banned or strike_count >= int(event.get("ban_threshold", 3)),
)
elif etype == "slash":
strike_count = current.strike_count + 1
updated = _registry_wallet_with(
current,
stake_balance=max(0, current.stake_balance - int(event["slash_amount"])),
strike_count=strike_count,
banned=current.banned or strike_count >= int(event.get("strike_threshold", 3)),
)
elif etype == "ban":
updated = _registry_wallet_with(current, banned=True)
elif etype == "completed_job":
updated = _registry_wallet_with(
current,
completed_job_count=current.completed_job_count + int(event.get("count", 1)),
last_active_ts=float(event.get("ts", time.time())),
)
elif etype == "set_reputation":
updated = _registry_wallet_with(current, reputation=float(event["reputation"]))
elif etype == "audit":
updated = _registry_wallet_with(current, last_audit_ts=float(event["ts"]))
elif etype == "audit_outcome":
# ADR-0018 §6: reputation moves only from tracker-verified audit
# outcomes. Strike/ban stay on the existing slash/strike events —
# this event never touches strike_count to avoid double-counting
# a single failed audit that already went through submit_slash_proof.
delta = REPUTATION_CLEAN_AUDIT_DELTA if event["passed"] else REPUTATION_FAILED_AUDIT_DELTA
reputation = min(REPUTATION_MAX, max(REPUTATION_MIN, current.reputation + delta))
updated = _registry_wallet_with(
current,
reputation=reputation,
last_audit_ts=float(event.get("ts", time.time())),
)
elif etype == "inactivity_decay":
reputation = max(
REPUTATION_MIN,
current.reputation - float(event.get("amount", REPUTATION_INACTIVITY_DECAY)),
)
updated = _registry_wallet_with(
current,
reputation=reputation,
# Resets the idle clock so decay applies at most once per window.
last_active_ts=float(event.get("ts", time.time())),
)
else:
return
self._state.registry[wallet_address] = updated
self._seen_event_ids.add(event["id"])
self._event_log.append(event)
self._dirty = True
def _init_db(self) -> None:
con = sqlite3.connect(self._db_path) # type: ignore[arg-type]
con.execute(
"CREATE TABLE IF NOT EXISTS registry_events "
"(event_id TEXT PRIMARY KEY, payload TEXT NOT NULL, ts REAL NOT NULL)"
)
con.commit()
con.close()
def _load_from_db(self) -> None:
con = sqlite3.connect(self._db_path) # type: ignore[arg-type]
rows = con.execute(
"SELECT payload FROM registry_events ORDER BY ts, event_id"
).fetchall()
con.close()
with self._lock:
for (payload,) in rows:
try:
event = json.loads(payload)
except json.JSONDecodeError:
continue
if event.get("id") not in self._seen_event_ids:
self._apply_locked(event)
self._dirty = False
def save_to_db(self) -> None:
if not self._db_path:
return
with self._lock:
if not self._dirty:
return
events = list(self._event_log)
self._dirty = False
con = sqlite3.connect(self._db_path) # type: ignore[arg-type]
con.executemany(
"INSERT OR IGNORE INTO registry_events (event_id, payload, ts) VALUES (?, ?, ?)",
[(e["id"], json.dumps(e), float(e.get("ts", 0.0))) for e in events],
)
con.commit()
con.close()
def _registry_wallet_with(wallet: RegistryWallet, **changes: object) -> RegistryWallet:
values = {
"stake_balance": wallet.stake_balance,
"strike_count": wallet.strike_count,
"banned": wallet.banned,
"completed_job_count": wallet.completed_job_count,
"reputation": wallet.reputation,
"last_audit_ts": wallet.last_audit_ts,
"last_active_ts": wallet.last_active_ts,
}
values.update(changes)
return RegistryWallet(**values)
@dataclass(frozen=True) @dataclass(frozen=True)
@@ -62,6 +241,7 @@ class ValidationEvent:
messages: list[dict] messages: list[dict]
observed_output: str observed_output: str
route_nodes: list[dict] route_nodes: list[dict]
ts: float = field(default_factory=time.time)
@dataclass(frozen=True) @dataclass(frozen=True)
@@ -103,34 +283,34 @@ class _LocalContractState:
class RegistryContract: class RegistryContract:
"""Registry wrapper for node stake, strikes, and bans.""" """Registry wrapper for node stake, strikes, and bans."""
def __init__(self, state: _LocalContractState, cluster: str) -> None: def __init__(self, state: _LocalContractState, cluster: str, event_log: RegistryEventLog) -> None:
self._state = state self._state = state
self._cluster = cluster self._cluster = cluster
self._event_log = event_log
def submit_stake(self, wallet_address: str, amount: int) -> dict: def submit_stake(self, wallet_address: str, amount: int) -> dict:
if amount <= 0: if amount <= 0:
raise ValueError("stake amount must be positive") raise ValueError("stake amount must be positive")
current = self.get_wallet(wallet_address) self._event_log.record({
self._state.registry[wallet_address] = RegistryWallet( "id": f"stake-{uuid.uuid4().hex}",
stake_balance=current.stake_balance + amount, "type": "stake",
strike_count=current.strike_count, "wallet": wallet_address,
banned=current.banned, "amount": amount,
completed_job_count=current.completed_job_count, "ts": time.time(),
) })
return {"signature": f"local-stake-{wallet_address}", "cluster": self._cluster} return {"signature": f"local-stake-{wallet_address}", "cluster": self._cluster}
def get_wallet(self, wallet_address: str) -> RegistryWallet: def get_wallet(self, wallet_address: str) -> RegistryWallet:
return self._state.registry.get(wallet_address, RegistryWallet()) return self._state.registry.get(wallet_address, RegistryWallet())
def record_strike(self, wallet_address: str, ban_threshold: int = 3) -> dict: def record_strike(self, wallet_address: str, ban_threshold: int = 3) -> dict:
current = self.get_wallet(wallet_address) self._event_log.record({
strike_count = current.strike_count + 1 "id": f"strike-{uuid.uuid4().hex}",
self._state.registry[wallet_address] = RegistryWallet( "type": "strike",
stake_balance=current.stake_balance, "wallet": wallet_address,
strike_count=strike_count, "ban_threshold": ban_threshold,
banned=current.banned or strike_count >= ban_threshold, "ts": time.time(),
completed_job_count=current.completed_job_count, })
)
return {"signature": f"local-strike-{wallet_address}", "cluster": self._cluster} return {"signature": f"local-strike-{wallet_address}", "cluster": self._cluster}
def submit_slash_proof( def submit_slash_proof(
@@ -150,24 +330,24 @@ class RegistryContract:
raise ValueError("strike_threshold must be positive") raise ValueError("strike_threshold must be positive")
current = self.get_wallet(wallet_address) current = self.get_wallet(wallet_address)
stake_after = max(0, current.stake_balance - slash_amount) self._event_log.record({
strike_count = current.strike_count + 1 "id": f"slash-{uuid.uuid4().hex}",
banned = current.banned or strike_count >= strike_threshold "type": "slash",
self._state.registry[wallet_address] = RegistryWallet( "wallet": wallet_address,
stake_balance=stake_after, "slash_amount": slash_amount,
strike_count=strike_count, "strike_threshold": strike_threshold,
banned=banned, "ts": time.time(),
completed_job_count=current.completed_job_count, })
) updated = self.get_wallet(wallet_address)
receipt = SlashReceipt( receipt = SlashReceipt(
signature=f"local-slash-{wallet_address}-{len(self._state.slash_receipts) + 1}", signature=f"local-slash-{wallet_address}-{len(self._state.slash_receipts) + 1}",
cluster=self._cluster, cluster=self._cluster,
wallet_address=wallet_address, wallet_address=wallet_address,
slash_amount=slash_amount, slash_amount=slash_amount,
stake_before=current.stake_balance, stake_before=current.stake_balance,
stake_after=stake_after, stake_after=updated.stake_balance,
strike_count=strike_count, strike_count=updated.strike_count,
banned=banned, banned=updated.banned,
reason=reason, reason=reason,
) )
self._state.slash_receipts.append(receipt) self._state.slash_receipts.append(receipt)
@@ -175,13 +355,12 @@ class RegistryContract:
return receipt return receipt
def ban_wallet(self, wallet_address: str) -> dict: def ban_wallet(self, wallet_address: str) -> dict:
current = self.get_wallet(wallet_address) self._event_log.record({
self._state.registry[wallet_address] = RegistryWallet( "id": f"ban-{uuid.uuid4().hex}",
stake_balance=current.stake_balance, "type": "ban",
strike_count=current.strike_count, "wallet": wallet_address,
banned=True, "ts": time.time(),
completed_job_count=current.completed_job_count, })
)
return {"signature": f"local-ban-{wallet_address}", "cluster": self._cluster} return {"signature": f"local-ban-{wallet_address}", "cluster": self._cluster}
def has_minimum_stake(self, wallet_address: str | None, minimum_stake: int) -> bool: def has_minimum_stake(self, wallet_address: str | None, minimum_stake: int) -> bool:
@@ -195,20 +374,91 @@ class RegistryContract:
return dict(self._state.registry) return dict(self._state.registry)
def record_completed_job(self, wallet_address: str) -> RegistryWallet: def record_completed_job(self, wallet_address: str) -> RegistryWallet:
current = self.get_wallet(wallet_address) self.record_completed_jobs(wallet_address, 1)
updated = RegistryWallet( return self.get_wallet(wallet_address)
stake_balance=current.stake_balance,
strike_count=current.strike_count, def record_completed_jobs(self, wallet_address: str, count: int, *, ts: float | None = None) -> RegistryWallet:
banned=current.banned, if count <= 0:
completed_job_count=current.completed_job_count + 1, raise ValueError("completed job count must be positive")
) self._event_log.record({
self._state.registry[wallet_address] = updated "id": f"job-{uuid.uuid4().hex}",
return updated "type": "completed_job",
"wallet": wallet_address,
"count": count,
"ts": time.time() if ts is None else ts,
})
return self.get_wallet(wallet_address)
def set_reputation(self, wallet_address: str, reputation: float) -> RegistryWallet:
self._event_log.record({
"id": f"reputation-{uuid.uuid4().hex}",
"type": "set_reputation",
"wallet": wallet_address,
"reputation": reputation,
"ts": time.time(),
})
return self.get_wallet(wallet_address)
def record_audit(self, wallet_address: str, ts: float | None = None) -> RegistryWallet:
audit_ts = time.time() if ts is None else ts
self._event_log.record({
"id": f"audit-{uuid.uuid4().hex}",
"type": "audit",
"wallet": wallet_address,
"ts": audit_ts,
})
return self.get_wallet(wallet_address)
def probationary_jobs_remaining(self, wallet_address: str) -> int: def probationary_jobs_remaining(self, wallet_address: str) -> int:
wallet = self.get_wallet(wallet_address) wallet = self.get_wallet(wallet_address)
return max(0, self._state.probationary_job_count - wallet.completed_job_count) return max(0, self._state.probationary_job_count - wallet.completed_job_count)
def record_audit_outcome(self, wallet_address: str, *, passed: bool, ts: float | None = None) -> RegistryWallet:
"""ADR-0018 §6: the only reputation signal — clean audits build score
slowly, a failed audit loses it instantly. Strikes/bans are recorded
separately (`record_strike` / `submit_slash_proof`) so a single
failed audit is never double-counted as two strikes."""
self._event_log.record({
"id": f"audit-outcome-{uuid.uuid4().hex}",
"type": "audit_outcome",
"wallet": wallet_address,
"passed": passed,
"ts": time.time() if ts is None else ts,
})
return self.get_wallet(wallet_address)
def routing_multiplier(self, wallet_address: str) -> float:
"""ADR-0018 §6: ×0.8 routing/payout weight per strike, separate from
the forfeiture penalty (which stays full pending balance)."""
return self.get_wallet(wallet_address).routing_multiplier
def apply_inactivity_decay(
self,
*,
idle_seconds: float = REPUTATION_INACTIVITY_SECONDS,
decay_amount: float = REPUTATION_INACTIVITY_DECAY,
now: float | None = None,
) -> dict[str, RegistryWallet]:
"""ADR-0018 §6: reputation decays for wallets with no completed job
in `idle_seconds`. Decaying resets the idle clock, so a wallet decays
at most once per idle window rather than every call while still idle."""
current_ts = time.time() if now is None else now
decayed: dict[str, RegistryWallet] = {}
for wallet_address, wallet in list(self._state.registry.items()):
if wallet.banned or wallet.last_active_ts is None:
continue
if current_ts - wallet.last_active_ts < idle_seconds:
continue
self._event_log.record({
"id": f"inactivity-decay-{uuid.uuid4().hex}",
"type": "inactivity_decay",
"wallet": wallet_address,
"amount": decay_amount,
"ts": current_ts,
})
decayed[wallet_address] = self.get_wallet(wallet_address)
return decayed
class ValidationContract: class ValidationContract:
"""Validation event log consumed by the optimistic fraud detector.""" """Validation event log consumed by the optimistic fraud detector."""
@@ -224,6 +474,7 @@ class ValidationContract:
messages: list[dict], messages: list[dict],
observed_output: str, observed_output: str,
route_nodes: list[dict], route_nodes: list[dict],
ts: float | None = None,
) -> ValidationEvent: ) -> ValidationEvent:
if not session_id: if not session_id:
raise ValueError("session_id is required") raise ValueError("session_id is required")
@@ -242,6 +493,7 @@ class ValidationContract:
messages=[dict(message) for message in messages], messages=[dict(message) for message in messages],
observed_output=observed_output, observed_output=observed_output,
route_nodes=[dict(node) for node in route_nodes], route_nodes=[dict(node) for node in route_nodes],
**({"ts": ts} if ts is not None else {}),
) )
self._state.validation_events.append(event) self._state.validation_events.append(event)
return event return event
@@ -331,10 +583,12 @@ class SettlementContract:
state: _LocalContractState, state: _LocalContractState,
cluster: str, cluster: str,
cost_per_layer_token_lamport: int, cost_per_layer_token_lamport: int,
registry: RegistryContract,
) -> None: ) -> None:
self._state = state self._state = state
self._cluster = cluster self._cluster = cluster
self._cost_per_layer_token_lamport = cost_per_layer_token_lamport self._cost_per_layer_token_lamport = cost_per_layer_token_lamport
self._registry = registry
def settle_epoch( def settle_epoch(
self, self,
@@ -423,13 +677,7 @@ class SettlementContract:
return self._state.token_balances.get(wallet_address, 0) return self._state.token_balances.get(wallet_address, 0)
def _record_completed_jobs(self, wallet_address: str, count: int) -> None: def _record_completed_jobs(self, wallet_address: str, count: int) -> None:
current = self._state.registry.get(wallet_address, RegistryWallet()) self._registry.record_completed_jobs(wallet_address, count)
self._state.registry[wallet_address] = RegistryWallet(
stake_balance=current.stake_balance,
strike_count=current.strike_count,
banned=current.banned,
completed_job_count=current.completed_job_count + count,
)
def deployment_plan(self) -> dict: def deployment_plan(self) -> dict:
"""Return the configured manual testnet deployment targets.""" """Return the configured manual testnet deployment targets."""
@@ -449,6 +697,7 @@ class LocalSolanaContracts:
cost_per_layer_token_lamport: int = 1, cost_per_layer_token_lamport: int = 1,
starting_credit_lamports: int = 1_000, starting_credit_lamports: int = 1_000,
probationary_job_count: int = 50, probationary_job_count: int = 50,
registry_db: str | None = None,
) -> None: ) -> None:
if cost_per_layer_token_lamport <= 0: if cost_per_layer_token_lamport <= 0:
raise ValueError("cost_per_layer_token_lamport must be positive") raise ValueError("cost_per_layer_token_lamport must be positive")
@@ -459,15 +708,20 @@ class LocalSolanaContracts:
self.cluster = cluster self.cluster = cluster
self._state = _LocalContractState() self._state = _LocalContractState()
self._state.probationary_job_count = probationary_job_count self._state.probationary_job_count = probationary_job_count
self.registry = RegistryContract(self._state, cluster) self.registry_log = RegistryEventLog(self._state, registry_db)
self.registry = RegistryContract(self._state, cluster, self.registry_log)
self.validation = ValidationContract(self._state) self.validation = ValidationContract(self._state)
self.payment = PaymentContract(self._state, cluster, starting_credit_lamports) self.payment = PaymentContract(self._state, cluster, starting_credit_lamports)
self.settlement = SettlementContract( self.settlement = SettlementContract(
self._state, self._state,
cluster, cluster,
cost_per_layer_token_lamport, cost_per_layer_token_lamport,
self.registry,
) )
def save_to_db(self) -> None:
self.registry_log.save_to_db()
def _notify_slash(receipt: SlashReceipt, webhook_url: str | None) -> None: def _notify_slash(receipt: SlashReceipt, webhook_url: str | None) -> None:
message = ( message = (
@@ -503,7 +757,15 @@ __all__ = [
"ComputeAttribution", "ComputeAttribution",
"LocalSolanaContracts", "LocalSolanaContracts",
"PaymentContract", "PaymentContract",
"REPUTATION_CLEAN_AUDIT_DELTA",
"REPUTATION_FAILED_AUDIT_DELTA",
"REPUTATION_INACTIVITY_DECAY",
"REPUTATION_INACTIVITY_SECONDS",
"REPUTATION_MAX",
"REPUTATION_MIN",
"ROUTING_STRIKE_MULTIPLIER",
"RegistryContract", "RegistryContract",
"RegistryEventLog",
"RegistryWallet", "RegistryWallet",
"SettlementContract", "SettlementContract",
"SettlementResult", "SettlementResult",

View File

@@ -3,12 +3,45 @@
from __future__ import annotations from __future__ import annotations
import argparse import argparse
import os
import socket import socket
import sys import sys
import time import time
from pathlib import Path from pathlib import Path
def _load_env_file(path: Path) -> None:
"""Load simple KEY=VALUE pairs from an env file without overriding env vars."""
if not path.exists():
return
try:
lines = path.read_text().splitlines()
except OSError:
return
for line in lines:
text = line.strip()
if not text or text.startswith("#"):
continue
if text.startswith("export "):
text = text[len("export "):].strip()
if "=" not in text:
continue
key, value = text.split("=", 1)
key = key.strip()
if not key or key in os.environ:
continue
value = value.strip()
if len(value) >= 2 and value[0] == value[-1] and value[0] in {"'", '"'}:
value = value[1:-1]
os.environ[key] = value
def _load_env_defaults() -> None:
"""Load local and user-level node env defaults before config defaults are imported."""
_load_env_file(Path.cwd() / ".env")
_load_env_file(Path.home() / ".config" / "meshnet" / "secrets.env")
def _run_node(cfg: dict) -> None: def _run_node(cfg: dict) -> None:
"""Start the node and hand off to the live dashboard. Blocks until Ctrl-C.""" """Start the node and hand off to the live dashboard. Blocks until Ctrl-C."""
from .startup import run_startup from .startup import run_startup
@@ -19,11 +52,11 @@ def _run_node(cfg: dict) -> None:
node = run_startup( node = run_startup(
tracker_url=cfg["tracker_url"], tracker_url=cfg["tracker_url"],
port=cfg.get("port", 7000), port=cfg.get("port", 7000),
model=cfg.get("model_name") or "stub-model", model=cfg.get("model_name") or None,
model_id=cfg.get("model_hf_repo") or None, model_id=cfg.get("model_hf_repo") or None,
shard_start=cfg.get("shard_start"), shard_start=cfg.get("shard_start"),
shard_end=cfg.get("shard_end"), shard_end=cfg.get("shard_end"),
quantization=cfg.get("quantization", "int8").replace("bf16", "bfloat16"), quantization=cfg.get("quantization", "auto").replace("bf16", "bfloat16"),
wallet_path=Path(cfg["wallet_path"]) if cfg.get("wallet_path") else None, wallet_path=Path(cfg["wallet_path"]) if cfg.get("wallet_path") else None,
cache_dir=Path(cfg["download_dir"]) if cfg.get("download_dir") else None, cache_dir=Path(cfg["download_dir"]) if cfg.get("download_dir") else None,
host=cfg.get("host", "0.0.0.0"), host=cfg.get("host", "0.0.0.0"),
@@ -32,6 +65,9 @@ def _run_node(cfg: dict) -> None:
vram_mb_override=cfg.get("vram_mb_override"), vram_mb_override=cfg.get("vram_mb_override"),
max_loaded_shards=int(cfg.get("max_loaded_shards", 1)), max_loaded_shards=int(cfg.get("max_loaded_shards", 1)),
debug=bool(cfg.get("debug", False)), debug=bool(cfg.get("debug", False)),
tracker_source_disabled=bool(cfg.get("tracker_source_disabled", False)),
torch_threads=cfg.get("torch_threads"),
torch_interop_threads=cfg.get("torch_interop_threads"),
) )
except Exception as exc: except Exception as exc:
print(f"\nERROR: {exc}", file=sys.stderr, flush=True) print(f"\nERROR: {exc}", file=sys.stderr, flush=True)
@@ -54,6 +90,19 @@ def _run_node(cfg: dict) -> None:
) )
def _resolve_model_flags(
model: str | None,
model_id: str | None,
) -> tuple[str | None, str | None]:
"""Return (model_name, hf_repo_or_none) from --model / --model-id flags."""
explicit = model_id or model
if not explicit:
return None, None
if "/" in explicit:
return explicit.split("/")[-1], explicit
return explicit, None
def _first_available_port(host: str, start: int = 7000, attempts: int = 100) -> int: def _first_available_port(host: str, start: int = 7000, attempts: int = 100) -> int:
"""Return the first TCP port bindable on host, starting at start.""" """Return the first TCP port bindable on host, starting at start."""
bind_host = "" if host == "0.0.0.0" else host bind_host = "" if host == "0.0.0.0" else host
@@ -86,9 +135,10 @@ def _cmd_default(args) -> int:
# Apply CLI overrides on top of saved config # Apply CLI overrides on top of saved config
overrides: dict = {} overrides: dict = {}
if args.model: model_name, hf_repo = _resolve_model_flags(args.model, getattr(args, "model_id", None))
overrides["model_hf_repo"] = args.model if model_name is not None:
overrides["model_name"] = args.model.split("/")[-1] overrides["model_name"] = model_name
overrides["model_hf_repo"] = hf_repo or ""
if args.quantization: if args.quantization:
overrides["quantization"] = args.quantization overrides["quantization"] = args.quantization
if args.download_dir: if args.download_dir:
@@ -115,6 +165,12 @@ def _cmd_default(args) -> int:
overrides["max_loaded_shards"] = args.max_shards overrides["max_loaded_shards"] = args.max_shards
if args.debug: if args.debug:
overrides["debug"] = True overrides["debug"] = True
if getattr(args, "tracker_source_disabled", False):
overrides["tracker_source_disabled"] = True
if getattr(args, "torch_threads", None) is not None:
overrides["torch_threads"] = args.torch_threads
if getattr(args, "torch_interop_threads", None) is not None:
overrides["torch_interop_threads"] = args.torch_interop_threads
if overrides: if overrides:
cfg = merge_cli_overrides(cfg, **overrides) cfg = merge_cli_overrides(cfg, **overrides)
@@ -166,21 +222,22 @@ def _cmd_config(args) -> int:
def _cmd_start(args) -> int: def _cmd_start(args) -> int:
"""Legacy `start` subcommand — preserves backward compatibility with existing tests.""" """Legacy `start` subcommand — preserves backward compatibility with existing tests."""
from .config import load_config, DEFAULTS from .config import DEFAULTS
# Build a transient config from flags (don't write to disk) # Build a transient config from flags (don't write to disk)
cfg = dict(DEFAULTS) cfg = dict(DEFAULTS)
cfg["tracker_url"] = args.tracker if args.tracker:
cfg["tracker_url"] = args.tracker
cfg["port"] = args.port if args.port is not None else _first_available_port(args.host) cfg["port"] = args.port if args.port is not None else _first_available_port(args.host)
if args.model_id is None and "/" in args.model: model_name, hf_repo = _resolve_model_flags(
cfg["model_hf_repo"] = args.model args.model or cfg.get("model_hf_repo") or cfg.get("model_name") or None,
cfg["model_name"] = args.model.split("/")[-1] args.model_id,
else: )
cfg["model_name"] = args.model if model_name is not None:
cfg["model_name"] = model_name
cfg["model_hf_repo"] = hf_repo or ""
cfg["quantization"] = args.quantization cfg["quantization"] = args.quantization
cfg["host"] = args.host cfg["host"] = args.host
if args.model_id:
cfg["model_hf_repo"] = args.model_id
if args.shard_start is not None: if args.shard_start is not None:
cfg["shard_start"] = args.shard_start cfg["shard_start"] = args.shard_start
if args.shard_end is not None: if args.shard_end is not None:
@@ -198,7 +255,7 @@ def _cmd_start(args) -> int:
tracker_url=cfg["tracker_url"], tracker_url=cfg["tracker_url"],
port=cfg["port"], port=cfg["port"],
model=cfg["model_name"], model=cfg["model_name"],
model_id=cfg.get("model_hf_repo"), model_id=cfg.get("model_hf_repo") or None,
shard_start=cfg.get("shard_start"), shard_start=cfg.get("shard_start"),
shard_end=cfg.get("shard_end"), shard_end=cfg.get("shard_end"),
quantization=cfg["quantization"].replace("bf16", "bfloat16"), quantization=cfg["quantization"].replace("bf16", "bfloat16"),
@@ -210,6 +267,9 @@ def _cmd_start(args) -> int:
vram_mb_override=getattr(args, "memory", None), vram_mb_override=getattr(args, "memory", None),
max_loaded_shards=getattr(args, "max_shards", 1), max_loaded_shards=getattr(args, "max_shards", 1),
debug=getattr(args, "debug", False), debug=getattr(args, "debug", False),
tracker_source_disabled=getattr(args, "tracker_source_disabled", False),
torch_threads=getattr(args, "torch_threads", None),
torch_interop_threads=getattr(args, "torch_interop_threads", None),
) )
except Exception as exc: except Exception as exc:
print(f"ERROR: {exc}", file=sys.stderr, flush=True) print(f"ERROR: {exc}", file=sys.stderr, flush=True)
@@ -224,6 +284,8 @@ def _cmd_start(args) -> int:
def main() -> None: def main() -> None:
_load_env_defaults()
parser = argparse.ArgumentParser( parser = argparse.ArgumentParser(
prog="meshnet-node", prog="meshnet-node",
description="Distributed AI Inference — Node Client", description="Distributed AI Inference — Node Client",
@@ -239,11 +301,14 @@ def main() -> None:
) )
# Flags that apply to the no-subcommand (default) path # Flags that apply to the no-subcommand (default) path
parser.add_argument("--model", metavar="HF_REPO", help="HuggingFace repo ID to serve") parser.add_argument("--model", metavar="MODEL", help="Model name or HuggingFace repo ID to serve")
parser.add_argument("--model-id", metavar="MODEL", help="Alias for --model (catalog name or HuggingFace repo)")
parser.add_argument("--quantization", "-q", choices=["bf16", "int8", "nf4", "bfloat16"], parser.add_argument("--quantization", "-q", choices=["bf16", "int8", "nf4", "bfloat16"],
help="Quantization level") help="Quantization level")
parser.add_argument("--download-dir", metavar="PATH", help="Model download directory") parser.add_argument("--download-dir", metavar="PATH", help="Model download directory")
parser.add_argument("--tracker", metavar="URL", help="Tracker URL") parser.add_argument("--tracker", metavar="URL", help="Tracker URL")
parser.add_argument("--tracker-source-disabled", action="store_true",
help="Skip tracker/peer model-file sources and download from HuggingFace directly")
parser.add_argument("--wallet", metavar="PATH", help="Wallet file path") parser.add_argument("--wallet", metavar="PATH", help="Wallet file path")
parser.add_argument("--shard-start", type=int, metavar="N", help="Pin shard start layer") parser.add_argument("--shard-start", type=int, metavar="N", help="Pin shard start layer")
parser.add_argument("--shard-end", type=int, metavar="N", help="Pin shard end layer") parser.add_argument("--shard-end", type=int, metavar="N", help="Pin shard end layer")
@@ -256,6 +321,10 @@ def main() -> None:
help="Override autodetected VRAM/RAM budget in MB used for shard assignment") help="Override autodetected VRAM/RAM budget in MB used for shard assignment")
parser.add_argument("--max-shards", type=int, metavar="N", default=None, parser.add_argument("--max-shards", type=int, metavar="N", default=None,
help="Maximum shard slots this node advertises to the tracker (default 1)") help="Maximum shard slots this node advertises to the tracker (default 1)")
parser.add_argument("--torch-threads", type=int, metavar="N",
help="Set PyTorch intra-op CPU worker threads")
parser.add_argument("--torch-interop-threads", type=int, metavar="N",
help="Set PyTorch inter-op CPU worker threads")
parser.add_argument("--debug", action="store_true", help="Enable verbose node debug logging") parser.add_argument("--debug", action="store_true", help="Enable verbose node debug logging")
parser.add_argument("--no-tui", action="store_true", help="Plain-text output (no rich dashboard)") parser.add_argument("--no-tui", action="store_true", help="Plain-text output (no rich dashboard)")
parser.add_argument("--compact", action="store_true", help="Single-line status output") parser.add_argument("--compact", action="store_true", help="Single-line status output")
@@ -272,13 +341,13 @@ def main() -> None:
# start subcommand (legacy / backward-compat) # start subcommand (legacy / backward-compat)
start_cmd = subparsers.add_parser("start", help="Start node (legacy flags)") start_cmd = subparsers.add_parser("start", help="Start node (legacy flags)")
start_cmd.add_argument("--tracker", default="http://localhost:8080") start_cmd.add_argument("--tracker")
start_cmd.add_argument("--port", type=int) start_cmd.add_argument("--port", type=int)
start_cmd.add_argument("--model", default="stub-model") start_cmd.add_argument("--model", help="Model name or HuggingFace repo ID")
start_cmd.add_argument("--model-id", help="HuggingFace repo ID") start_cmd.add_argument("--model-id", help="Alias for --model (catalog name or HuggingFace repo)")
start_cmd.add_argument("--shard-start", type=int) start_cmd.add_argument("--shard-start", type=int)
start_cmd.add_argument("--shard-end", type=int) start_cmd.add_argument("--shard-end", type=int)
start_cmd.add_argument("--quantization", choices=["bfloat16", "int8", "nf4", "bf16"], default="int8") start_cmd.add_argument("--quantization", choices=["auto", "bfloat16", "int8", "nf4", "bf16"], default="auto")
start_cmd.add_argument("--host", default="0.0.0.0") start_cmd.add_argument("--host", default="0.0.0.0")
start_cmd.add_argument("--advertise-host") start_cmd.add_argument("--advertise-host")
start_cmd.add_argument("--tracker-mode", action="store_true") start_cmd.add_argument("--tracker-mode", action="store_true")
@@ -291,7 +360,13 @@ def main() -> None:
help="Override autodetected VRAM/RAM budget in MB used for shard assignment") help="Override autodetected VRAM/RAM budget in MB used for shard assignment")
start_cmd.add_argument("--max-shards", type=int, default=1, metavar="N", start_cmd.add_argument("--max-shards", type=int, default=1, metavar="N",
help="Maximum shard slots this node advertises to the tracker (default 1)") help="Maximum shard slots this node advertises to the tracker (default 1)")
start_cmd.add_argument("--torch-threads", type=int, metavar="N",
help="Set PyTorch intra-op CPU worker threads")
start_cmd.add_argument("--torch-interop-threads", type=int, metavar="N",
help="Set PyTorch inter-op CPU worker threads")
start_cmd.add_argument("--debug", action="store_true", help="Enable verbose node debug logging") start_cmd.add_argument("--debug", action="store_true", help="Enable verbose node debug logging")
start_cmd.add_argument("--tracker-source-disabled", action="store_true",
help="Skip tracker/peer model-file sources and download from HuggingFace directly")
args = parser.parse_args() args = parser.parse_args()

View File

@@ -9,14 +9,21 @@ from pathlib import Path
_DEFAULT_CONFIG_DIR = Path.home() / ".config" / "meshnet" _DEFAULT_CONFIG_DIR = Path.home() / ".config" / "meshnet"
_DEFAULT_CONFIG_FILE = _DEFAULT_CONFIG_DIR / "config.json" _DEFAULT_CONFIG_FILE = _DEFAULT_CONFIG_DIR / "config.json"
_DEFAULT_DOWNLOAD_DIR = Path.home() / ".meshnet" / "models" # MESHNET_DOWNLOAD_DIR overrides the model store for every node on this
_DEFAULT_TRACKER_URL = "http://localhost:8080" # machine (all CLI flows fall back to this default; --download-dir still wins).
_DEFAULT_DOWNLOAD_DIR = Path(
os.environ.get("MESHNET_DOWNLOAD_DIR", str(Path.home() / ".meshnet" / "models"))
)
_DEFAULT_TRACKER_URL = os.environ.get("MESHNET_TRACKER_URL", "http://localhost:8080")
_DEFAULT_WALLET_PATH = str(Path.home() / ".config" / "meshnet" / "wallet.json") _DEFAULT_WALLET_PATH = str(Path.home() / ".config" / "meshnet" / "wallet.json")
_DEFAULT_QUANTIZATION = "nf4" _DEFAULT_QUANTIZATION = "auto"
_DEFAULT_MODEL = os.environ.get("MESHNET_MODEL_ID") or os.environ.get("MESHNET_MODEL", "")
_DEFAULT_MODEL_HF_REPO = _DEFAULT_MODEL if "/" in _DEFAULT_MODEL else ""
_DEFAULT_MODEL_NAME = _DEFAULT_MODEL.split("/")[-1] if "/" in _DEFAULT_MODEL else _DEFAULT_MODEL
DEFAULTS = { DEFAULTS = {
"model_hf_repo": "", "model_hf_repo": _DEFAULT_MODEL_HF_REPO,
"model_name": "", "model_name": _DEFAULT_MODEL_NAME,
"quantization": _DEFAULT_QUANTIZATION, "quantization": _DEFAULT_QUANTIZATION,
"download_dir": str(_DEFAULT_DOWNLOAD_DIR), "download_dir": str(_DEFAULT_DOWNLOAD_DIR),
"tracker_url": _DEFAULT_TRACKER_URL, "tracker_url": _DEFAULT_TRACKER_URL,

View File

@@ -1,6 +1,6 @@
"""Shard downloader — fetches model shards from peers or HuggingFace Hub. """Shard downloader — fetches model files from peers, tracker sources, or HuggingFace.
Cache layout: ~/.cache/meshnet/shards/<model>/layers_<start>-<end>/ Cache layout: ~/.cache/meshnet/shards/<model>/
For "stub-model" (no HF repo), a placeholder JSON file is written so the For "stub-model" (no HF repo), a placeholder JSON file is written so the
test suite never touches the network. test suite never touches the network.
@@ -8,9 +8,11 @@ test suite never touches the network.
import hashlib import hashlib
import json import json
import os
import shutil import shutil
import tarfile import tarfile
import tempfile import tempfile
import time
import urllib.parse import urllib.parse
import urllib.request import urllib.request
from pathlib import Path from pathlib import Path
@@ -18,6 +20,12 @@ from typing import Any
_DEFAULT_CACHE = Path.home() / ".cache" / "meshnet" / "shards" _DEFAULT_CACHE = Path.home() / ".cache" / "meshnet" / "shards"
_PEER_TIMEOUT_SECONDS = 2.0 _PEER_TIMEOUT_SECONDS = 2.0
# Model-source tar streams are multi-GB; a short socket timeout must not kill
# them on a transient read stall. Peer probes keep the short timeout because
# they run sequentially before the race and may hit dead endpoints.
_MODEL_SOURCE_TIMEOUT_SECONDS = 30.0
_PROGRESS_INTERVAL_BYTES = 512 * 1024 * 1024
_FILE_RETRY_ATTEMPTS = 3
def compute_shard_checksum(shard_dir: Path) -> str: def compute_shard_checksum(shard_dir: Path) -> str:
@@ -36,7 +44,8 @@ def compute_shard_checksum(shard_dir: Path) -> str:
def write_shard_archive(shard_dir: Path, out_file: Any) -> None: def write_shard_archive(shard_dir: Path, out_file: Any) -> None:
"""Write a tar archive for *shard_dir* to a binary file-like object.""" """Write a tar archive for *shard_dir* to a binary file-like object."""
with tarfile.open(fileobj=out_file, mode="w|") as archive: # dereference: HF cache snapshots are symlinks into blobs/ — ship contents.
with tarfile.open(fileobj=out_file, mode="w|", dereference=True) as archive:
for path in sorted(p for p in shard_dir.rglob("*") if p.is_file()): for path in sorted(p for p in shard_dir.rglob("*") if p.is_file()):
archive.add(path, arcname=path.relative_to(shard_dir).as_posix()) archive.add(path, arcname=path.relative_to(shard_dir).as_posix())
@@ -97,14 +106,340 @@ def _download_shard_from_peer(
_safe_extract_shard(archive_path, extract_dir) _safe_extract_shard(archive_path, extract_dir)
if compute_shard_checksum(extract_dir) != checksum: if compute_shard_checksum(extract_dir) != checksum:
return False return False
if shard_dir.exists(): _merge_tree(extract_dir, shard_dir)
shutil.rmtree(shard_dir)
shutil.move(str(extract_dir), str(shard_dir))
return True return True
except Exception: except Exception:
return False return False
class _TarOnlySource(Exception):
"""The server ignored ?file= and streamed a tar — no single-file support."""
def _fetch_source_file(
file_url: str,
dest: Path,
timeout: float,
on_chunk=None,
) -> int:
"""Download one file; skip if *dest* already matches the remote size.
Returns the file's final size. Raises on any failure, including a
short read against the server's Content-Length.
"""
with urllib.request.urlopen(file_url, timeout=timeout) as resp:
ctype = resp.getheader("Content-Type") if hasattr(resp, "getheader") else None
if isinstance(ctype, str) and "x-tar" in ctype:
raise _TarOnlySource(file_url)
length = resp.getheader("Content-Length") if hasattr(resp, "getheader") else None
expected = int(length) if isinstance(length, str) and length.isdigit() else None
if expected is not None and dest.exists() and dest.stat().st_size == expected:
if on_chunk is not None:
on_chunk(expected)
return expected # complete from an earlier attempt/run
received = 0
with dest.open("wb") as out:
while True:
chunk = resp.read(1024 * 1024)
if not chunk:
break
out.write(chunk)
received += len(chunk)
if on_chunk is not None:
on_chunk(len(chunk))
if expected is not None and received != expected:
raise OSError(f"short read: got {received} of {expected} bytes")
return received
class _SourceProgress:
"""tqdm bar over the whole per-file download (total / speed / ETA),
falling back to plain per-file prints when tqdm is unavailable."""
def __init__(self, enabled: bool, label: str, total_bytes: int | None):
self._label = label
self._bar = None
self._enabled = enabled
if enabled and total_bytes:
try:
from tqdm import tqdm # type: ignore[import]
self._bar = tqdm(
total=total_bytes,
unit="B",
unit_scale=True,
unit_divisor=1024,
desc=f"Downloading ({label})",
)
except Exception:
self._bar = None
def add_bytes(self, n: int) -> None:
if self._bar is not None:
self._bar.update(n)
def rewind(self, n: int) -> None:
"""Roll the bar back after a failed attempt so retries don't double-count."""
if self._bar is not None and n:
self._bar.update(-n)
def file_done(self, index: int, count: int, rel: str, size: int, reused: bool) -> None:
note = "already complete, " if reused else ""
line = f" {self._label}: [{index}/{count}] {rel} ({note}{size / 1e9:.2f} GB)"
if self._bar is not None:
self._bar.set_postfix_str(f"{index}/{count} files", refresh=False)
elif self._enabled:
print(line, flush=True)
def message(self, text: str) -> None:
if self._bar is not None:
self._bar.write(text)
elif self._enabled:
print(text, flush=True)
def close(self) -> None:
if self._bar is not None:
self._bar.close()
def _reuse_local_file(expected: int, dest: Path, final: Path) -> bool:
"""Reuse an already-complete copy of a file instead of re-downloading."""
if dest.exists() and dest.stat().st_size == expected:
return True
if final.exists() and final.stat().st_size == expected:
try:
os.link(final, dest)
except OSError:
shutil.copy2(final, dest)
return True
return False
def _valid_source_rel_files(source: dict) -> list[str]:
return [
rel for rel in (source.get("files") or [])
if isinstance(rel, str) and rel and not rel.startswith("/") and ".." not in Path(rel).parts
]
def _source_files_cached(source: dict, shard_dir: Path) -> bool:
rel_files = _valid_source_rel_files(source)
if not rel_files:
return False
sizes = source.get("file_sizes")
if not isinstance(sizes, dict):
return False
for rel in rel_files:
expected = sizes.get(rel)
path = shard_dir / rel
if not isinstance(expected, int) or not path.exists() or path.stat().st_size != expected:
return False
return True
def _merge_tree(src: Path, dest: Path) -> None:
dest.mkdir(parents=True, exist_ok=True)
for path in sorted(p for p in src.rglob("*") if p.is_file()):
target = dest / path.relative_to(src)
target.parent.mkdir(parents=True, exist_ok=True)
if target.exists():
target.unlink()
shutil.move(str(path), str(target))
def _download_source_files(
source: dict,
shard_dir: Path,
timeout: float,
progress: bool,
label: str,
) -> Path | None:
"""Per-file download from a model source — retries and resumes per file.
Far more robust than one multi-GB tar stream on flaky links: a dropped
connection costs at most one file, and completed files are skipped when
the download is retried or the node is restarted.
"""
url = source.get("url")
rel_files = _valid_source_rel_files(source)
if not isinstance(url, str) or not url or not rel_files:
return None
sizes = source.get("file_sizes")
if not isinstance(sizes, dict):
sizes = {}
partial_dir = shard_dir.parent / f"{shard_dir.name}.partial"
partial_dir.mkdir(parents=True, exist_ok=True)
sep = "&" if "?" in url else "?"
known_sizes = [sizes.get(rel) for rel in rel_files]
total_bytes = sum(s for s in known_sizes if isinstance(s, int)) if all(
isinstance(s, int) for s in known_sizes
) else None
tracker_bar = _SourceProgress(progress, label, total_bytes)
try:
for index, rel in enumerate(rel_files, start=1):
dest = partial_dir / rel
dest.parent.mkdir(parents=True, exist_ok=True)
known_size = sizes.get(rel)
if isinstance(known_size, int) and _reuse_local_file(known_size, dest, shard_dir / rel):
tracker_bar.add_bytes(known_size)
tracker_bar.file_done(index, len(rel_files), rel, known_size, reused=True)
continue
file_url = f"{url}{sep}{urllib.parse.urlencode({'file': rel})}"
for attempt in range(1, _FILE_RETRY_ATTEMPTS + 1):
counted = 0
def _on_chunk(n: int) -> None:
nonlocal counted
counted += n
tracker_bar.add_bytes(n)
try:
size = _fetch_source_file(file_url, dest, timeout, on_chunk=_on_chunk)
tracker_bar.file_done(index, len(rel_files), rel, size, reused=False)
break
except _TarOnlySource:
tracker_bar.message(f" {label}: no single-file support — using tar stream")
return None
except Exception as exc:
tracker_bar.rewind(counted)
tracker_bar.message(
f" {label}: {rel} attempt {attempt}/{_FILE_RETRY_ATTEMPTS} failed: {exc!r}"
)
if attempt == _FILE_RETRY_ATTEMPTS:
return None
time.sleep(1.0 * attempt)
finally:
tracker_bar.close()
_merge_tree(partial_dir, shard_dir)
try:
partial_dir.rmdir()
except OSError:
pass
return shard_dir
def _download_model_source(
source: dict,
shard_dir: Path,
timeout: float,
progress: bool = False,
label: str = "model-source",
) -> Path | None:
# Prefer per-file transfers whenever the source advertises its file list;
# fall through to the tar stream if the server lacks single-file support
# or per-file transfers keep failing.
if source.get("files"):
fetched = _download_source_files(source, shard_dir, timeout, progress, label)
if fetched is not None:
return fetched
url = source.get("url")
if not isinstance(url, str) or not url:
endpoint = source.get("endpoint")
if not isinstance(endpoint, str):
return None
url = f"{endpoint.rstrip('/')}/v1/model-files/download"
shard_dir.parent.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix="meshnet-model-source-", dir=shard_dir.parent) as tmp:
tmp_root = Path(tmp)
archive_path = tmp_root / "model-files.tar"
extract_dir = tmp_root / "extract"
extract_dir.mkdir()
try:
received = 0
next_report = _PROGRESS_INTERVAL_BYTES
with urllib.request.urlopen(url, timeout=timeout) as resp, archive_path.open("wb") as out:
while True:
chunk = resp.read(1024 * 1024)
if not chunk:
break
out.write(chunk)
received += len(chunk)
if progress and received >= next_report:
print(f" {label}: {received / 1e9:.1f} GB received ...", flush=True)
next_report += _PROGRESS_INTERVAL_BYTES
if progress:
print(f" {label}: transfer complete ({received / 1e9:.2f} GB), extracting ...", flush=True)
_safe_extract_shard(archive_path, extract_dir)
_merge_tree(extract_dir, shard_dir)
return shard_dir
except Exception as exc:
if progress:
print(f" {label}: download failed ({url}): {exc!r}", flush=True)
return None
def _download_huggingface_subset(
hf_repo: str,
cache_dir: Path,
shard_dir: Path,
allow_patterns: list[str] | None,
) -> Path:
from huggingface_hub import snapshot_download # type: ignore[import]
kwargs = {
"repo_id": hf_repo,
"cache_dir": str(cache_dir),
"local_dir": str(shard_dir),
}
if allow_patterns:
kwargs["allow_patterns"] = allow_patterns
try:
return Path(snapshot_download(**kwargs))
except TypeError:
kwargs.pop("allow_patterns", None)
return Path(snapshot_download(**kwargs))
def _allow_patterns_from_sources(model_sources: list[dict]) -> list[str] | None:
patterns: set[str] = set()
for source in model_sources:
for rel in source.get("files") or []:
if isinstance(rel, str) and rel and not rel.startswith("/") and ".." not in Path(rel).parts:
patterns.add(rel)
return sorted(patterns) if patterns else None
def _allow_patterns_from_remote_index(
hf_repo: str,
cache_dir: Path,
shard_start: int,
shard_end: int,
) -> list[str] | None:
"""Fetch just the SafeTensors index + config (a few KB) from HF and compute
which weight files the assigned layer range needs, so a HuggingFace fallback
download stays layer-scoped even when the tracker has no model_sources
(e.g. it has no local snapshot for this repo cached yet)."""
try:
from huggingface_hub import hf_hub_download # type: ignore[import]
from .safetensors_selection import (
INDEX_FILENAME,
METADATA_FILENAMES,
layers_from_config_dict,
select_files_for_layers_from_index,
)
index_path = hf_hub_download(repo_id=hf_repo, filename=INDEX_FILENAME, cache_dir=str(cache_dir))
weight_map = json.loads(Path(index_path).read_text(encoding="utf-8")).get("weight_map")
except Exception:
return None
if not isinstance(weight_map, dict):
return None
total_layers: int | None = None
try:
config_path = hf_hub_download(repo_id=hf_repo, filename="config.json", cache_dir=str(cache_dir))
config = json.loads(Path(config_path).read_text(encoding="utf-8"))
total_layers = layers_from_config_dict(config)
except Exception:
pass
selected = select_files_for_layers_from_index(
weight_map, shard_start, shard_end, total_layers=total_layers
)
return sorted(selected | METADATA_FILENAMES)
def download_shard( def download_shard(
model: str, model: str,
shard_start: int, shard_start: int,
@@ -113,6 +448,7 @@ def download_shard(
hf_repo: str | None = None, hf_repo: str | None = None,
progress: bool = True, progress: bool = True,
peers: list[dict] | None = None, peers: list[dict] | None = None,
model_sources: list[dict] | None = None,
peer_timeout: float = _PEER_TIMEOUT_SECONDS, peer_timeout: float = _PEER_TIMEOUT_SECONDS,
) -> Path: ) -> Path:
"""Ensure the shard is present in *cache_dir* and return its local path. """Ensure the shard is present in *cache_dir* and return its local path.
@@ -122,7 +458,16 @@ def download_shard(
the test suite hermetic while the real download path is exercised by the test suite hermetic while the real download path is exercised by
passing a non-stub *hf_repo*. passing a non-stub *hf_repo*.
""" """
shard_dir = cache_dir / model / f"layers_{shard_start}-{shard_end}" shard_dir = cache_dir / model
if progress:
print(f" Target location: {shard_dir}", flush=True)
for source in model_sources or []:
label = str(source.get("type") or "model-source")
if _source_files_cached(source, shard_dir):
if progress:
print(f" [{label}] requested files already cached at {shard_dir}", flush=True)
return shard_dir
for peer in peers or []: for peer in peers or []:
if progress: if progress:
@@ -157,18 +502,43 @@ def download_shard(
print(f" [stub] shard already cached at {shard_dir}", flush=True) print(f" [stub] shard already cached at {shard_dir}", flush=True)
return shard_dir return shard_dir
from huggingface_hub import snapshot_download # type: ignore[import]
if progress: if progress:
print( print(
f" Downloading layers {shard_start}-{shard_end} from {hf_repo} ...", f" Downloading layers {shard_start}-{shard_end} from {hf_repo} ...",
flush=True, flush=True,
) )
print(" download source: HuggingFace", flush=True) # Tracker (or peer) model sources are preferred outright — usually LAN-fast.
# HuggingFace is only the fallback when every advertised source fails.
for source in model_sources or []:
label = str(source.get("type") or "model-source")
if progress:
print(f" Downloading from {label} model source (HuggingFace is the fallback) ...", flush=True)
fetched = _download_model_source(
source,
shard_dir,
timeout=max(peer_timeout, _MODEL_SOURCE_TIMEOUT_SECONDS),
progress=progress,
label=label,
)
if fetched is not None:
if progress:
print(f" download source: {label}", flush=True)
return fetched
if model_sources and progress:
print(" All model sources failed — falling back to HuggingFace ...", flush=True)
local_dir = snapshot_download( allow_patterns = None
repo_id=hf_repo, if model_sources:
cache_dir=str(cache_dir), allow_patterns = _allow_patterns_from_sources(model_sources)
local_dir=str(shard_dir), if allow_patterns is None:
) allow_patterns = _allow_patterns_from_remote_index(hf_repo, cache_dir, shard_start, shard_end)
return Path(local_dir) if progress:
if allow_patterns:
print(" download source: HuggingFace (layer-filtered)", flush=True)
else:
print(
" download source: HuggingFace (full snapshot — no SafeTensors index found)",
flush=True,
)
return _download_huggingface_subset(hf_repo, cache_dir, shard_dir, allow_patterns)

View File

@@ -4,10 +4,11 @@ from __future__ import annotations
import base64 import base64
from dataclasses import dataclass from dataclasses import dataclass
import json
from pathlib import Path from pathlib import Path
from typing import Any, Literal from typing import Any, Literal
Quantization = Literal["bfloat16", "int8", "nf4"] Quantization = Literal["auto", "bfloat16", "int8", "nf4"]
class ModelBackendError(RuntimeError): class ModelBackendError(RuntimeError):
@@ -22,6 +23,10 @@ class InsufficientVRAMError(ModelBackendError):
"""Raised when a requested shard cannot fit in available CUDA memory.""" """Raised when a requested shard cannot fit in available CUDA memory."""
class PartialModelLoadUnsupported(ModelBackendError):
"""Raised when a shard cannot be materialized from a local snapshot subset."""
@dataclass(frozen=True) @dataclass(frozen=True)
class TensorPayload: class TensorPayload:
body: bytes body: bytes
@@ -31,14 +36,14 @@ class TensorPayload:
def validate_quantization(value: str) -> Quantization: def validate_quantization(value: str) -> Quantization:
if value not in {"bfloat16", "int8", "nf4"}: if value not in {"auto", "bfloat16", "int8", "nf4"}:
raise ValueError("quantization must be one of: bfloat16, int8, nf4") raise ValueError("quantization must be one of: auto, bfloat16, int8, nf4")
return value # type: ignore[return-value] return value # type: ignore[return-value]
def build_quantization_config(quantization: Quantization) -> Any | None: def build_quantization_config(quantization: Quantization) -> Any | None:
"""Return a transformers BitsAndBytesConfig for quantized weights.""" """Return a transformers BitsAndBytesConfig for quantized weights."""
if quantization == "bfloat16": if quantization in {"auto", "bfloat16"}:
return None return None
try: try:
import torch import torch
@@ -65,7 +70,7 @@ class TorchModelShard:
model_id: str, model_id: str,
shard_start: int, shard_start: int,
shard_end: int, shard_end: int,
quantization: Quantization = "bfloat16", quantization: Quantization = "auto",
cache_dir: Path | None = None, cache_dir: Path | None = None,
) -> None: ) -> None:
if shard_start < 0 or shard_end < 0 or shard_start > shard_end: if shard_start < 0 or shard_end < 0 or shard_start > shard_end:
@@ -77,7 +82,7 @@ class TorchModelShard:
try: try:
import torch import torch
from transformers import AutoModelForCausalLM, AutoTokenizer from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer
except ModuleNotFoundError as exc: except ModuleNotFoundError as exc:
raise MissingModelDependencyError( raise MissingModelDependencyError(
"real model backend requires torch, transformers, safetensors, accelerate, and bitsandbytes" "real model backend requires torch, transformers, safetensors, accelerate, and bitsandbytes"
@@ -85,18 +90,48 @@ class TorchModelShard:
self.torch = torch self.torch = torch
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu") self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
quant_config = build_quantization_config(quantization) load_source = str(cache_dir) if cache_dir is not None and (cache_dir / "config.json").exists() else model_id
quant_config, dtype, uses_quantized_weights = _model_load_plan(
AutoConfig,
load_source,
quantization,
torch,
None if load_source != model_id else cache_dir,
)
try: try:
self.model = AutoModelForCausalLM.from_pretrained( total_layers_hint = _total_layers_for_local_snapshot(AutoConfig, load_source)
model_id, if _should_partial_materialize_shard(
quantization_config=quant_config, load_source,
device_map="auto" if quant_config is not None else None, shard_start,
dtype=torch.bfloat16, shard_end,
low_cpu_mem_usage=True, total_layers_hint=total_layers_hint,
cache_dir=str(cache_dir) if cache_dir is not None else None, uses_quantized_weights=uses_quantized_weights,
) ):
if quant_config is None: self.model = _load_partial_model_from_snapshot(
self.model.to(self.device) AutoConfig,
AutoModelForCausalLM,
torch,
load_source,
shard_start,
shard_end,
dtype,
self.device,
)
else:
load_kwargs = {
"device_map": "auto" if uses_quantized_weights else None,
"dtype": dtype,
"low_cpu_mem_usage": True,
"cache_dir": str(cache_dir) if cache_dir is not None and load_source == model_id else None,
}
if quant_config is not None:
load_kwargs["quantization_config"] = quant_config
self.model = AutoModelForCausalLM.from_pretrained(
load_source,
**load_kwargs,
)
if not uses_quantized_weights:
self.model.to(self.device)
except Exception as exc: except Exception as exc:
if _looks_like_oom(exc): if _looks_like_oom(exc):
raise InsufficientVRAMError( raise InsufficientVRAMError(
@@ -107,8 +142,8 @@ class TorchModelShard:
self.model.eval() self.model.eval()
self.tokenizer = AutoTokenizer.from_pretrained( self.tokenizer = AutoTokenizer.from_pretrained(
model_id, load_source,
cache_dir=str(cache_dir) if cache_dir is not None else None, cache_dir=str(cache_dir) if cache_dir is not None and load_source == model_id else None,
) )
self.layers = _model_layers(self.model) self.layers = _model_layers(self.model)
self.total_layers = len(self.layers) self.total_layers = len(self.layers)
@@ -340,12 +375,200 @@ def load_torch_shard(
model_id: str, model_id: str,
shard_start: int, shard_start: int,
shard_end: int, shard_end: int,
quantization: Quantization = "bfloat16", quantization: Quantization = "auto",
cache_dir: Path | None = None, cache_dir: Path | None = None,
) -> TorchModelShard: ) -> TorchModelShard:
return TorchModelShard(model_id, shard_start, shard_end, quantization, cache_dir) return TorchModelShard(model_id, shard_start, shard_end, quantization, cache_dir)
def _total_layers_for_local_snapshot(auto_config: Any, load_source: str) -> int | None:
snapshot_dir = Path(load_source)
if not (snapshot_dir / "config.json").exists():
return None
from .model_catalog import layers_from_config
try:
cfg = auto_config.from_pretrained(str(snapshot_dir))
except Exception:
return None
return layers_from_config(cfg)
def _should_partial_materialize_shard(
load_source: str,
shard_start: int,
shard_end: int,
*,
total_layers_hint: int | None,
uses_quantized_weights: bool,
) -> bool:
if uses_quantized_weights:
return False
snapshot_dir = Path(load_source)
if not snapshot_dir.exists() or not (snapshot_dir / "config.json").exists():
return False
if not (snapshot_dir / "model.safetensors.index.json").exists():
return False
if total_layers_hint is None:
return False
return not (shard_start == 0 and shard_end >= total_layers_hint - 1)
def _load_partial_model_from_snapshot(
auto_config: Any,
auto_model_for_causal_lm: Any,
torch: Any,
load_source: str,
shard_start: int,
shard_end: int,
dtype: Any,
device: Any,
*,
init_empty_weights_fn: Any | None = None,
set_tensor_fn: Any | None = None,
safe_open_fn: Any | None = None,
) -> Any:
from .model_catalog import layers_from_config
from .safetensors_selection import (
INDEX_FILENAME,
select_tensor_names_for_layers_from_index,
)
if init_empty_weights_fn is None:
from accelerate import init_empty_weights as init_empty_weights_fn
if set_tensor_fn is None:
from accelerate.utils import set_module_tensor_to_device as set_tensor_fn
if safe_open_fn is None:
from safetensors import safe_open as safe_open_fn
snapshot_dir = Path(load_source)
cfg = auto_config.from_pretrained(str(snapshot_dir))
total_layers = layers_from_config(cfg)
if total_layers is None:
raise PartialModelLoadUnsupported(
f"could not determine num_hidden_layers for local snapshot {snapshot_dir}"
)
if shard_end >= total_layers:
raise ValueError(
f"shard_end {shard_end} exceeds last layer index {total_layers - 1}"
)
index_path = snapshot_dir / INDEX_FILENAME
try:
index = json.loads(index_path.read_text(encoding="utf-8"))
except FileNotFoundError as exc:
raise PartialModelLoadUnsupported(
f"missing SafeTensors index for partial load: {index_path}"
) from exc
weight_map = index.get("weight_map")
if not isinstance(weight_map, dict):
raise PartialModelLoadUnsupported(f"{INDEX_FILENAME} must contain a weight_map object")
tensor_names = select_tensor_names_for_layers_from_index(
weight_map,
shard_start,
shard_end,
total_layers=total_layers,
)
if not tensor_names:
raise PartialModelLoadUnsupported(
f"no checkpoint tensors matched layers {shard_start}-{shard_end} in {snapshot_dir}"
)
with init_empty_weights_fn():
model = auto_model_for_causal_lm.from_config(cfg, torch_dtype=dtype)
tie_weights = getattr(model, "tie_weights", None)
if callable(tie_weights):
tie_weights()
tensors_by_file: dict[str, list[str]] = {}
for tensor_name in sorted(tensor_names):
rel_file = weight_map.get(tensor_name)
if not isinstance(rel_file, str):
continue
tensors_by_file.setdefault(rel_file, []).append(tensor_name)
for rel_file, names in tensors_by_file.items():
checkpoint_file = snapshot_dir / rel_file
if not checkpoint_file.exists():
raise PartialModelLoadUnsupported(
f"checkpoint file advertised in {INDEX_FILENAME} is missing: {checkpoint_file}"
)
with safe_open_fn(str(checkpoint_file), framework="pt", device="cpu") as handle:
for tensor_name in names:
set_tensor_fn(
model,
tensor_name,
device,
value=handle.get_tensor(tensor_name),
dtype=dtype,
)
for module in _active_modules_for_shard(model, shard_start, shard_end):
if hasattr(module, "to"):
module.to(device)
return model
def _model_load_plan(
auto_config: Any,
model_id: str,
quantization: Quantization,
torch: Any,
cache_dir: Path | None = None,
) -> tuple[Any | None, Any, bool]:
"""Return (explicit quant config, dtype, uses quantized weights)."""
if quantization != "auto":
quant_config = build_quantization_config(quantization)
return quant_config, torch.bfloat16, quant_config is not None
cfg = auto_config.from_pretrained(
model_id,
cache_dir=str(cache_dir) if cache_dir is not None else None,
)
if _native_quantization_config(cfg) is not None:
return None, _native_torch_dtype(cfg, torch), True
return None, _native_torch_dtype(cfg, torch), False
def _config_candidates(cfg: Any) -> list[Any]:
candidates = [cfg]
get_text_config = getattr(cfg, "get_text_config", None)
if callable(get_text_config):
try:
candidates.append(get_text_config())
except Exception:
pass
text_config = getattr(cfg, "text_config", None)
if text_config is not None:
candidates.append(text_config)
return candidates
def _native_quantization_config(cfg: Any) -> Any | None:
for candidate in _config_candidates(cfg):
quant_config = getattr(candidate, "quantization_config", None)
if quant_config:
return quant_config
return None
def _native_torch_dtype(cfg: Any, torch: Any) -> Any:
for candidate in _config_candidates(cfg):
for attr in ("dtype", "torch_dtype"):
dtype = getattr(candidate, attr, None)
if dtype is None:
continue
if isinstance(dtype, str):
dtype_name = dtype.removeprefix("torch.")
dtype_value = getattr(torch, dtype_name, None)
if dtype_value is not None:
return dtype_value
else:
return dtype
return torch.bfloat16
def _model_layers(model: Any) -> Any: def _model_layers(model: Any) -> Any:
if hasattr(model, "model") and hasattr(model.model, "layers"): if hasattr(model, "model") and hasattr(model.model, "layers"):
return model.model.layers return model.model.layers
@@ -372,6 +595,37 @@ def _position_embeddings(model: Any) -> Any | None:
return None return None
def _rotary_embedding_module(model: Any) -> Any | None:
if hasattr(model, "model") and hasattr(model.model, "rotary_emb"):
return model.model.rotary_emb
if hasattr(model, "transformer") and hasattr(model.transformer, "rotary_emb"):
return model.transformer.rotary_emb
return None
def _active_modules_for_shard(model: Any, shard_start: int, shard_end: int) -> list[Any]:
active: list[Any] = []
def add(module: Any | None) -> None:
if module is None:
return
if any(existing is module for existing in active):
return
active.append(module)
if shard_start == 0:
add(_embed_tokens(model))
add(_position_embeddings(model))
add(_rotary_embedding_module(model))
for layer in _model_layers(model)[shard_start:shard_end + 1]:
add(layer)
total_layers = len(_model_layers(model))
if shard_end >= total_layers - 1:
add(_final_norm(model))
add(getattr(model, "lm_head", None))
return active
def _final_norm(model: Any) -> Any | None: def _final_norm(model: Any) -> Any | None:
if hasattr(model, "model") and hasattr(model.model, "norm"): if hasattr(model, "model") and hasattr(model.model, "norm"):
return model.model.norm return model.model.norm
@@ -415,11 +669,7 @@ def _rotary_position_embeddings(model: Any, hidden_states: Any, position_ids: An
"""Return model-level rotary embeddings required by newer HF decoder layers.""" """Return model-level rotary embeddings required by newer HF decoder layers."""
if position_ids is None: if position_ids is None:
return None return None
rotary = None rotary = _rotary_embedding_module(model)
if hasattr(model, "model") and hasattr(model.model, "rotary_emb"):
rotary = model.model.rotary_emb
elif hasattr(model, "transformer") and hasattr(model.transformer, "rotary_emb"):
rotary = model.transformer.rotary_emb
if rotary is None: if rotary is None:
return None return None
return rotary(hidden_states, position_ids) return rotary(hidden_states, position_ids)

View File

@@ -64,6 +64,17 @@ def _load_model_metadata() -> dict[str, dict]:
_MODEL_METADATA = _load_model_metadata() _MODEL_METADATA = _load_model_metadata()
def _local_model_path(hf_repo: str, cache_dir: Path | None) -> Path | None:
if cache_dir is None:
return None
if (cache_dir / "config.json").exists():
return cache_dir
candidate = cache_dir / hf_repo.split("/")[-1]
if (candidate / "config.json").exists():
return candidate
return None
CURATED_MODELS: list[ModelPreset] = [ CURATED_MODELS: list[ModelPreset] = [
ModelPreset( ModelPreset(
name="Qwen2.5-0.5B-Instruct", name="Qwen2.5-0.5B-Instruct",
@@ -159,6 +170,30 @@ CURATED_MODELS: list[ModelPreset] = [
] ]
def layers_from_config(cfg) -> int | None:
"""Extract the transformer layer count from a HuggingFace config object.
Composite configs (vision-language, some MoE) nest the decoder settings in
``text_config`` — e.g. Qwen3.5-MoE has no top-level ``num_hidden_layers``.
"""
candidates = [cfg]
get_text_config = getattr(cfg, "get_text_config", None)
if callable(get_text_config):
try:
candidates.append(get_text_config())
except Exception:
pass
nested = getattr(cfg, "text_config", None)
if nested is not None:
candidates.append(nested)
for candidate in candidates:
for attr in ("num_hidden_layers", "num_layers", "n_layer", "n_layers"):
value = getattr(candidate, attr, None)
if value is not None:
return int(value)
return None
def detect_num_layers(hf_repo: str) -> int | None: def detect_num_layers(hf_repo: str) -> int | None:
"""Return num_hidden_layers from HuggingFace config.json (downloads ~1 KB only).""" """Return num_hidden_layers from HuggingFace config.json (downloads ~1 KB only)."""
# Check curated list first (no network call) # Check curated list first (no network call)
@@ -168,7 +203,7 @@ def detect_num_layers(hf_repo: str) -> int | None:
try: try:
from transformers import AutoConfig # type: ignore[import] from transformers import AutoConfig # type: ignore[import]
cfg = AutoConfig.from_pretrained(hf_repo) cfg = AutoConfig.from_pretrained(hf_repo)
return int(cfg.num_hidden_layers) return layers_from_config(cfg)
except Exception: except Exception:
return None return None
@@ -191,10 +226,14 @@ def model_metadata_for(
try: try:
from transformers import AutoConfig # type: ignore[import] from transformers import AutoConfig # type: ignore[import]
local_model = _local_model_path(hf_repo, cache_dir)
load_source = str(local_model) if local_model is not None else hf_repo
cfg = AutoConfig.from_pretrained( cfg = AutoConfig.from_pretrained(
hf_repo, load_source,
cache_dir=str(cache_dir) if cache_dir is not None else None, cache_dir=str(cache_dir) if cache_dir is not None and local_model is None else None,
) )
# Composite configs (VLM/MoE) nest decoder fields in text_config.
text_cfg = getattr(cfg, "text_config", None) or cfg
for attr, key in ( for attr, key in (
("model_type", "architecture"), ("model_type", "architecture"),
("num_hidden_layers", "num_layers"), ("num_hidden_layers", "num_layers"),
@@ -204,8 +243,14 @@ def model_metadata_for(
("max_position_embeddings", "context_length"), ("max_position_embeddings", "context_length"),
): ):
value = getattr(cfg, attr, None) value = getattr(cfg, attr, None)
if value is None:
value = getattr(text_cfg, attr, None)
if value is not None: if value is not None:
metadata[key] = value metadata[key] = value
if "num_layers" not in metadata:
layers = layers_from_config(cfg)
if layers is not None:
metadata["num_layers"] = layers
except Exception: except Exception:
pass pass
return metadata return metadata

View File

@@ -20,6 +20,8 @@
"vision_encoder_parameters": "400M", "vision_encoder_parameters": "400M",
"license": "modified-mit", "license": "modified-mit",
"native_quantization": "int4", "native_quantization": "int4",
"canonical_audit_dtype": "bfloat16",
"canonical_audit_quantization": "bfloat16",
"download_size_gb": 595, "download_size_gb": 595,
"recommended_short_name": "kimi-k2.7", "recommended_short_name": "kimi-k2.7",
"recommended_engines": [ "recommended_engines": [

View File

@@ -5,14 +5,18 @@ from __future__ import annotations
import base64 import base64
import json import json
import logging import logging
import os
import threading import threading
import time import time
import urllib.error import urllib.error
import urllib.request import urllib.request
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass from dataclasses import dataclass
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
DEFAULT_MAX_CONCURRENCY = 8
@dataclass(frozen=True) @dataclass(frozen=True)
class RelayBridgeInfo: class RelayBridgeInfo:
@@ -32,8 +36,23 @@ def _make_envelope(topic: str, payload: dict, peer_id: str) -> dict:
} }
def _max_concurrency_from_env() -> int:
try:
value = int(os.environ.get("MESHNET_RELAY_CONCURRENCY", DEFAULT_MAX_CONCURRENCY))
except (TypeError, ValueError):
return DEFAULT_MAX_CONCURRENCY
return max(1, value)
class RelayHttpBridge: class RelayHttpBridge:
"""Connect outbound to a relay and proxy relay HTTP requests to localhost.""" """Connect outbound to a relay and proxy relay HTTP requests to localhost.
Requests are dispatched on a bounded worker pool (US-037) so a node that is
the head of one route can still serve per-token ``/forward`` hops of another.
Streaming responses (``text/event-stream``) are forwarded as multiple chunk
frames sharing one ``request_id`` (US-036); everything else stays a single
frame for backward compatibility.
"""
def __init__( def __init__(
self, self,
@@ -42,15 +61,20 @@ class RelayHttpBridge:
local_base_url: str, local_base_url: str,
advertised_addr: str, advertised_addr: str,
reconnect_interval: float = 3.0, reconnect_interval: float = 3.0,
max_concurrency: int | None = None,
) -> None: ) -> None:
self.relay_url = relay_url.rstrip("/") self.relay_url = relay_url.rstrip("/")
self.peer_id = peer_id self.peer_id = peer_id
self.local_base_url = local_base_url.rstrip("/") self.local_base_url = local_base_url.rstrip("/")
self.advertised_addr = advertised_addr self.advertised_addr = advertised_addr
self.reconnect_interval = reconnect_interval self.reconnect_interval = reconnect_interval
self.max_concurrency = max(1, max_concurrency) if max_concurrency else _max_concurrency_from_env()
self._running = False self._running = False
self._thread: threading.Thread | None = None self._thread: threading.Thread | None = None
self._connected = threading.Event() self._connected = threading.Event()
self._executor: ThreadPoolExecutor | None = None
self._send_lock = threading.Lock()
self._ws = None
@property @property
def relay_addr(self) -> str: def relay_addr(self) -> str:
@@ -61,6 +85,9 @@ class RelayHttpBridge:
def start(self) -> RelayBridgeInfo: def start(self) -> RelayBridgeInfo:
self._running = True self._running = True
self._executor = ThreadPoolExecutor(
max_workers=self.max_concurrency, thread_name_prefix="relay-http-worker"
)
self._thread = threading.Thread(target=self._run, daemon=True, name="relay-http-bridge") self._thread = threading.Thread(target=self._run, daemon=True, name="relay-http-bridge")
self._thread.start() self._thread.start()
return RelayBridgeInfo(peer_id=self.peer_id, relay_addr=self.relay_addr) return RelayBridgeInfo(peer_id=self.peer_id, relay_addr=self.relay_addr)
@@ -72,6 +99,8 @@ class RelayHttpBridge:
self._running = False self._running = False
if self._thread: if self._thread:
self._thread.join(timeout=3.0) self._thread.join(timeout=3.0)
if self._executor is not None:
self._executor.shutdown(wait=False)
def _run(self) -> None: def _run(self) -> None:
import websockets.sync.client as wsc # type: ignore[import] import websockets.sync.client as wsc # type: ignore[import]
@@ -79,6 +108,7 @@ class RelayHttpBridge:
while self._running: while self._running:
try: try:
with wsc.connect(self.relay_url, open_timeout=5) as ws: with wsc.connect(self.relay_url, open_timeout=5) as ws:
self._ws = ws
self._connected.set() self._connected.set()
ws.send(json.dumps(_make_envelope( ws.send(json.dumps(_make_envelope(
"peer-register", "peer-register",
@@ -99,19 +129,36 @@ class RelayHttpBridge:
payload = envelope.get("payload", {}) payload = envelope.get("payload", {})
if payload.get("target_peer") not in {None, self.peer_id}: if payload.get("target_peer") not in {None, self.peer_id}:
continue continue
response = self._handle_request(payload) if self._executor is None:
ws.send(json.dumps(_make_envelope( break
"relay-http-response", self._executor.submit(self._process_request, payload)
response,
self.peer_id,
)))
except Exception as exc: except Exception as exc:
self._connected.clear() self._connected.clear()
self._ws = None
if self._running: if self._running:
log.debug("relay bridge disconnected: %s", exc) log.debug("relay bridge disconnected: %s", exc)
time.sleep(self.reconnect_interval) time.sleep(self.reconnect_interval)
self._ws = None
def _handle_request(self, payload: dict) -> dict: def _send_response_frame(self, payload: dict) -> bool:
"""Send one relay-http-response frame; False if the socket is gone.
The lock is held per frame so concurrent workers interleave whole
frames on the shared WebSocket, never torn ones.
"""
ws = self._ws
if ws is None:
return False
message = json.dumps(_make_envelope("relay-http-response", payload, self.peer_id))
try:
with self._send_lock:
ws.send(message)
return True
except Exception as exc:
log.debug("relay bridge send failed (request orphaned): %s", exc)
return False
def _process_request(self, payload: dict) -> None:
request_id = str(payload.get("request_id") or "") request_id = str(payload.get("request_id") or "")
method = str(payload.get("method") or "POST").upper() method = str(payload.get("method") or "POST").upper()
path = str(payload.get("path") or "/") path = str(payload.get("path") or "/")
@@ -130,10 +177,14 @@ class RelayHttpBridge:
req = urllib.request.Request(url, data=data, headers=headers, method=method) req = urllib.request.Request(url, data=data, headers=headers, method=method)
try: try:
with urllib.request.urlopen(req, timeout=300.0) as resp: with urllib.request.urlopen(req, timeout=300.0) as resp:
resp_bytes = resp.read()
resp_headers = dict(resp.headers) resp_headers = dict(resp.headers)
content_type = resp.headers.get("Content-Type", "")
if "text/event-stream" in content_type:
self._stream_response(request_id, resp, resp_headers)
return
resp_bytes = resp.read()
# Forward all X-Meshnet-* headers so the caller can reconstruct the activation. # Forward all X-Meshnet-* headers so the caller can reconstruct the activation.
is_binary = "octet-stream" in resp.headers.get("Content-Type", "") is_binary = "octet-stream" in content_type
result: dict = { result: dict = {
"request_id": request_id, "request_id": request_id,
"status": resp.status, "status": resp.status,
@@ -143,21 +194,66 @@ class RelayHttpBridge:
result["body_base64"] = base64.b64encode(resp_bytes).decode() result["body_base64"] = base64.b64encode(resp_bytes).decode()
else: else:
result["body"] = resp_bytes.decode(errors="replace") result["body"] = resp_bytes.decode(errors="replace")
return result self._send_response_frame(result)
except urllib.error.HTTPError as exc: except urllib.error.HTTPError as exc:
return { self._send_response_frame({
"request_id": request_id, "request_id": request_id,
"status": exc.code, "status": exc.code,
"headers": {"Content-Type": exc.headers.get("Content-Type", "application/json")}, "headers": {"Content-Type": exc.headers.get("Content-Type", "application/json")},
"body": exc.read().decode(errors="replace"), "body": exc.read().decode(errors="replace"),
} })
except Exception as exc: except Exception as exc:
return { self._send_response_frame({
"request_id": request_id, "request_id": request_id,
"status": 503, "status": 503,
"headers": {"Content-Type": "application/json"}, "headers": {"Content-Type": "application/json"},
"body": json.dumps({"error": f"relay bridge local request failed: {exc}"}), "body": json.dumps({"error": f"relay bridge local request failed: {exc}"}),
} })
def _stream_response(self, request_id: str, resp, resp_headers: dict) -> None:
"""Forward an SSE response as chunk frames, one per complete SSE event.
Frame order: header frame (status + headers), chunk frames, done frame.
A receiver that sees no ``stream`` key treats the frame as a complete
legacy response, so non-streaming peers are unaffected.
"""
sent = self._send_response_frame({
"request_id": request_id,
"status": resp.status,
"headers": resp_headers,
"stream": True,
"done": False,
})
if not sent:
return
event_lines: list[str] = []
for raw_line in resp:
line = raw_line.decode(errors="replace")
event_lines.append(line)
if line.strip():
continue
# Blank line terminates one SSE event — flush it as a frame.
if not self._send_response_frame({
"request_id": request_id,
"stream": True,
"chunk": "".join(event_lines),
"done": False,
}):
return
event_lines = []
if event_lines:
if not self._send_response_frame({
"request_id": request_id,
"stream": True,
"chunk": "".join(event_lines),
"done": False,
}):
return
self._send_response_frame({
"request_id": request_id,
"stream": True,
"done": True,
})
def peer_id_from_wallet(wallet_address: str) -> str: def peer_id_from_wallet(wallet_address: str) -> str:

View File

@@ -0,0 +1,210 @@
"""Layer-aware SafeTensors snapshot file selection."""
from __future__ import annotations
import json
import re
from pathlib import Path
from typing import Any
INDEX_FILENAME = "model.safetensors.index.json"
_LAYER_RE = re.compile(
r"(?:^|\.)"
r"(?:model\.layers|layers|h|blocks|decoder\.layers|encoder\.layers)"
r"\.(\d+)(?:\.|$)"
)
METADATA_FILENAMES = {
INDEX_FILENAME,
"config.json",
"generation_config.json",
"preprocessor_config.json",
"special_tokens_map.json",
"tokenizer.json",
"tokenizer.model",
"tokenizer_config.json",
"vocab.json",
"merges.txt",
"added_tokens.json",
}
_METADATA_PREFIXES = ("config.", "tokenizer.", "tokenizer_", "vocab.")
_HEAD_MARKERS = (
"embed",
"embedding",
"embed_tokens",
"wte",
"wpe",
)
_TAIL_EXACT = {
"lm_head.weight",
"lm_head.bias",
"model.norm.weight",
"model.norm.bias",
"transformer.ln_f.weight",
"transformer.ln_f.bias",
"decoder.final_layer_norm.weight",
"decoder.final_layer_norm.bias",
}
_TAIL_MARKERS = (
".lm_head.",
".norm.",
".ln_f.",
".final_layer_norm.",
)
def select_safetensors_files_for_layers(
model_dir: str | Path,
start_layer: int,
end_layer: int,
*,
total_layers: int | None = None,
) -> list[str]:
"""Return relative snapshot files needed for an inclusive layer range.
The returned list always includes root-level config/tokenizer metadata and
the SafeTensors index. Weight shard files are included only when at least one
tensor in the index belongs to the assigned layer range, or when the tensor
is needed by the head/tail shard.
"""
if start_layer < 0:
raise ValueError("start_layer must be non-negative")
if end_layer < start_layer:
raise ValueError("end_layer must be greater than or equal to start_layer")
root = Path(model_dir)
index_path = root / INDEX_FILENAME
try:
index = json.loads(index_path.read_text(encoding="utf-8"))
except FileNotFoundError as exc:
raise FileNotFoundError(f"missing SafeTensors index: {index_path}") from exc
weight_map = index.get("weight_map")
if not isinstance(weight_map, dict):
raise ValueError(f"{INDEX_FILENAME} must contain a weight_map object")
inferred_total_layers = total_layers if total_layers is not None else _read_total_layers(root)
selected = _metadata_files(root)
selected |= select_files_for_layers_from_index(
weight_map, start_layer, end_layer, total_layers=inferred_total_layers
)
return sorted(selected)
def select_files_for_layers_from_index(
weight_map: dict[str, str],
start_layer: int,
end_layer: int,
*,
total_layers: int | None = None,
) -> set[str]:
"""Pure variant of the weight-file selection: takes an already-parsed
``weight_map`` (no local snapshot directory needed), so callers that only
have the index fetched over the network — not a full local snapshot — can
still compute which shard files they need. Combine the result with
``METADATA_FILENAMES`` for a complete download pattern set.
"""
selected: set[str] = set()
for tensor_name, rel_file in weight_map.items():
if not isinstance(tensor_name, str) or not isinstance(rel_file, str):
continue
if _tensor_belongs_to_range(tensor_name, start_layer, end_layer, total_layers):
selected.add(_normalise_relative_file(rel_file))
return selected
def select_tensor_names_for_layers_from_index(
weight_map: dict[str, str],
start_layer: int,
end_layer: int,
*,
total_layers: int | None = None,
) -> set[str]:
"""Pure variant that returns checkpoint tensor names instead of file paths."""
selected: set[str] = set()
for tensor_name, rel_file in weight_map.items():
if not isinstance(tensor_name, str) or not isinstance(rel_file, str):
continue
if _tensor_belongs_to_range(tensor_name, start_layer, end_layer, total_layers):
selected.add(tensor_name)
return selected
def _tensor_belongs_to_range(
tensor_name: str,
start_layer: int,
end_layer: int,
total_layers: int | None,
) -> bool:
layer = _layer_index(tensor_name)
if layer is not None:
return start_layer <= layer <= end_layer
if start_layer == 0 and _is_head_tensor(tensor_name):
return True
if total_layers is not None and end_layer >= total_layers - 1 and _is_tail_tensor(tensor_name):
return True
return False
def _layer_index(tensor_name: str) -> int | None:
match = _LAYER_RE.search(tensor_name)
if match is None:
return None
return int(match.group(1))
def _is_head_tensor(tensor_name: str) -> bool:
lowered = tensor_name.lower()
return any(marker in lowered for marker in _HEAD_MARKERS)
def _is_tail_tensor(tensor_name: str) -> bool:
lowered = tensor_name.lower()
return lowered in _TAIL_EXACT or any(marker in lowered for marker in _TAIL_MARKERS)
def _metadata_files(root: Path) -> set[str]:
files = {INDEX_FILENAME}
for path in root.iterdir():
if not path.is_file():
continue
name = path.name
if name in METADATA_FILENAMES or name.startswith(_METADATA_PREFIXES):
files.add(name)
return files
def _read_total_layers(root: Path) -> int | None:
config_path = root / "config.json"
if not config_path.exists():
return None
config = json.loads(config_path.read_text(encoding="utf-8"))
return layers_from_config_dict(config)
def layers_from_config_dict(config: dict[str, Any]) -> int | None:
for key in ("num_hidden_layers", "num_layers", "n_layer", "n_layers"):
value = config.get(key)
if isinstance(value, int) and value > 0:
return value
text_config = config.get("text_config")
if isinstance(text_config, dict):
return layers_from_config_dict(text_config)
return None
def _normalise_relative_file(rel_file: str) -> str:
path = Path(rel_file)
if path.is_absolute() or ".." in path.parts:
raise ValueError(f"unsafe relative file in {INDEX_FILENAME}: {rel_file}")
return path.as_posix()

View File

@@ -3,6 +3,7 @@
from __future__ import annotations from __future__ import annotations
import json import json
import os
import socket import socket
import sys import sys
import threading import threading
@@ -25,6 +26,86 @@ from .wallet import load_or_create_wallet
_DEFAULT_BYTES_PER_LAYER = 30 * 1024 * 1024 _DEFAULT_BYTES_PER_LAYER = 30 * 1024 * 1024
def _downloaded_model_inventory(
model: str,
shard_start: int,
shard_end: int,
shard_path: Path,
hf_repo: str | None = None,
model_sources: list[dict] | None = None,
) -> list[dict]:
"""Return a cheap local inventory record without reading model file contents."""
file_count = 0
total_bytes = 0
existing_rel_files: set[str] = set()
if shard_path.exists():
for path in shard_path.rglob("*"):
if not path.is_file():
continue
file_count += 1
try:
existing_rel_files.add(path.relative_to(shard_path).as_posix())
except ValueError:
pass
try:
total_bytes += path.stat().st_size
except OSError:
pass
record = {
"model": model,
"shard_start": shard_start,
"shard_end": shard_end,
"path": str(shard_path),
"file_count": file_count,
"total_bytes": total_bytes,
}
if hf_repo is not None:
record["hf_repo"] = hf_repo
expected_files: set[str] = set()
file_sizes: dict[str, int] = {}
for source in model_sources or []:
for rel in source.get("full_files") or source.get("files") or []:
if isinstance(rel, str) and rel and not rel.startswith("/") and ".." not in Path(rel).parts:
expected_files.add(rel)
sizes = source.get("file_sizes")
if isinstance(sizes, dict):
for rel, size in sizes.items():
if isinstance(rel, str) and isinstance(size, int):
file_sizes[rel] = size
if expected_files:
expected_bytes = sum(file_sizes.get(rel, 0) for rel in expected_files)
local_expected_files = existing_rel_files & expected_files
local_expected_bytes = sum(file_sizes.get(rel, 0) for rel in local_expected_files)
record["expected_file_count"] = len(expected_files)
record["local_expected_file_count"] = len(local_expected_files)
record["expected_bytes"] = expected_bytes
record["local_expected_bytes"] = local_expected_bytes
record["local_model_percentage"] = (
round((local_expected_bytes / expected_bytes) * 100, 4)
if expected_bytes > 0
else 0.0
)
return [record]
def _registration_shard_checksum(model: str, shard_path: Path) -> str | None:
"""Only checksum tiny stub shards; real model folders are too large to hash at startup."""
if model != "stub-model":
return None
return compute_shard_checksum(shard_path)
def _model_cache_path(model_id: str, cache_dir: Path | None) -> Path | None:
if cache_dir is None:
return None
if (cache_dir / "config.json").exists():
return cache_dir
candidate = cache_dir / model_id.split("/")[-1]
if candidate.exists():
return candidate
return None
def _memory_budget(device: str, vram_mb: int, ram_mb: int, shared_vram_mb: int = 0) -> tuple[int, str]: def _memory_budget(device: str, vram_mb: int, ram_mb: int, shared_vram_mb: int = 0) -> tuple[int, str]:
"""Return the capacity budget in MB and whether it came from VRAM or RAM.""" """Return the capacity budget in MB and whether it came from VRAM or RAM."""
if device == "cuda" and vram_mb > 0: if device == "cuda" and vram_mb > 0:
@@ -34,6 +115,23 @@ def _memory_budget(device: str, vram_mb: int, ram_mb: int, shared_vram_mb: int =
return max(0, ram_mb), "RAM" return max(0, ram_mb), "RAM"
def _full_model_sources(model_sources: list[dict]) -> list[dict]:
"""Use tracker full-snapshot URLs for real HF model loading."""
full_sources: list[dict] = []
for source in model_sources:
full_url = source.get("full_url")
if isinstance(full_url, str) and full_url:
full_sources.append({
**source,
"url": full_url,
# full_files (when advertised) enables robust per-file download
# of the whole snapshot; empty list falls back to the tar stream.
"files": source.get("full_files") or [],
"type": f"{source.get('type') or 'model-source'}-full",
})
return full_sources
def _hardware_label(device: str, gpu_name: str | None = None) -> str: def _hardware_label(device: str, gpu_name: str | None = None) -> str:
if device == "cuda": if device == "cuda":
return "CUDA" return "CUDA"
@@ -42,30 +140,112 @@ def _hardware_label(device: str, gpu_name: str | None = None) -> str:
return "CPU" return "CPU"
def _max_assignable_layers(memory_mb: int, total_layers: int | None) -> int: def _positive_int(value: int | str | None, name: str) -> int | None:
if value is None or value == "":
return None
try:
parsed = int(value)
except (TypeError, ValueError) as exc:
raise ValueError(f"{name} must be a positive integer") from exc
if parsed < 1:
raise ValueError(f"{name} must be a positive integer")
return parsed
def _configure_torch_threads(
torch_threads: int | None = None,
torch_interop_threads: int | None = None,
) -> dict[str, int]:
"""Apply PyTorch CPU thread settings before model load/benchmark."""
intra_threads = _positive_int(
torch_threads if torch_threads is not None else os.environ.get("MESHNET_TORCH_THREADS"),
"--torch-threads",
)
interop_threads = _positive_int(
torch_interop_threads
if torch_interop_threads is not None
else os.environ.get("MESHNET_TORCH_INTEROP_THREADS"),
"--torch-interop-threads",
)
if intra_threads is not None:
os.environ.setdefault("OMP_NUM_THREADS", str(intra_threads))
os.environ.setdefault("MKL_NUM_THREADS", str(intra_threads))
try:
import torch
except ModuleNotFoundError:
return {}
if intra_threads is not None:
torch.set_num_threads(intra_threads)
if interop_threads is not None:
torch.set_num_interop_threads(interop_threads)
active: dict[str, int] = {}
try:
active["torch_threads"] = int(torch.get_num_threads())
except Exception:
pass
try:
active["torch_interop_threads"] = int(torch.get_num_interop_threads())
except Exception:
pass
return active
def _max_assignable_layers(
memory_mb: int,
total_layers: int | None,
bytes_per_layer: int | None = None,
) -> int:
if total_layers is None or total_layers <= 0 or memory_mb <= 0: if total_layers is None or total_layers <= 0 or memory_mb <= 0:
return 0 return 0
budget_bytes = memory_mb * 1024 * 1024 budget_bytes = memory_mb * 1024 * 1024
return min(total_layers, int((budget_bytes * 0.8) // _DEFAULT_BYTES_PER_LAYER)) layer_bytes = bytes_per_layer or _DEFAULT_BYTES_PER_LAYER
return min(total_layers, int((budget_bytes * 0.8) // layer_bytes))
def _shard_budget_line(memory_mb: int, memory_source: str, total_layers: int | None, quantization: str) -> str: def _shard_budget_line(
memory_mb: int,
memory_source: str,
total_layers: int | None,
quantization: str,
bytes_per_layer: int | None = None,
) -> str:
memory_gb = memory_mb / 1024 memory_gb = memory_mb / 1024
gb_str = f"{memory_gb:.1f} GB" gb_str = f"{memory_gb:.1f} GB"
budget_quantization = "bfloat16" if quantization == "auto" else quantization
if total_layers is None or total_layers <= 0: if total_layers is None or total_layers <= 0:
return f"Memory budget: {gb_str} {memory_source}; shard budget: unknown model layer count" return f"Memory budget: {gb_str} {memory_source}; shard budget: unknown model layer count"
max_layers = _max_assignable_layers(memory_mb, total_layers) max_layers = _max_assignable_layers(memory_mb, total_layers, bytes_per_layer=bytes_per_layer)
# Remaining capacity after one full model load (rough estimate) # Remaining capacity after one full model load (rough estimate)
shard_bytes = max_layers * _DEFAULT_BYTES_PER_LAYER shard_bytes = max_layers * (bytes_per_layer or _DEFAULT_BYTES_PER_LAYER)
remaining_gb = (memory_mb * 1024 * 1024 - shard_bytes) / (1024 ** 3) remaining_gb = (memory_mb * 1024 * 1024 - shard_bytes) / (1024 ** 3)
remaining_str = f"; {remaining_gb:.1f} GB remaining after full load" if remaining_gb > 1 else "" remaining_str = f"; {remaining_gb:.1f} GB remaining after full load" if remaining_gb > 1 else ""
return ( return (
f"Memory budget: {gb_str} {memory_source}; " f"Memory budget: {gb_str} {memory_source}; "
f"Shard budget: up to {max_layers}/{total_layers} layers at {quantization}" f"Shard budget: up to {max_layers}/{total_layers} layers at {budget_quantization}"
f"{remaining_str}" f"{remaining_str}"
) )
def _assignment_bytes_per_layer(assignment: dict, quantization: str) -> int | None:
bytes_per_layer = assignment.get("bytes_per_layer")
if isinstance(bytes_per_layer, int) and bytes_per_layer > 0:
return bytes_per_layer
if not isinstance(bytes_per_layer, dict):
return None
keys = [quantization, "bfloat16", "bf16", "int8", "nf4"]
for key in keys:
value = bytes_per_layer.get(key)
if isinstance(value, int) and value > 0:
return value
for value in bytes_per_layer.values():
if isinstance(value, int) and value > 0:
return value
return None
def _post_json(url: str, payload: dict, timeout: float = 10.0) -> dict: def _post_json(url: str, payload: dict, timeout: float = 10.0) -> dict:
data = json.dumps(payload).encode() data = json.dumps(payload).encode()
req = urllib.request.Request( req = urllib.request.Request(
@@ -151,6 +331,9 @@ def _attach_relay_bridge(node: StubNodeServer | TorchNodeServer, bridge: RelayHt
node.stop = _stop_with_bridge # type: ignore[method-assign] node.stop = _stop_with_bridge # type: ignore[method-assign]
_PENDING_NODE_ID = "pending"
def _start_heartbeat( def _start_heartbeat(
tracker_url: str, tracker_url: str,
node_id: str, node_id: str,
@@ -188,10 +371,33 @@ def _start_heartbeat(
try: try:
resp = _post_json(f"{tracker_url}/v1/nodes/register", register_payload) resp = _post_json(f"{tracker_url}/v1/nodes/register", register_payload)
node_id = resp.get("node_id", node_id) node_id = resp.get("node_id", node_id)
if node_ref is not None:
setattr(node_ref, "tracker_node_id", node_id)
return True return True
except Exception: except Exception:
return False return False
def _register_additional_assignment(applied: dict) -> None:
model_id = str(applied.get("model") or register_payload.get("hf_repo") or register_payload.get("model"))
extra_payload = {
**register_payload,
"model": model_id.split("/")[-1],
"hf_repo": model_id if "/" in model_id else register_payload.get("hf_repo"),
"shard_start": applied["shard_start"],
"shard_end": applied["shard_end"],
"quantization": applied.get("quantization", register_payload.get("quantization")),
"tracker_mode": bool(applied.get("tracker_mode", False)),
"managed_assignment": True,
}
try:
reg_resp = _post_json(f"{tracker_url}/v1/nodes/register", extra_payload)
print(
f" [node] registered additional model — node ID: {reg_resp.get('node_id')}",
flush=True,
)
except Exception as exc:
print(f" [node] WARNING: additional model registration failed: {exc}", flush=True)
def _apply_directives(directives: list[dict]) -> None: def _apply_directives(directives: list[dict]) -> None:
if not directives: if not directives:
return return
@@ -204,6 +410,9 @@ def _start_heartbeat(
print(f" [node] WARNING: failed to apply tracker directives: {exc}", flush=True) print(f" [node] WARNING: failed to apply tracker directives: {exc}", flush=True)
return return
if applied: if applied:
if applied.get("action") == "ADD_SHARD":
_register_additional_assignment(applied)
return
model_id = applied.get("model", register_payload.get("hf_repo") or register_payload.get("model")) model_id = applied.get("model", register_payload.get("hf_repo") or register_payload.get("model"))
register_payload["model"] = str(model_id).split("/")[-1] register_payload["model"] = str(model_id).split("/")[-1]
register_payload["hf_repo"] = model_id register_payload["hf_repo"] = model_id
@@ -215,7 +424,7 @@ def _start_heartbeat(
def _loop() -> None: def _loop() -> None:
nonlocal node_id nonlocal node_id
hb_url = f"{tracker_url}/v1/nodes/{node_id}/heartbeat" hb_url = f"{tracker_url}/v1/nodes/{node_id}/heartbeat"
outage_streak = 0 # consecutive intervals where tracker was unreachable outage_streak = 1 if node_id == _PENDING_NODE_ID else 0
while True: while True:
time.sleep(interval) time.sleep(interval)
@@ -243,11 +452,12 @@ def _start_heartbeat(
new_asgn = resp.get("new_assignment") new_asgn = resp.get("new_assignment")
if new_asgn: if new_asgn:
print( print(
f" [node] tracker reassignment received: " f" [node] tracker assignment received: "
f"model={new_asgn.get('model')!r} " f"action={new_asgn.get('action')!r} model={new_asgn.get('model')!r} "
f"shards={new_asgn.get('shard_start')}-{new_asgn.get('shard_end')}", f"shards={new_asgn.get('shard_start')}-{new_asgn.get('shard_end')}",
flush=True, flush=True,
) )
_apply_directives([new_asgn])
except urllib.error.HTTPError as exc: except urllib.error.HTTPError as exc:
if exc.code == 404: if exc.code == 404:
# Node was purged (e.g. long gap before restart noticed) — re-register now. # Node was purged (e.g. long gap before restart noticed) — re-register now.
@@ -269,6 +479,34 @@ def _start_heartbeat(
return t return t
def _register_with_tracker(
tracker_url: str,
reg_payload: dict,
node: Any,
start_time: float,
) -> str | None:
"""Register with the tracker, or start background retries when it is unreachable."""
try:
reg_resp = _post_json(f"{tracker_url}/v1/nodes/register", reg_payload)
tracker_node_id = str(reg_resp.get("node_id") or "?")
setattr(node, "tracker_node_id", tracker_node_id)
print(f" Registered with tracker — node ID: {tracker_node_id}", flush=True)
_start_heartbeat(tracker_url, tracker_node_id, reg_payload, node_ref=node, start_time=start_time)
return tracker_node_id
except Exception as exc:
setattr(node, "tracker_node_id", None)
print(f" Warning: tracker registration failed: {exc}", flush=True)
print(" [node] will retry registration in the background", flush=True)
_start_heartbeat(
tracker_url,
_PENDING_NODE_ID,
reg_payload,
node_ref=node,
start_time=start_time,
)
return None
def _warn_virtual_network_ip(ip: str | None) -> None: def _warn_virtual_network_ip(ip: str | None) -> None:
"""Print a warning when the auto-detected advertise IP is in a known virtual-network range. """Print a warning when the auto-detected advertise IP is in a known virtual-network range.
@@ -302,11 +540,11 @@ def _warn_virtual_network_ip(ip: str | None) -> None:
def run_startup( def run_startup(
tracker_url: str, tracker_url: str,
port: int = 0, port: int = 0,
model: str = "stub-model", model: str | None = None,
model_id: str | None = None, model_id: str | None = None,
shard_start: int | None = None, shard_start: int | None = None,
shard_end: int | None = None, shard_end: int | None = None,
quantization: str = "bfloat16", quantization: str = "auto",
wallet_path: Path | None = None, wallet_path: Path | None = None,
cache_dir: Path | None = None, cache_dir: Path | None = None,
host: str = "127.0.0.1", host: str = "127.0.0.1",
@@ -316,6 +554,9 @@ def run_startup(
vram_mb_override: int | None = None, vram_mb_override: int | None = None,
max_loaded_shards: int = 1, max_loaded_shards: int = 1,
debug: bool = False, debug: bool = False,
tracker_source_disabled: bool = False,
torch_threads: int | None = None,
torch_interop_threads: int | None = None,
) -> StubNodeServer | TorchNodeServer: ) -> StubNodeServer | TorchNodeServer:
"""Execute the full startup sequence and return a running node server. """Execute the full startup sequence and return a running node server.
@@ -356,6 +597,12 @@ def run_startup(
print("Detecting hardware...", flush=True) print("Detecting hardware...", flush=True)
hw = detect_hardware() hw = detect_hardware()
torch_thread_config = _configure_torch_threads(torch_threads, torch_interop_threads)
if torch_thread_config:
hw.update(torch_thread_config)
intra = torch_thread_config.get("torch_threads", "?")
interop = torch_thread_config.get("torch_interop_threads", "?")
print(f" PyTorch threads: intra-op={intra}, inter-op={interop}", flush=True)
device: str = hw["device"] device: str = hw["device"]
gpu_name: str | None = hw.get("gpu_name") gpu_name: str | None = hw.get("gpu_name")
vram_mb: int = hw.get("vram_mb", 0) vram_mb: int = hw.get("vram_mb", 0)
@@ -419,8 +666,12 @@ def run_startup(
if probationary_line is not None: if probationary_line is not None:
print(f" {probationary_line}", flush=True) print(f" {probationary_line}", flush=True)
pinned_shard_start = shard_start
pinned_shard_end = shard_end
user_pinned_shard = pinned_shard_start is not None or pinned_shard_end is not None
if model_id: # treat "" the same as None — no explicit model given if model_id: # treat "" the same as None — no explicit model given
user_pinned_shard = shard_start is not None or shard_end is not None full_sources: list[dict] = []
# Auto-detect shard range from model config if not explicitly provided # Auto-detect shard range from model config if not explicitly provided
if shard_start is None or shard_end is None: if shard_start is None or shard_end is None:
try: try:
@@ -442,6 +693,19 @@ def run_startup(
if net_asgn.get("hf_repo") == model_id and net_asgn.get("gap_found"): if net_asgn.get("hf_repo") == model_id and net_asgn.get("gap_found"):
shard_start = net_asgn["shard_start"] shard_start = net_asgn["shard_start"]
shard_end = net_asgn["shard_end"] shard_end = net_asgn["shard_end"]
full_sources = (
[] if tracker_source_disabled
else _full_model_sources(net_asgn.get("model_sources", []))
)
if full_sources:
cache_dir = download_shard(
model_id.split("/")[-1],
shard_start,
shard_end,
cache_dir=cache_dir or Path.home() / ".cache" / "meshnet" / "shards",
hf_repo=model_id,
model_sources=full_sources,
)
print( print(
f" Tracker found uncovered shard: " f" Tracker found uncovered shard: "
f"layers {shard_start}{shard_end} (of {detected})", f"layers {shard_start}{shard_end} (of {detected})",
@@ -465,6 +729,7 @@ def run_startup(
route_timeout=route_timeout, route_timeout=route_timeout,
cache_dir=cache_dir, cache_dir=cache_dir,
debug=debug, debug=debug,
max_loaded_shards=max_loaded_shards,
) )
_node_start_time = time.monotonic() _node_start_time = time.monotonic()
actual_port = node.start() actual_port = node.start()
@@ -487,6 +752,7 @@ def run_startup(
_attach_relay_bridge(node, relay_bridge) _attach_relay_bridge(node, relay_bridge)
# Register with tracker so other nodes can auto-join this model. # Register with tracker so other nodes can auto-join this model.
total_layers = getattr(getattr(node, "backend", None), "total_layers", None) total_layers = getattr(getattr(node, "backend", None), "total_layers", None)
model_cache_path = _model_cache_path(model_id, cache_dir)
reg_payload = { reg_payload = {
"endpoint": endpoint, "endpoint": endpoint,
"model": model_id.split("/")[-1], "model": model_id.split("/")[-1],
@@ -501,19 +767,24 @@ def run_startup(
"tracker_mode": (shard_start == 0), "tracker_mode": (shard_start == 0),
"managed_assignment": not user_pinned_shard, "managed_assignment": not user_pinned_shard,
"model_metadata": model_metadata_for(model_id, total_layers, cache_dir=cache_dir), "model_metadata": model_metadata_for(model_id, total_layers, cache_dir=cache_dir),
"downloaded_models": (
_downloaded_model_inventory(
model_id.split("/")[-1],
shard_start,
shard_end,
model_cache_path,
hf_repo=model_id,
model_sources=full_sources,
)
if model_cache_path is not None
else []
),
**registration_capabilities, **registration_capabilities,
**relay_fields, **relay_fields,
} }
tracker_node_id: str | None = None tracker_node_id = _register_with_tracker(
try: tracker_url, reg_payload, node, _node_start_time,
reg_resp = _post_json(f"{tracker_url}/v1/nodes/register", reg_payload) )
tracker_node_id = str(reg_resp.get("node_id") or "?")
setattr(node, "tracker_node_id", tracker_node_id)
print(f" Registered with tracker — node ID: {tracker_node_id}", flush=True)
_start_heartbeat(tracker_url, tracker_node_id, reg_payload, node_ref=node, start_time=_node_start_time)
except Exception as exc:
setattr(node, "tracker_node_id", None)
print(f" Warning: tracker registration failed: {exc}", flush=True)
print( print(
f"\n{'=' * 32}\n" f"\n{'=' * 32}\n"
@@ -531,30 +802,57 @@ def run_startup(
flush=True, flush=True,
) )
return node return node
if shard_start is not None or shard_end is not None: if user_pinned_shard and not model:
raise ValueError("--shard-start / --shard-end require --model-id") raise ValueError("--shard-start / --shard-end require --model")
# 3a. Auto-join: query tracker for network-wide HF model assignment. # 3a. Auto-join: query tracker for network-wide HF model assignment.
print("Querying tracker for network assignment...", flush=True) # Skipped when the user explicitly requested a model — the shard-assignment
assign_qs = urllib.parse.urlencode({"device": device, "vram_mb": assignment_vram_mb, "ram_mb": ram_mb}) # query below (/v1/nodes/assign?model=…) is authoritative there, and a fresh
# tracker would otherwise print a scary 503 for the model-less auto-join.
net_assignment: dict = {} net_assignment: dict = {}
try: if model_id or (model and model != "stub-model"):
net_assignment = _get_json(f"{tracker_url}/v1/network/assign?{assign_qs}") if model:
except Exception as exc: print(f"Model {model!r} requested explicitly — skipping network auto-join.", flush=True)
print(f" (auto-join unavailable: {exc})", flush=True) else:
print("Querying tracker for network assignment...", flush=True)
assign_qs = urllib.parse.urlencode({"device": device, "vram_mb": assignment_vram_mb, "ram_mb": ram_mb})
try:
net_assignment = _get_json(f"{tracker_url}/v1/network/assign?{assign_qs}")
except Exception as exc:
print(f" (auto-join unavailable: {exc})", flush=True)
assigned_hf_repo: str | None = net_assignment.get("hf_repo") assigned_hf_repo: str | None = net_assignment.get("hf_repo")
_gap_found: bool = bool(net_assignment.get("gap_found", False)) _gap_found: bool = bool(net_assignment.get("gap_found", False))
if assigned_hf_repo and _gap_found: if assigned_hf_repo:
assigned_shard_start: int = net_assignment["shard_start"] assigned_shard_start: int = net_assignment["shard_start"]
assigned_shard_end: int = net_assignment["shard_end"] assigned_shard_end: int = net_assignment["shard_end"]
assigned_num_layers: int = net_assignment["num_layers"] assigned_num_layers: int = net_assignment["num_layers"]
print( assigned_model_sources: list[dict] = net_assignment.get("model_sources", [])
f" Assigned: {assigned_hf_repo} " if _gap_found:
f"layers {assigned_shard_start}{assigned_shard_end} " print(
f"(of {assigned_num_layers})", f" Assigned gap: {assigned_hf_repo} "
flush=True, f"layers {assigned_shard_start}{assigned_shard_end} "
) f"(of {assigned_num_layers})",
flush=True,
)
else:
print(
f" Assigned redundant copy: {assigned_hf_repo} "
f"layers {assigned_shard_start}{assigned_shard_end} "
f"(of {assigned_num_layers})",
flush=True,
)
full_sources = [] if tracker_source_disabled else _full_model_sources(assigned_model_sources)
if full_sources:
print("Downloading assigned model snapshot...", flush=True)
cache_dir = download_shard(
assigned_hf_repo.split("/")[-1],
assigned_shard_start,
assigned_shard_end,
cache_dir=cache_dir or Path.home() / ".cache" / "meshnet" / "shards",
hf_repo=assigned_hf_repo,
model_sources=full_sources,
)
print("Loading real PyTorch model shard...", flush=True) print("Loading real PyTorch model shard...", flush=True)
node = TorchNodeServer( node = TorchNodeServer(
host=host, host=host,
@@ -567,6 +865,7 @@ def run_startup(
route_timeout=route_timeout, route_timeout=route_timeout,
cache_dir=cache_dir, cache_dir=cache_dir,
debug=debug, debug=debug,
max_loaded_shards=max_loaded_shards,
) )
_node_start_time = time.monotonic() _node_start_time = time.monotonic()
actual_port = node.start() actual_port = node.start()
@@ -581,6 +880,7 @@ def run_startup(
relay_url=relay_url, relay_url=relay_url,
) )
_attach_relay_bridge(node, relay_bridge) _attach_relay_bridge(node, relay_bridge)
model_cache_path = _model_cache_path(assigned_hf_repo, cache_dir)
auto_reg_payload = { auto_reg_payload = {
"endpoint": endpoint, "endpoint": endpoint,
"model": assigned_hf_repo.split("/")[-1], "model": assigned_hf_repo.split("/")[-1],
@@ -595,19 +895,24 @@ def run_startup(
"tracker_mode": (assigned_shard_start == 0), "tracker_mode": (assigned_shard_start == 0),
"managed_assignment": True, "managed_assignment": True,
"model_metadata": model_metadata_for(assigned_hf_repo, assigned_num_layers, cache_dir=cache_dir), "model_metadata": model_metadata_for(assigned_hf_repo, assigned_num_layers, cache_dir=cache_dir),
"downloaded_models": (
_downloaded_model_inventory(
assigned_hf_repo.split("/")[-1],
assigned_shard_start,
assigned_shard_end,
model_cache_path,
hf_repo=assigned_hf_repo,
model_sources=full_sources,
)
if model_cache_path is not None
else []
),
**registration_capabilities, **registration_capabilities,
**relay_fields, **relay_fields,
} }
tracker_node_id = None tracker_node_id = _register_with_tracker(
try: tracker_url, auto_reg_payload, node, _node_start_time,
reg_resp = _post_json(f"{tracker_url}/v1/nodes/register", auto_reg_payload) )
tracker_node_id = str(reg_resp.get("node_id") or "?")
setattr(node, "tracker_node_id", tracker_node_id)
print(f" Registered with tracker — node ID: {tracker_node_id}", flush=True)
_start_heartbeat(tracker_url, tracker_node_id, auto_reg_payload, node_ref=node, start_time=_node_start_time)
except Exception as exc:
setattr(node, "tracker_node_id", None)
print(f" Warning: tracker registration failed: {exc}", flush=True)
shard_count = assigned_shard_end - assigned_shard_start + 1 shard_count = assigned_shard_end - assigned_shard_start + 1
print( print(
f"\n{'=' * 32}\n" f"\n{'=' * 32}\n"
@@ -627,12 +932,21 @@ def run_startup(
) )
return node return node
# 3b. Shard assignment from tracker (stub-model / preset-based path) if not assigned_hf_repo and model is None:
raise RuntimeError(
"Tracker did not assign a model. Join a network that already serves one, "
"or start with --model <HF_REPO>."
)
# 3b. Stub preset path (tests / explicit stub-model) or named preset models.
print("Querying tracker for shard assignment...", flush=True) print("Querying tracker for shard assignment...", flush=True)
assign_qs = urllib.parse.urlencode({ assign_qs = urllib.parse.urlencode({
"model": model, "model": model or "stub-model",
"device": device, "device": device,
"vram_mb": vram_mb, # CPU-mode nodes must be sized by RAM: a detected-but-unusable GPU's
# VRAM would otherwise cap the shard (e.g. 8 GB VRAM → 3 layers on a
# 79 GB box whose Torch has no CUDA).
"vram_mb": assignment_vram_mb,
"ram_mb": ram_mb, "ram_mb": ram_mb,
}) })
try: try:
@@ -641,12 +955,25 @@ def run_startup(
print(f" ERROR: Cannot reach tracker at {tracker_url}: {exc}", file=sys.stderr, flush=True) print(f" ERROR: Cannot reach tracker at {tracker_url}: {exc}", file=sys.stderr, flush=True)
raise raise
shard_start: int = assignment["shard_start"] shard_start = assignment["shard_start"]
shard_end: int = assignment["shard_end"] shard_end = assignment["shard_end"]
if user_pinned_shard:
if pinned_shard_start is not None:
shard_start = pinned_shard_start
if pinned_shard_end is not None:
shard_end = pinned_shard_end
assigned_model: str = assignment.get("model", model) assigned_model: str = assignment.get("model", model)
hf_repo: str | None = assignment.get("hf_repo") hf_repo: str | None = assignment.get("hf_repo")
peers: list[dict] = assignment.get("peers", []) peers: list[dict] = assignment.get("peers", [])
print(f" Shard: layers {shard_start}-{shard_end} of {assigned_model}", flush=True) model_sources: list[dict] = [] if tracker_source_disabled else assignment.get("model_sources", [])
assignment_bytes_per_layer = _assignment_bytes_per_layer(assignment, quantization)
if user_pinned_shard:
print(
f" Shard: layers {shard_start}-{shard_end} of {assigned_model} (pinned)",
flush=True,
)
else:
print(f" Shard: layers {shard_start}-{shard_end} of {assigned_model}", flush=True)
# 4. Download shard # 4. Download shard
print("Downloading shard...", flush=True) print("Downloading shard...", flush=True)
@@ -657,8 +984,18 @@ def run_startup(
dl_kwargs["hf_repo"] = hf_repo dl_kwargs["hf_repo"] = hf_repo
if peers: if peers:
dl_kwargs["peers"] = peers dl_kwargs["peers"] = peers
if model_sources:
dl_kwargs["model_sources"] = model_sources
shard_path = download_shard(assigned_model, shard_start, shard_end, **dl_kwargs) shard_path = download_shard(assigned_model, shard_start, shard_end, **dl_kwargs)
shard_checksum = compute_shard_checksum(shard_path) shard_checksum = _registration_shard_checksum(assigned_model, shard_path)
downloaded_models = _downloaded_model_inventory(
assigned_model,
shard_start,
shard_end,
shard_path,
hf_repo=hf_repo,
model_sources=model_sources,
)
print(f" Cached at: {shard_path}", flush=True) print(f" Cached at: {shard_path}", flush=True)
# 5. Start HTTP server # 5. Start HTTP server
@@ -672,6 +1009,7 @@ def run_startup(
model=assigned_model, model=assigned_model,
shard_path=shard_path, shard_path=shard_path,
) )
_node_start_time = time.monotonic()
actual_port = node.start() actual_port = node.start()
public_host = advertise_host or (socket.getfqdn() if host == "0.0.0.0" else host) public_host = advertise_host or (socket.getfqdn() if host == "0.0.0.0" else host)
endpoint = f"http://{public_host}:{actual_port}" endpoint = f"http://{public_host}:{actual_port}"
@@ -687,24 +1025,28 @@ def run_startup(
# 6. Register with tracker # 6. Register with tracker
print("Registering with tracker...", flush=True) print("Registering with tracker...", flush=True)
reg_payload = {
"endpoint": endpoint,
"model": assigned_model,
"shard_start": shard_start,
"shard_end": shard_end,
"shard_checksum": shard_checksum,
"downloaded_models": downloaded_models,
"hardware_profile": hw,
"wallet_address": address,
"score": 1.0,
"managed_assignment": not user_pinned_shard,
**registration_capabilities,
**relay_fields,
}
try: try:
reg_resp = _post_json( reg_resp = _post_json(
f"{tracker_url}/v1/nodes/register", f"{tracker_url}/v1/nodes/register",
{ reg_payload,
"endpoint": endpoint,
"model": assigned_model,
"shard_start": shard_start,
"shard_end": shard_end,
"shard_checksum": shard_checksum,
"hardware_profile": hw,
"wallet_address": address,
"score": 1.0,
**registration_capabilities,
**relay_fields,
},
) )
node_id = str(reg_resp["node_id"]) node_id = str(reg_resp["node_id"])
setattr(node, "tracker_node_id", node_id) setattr(node, "tracker_node_id", node_id)
_start_heartbeat(tracker_url, node_id, reg_payload, node_ref=node, start_time=_node_start_time)
except Exception: except Exception:
node.stop() node.stop()
raise raise
@@ -718,7 +1060,7 @@ def run_startup(
f"meshnet-node ready\n" f"meshnet-node ready\n"
f" Wallet: {address}\n" f" Wallet: {address}\n"
f" Shard: layers {shard_start}-{shard_end} ({assigned_model})\n" f" Shard: layers {shard_start}-{shard_end} ({assigned_model})\n"
f" {_shard_budget_line(memory_budget_mb, memory_budget_source, assignment.get('model_layers_end', shard_end) + 1, quantization)}\n" f" {_shard_budget_line(memory_budget_mb, memory_budget_source, assignment.get('model_layers_end', shard_end) + 1, quantization, bytes_per_layer=assignment_bytes_per_layer)}\n"
f" Endpoint: {endpoint}\n" f" Endpoint: {endpoint}\n"
f" Node ID: {node_id}\n" f" Node ID: {node_id}\n"
f" Hardware: {hw_str}\n" f" Hardware: {hw_str}\n"
@@ -734,11 +1076,22 @@ def _detect_num_layers(model_id: str, cache_dir: Path | None = None) -> int | No
"""Fetch num_hidden_layers from HuggingFace model config (downloads ~1 KB config.json only).""" """Fetch num_hidden_layers from HuggingFace model config (downloads ~1 KB config.json only)."""
try: try:
from transformers import AutoConfig # type: ignore[import] from transformers import AutoConfig # type: ignore[import]
from .model_catalog import layers_from_config
local_model = _model_cache_path(model_id, cache_dir)
load_source = str(local_model) if local_model is not None else model_id
cfg = AutoConfig.from_pretrained( cfg = AutoConfig.from_pretrained(
model_id, load_source,
cache_dir=str(cache_dir) if cache_dir is not None else None, cache_dir=str(cache_dir) if cache_dir is not None and local_model is None else None,
) )
return int(cfg.num_hidden_layers) layers = layers_from_config(cfg)
if layers is None:
print(
f" Warning: no layer count in {model_id} config "
"(checked top level and text_config)", flush=True,
)
return layers
except Exception as exc: except Exception as exc:
print(f" Warning: could not read model config from HF: {exc}", flush=True) print(f" Warning: could not read model config from HF: {exc}", flush=True)
return None return None

View File

@@ -75,20 +75,39 @@ class _TorchHTTPServer(http.server.HTTPServer):
tracker_url: str | None = None, tracker_url: str | None = None,
route_timeout: float = 30.0, route_timeout: float = 30.0,
debug: bool = False, debug: bool = False,
max_loaded_shards: int = 1,
): ):
super().__init__(addr, handler) super().__init__(addr, handler)
self.backend = backend self.backend = backend
self.backends: dict[str, TorchModelShard] = {backend.model_id: backend}
self.received_activations = False self.received_activations = False
self.forward_chunk_count = 0 self.forward_chunk_count = 0
self.tracker_mode = tracker_mode self.tracker_mode = tracker_mode
self.tracker_url = tracker_url self.tracker_url = tracker_url
self.route_timeout = route_timeout self.route_timeout = route_timeout
self.debug = debug self.debug = debug
self.max_loaded_shards = max(1, max_loaded_shards)
self.total_requests: int = 0 self.total_requests: int = 0
self.failed_requests: int = 0 self.failed_requests: int = 0
self.queue_depth: int = 0 self.queue_depth: int = 0
self._stats_lock = threading.Lock() self._stats_lock = threading.Lock()
def resolve_backend(self, model_name: str | None) -> TorchModelShard | None:
if not model_name:
return self.backend
wanted = model_name.strip().lower()
for key, shard_backend in self.backends.items():
key_l = key.lower()
if key_l == wanted or key_l.rsplit("/", 1)[-1] == wanted:
return shard_backend
return self.backend
def chat_enabled(self) -> bool:
return any(
shard_backend.is_head
for shard_backend in self.backends.values()
)
class _TorchHandler(http.server.BaseHTTPRequestHandler): class _TorchHandler(http.server.BaseHTTPRequestHandler):
def log_message(self, fmt, *args): # noqa: suppress request logs in tests def log_message(self, fmt, *args): # noqa: suppress request logs in tests
@@ -100,7 +119,7 @@ class _TorchHandler(http.server.BaseHTTPRequestHandler):
self._handle_forward() self._handle_forward()
elif self.path == "/v1/infer": elif self.path == "/v1/infer":
self._handle_infer() self._handle_infer()
elif self.path == "/v1/chat/completions" and server.tracker_mode: elif self.path == "/v1/chat/completions" and server.chat_enabled():
self._handle_chat_completions() self._handle_chat_completions()
else: else:
self.send_response(404) self.send_response(404)
@@ -284,22 +303,26 @@ class _TorchHandler(http.server.BaseHTTPRequestHandler):
messages = [] messages = []
stream = bool(body.get("stream", False)) stream = bool(body.get("stream", False))
model_name = str(body.get("model", "")) model_name = str(body.get("model", ""))
backend = server.resolve_backend(model_name)
if backend is None or not backend.is_head:
self._send_json(400, {"error": "model not loaded on this node"})
return
max_tokens = int(body.get("max_tokens") or body.get("max_new_tokens") or 256) max_tokens = int(body.get("max_tokens") or body.get("max_new_tokens") or 256)
temperature = float(body.get("temperature") or 1.0) temperature = float(body.get("temperature") or 1.0)
top_p = float(body.get("top_p") or 1.0) top_p = float(body.get("top_p") or 1.0)
# Fast path: this node owns the complete model — use HF generate() with KV cache. # Fast path: this node owns the complete model — use HF generate() with KV cache.
# Avoids the single-token-per-forward-pass limitation of the distributed path. # Avoids the single-token-per-forward-pass limitation of the distributed path.
if server.backend.is_head and server.backend.is_tail: if backend.is_head and backend.is_tail:
try: try:
if stream: if stream:
self._stream_openai_response( self._stream_openai_response(
server.backend.generate_text_streaming(messages, max_tokens, temperature, top_p), backend.generate_text_streaming(messages, max_tokens, temperature, top_p),
model_name, model_name,
) )
else: else:
text = server.backend.generate_text(messages, max_tokens, temperature, top_p) text = backend.generate_text(messages, max_tokens, temperature, top_p)
self._send_openai_response(text, model_name, False, messages) self._send_openai_response(text, model_name, False, messages, backend=backend)
except Exception as exc: except Exception as exc:
self._record_failed_request() self._record_failed_request()
self._send_json(500, {"error": f"generation failed: {exc}"}) self._send_json(500, {"error": f"generation failed: {exc}"})
@@ -309,7 +332,7 @@ class _TorchHandler(http.server.BaseHTTPRequestHandler):
# We do N single-step forward passes (no cross-node KV cache), which is slow # We do N single-step forward passes (no cross-node KV cache), which is slow
# but correct. Each step: head encodes current sequence → forwards through route # but correct. Each step: head encodes current sequence → forwards through route
# → tail returns the next token string → append → repeat. # → tail returns the next token string → append → repeat.
remaining_route = self._get_remaining_route(model_name) remaining_route = self._get_remaining_route(model_name, backend=backend)
print( print(
f" [node] chat route model={model_name!r} max_tokens={max_tokens} " f" [node] chat route model={model_name!r} max_tokens={max_tokens} "
f"downstream={remaining_route}", f"downstream={remaining_route}",
@@ -318,11 +341,10 @@ class _TorchHandler(http.server.BaseHTTPRequestHandler):
if not remaining_route: if not remaining_route:
self._send_openai_response( self._send_openai_response(
"error: no downstream route — check tracker connectivity", "error: no downstream route — check tracker connectivity",
model_name, False, messages, model_name, False, messages, backend=backend,
) )
return return
backend = server.backend
# Format with chat template so the model knows it's in assistant mode. # Format with chat template so the model knows it's in assistant mode.
try: try:
if hasattr(backend.tokenizer, "apply_chat_template"): if hasattr(backend.tokenizer, "apply_chat_template"):
@@ -342,13 +364,17 @@ class _TorchHandler(http.server.BaseHTTPRequestHandler):
generated: list[str] = [] generated: list[str] = []
current_text = prompt_text current_text = prompt_text
stream_emit = None
if stream:
stream_emit = self._start_openai_stream(model_name)
for _ in range(max_tokens): for _ in range(max_tokens):
try: try:
payload = backend.encode_prompt(current_text) payload = backend.encode_prompt(current_text)
except Exception as exc: except Exception as exc:
print(f" [node] distributed encode error: {exc}", flush=True) print(f" [node] distributed encode error: {exc}", flush=True)
break break
token_str = self._run_downstream_pipeline(payload, remaining_route) token_str = self._run_downstream_pipeline(payload, remaining_route, backend=backend)
if not token_str: if not token_str:
break break
# Stop on error responses or EOS. # Stop on error responses or EOS.
@@ -357,12 +383,17 @@ class _TorchHandler(http.server.BaseHTTPRequestHandler):
if eos_token and token_str == eos_token: if eos_token and token_str == eos_token:
break break
generated.append(token_str) generated.append(token_str)
if stream_emit is not None:
stream_emit(token_str)
current_text = current_text + token_str current_text = current_text + token_str
result_text = "".join(generated) result_text = "".join(generated)
self._send_openai_response(result_text, model_name, stream, messages) if stream_emit is not None:
stream_emit(None)
return
self._send_openai_response(result_text, model_name, stream, messages, backend=backend)
def _get_remaining_route(self, model: str) -> list[dict]: def _get_remaining_route(self, model: str, *, backend: TorchModelShard | None = None) -> list[dict]:
"""Return downstream hops as dicts with endpoint, start_layer, and optional relay_addr. """Return downstream hops as dicts with endpoint, start_layer, and optional relay_addr.
Fast path reads X-Meshnet-Route header injected by the tracker. Fast path reads X-Meshnet-Route header injected by the tracker.
@@ -395,9 +426,10 @@ class _TorchHandler(http.server.BaseHTTPRequestHandler):
# Slow path: query the tracker (direct node-to-node calls, or tracker didn't inject). # Slow path: query the tracker (direct node-to-node calls, or tracker didn't inject).
server: _TorchHTTPServer = self.server # type: ignore[assignment] server: _TorchHTTPServer = self.server # type: ignore[assignment]
active_backend = backend or server.backend
if server.tracker_url is None: if server.tracker_url is None:
return [] return []
route_model = getattr(server.backend, "model_id", None) or model route_model = getattr(active_backend, "model_id", None) or model
try: try:
url = f"{server.tracker_url}/v1/route?model={urllib.parse.quote(route_model)}" url = f"{server.tracker_url}/v1/route?model={urllib.parse.quote(route_model)}"
with urllib.request.urlopen(url, timeout=server.route_timeout) as r: with urllib.request.urlopen(url, timeout=server.route_timeout) as r:
@@ -424,18 +456,19 @@ class _TorchHandler(http.server.BaseHTTPRequestHandler):
print(f" [node] WARNING: route lookup failed for {route_model!r}: {exc}", flush=True) print(f" [node] WARNING: route lookup failed for {route_model!r}: {exc}", flush=True)
return [] return []
def _run_downstream_pipeline(self, payload: object, route: list[dict]) -> str: def _run_downstream_pipeline(self, payload: object, route: list[dict], *, backend: TorchModelShard | None = None) -> str:
server: _TorchHTTPServer = self.server # type: ignore[assignment] server: _TorchHTTPServer = self.server # type: ignore[assignment]
active_backend = backend or server.backend
if not route: if not route:
# Partial shard at tail: decode the activation from the previous node. # Partial shard at tail: decode the activation from the previous node.
# Full single-node (head+tail) is handled before entering this method. # Full single-node (head+tail) is handled before entering this method.
if server.backend.is_tail: if active_backend.is_tail:
try: try:
tensor = server.backend.torch.frombuffer( tensor = active_backend.torch.frombuffer(
bytearray(payload.body), # type: ignore[union-attr] bytearray(payload.body), # type: ignore[union-attr]
dtype=server.backend.torch.bfloat16, dtype=active_backend.torch.bfloat16,
).reshape(payload.shape).to(server.backend.device) # type: ignore[union-attr] ).reshape(payload.shape).to(active_backend.device) # type: ignore[union-attr]
return server.backend.decode_tail(tensor) return active_backend.decode_tail(tensor)
except Exception as exc: except Exception as exc:
return f"decode error: {exc}" return f"decode error: {exc}"
return "no downstream route available for non-tail shard" return "no downstream route available for non-tail shard"
@@ -526,6 +559,15 @@ class _TorchHandler(http.server.BaseHTTPRequestHandler):
def _stream_openai_response(self, token_iter, model: str) -> None: def _stream_openai_response(self, token_iter, model: str) -> None:
"""Stream tokens from an iterator as SSE chunks.""" """Stream tokens from an iterator as SSE chunks."""
emit = self._start_openai_stream(model)
for token_text in token_iter:
if not token_text:
continue
emit(token_text)
emit(None)
def _start_openai_stream(self, model: str):
"""Open an OpenAI-compatible SSE response and return a token emitter."""
chunk_id = "chatcmpl-node" chunk_id = "chatcmpl-node"
created = int(time.time()) created = int(time.time())
self.send_response(200) self.send_response(200)
@@ -537,7 +579,7 @@ class _TorchHandler(http.server.BaseHTTPRequestHandler):
try: try:
self.wfile.write(f"data: {data}\n\n".encode()) self.wfile.write(f"data: {data}\n\n".encode())
self.wfile.flush() self.wfile.flush()
except BrokenPipeError: except (BrokenPipeError, ConnectionResetError):
pass pass
_emit(json.dumps({ _emit(json.dumps({
@@ -545,24 +587,27 @@ class _TorchHandler(http.server.BaseHTTPRequestHandler):
"model": model, "model": model,
"choices": [{"index": 0, "delta": {"role": "assistant", "content": ""}, "finish_reason": None}], "choices": [{"index": 0, "delta": {"role": "assistant", "content": ""}, "finish_reason": None}],
})) }))
for token_text in token_iter:
if not token_text: def emit_token(token_text: str | None) -> None:
continue if token_text is None:
_emit(json.dumps({
"id": chunk_id, "object": "chat.completion.chunk", "created": created,
"model": model,
"choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}],
}))
try:
self.wfile.write(b"data: [DONE]\n\n")
self.wfile.flush()
except (BrokenPipeError, ConnectionResetError):
pass
return
_emit(json.dumps({ _emit(json.dumps({
"id": chunk_id, "object": "chat.completion.chunk", "created": created, "id": chunk_id, "object": "chat.completion.chunk", "created": created,
"model": model, "model": model,
"choices": [{"index": 0, "delta": {"content": token_text}, "finish_reason": None}], "choices": [{"index": 0, "delta": {"content": token_text}, "finish_reason": None}],
})) }))
_emit(json.dumps({
"id": chunk_id, "object": "chat.completion.chunk", "created": created, return emit_token
"model": model,
"choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}],
}))
try:
self.wfile.write(b"data: [DONE]\n\n")
self.wfile.flush()
except BrokenPipeError:
pass
def _send_openai_response( def _send_openai_response(
self, self,
@@ -570,11 +615,13 @@ class _TorchHandler(http.server.BaseHTTPRequestHandler):
model: str, model: str,
stream: bool, stream: bool,
messages: list[dict] | None = None, messages: list[dict] | None = None,
backend: TorchModelShard | None = None,
) -> None: ) -> None:
chunk_id = "chatcmpl-node" chunk_id = "chatcmpl-node"
created = int(time.time()) created = int(time.time())
active_backend = backend or self.server.backend # type: ignore[attr-defined]
if not stream: if not stream:
usage = _usage_for_response(self.server.backend, messages or [], text) # type: ignore[attr-defined] usage = _usage_for_response(active_backend, messages or [], text)
self._send_json(200, { self._send_json(200, {
"id": chunk_id, "id": chunk_id,
"object": "chat.completion", "object": "chat.completion",
@@ -685,9 +732,11 @@ class TorchNodeServer:
route_timeout: float = 30.0, route_timeout: float = 30.0,
cache_dir: Path | None = None, cache_dir: Path | None = None,
debug: bool = False, debug: bool = False,
max_loaded_shards: int = 1,
) -> None: ) -> None:
self._host = host self._host = host
self._requested_port = port self._requested_port = port
self._max_loaded_shards = max(1, max_loaded_shards)
self._backend = backend or _load_backend( self._backend = backend or _load_backend(
model_id, model_id,
shard_start, shard_start,
@@ -695,6 +744,7 @@ class TorchNodeServer:
quantization, quantization,
cache_dir, cache_dir,
) )
self._backends: dict[str, TorchModelShard] = {self._backend.model_id: self._backend}
# Auto-detect tracker mode: enabled when shard_start == 0 or explicitly set # Auto-detect tracker mode: enabled when shard_start == 0 or explicitly set
self._tracker_mode = tracker_mode if tracker_mode is not None else (shard_start == 0) self._tracker_mode = tracker_mode if tracker_mode is not None else (shard_start == 0)
self._tracker_url = tracker_url self._tracker_url = tracker_url
@@ -733,41 +783,64 @@ class TorchNodeServer:
def queue_depth(self) -> int: def queue_depth(self) -> int:
return self._server.queue_depth if self._server is not None else 0 return self._server.queue_depth if self._server is not None else 0
@property
def loaded_model_ids(self) -> list[str]:
return list(self._backends.keys())
def apply_tracker_directives(self, directives: list[dict]) -> dict | None: def apply_tracker_directives(self, directives: list[dict]) -> dict | None:
"""Apply tracker LOAD_SHARD directives by hot-swapping the loaded backend.""" """Apply tracker shard directives (LOAD_SHARD replace, ADD_SHARD load-more)."""
add_directive = next(
(directive for directive in reversed(directives) if directive.get("action") == "ADD_SHARD"),
None,
)
load_directive = next( load_directive = next(
(directive for directive in reversed(directives) if directive.get("action") == "LOAD_SHARD"), (directive for directive in reversed(directives) if directive.get("action") == "LOAD_SHARD"),
None, None,
) )
if load_directive is None: directive = add_directive or load_directive
if directive is None:
return None return None
shard_start = int(load_directive["shard_start"]) shard_start = int(directive["shard_start"])
shard_end = int(load_directive["shard_end"]) shard_end = int(directive["shard_end"])
quantization = str(load_directive.get("quantization") or self._backend.quantization) quantization = str(directive.get("quantization") or self._backend.quantization)
model_id = str(load_directive.get("model") or self._backend.model_id) model_id = str(directive.get("model") or self._backend.model_id)
replacing = directive.get("action") == "LOAD_SHARD"
if not replacing and len(self._backends) >= self._max_loaded_shards:
print(
f" [node] WARNING: ignoring ADD_SHARD for {model_id!r}"
f"loaded {len(self._backends)}/{self._max_loaded_shards} slots full",
flush=True,
)
return None
action_label = "reassigned" if replacing else "additional"
print( print(
f" [node] loading reassigned shard: {model_id} layers {shard_start}-{shard_end}", f" [node] loading {action_label} shard: {model_id} layers {shard_start}-{shard_end}",
flush=True, flush=True,
) )
try: try:
new_backend = _load_backend(model_id, shard_start, shard_end, quantization, self._cache_dir) new_backend = _load_backend(model_id, shard_start, shard_end, quantization, self._cache_dir)
except TypeError: except TypeError:
new_backend = _load_backend(model_id, shard_start, shard_end, quantization) new_backend = _load_backend(model_id, shard_start, shard_end, quantization)
self._backend = new_backend self._backends[model_id] = new_backend
self._tracker_mode = shard_start == 0 if replacing or shard_start == 0:
if self._server is not None: self._backend = new_backend
self._server.backend = new_backend self._tracker_mode = shard_start == 0
self._server.tracker_mode = self._tracker_mode
print( print(
f" [node] loaded reassigned shard: {model_id} layers {shard_start}-{shard_end}", f" [node] loaded {action_label} shard: {model_id} layers {shard_start}-{shard_end}",
flush=True, flush=True,
) )
if self._server is not None:
self._server.backends = dict(self._backends)
if replacing or shard_start == 0:
self._server.backend = new_backend
self._server.tracker_mode = self._tracker_mode
return { return {
"action": directive.get("action"),
"model": model_id, "model": model_id,
"shard_start": shard_start, "shard_start": shard_start,
"shard_end": shard_end, "shard_end": shard_end,
"quantization": quantization, "quantization": quantization,
"tracker_mode": self._tracker_mode, "tracker_mode": shard_start == 0,
} }
def start(self) -> int: def start(self) -> int:
@@ -781,7 +854,9 @@ class TorchNodeServer:
self._tracker_url, self._tracker_url,
self._route_timeout, self._route_timeout,
self._debug, self._debug,
self._max_loaded_shards,
) )
self._server.backends = dict(self._backends)
self.port = self._server.server_address[1] self.port = self._server.server_address[1]
self._thread = threading.Thread(target=self._server.serve_forever, daemon=True) self._thread = threading.Thread(target=self._server.serve_forever, daemon=True)
self._thread.start() self._thread.start()

View File

@@ -19,6 +19,7 @@ dependencies = [
"transformers>=4.39", "transformers>=4.39",
"websockets>=13", "websockets>=13",
"zstandard>=0.22", "zstandard>=0.22",
"kernels>=0.11.1,<0.16",
] ]
[project.scripts] [project.scripts]

View File

@@ -57,7 +57,9 @@ class RelayServer:
self._ready = threading.Event() self._ready = threading.Event()
self._running = False self._running = False
self._stop_event: asyncio.Event | None = None self._stop_event: asyncio.Event | None = None
self._pending_rpc: dict[str, asyncio.Future] = {} # request_id → queue of relay-http-response frames (US-036: a streamed
# response is a sequence of frames; a frame without "stream" is terminal).
self._pending_rpc: dict[str, asyncio.Queue] = {}
@property @property
def registry(self) -> PeerRegistry: def registry(self) -> PeerRegistry:
@@ -172,9 +174,9 @@ class RelayServer:
if topic == "relay-http-response": if topic == "relay-http-response":
payload = envelope.get("payload", {}) payload = envelope.get("payload", {})
request_id = payload.get("request_id") request_id = payload.get("request_id")
fut = self._pending_rpc.pop(request_id, None) queue = self._pending_rpc.get(request_id)
if fut is not None and not fut.done(): if queue is not None:
fut.set_result(payload) queue.put_nowait(payload)
continue continue
# Fan out to all other registered peers # Fan out to all other registered peers
@@ -240,8 +242,12 @@ class RelayServer:
request_id = str(payload.get("request_id") or uuid.uuid4()) request_id = str(payload.get("request_id") or uuid.uuid4())
payload["request_id"] = request_id payload["request_id"] = request_id
payload["target_peer"] = target_peer_id payload["target_peer"] = target_peer_id
fut = self._loop.create_future() if self._loop is not None else asyncio.get_running_loop().create_future() queue: asyncio.Queue = asyncio.Queue()
self._pending_rpc[request_id] = fut self._pending_rpc[request_id] = queue
overall_timeout = 310.0
idle_timeout = 120.0
loop = asyncio.get_running_loop()
deadline = loop.time() + overall_timeout
try: try:
await target.ws.send(json.dumps({ await target.ws.send(json.dumps({
"topic": "relay-http-request", "topic": "relay-http-request",
@@ -249,8 +255,19 @@ class RelayServer:
"from_peer": "relay", "from_peer": "relay",
"payload": payload, "payload": payload,
})) }))
response = await asyncio.wait_for(fut, timeout=310.0) # Forward frames until a terminal one: streamed responses (US-036)
await ws_requester.send(json.dumps(response)) # end with {"stream": true, "done": true}; a frame without "stream"
# is a complete legacy single response.
while True:
remaining = deadline - loop.time()
if remaining <= 0:
raise asyncio.TimeoutError
frame = await asyncio.wait_for(
queue.get(), timeout=min(idle_timeout, remaining)
)
await ws_requester.send(json.dumps(frame))
if not frame.get("stream") or frame.get("done"):
break
except asyncio.TimeoutError: except asyncio.TimeoutError:
await ws_requester.send(json.dumps({ await ws_requester.send(json.dumps({
"request_id": request_id, "request_id": request_id,

View File

@@ -176,6 +176,14 @@ class AccountStore:
with self._lock: with self._lock:
return api_key in self._revoked_keys return api_key in self._revoked_keys
def is_active_key(self, api_key: str) -> bool:
with self._lock:
return api_key in self._active_keys
def owner_of_key(self, api_key: str) -> str | None:
with self._lock:
return self._active_keys.get(api_key)
# ---- views ---- # ---- views ----
def _public_view(self, record: dict) -> dict: def _public_view(self, record: dict) -> dict:

View File

@@ -0,0 +1,75 @@
"""Unified tracker auth primitives (ADR-0017, alpha issues 01/02/20).
Two mechanisms live here:
- **Hive peer HMAC** — gossip mutation endpoints require a signature computed
as HMAC-SHA256(hive_secret, "<timestamp>." + raw_body). All trackers in a
hive share one secret (``--hive-secret`` / MESHNET_HIVE_SECRET). Timestamps
outside the skew window are rejected to blunt replay.
- **Validator service token** — a dedicated bearer credential distinct from
client API keys and admin sessions (``--validator-service-token`` /
MESHNET_VALIDATOR_SERVICE_TOKEN), resolved to the ``validator`` role.
Role resolution itself happens in the request handler (it needs the account
store); these are the shared, dependency-free pieces.
"""
from __future__ import annotations
import hmac
import hashlib
import time
HIVE_SIGNATURE_HEADER = "X-Meshnet-Hive-Signature"
HIVE_TIMESTAMP_HEADER = "X-Meshnet-Hive-Timestamp"
HIVE_MAX_CLOCK_SKEW_SECONDS = 300.0
def _hive_digest(secret: str, timestamp: str, body: bytes) -> str:
return hmac.new(
secret.encode(), timestamp.encode() + b"." + body, hashlib.sha256
).hexdigest()
def sign_hive_request(secret: str, body: bytes, *, timestamp: float | None = None) -> dict[str, str]:
"""Headers a tracker attaches when pushing gossip to a hive peer."""
ts = f"{timestamp if timestamp is not None else time.time():.3f}"
return {
HIVE_SIGNATURE_HEADER: _hive_digest(secret, ts, body),
HIVE_TIMESTAMP_HEADER: ts,
}
def verify_hive_request(
secret: str | None,
headers,
body: bytes,
*,
now: float | None = None,
) -> bool:
"""True only when the request carries a fresh, valid hive signature.
Fails closed: no configured secret means no gossip is accepted.
"""
if not secret:
return False
signature = headers.get(HIVE_SIGNATURE_HEADER)
timestamp = headers.get(HIVE_TIMESTAMP_HEADER)
if not signature or not timestamp:
return False
try:
ts_value = float(timestamp)
except ValueError:
return False
current = now if now is not None else time.time()
if abs(current - ts_value) > HIVE_MAX_CLOCK_SKEW_SECONDS:
return False
return hmac.compare_digest(signature, _hive_digest(secret, timestamp, body))
def is_validator_token(token: str | None, configured: str | None) -> bool:
"""Constant-time check of a presented bearer token against the configured
validator service token."""
if not token or not configured:
return False
return hmac.compare_digest(token, configured)

View File

@@ -19,11 +19,23 @@ import time
import uuid import uuid
DEFAULT_PRICE_PER_1K_TOKENS = 0.02 # USDT DEFAULT_PRICE_PER_1K_TOKENS = 0.02 # USDT
DEFAULT_STARTING_CREDIT = 1.0 # USDT of Caller Credit for a new API key DEFAULT_STARTING_CREDIT = 0.0 # USDT; accounts must be funded before inference
DEFAULT_BILLING_DB_PATH = "billing.sqlite" DEFAULT_BILLING_DB_PATH = "billing.sqlite"
NODE_REVENUE_SHARE = 0.90 # nodes 90% / protocol cut 10% (ADR-0015) NODE_REVENUE_SHARE = 0.90 # nodes 90% / protocol cut 10% (ADR-0015)
def _normalize_rates(value: "float | tuple[float, float] | dict") -> tuple[float, float]:
"""Coerce a price spec into an (input_per_1k, output_per_1k) pair."""
if isinstance(value, dict):
base = value.get("price")
inp = value.get("input", base)
out = value.get("output", base)
return (float(inp), float(out))
if isinstance(value, (tuple, list)):
return (float(value[0]), float(value[1]))
return (float(value), float(value))
class BillingLedger: class BillingLedger:
"""Thread-safe USDT ledger with SQLite persistence and event replication.""" """Thread-safe USDT ledger with SQLite persistence and event replication."""
@@ -33,13 +45,17 @@ class BillingLedger:
self, self,
db_path: str | None = None, db_path: str | None = None,
*, *,
prices: dict[str, float] | None = None, prices: dict[str, float | tuple[float, float]] | None = None,
default_price_per_1k: float = DEFAULT_PRICE_PER_1K_TOKENS, default_price_per_1k: float = DEFAULT_PRICE_PER_1K_TOKENS,
starting_credit: float = DEFAULT_STARTING_CREDIT, starting_credit: float = DEFAULT_STARTING_CREDIT,
node_share: float = NODE_REVENUE_SHARE, node_share: float = NODE_REVENUE_SHARE,
) -> None: ) -> None:
self._db_path = db_path self._db_path = db_path
self._prices = dict(prices) if prices else {} # US-045: per-model (input_per_1k, output_per_1k). A bare float in
# ``prices`` sets both rates (legacy single-rate models).
self._prices: dict[str, tuple[float, float]] = {
model: _normalize_rates(value) for model, value in (prices or {}).items()
}
self._default_price_per_1k = default_price_per_1k self._default_price_per_1k = default_price_per_1k
self._starting_credit = starting_credit self._starting_credit = starting_credit
self._node_share = node_share self._node_share = node_share
@@ -62,18 +78,30 @@ class BillingLedger:
# ---- pricing ---- # ---- pricing ----
def price_for(self, model: str) -> float: def price_for(self, model: str) -> float:
return self._prices.get(model, self._default_price_per_1k) """Blended (average) per-1k rate — kept for estimators and history logs."""
rates = self._prices.get(model)
if rates is None:
return self._default_price_per_1k
return (rates[0] + rates[1]) / 2.0
def prices_for(self, model: str) -> tuple[float, float]:
"""(input_per_1k, output_per_1k) for a model (US-045)."""
return self._prices.get(model, (self._default_price_per_1k, self._default_price_per_1k))
def set_price(self, model: str, price_per_1k: float) -> None: def set_price(self, model: str, price_per_1k: float) -> None:
"""Legacy single-rate setter — applies the same rate to input and output."""
self.set_prices(model, price_per_1k, price_per_1k)
def set_prices(self, model: str, input_per_1k: float, output_per_1k: float) -> None:
with self._lock: with self._lock:
self._prices[model] = price_per_1k self._prices[model] = (float(input_per_1k), float(output_per_1k))
# ---- local operations (create + apply + log an event) ---- # ---- local operations (create + apply + log an event) ----
def ensure_client(self, api_key: str) -> float: def ensure_client(self, api_key: str) -> float:
"""Return the client's balance, granting Caller Credit on first touch.""" """Return the client's balance without granting implicit credit."""
with self._lock: with self._lock:
if api_key not in self._client_balances: if api_key not in self._client_balances and self._starting_credit > 0.0:
self._apply_locked({ self._apply_locked({
"id": f"credit-{uuid.uuid4().hex}", "id": f"credit-{uuid.uuid4().hex}",
"type": "credit", "type": "credit",
@@ -82,11 +110,34 @@ class BillingLedger:
"ts": time.time(), "ts": time.time(),
"note": "caller-credit", "note": "caller-credit",
}) })
return self._client_balances[api_key] return self._client_balances.get(api_key, 0.0)
def has_funds(self, api_key: str) -> bool: def has_funds(self, api_key: str) -> bool:
return self.ensure_client(api_key) > 0.0 return self.ensure_client(api_key) > 0.0
def grant_caller_credit(self, api_key: str, account_id: str, amount: float) -> bool:
"""Grant the one-time Caller Credit for an account (US-039).
The event id is derived from the account, not the key, so the grant is
idempotent per account — across retries, additional keys, and hive
gossip replication alike. Returns True only when credit was applied.
"""
if amount <= 0:
return False
event_id = f"caller-credit-{account_id}"
with self._lock:
if event_id in self._seen_event_ids:
return False
self._apply_locked({
"id": event_id,
"type": "credit",
"api_key": api_key,
"amount": amount,
"ts": time.time(),
"note": "caller-credit",
})
return True
def credit_client(self, api_key: str, amount: float, *, note: str = "deposit") -> float: def credit_client(self, api_key: str, amount: float, *, note: str = "deposit") -> float:
if amount <= 0: if amount <= 0:
raise ValueError("credit amount must be positive") raise ValueError("credit amount must be positive")
@@ -107,9 +158,17 @@ class BillingLedger:
model: str, model: str,
total_tokens: int, total_tokens: int,
node_work: list[tuple[str | None, int]], node_work: list[tuple[str | None, int]],
*,
input_tokens: int | None = None,
output_tokens: int | None = None,
) -> dict: ) -> dict:
"""Debit the client and split the fee 90/10. """Debit the client and split the fee 90/10.
With ``input_tokens``/``output_tokens`` (US-045) the cost is
``input·in_rate + output·out_rate``; without them, legacy behavior —
``total_tokens`` at the blended rate. Replayed/gossiped events apply
their recorded ``cost``, so old events are unaffected either way.
``node_work`` is ``[(wallet_address | None, work_units), ...]`` for the ``node_work`` is ``[(wallet_address | None, work_units), ...]`` for the
nodes that served the request. Work units of nodes without a wallet nodes that served the request. Work units of nodes without a wallet
accrue to the protocol cut — there is nowhere to pay them out. accrue to the protocol cut — there is nowhere to pay them out.
@@ -117,7 +176,14 @@ class BillingLedger:
request is then rejected by ``has_funds`` (post-pay drift, standard request is then rejected by ``has_funds`` (post-pay drift, standard
metered-billing behavior). metered-billing behavior).
""" """
cost = self.price_for(model) * max(0, total_tokens) / 1000.0 if input_tokens is not None or output_tokens is not None:
in_rate, out_rate = self.prices_for(model)
in_tokens = max(0, input_tokens or 0)
out_tokens = max(0, output_tokens or 0)
cost = (in_tokens * in_rate + out_tokens * out_rate) / 1000.0
total_tokens = in_tokens + out_tokens
else:
cost = self.price_for(model) * max(0, total_tokens) / 1000.0
total_work = sum(max(0, w) for _, w in node_work) total_work = sum(max(0, w) for _, w in node_work)
node_pool = cost * self._node_share node_pool = cost * self._node_share
shares: dict[str, float] = {} shares: dict[str, float] = {}
@@ -127,7 +193,7 @@ class BillingLedger:
shares[wallet] = shares.get(wallet, 0.0) + node_pool * work / total_work shares[wallet] = shares.get(wallet, 0.0) + node_pool * work / total_work
protocol_amount = cost - sum(shares.values()) protocol_amount = cost - sum(shares.values())
with self._lock: with self._lock:
if api_key not in self._client_balances: if api_key not in self._client_balances and self._starting_credit > 0.0:
self._apply_locked({ self._apply_locked({
"id": f"credit-{uuid.uuid4().hex}", "id": f"credit-{uuid.uuid4().hex}",
"type": "credit", "type": "credit",
@@ -142,6 +208,9 @@ class BillingLedger:
"api_key": api_key, "api_key": api_key,
"model": model, "model": model,
"total_tokens": total_tokens, "total_tokens": total_tokens,
**({"input_tokens": max(0, input_tokens or 0),
"output_tokens": max(0, output_tokens or 0)}
if (input_tokens is not None or output_tokens is not None) else {}),
"cost": cost, "cost": cost,
"shares": shares, "shares": shares,
"protocol_amount": protocol_amount, "protocol_amount": protocol_amount,
@@ -150,14 +219,21 @@ class BillingLedger:
self._apply_locked(event) self._apply_locked(event)
return event return event
def bind_wallet(self, api_key: str, wallet: str) -> dict: def bind_wallet(self, api_key: str, wallet: str, *, admin_override: bool = False) -> dict:
"""Bind a client wallet pubkey to an API key (US-032 deposits).""" """Bind a client wallet pubkey to an API key (US-032 deposits, C6).
A wallet already bound to a *different* api_key is left untouched
unless ``admin_override`` is set — enforced in ``_apply_locked`` so a
conflicting gossip ``bind`` event can never silently clobber an
existing binding either. Callers should check ``event["rejected"]``.
"""
with self._lock: with self._lock:
event = { event = {
"id": f"bind-{uuid.uuid4().hex}", "id": f"bind-{uuid.uuid4().hex}",
"type": "bind", "type": "bind",
"api_key": api_key, "api_key": api_key,
"wallet": wallet, "wallet": wallet,
"admin_override": admin_override,
"ts": time.time(), "ts": time.time(),
} }
self._apply_locked(event) self._apply_locked(event)
@@ -262,10 +338,17 @@ class BillingLedger:
] ]
def settle_node_payout(self, wallet: str, amount: float, *, reference: str = "") -> dict: def settle_node_payout(self, wallet: str, amount: float, *, reference: str = "") -> dict:
"""Deduct a paid-out amount from a node's pending balance (US-033 hook).""" """Deduct a paid-out amount from a node's pending balance (US-033 hook).
ADR-0015: clamps to whatever is still pending under the same lock as
the deduction, so a forfeiture that lands between the settlement
loop's `payables()` snapshot and this call is never paid out on top
of — the wallet gets at most what remains, never a stale amount.
"""
if amount <= 0: if amount <= 0:
raise ValueError("payout amount must be positive") raise ValueError("payout amount must be positive")
with self._lock: with self._lock:
amount = min(amount, self._node_pending.get(wallet, 0.0))
event = { event = {
"id": f"payout-{uuid.uuid4().hex}", "id": f"payout-{uuid.uuid4().hex}",
"type": "payout", "type": "payout",
@@ -348,7 +431,12 @@ class BillingLedger:
self._node_pending[wallet] = self._node_pending.get(wallet, 0.0) - amount self._node_pending[wallet] = self._node_pending.get(wallet, 0.0) - amount
self._protocol_cut += amount self._protocol_cut += amount
elif etype == "bind": elif etype == "bind":
self._wallet_bindings[event["wallet"]] = event["api_key"] wallet = event["wallet"]
existing = self._wallet_bindings.get(wallet)
if existing is not None and existing != event["api_key"] and not event.get("admin_override"):
event["rejected"] = True
else:
self._wallet_bindings[wallet] = event["api_key"]
else: else:
return return
self._seen_event_ids.add(event["id"]) self._seen_event_ids.add(event["id"])
@@ -365,13 +453,13 @@ class BillingLedger:
with self._lock: with self._lock:
return self._node_pending.get(wallet, 0.0) return self._node_pending.get(wallet, 0.0)
def usage_for(self, api_keys: list[str], *, recent_limit: int = 20) -> dict: def usage_for(self, api_keys: list[str], *, recent_limit: int | None = None) -> dict:
"""Aggregate charge history for a set of API keys (dashboard view).""" """Aggregate charge history for a set of API keys (dashboard view)."""
keys = set(api_keys) keys = set(api_keys)
requests = 0 requests = 0
total_tokens = 0 total_tokens = 0
total_cost = 0.0 total_cost = 0.0
recent: list[dict] = [] records: list[dict] = []
with self._lock: with self._lock:
for event in self._event_log: for event in self._event_log:
if event.get("type") != "charge" or event.get("api_key") not in keys: if event.get("type") != "charge" or event.get("api_key") not in keys:
@@ -379,18 +467,20 @@ class BillingLedger:
requests += 1 requests += 1
total_tokens += int(event.get("total_tokens", 0)) total_tokens += int(event.get("total_tokens", 0))
total_cost += float(event.get("cost", 0.0)) total_cost += float(event.get("cost", 0.0))
recent.append({ records.append({
"api_key": event["api_key"], "api_key": event["api_key"],
"model": event.get("model"), "model": event.get("model"),
"total_tokens": event.get("total_tokens", 0), "total_tokens": event.get("total_tokens", 0),
"cost": event.get("cost", 0.0), "cost": event.get("cost", 0.0),
"ts": event.get("ts", 0.0), "ts": event.get("ts", 0.0),
}) })
recent = records[-recent_limit:] if recent_limit is not None else records
return { return {
"requests": requests, "requests": requests,
"total_tokens": total_tokens, "total_tokens": total_tokens,
"total_cost": total_cost, "total_cost": total_cost,
"recent": recent[-recent_limit:], "records": records,
"recent": recent,
} }
def snapshot(self) -> dict: def snapshot(self) -> dict:

View File

@@ -0,0 +1,223 @@
"""TOPLOC honest-noise calibration corpus (ADR-0018 consequences, issue 21).
Production TOPLOC audit thresholds must be derived from an empirical
honest-noise baseline across the active fleet's hardware, not guessed
(research-verifiable-inference.md §8 layer 3). This store persists one row
per (node wallet, GPU model, dtype) calibration run so thresholds can be
computed from a queryable corpus instead of a flat JSON dump, and re-derived
whenever the fleet's hardware mix changes.
"""
from __future__ import annotations
import json
import sqlite3
import threading
import time
import uuid
DEFAULT_CALIBRATION_DB_PATH = "toploc_calibration.sqlite"
# Headroom added on top of the observed p99 honest-noise envelope so normal
# hardware variance doesn't trip the recommended threshold (ADR-0018 §3).
DEFAULT_SAFETY_MARGIN = 0.20
DEFAULT_PERCENTILE = 0.99
class ToplocCalibrationStore:
"""Thread-safe SQLite-backed corpus of per-node TOPLOC divergence runs."""
def __init__(self, db_path: str | None = None) -> None:
self._db_path = db_path
self._lock = threading.Lock()
self._runs: list[dict] = []
if self._db_path:
self._init_db()
self._load_from_db()
def record_run(
self,
*,
node_wallet: str,
gpu_model: str | None,
dtype: str | None,
model: str,
passed: bool,
exp_intersections: float | None,
mant_err_mean: float | None,
mant_err_median: float | None,
ts: float | None = None,
) -> dict:
run = {
"id": f"cal-{uuid.uuid4().hex}",
"node_wallet": node_wallet,
"gpu_model": gpu_model or "unknown",
"dtype": dtype or "unknown",
"model": model,
"passed": bool(passed),
"exp_intersections": exp_intersections,
"mant_err_mean": mant_err_mean,
"mant_err_median": mant_err_median,
"ts": ts if ts is not None else time.time(),
}
with self._lock:
self._runs.append(run)
self._save_run(run)
return run
def runs(self) -> list[dict]:
with self._lock:
return list(self._runs)
def distinct_hardware_profiles(self) -> set[tuple[str, str]]:
with self._lock:
return {(r["gpu_model"], r["dtype"]) for r in self._runs}
def gate_status(self, *, min_hardware_profiles: int) -> dict:
"""Whether the corpus is broad enough to enable production thresholds.
Alpha exception (issue 21): with a small, fully hired/controlled VPS
fleet, ``min_hardware_profiles`` may legitimately equal the fleet's
actual distinct hardware count — this must be revisited before a
public/volunteer launch broadens the hardware mix.
"""
distinct = len(self.distinct_hardware_profiles())
return {
"distinct_hardware_profiles": distinct,
"min_hardware_profiles": min_hardware_profiles,
"sample_count": len(self._runs),
"ready": distinct > 0 and distinct >= min_hardware_profiles,
}
def envelope(
self,
*,
percentile: float = DEFAULT_PERCENTILE,
safety_margin: float = DEFAULT_SAFETY_MARGIN,
) -> dict:
"""Recommended tolerance constants derived from the corpus.
`exp_intersections` (higher = better match) gets a floor at its
worst-case (low) percentile minus margin; the mantissa errors
(higher = worse) get a ceiling at their worst-case (high) percentile
plus margin. Returns None for a metric with no samples yet.
"""
with self._lock:
runs = list(self._runs)
exp_vals = sorted(v for r in runs if (v := r["exp_intersections"]) is not None)
mean_vals = sorted(v for r in runs if (v := r["mant_err_mean"]) is not None)
median_vals = sorted(v for r in runs if (v := r["mant_err_median"]) is not None)
min_exp = _floor(exp_vals, 1.0 - percentile, safety_margin)
max_mean = _ceiling(mean_vals, percentile, safety_margin)
max_median = _ceiling(median_vals, percentile, safety_margin)
return {
"sample_count": len(runs),
"distinct_hardware_profiles": len(self.distinct_hardware_profiles()),
"percentile": percentile,
"safety_margin": safety_margin,
"recommended_min_exp_intersections": min_exp,
"recommended_max_mant_err_mean": max_mean,
"recommended_max_mant_err_median": max_median,
# In-sample estimate only: the fraction of this same honest
# corpus that the recommended thresholds would themselves flag.
# Not a substitute for independent validation data — but a
# documented starting estimate per issue 21's acceptance
# criteria, and a sanity check that the margin isn't too tight.
"estimated_false_positive_rate": _false_positive_rate(
runs, min_exp=min_exp, max_mean=max_mean, max_median=max_median,
),
}
# ---- persistence (billing.py pattern) ----
def _init_db(self) -> None:
con = sqlite3.connect(self._db_path) # type: ignore[arg-type]
con.execute(
"CREATE TABLE IF NOT EXISTS toploc_calibration_runs "
"(run_id TEXT PRIMARY KEY, node_wallet TEXT NOT NULL, "
"gpu_model TEXT NOT NULL, dtype TEXT NOT NULL, payload TEXT NOT NULL, "
"ts REAL NOT NULL)"
)
con.commit()
con.close()
def _load_from_db(self) -> None:
con = sqlite3.connect(self._db_path) # type: ignore[arg-type]
rows = con.execute(
"SELECT payload FROM toploc_calibration_runs ORDER BY ts, run_id"
).fetchall()
con.close()
for (payload,) in rows:
try:
self._runs.append(json.loads(payload))
except json.JSONDecodeError:
continue
def _save_run(self, run: dict) -> None:
if not self._db_path:
return
con = sqlite3.connect(self._db_path) # type: ignore[arg-type]
con.execute(
"INSERT OR IGNORE INTO toploc_calibration_runs "
"(run_id, node_wallet, gpu_model, dtype, payload, ts) VALUES (?, ?, ?, ?, ?, ?)",
(run["id"], run["node_wallet"], run["gpu_model"], run["dtype"], json.dumps(run), float(run["ts"])),
)
con.commit()
con.close()
def _percentile(sorted_vals: list[float], p: float) -> float:
if len(sorted_vals) == 1:
return sorted_vals[0]
k = (len(sorted_vals) - 1) * p
lo = int(k)
hi = min(lo + 1, len(sorted_vals) - 1)
if lo == hi:
return sorted_vals[lo]
return sorted_vals[lo] + (sorted_vals[hi] - sorted_vals[lo]) * (k - lo)
def _floor(sorted_vals: list[float], p: float, safety_margin: float) -> float | None:
if not sorted_vals:
return None
return max(0.0, _percentile(sorted_vals, p) * (1.0 - safety_margin))
def _ceiling(sorted_vals: list[float], p: float, safety_margin: float) -> float | None:
if not sorted_vals:
return None
return _percentile(sorted_vals, p) * (1.0 + safety_margin)
def _false_positive_rate(
runs: list[dict],
*,
min_exp: float | None,
max_mean: float | None,
max_median: float | None,
) -> float | None:
"""Fraction of the (honest, by construction) corpus that would be
flagged by the recommended thresholds — an in-sample false-positive
rate estimate, not out-of-sample validation."""
if not runs:
return None
flagged = 0
for r in runs:
exp = r["exp_intersections"]
mean = r["mant_err_mean"]
median = r["mant_err_median"]
would_flag = (
(min_exp is not None and exp is not None and exp < min_exp)
or (max_mean is not None and mean is not None and mean > max_mean)
or (max_median is not None and median is not None and median > max_median)
)
if would_flag:
flagged += 1
return flagged / len(runs)
__all__ = [
"DEFAULT_CALIBRATION_DB_PATH",
"DEFAULT_SAFETY_MARGIN",
"DEFAULT_PERCENTILE",
"ToplocCalibrationStore",
]

View File

@@ -1,15 +1,58 @@
"""meshnet-tracker CLI entry point.""" """meshnet-tracker CLI entry point."""
import argparse import argparse
import os
import sys import sys
import time import time
from pathlib import Path
from .accounts import DEFAULT_ACCOUNTS_DB_PATH from .accounts import DEFAULT_ACCOUNTS_DB_PATH
from .billing import DEFAULT_BILLING_DB_PATH from .billing import DEFAULT_BILLING_DB_PATH
from .server import TrackerServer, derive_relay_url_from_public_tracker_url from .hf_pricing import DEFAULT_HF_PRICING_LOG_DB_PATH
from .server import (
DEFAULT_CALLER_CREDIT_USDT,
DEFAULT_DEVNET_TOPUP_USDT,
TrackerServer,
derive_relay_url_from_public_tracker_url,
)
DEFAULT_REGISTRY_DB_PATH = "meshnet_registry.sqlite3"
def _load_env_file(path: Path) -> None:
"""Load simple KEY=VALUE pairs from an env file without overriding env vars."""
if not path.exists():
return
try:
lines = path.read_text().splitlines()
except OSError:
return
for line in lines:
text = line.strip()
if not text or text.startswith("#"):
continue
if text.startswith("export "):
text = text[len("export "):].strip()
if "=" not in text:
continue
key, value = text.split("=", 1)
key = key.strip()
if not key or key in os.environ:
continue
value = value.strip()
if len(value) >= 2 and value[0] == value[-1] and value[0] in {"'", '"'}:
value = value[1:-1]
os.environ[key] = value
def _load_env_defaults() -> None:
"""Load local and user-level tracker env defaults before parsing arguments."""
_load_env_file(Path.cwd() / ".env")
_load_env_file(Path.home() / ".config" / "meshnet" / "secrets.env")
def main() -> None: def main() -> None:
_load_env_defaults()
common = argparse.ArgumentParser(add_help=False) common = argparse.ArgumentParser(add_help=False)
common.add_argument("--host", default="0.0.0.0", help="Host interface to listen on") common.add_argument("--host", default="0.0.0.0", help="Host interface to listen on")
common.add_argument("--port", type=int, default=8080, help="Port to listen on") common.add_argument("--port", type=int, default=8080, help="Port to listen on")
@@ -54,6 +97,51 @@ def main() -> None:
action="store_true", action="store_true",
help="Disable the USDT billing ledger", help="Disable the USDT billing ledger",
) )
common.add_argument(
"--max-charge-per-request",
type=float,
default=None,
help=(
"Reject chat completion requests whose prompt plus requested completion "
"token bound would cost more than this many USDT"
),
)
common.add_argument(
"--starting-credit",
type=float,
default=DEFAULT_CALLER_CREDIT_USDT,
metavar="USDT",
help=(
"One-time Caller Credit granted when an account creates its first "
f"API key (default: {DEFAULT_CALLER_CREDIT_USDT}; set 0 to require "
"deposits before inference)"
),
)
common.add_argument(
"--devnet-topup",
type=float,
default=DEFAULT_DEVNET_TOPUP_USDT,
metavar="USDT",
help=(
"Dashboard devnet top-up faucet: each click credits this many USDT "
f"to one of the account's keys (default: {DEFAULT_DEVNET_TOPUP_USDT}; "
"MUST be 0 on mainnet deployments)"
),
)
common.add_argument(
"--registry-db",
default=DEFAULT_REGISTRY_DB_PATH,
metavar="PATH",
help=(
"SQLite database path for persisted strike/ban/reputation registry "
f"state (default: {DEFAULT_REGISTRY_DB_PATH})"
),
)
common.add_argument(
"--no-registry-contracts",
action="store_true",
help="Disable the local contract registry used for strike/ban/reputation enforcement",
)
common.add_argument( common.add_argument(
"--accounts-db", "--accounts-db",
default=DEFAULT_ACCOUNTS_DB_PATH, default=DEFAULT_ACCOUNTS_DB_PATH,
@@ -102,6 +190,77 @@ def main() -> None:
default=0.01, default=0.01,
help="Never pay out less than this many USDT", help="Never pay out less than this many USDT",
) )
common.add_argument(
"--validator-service-token",
default=None,
help=(
"Service token the validator uses on POST /v1/billing/forfeit "
"(default: MESHNET_VALIDATOR_SERVICE_TOKEN env; ADR-0017)"
),
)
common.add_argument(
"--hive-secret",
default=None,
help=(
"Shared secret authenticating gossip between tracker peers "
"(default: MESHNET_HIVE_SECRET env; required for multi-tracker replication)"
),
)
common.add_argument(
"--toploc-calibration-db",
default=None,
metavar="PATH",
help=(
"SQLite path for the AH-021 honest-noise TOPLOC calibration corpus "
"(enables POST /v1/calibration/toploc/run + GET /v1/calibration/toploc/results)"
),
)
common.add_argument(
"--toploc-reference-node-url",
default=None,
help="Reference node the calibration job teacher-forces claimed tokens against (see validator README)",
)
common.add_argument(
"--toploc-calibration-gate-min-hardware-profiles",
type=int,
default=1,
help=(
"Distinct (GPU model, dtype) profiles the corpus must cover before "
"gate_status.ready is true (alpha exception: fleet size is acceptable)"
),
)
common.add_argument(
"--enable-hf-pricing",
action="store_true",
help=(
"Enable the daily dynamic pricing refresh (issue 23): for presets with a "
"curated hf_aliases list, sets the client price to 80%% of the cheapest "
"matching HuggingFace inference-marketplace rate. Presets without "
"hf_aliases are unaffected and keep their static price."
),
)
common.add_argument(
"--hf-pricing-log-db",
default=None,
metavar="PATH",
help=(
"SQLite database path for the dynamic pricing change log "
f"(default when --enable-hf-pricing is set: {DEFAULT_HF_PRICING_LOG_DB_PATH}; "
"enables GET /v1/pricing/hf/history)"
),
)
common.add_argument(
"--hf-pricing-refresh-interval",
type=float,
default=86400.0,
help="Seconds between dynamic pricing refresh passes (default: daily)",
)
common.add_argument(
"--models-dir",
default=None,
metavar="PATH",
help="Local HuggingFace snapshot root advertised as tracker model-file source (default: MESHNET_MODELS_DIR)",
)
parser = argparse.ArgumentParser( parser = argparse.ArgumentParser(
prog="meshnet-tracker", prog="meshnet-tracker",
@@ -124,6 +283,11 @@ def main() -> None:
treasury = SolanaCustodialTreasury( treasury = SolanaCustodialTreasury(
args.solana_rpc_url, args.usdt_mint, args.treasury_keypair, args.solana_rpc_url, args.usdt_mint, args.treasury_keypair,
) )
contracts = None
if not args.no_registry_contracts:
from meshnet_contracts import LocalSolanaContracts # type: ignore[import-not-found]
contracts = LocalSolanaContracts(registry_db=args.registry_db)
server = TrackerServer( server = TrackerServer(
host=args.host, host=args.host,
port=args.port, port=args.port,
@@ -134,11 +298,27 @@ def main() -> None:
relay_url=relay_url, relay_url=relay_url,
enable_billing=not args.no_billing, enable_billing=not args.no_billing,
billing_db=None if args.no_billing else args.billing_db, billing_db=None if args.no_billing else args.billing_db,
max_charge_per_request=args.max_charge_per_request,
starting_credit=args.starting_credit,
devnet_topup_amount=args.devnet_topup,
contracts=contracts,
accounts_db=None if args.no_accounts else args.accounts_db, accounts_db=None if args.no_accounts else args.accounts_db,
treasury=treasury, treasury=treasury,
settle_period=args.settle_period, settle_period=args.settle_period,
payout_threshold=args.payout_threshold, payout_threshold=args.payout_threshold,
payout_dust_floor=args.payout_dust_floor, payout_dust_floor=args.payout_dust_floor,
validator_service_token=args.validator_service_token,
hive_secret=args.hive_secret,
toploc_calibration_db=args.toploc_calibration_db,
toploc_reference_node_url=args.toploc_reference_node_url,
toploc_calibration_gate_min_hardware_profiles=args.toploc_calibration_gate_min_hardware_profiles,
enable_hf_pricing=args.enable_hf_pricing,
hf_pricing_log_db=(
args.hf_pricing_log_db
or (DEFAULT_HF_PRICING_LOG_DB_PATH if args.enable_hf_pricing else None)
),
hf_pricing_refresh_interval=args.hf_pricing_refresh_interval,
models_dir=args.models_dir,
) )
port = server.start() port = server.start()
print(f"meshnet-tracker listening on http://{args.host}:{port}", flush=True) print(f"meshnet-tracker listening on http://{args.host}:{port}", flush=True)

View File

@@ -39,11 +39,55 @@
.form-row { display:flex; gap:8px; } .form-row { display:flex; gap:8px; }
.form-row button { white-space:nowrap; } .form-row button { white-space:nowrap; }
.error-msg { color:var(--bad); font-size:12px; min-height:16px; } .error-msg { color:var(--bad); font-size:12px; min-height:16px; }
.keybox { word-break:break-all; background:var(--bg); border:1px solid var(--border); .keybox { display:flex; flex-wrap:wrap; align-items:center; gap:6px;
position:relative;
word-break:break-all; background:var(--bg); border:1px solid var(--border);
border-radius:6px; padding:4px 8px; margin:4px 0; font-size:11px; } border-radius:6px; padding:4px 8px; margin:4px 0; font-size:11px; }
.key-text { cursor:text; flex:1 1 auto; min-width:12rem; }
.copy-tooltip {
position:absolute; right:8px; top:-26px;
background:var(--panel); border:1px solid var(--border); color:var(--ok);
padding:2px 8px; border-radius:4px; font-size:11px;
pointer-events:none; z-index:1; white-space:nowrap;
}
.tabs { display:flex; gap:10px; margin-bottom:8px; } .tabs { display:flex; gap:10px; margin-bottom:8px; }
.tabs a { color:var(--dim); cursor:pointer; } .tabs a { color:var(--dim); cursor:pointer; }
.tabs a.active { color:var(--accent); border-bottom:1px solid var(--accent); } .tabs a.active { color:var(--accent); border-bottom:1px solid var(--accent); }
.dashboard-tabs { display:flex; gap:10px; padding:10px 20px 0; border-bottom:1px solid var(--border); }
.dashboard-tabs button { border:0; border-bottom:1px solid transparent; border-radius:0;
background:transparent; color:var(--dim); padding:5px 0 8px; }
.dashboard-tabs button.active { color:var(--accent); border-bottom-color:var(--accent); }
.wide { grid-column:1 / -1; }
section[hidden] { display:none !important; }
.chat-shell { display:grid; grid-template-columns:minmax(0, 1.35fr) minmax(320px, 0.65fr); gap:12px; }
.chat-pane { display:flex; flex-direction:column; gap:10px; min-width:0; }
.chat-panel { background:var(--bg); border:1px solid var(--border); border-radius:6px; padding:10px; }
.chat-controls { display:flex; gap:10px; align-items:end; flex-wrap:wrap; }
.chat-controls label { display:flex; flex-direction:column; gap:4px; color:var(--dim); }
.chat-controls select { min-width:220px; }
.chat-history { display:flex; flex-direction:column; gap:8px; min-height:220px; max-height:420px; overflow:auto; }
.chat-message { border:1px solid #21262d; border-radius:6px; padding:8px 10px; background:#10151d; }
.chat-role { color:var(--dim); font-size:11px; text-transform:uppercase; letter-spacing:.06em; margin-bottom:4px; }
.chat-role-user { color:var(--accent); }
.chat-role-assistant { color:var(--ok); }
.chat-role-error { color:var(--bad); }
.chat-compose { display:flex; flex-direction:column; gap:8px; }
.chat-compose textarea { min-height:112px; resize:vertical; width:100%; }
.chat-status { color:var(--dim); font-size:12px; }
.console {
background:var(--bg); border:1px solid var(--border); border-radius:6px;
min-height:160px; max-height:280px; overflow:auto; padding:7px 9px;
white-space:pre-wrap; word-break:break-word; font-size:11px;
}
.console-line { padding:1px 0; border-bottom:1px solid #161b22; }
.console-time { color:var(--dim); }
.console-level-info { color:var(--accent); }
.console-level-warn { color:var(--warn); }
.console-level-error { color:var(--bad); }
.status-pending { color:var(--warn); }
.status-processing { color:var(--accent); }
.status-failed { color:var(--bad); }
.status-complete { color:var(--ok); }
</style> </style>
</head> </head>
<body> <body>
@@ -52,17 +96,52 @@
<span class="meta" id="self-url"></span> <span class="meta" id="self-url"></span>
<span class="meta" id="refreshed"></span> <span class="meta" id="refreshed"></span>
</header> </header>
<nav class="dashboard-tabs" aria-label="Dashboard sections">
<button id="tab-overview" class="active" onclick="switchDashboardTab('overview')">Overview</button>
<button id="tab-chat" onclick="switchDashboardTab('chat')">Chat</button>
<button id="tab-billing" style="display:none" onclick="switchDashboardTab('billing')">Billing</button>
<button id="tab-admin" style="display:none" onclick="switchDashboardTab('admin')">Admin</button>
</nav>
<main> <main>
<section id="account-section"><h2>Account</h2><div id="account">loading…</div></section> <section data-tab="overview" id="account-section"><h2>Account</h2><div id="account">loading…</div></section>
<section id="admin-section" style="display:none"><h2>All accounts (admin)</h2><div id="admin" class="empty"></div></section> <section data-tab="overview"><h2>Tracker hive</h2><div id="hive" class="empty">loading…</div></section>
<section><h2>Tracker hive</h2><div id="hive" class="empty">loading…</div></section> <section data-tab="overview"><h2>Nodes &amp; coverage</h2><div id="nodes" class="empty">loading…</div></section>
<section><h2>Nodes &amp; coverage</h2><div id="nodes" class="empty">loading…</div></section> <section data-tab="overview"><h2>Model usage (RPM)</h2><div id="stats" class="empty">loading…</div></section>
<section><h2>Client balances</h2><div id="clients" class="empty">loading</div></section> <section data-tab="overview" class="wide"><h2>Call wall</h2><div id="call-wall" class="empty">loading...</div></section>
<section><h2>Node pending payouts</h2><div id="pending" class="empty">loading…</div></section> <section data-tab="chat" class="wide">
<section><h2>Settlement history</h2><div id="settlements" class="empty">loading…</div></section> <h2>Chat / inference</h2>
<section><h2>Strikes / bans / forfeitures</h2><div id="fraud" class="empty">loading…</div></section> <div class="chat-shell">
<section><h2>Model usage (RPM)</h2><div id="stats" class="empty">loading…</div></section> <div class="chat-pane">
<section><h2>Node throughput</h2><div id="throughput" class="empty">loading…</div></section> <div class="chat-panel chat-controls">
<label>Model
<select id="chat-model" onchange="selectChatModel(this.value)"></select>
</label>
<button class="small" onclick="clearChatHistory()">clear history</button>
</div>
<div class="chat-panel chat-compose">
<textarea id="chat-prompt" placeholder="Ask a question or describe the task"></textarea>
<div class="form-row">
<button onclick="sendChat()" id="chat-send">Send</button>
</div>
</div>
</div>
<div class="chat-pane">
<div class="chat-panel">
<div id="chat-status" class="chat-status">select a model to start</div>
<div id="chat-history" class="chat-history empty">no messages yet</div>
</div>
</div>
</div>
</section>
<section data-tab="billing" data-logged-in-only><h2>Usage summary</h2><div id="usage-summary" class="empty">login required</div></section>
<section data-tab="billing" data-logged-in-only><h2>Node throughput</h2><div id="node-throughput" class="empty">login required</div></section>
<section data-tab="billing"><h2>Request history</h2><div id="billing-usage" class="empty">login required</div></section>
<section data-tab="billing" data-admin-only><h2>Node pending payouts</h2><div id="pending" class="empty">admin login required</div></section>
<section data-tab="billing" data-admin-only><h2>Settlement history</h2><div id="settlements" class="empty">admin login required</div></section>
<section data-tab="admin" id="admin-section"><h2>All accounts (admin)</h2><div id="admin" class="empty"></div></section>
<section data-tab="admin" data-admin-only><h2>Strikes / bans / forfeitures</h2><div id="fraud" class="empty">admin login required</div></section>
<section data-tab="admin"><h2>Client balances</h2><div id="clients" class="empty">admin login required</div></section>
<section data-tab="admin" class="wide"><h2>Console output</h2><div id="console" class="console empty">admin login required</div></section>
</main> </main>
<script> <script>
"use strict"; "use strict";
@@ -71,11 +150,15 @@ const esc = s => String(s).replace(/[&<>"]/g,
c => ({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"}[c])); c => ({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"}[c]));
const usdt = v => (Math.round(v * 1e6) / 1e6).toFixed(6); const usdt = v => (Math.round(v * 1e6) / 1e6).toFixed(6);
const tps = v => (v === null || v === undefined) ? "?" : (Math.round(v * 10) / 10).toFixed(1); const tps = v => (v === null || v === undefined) ? "?" : (Math.round(v * 10) / 10).toFixed(1);
const copies = v => (v === null || v === undefined) ? "?" : Number(v).toFixed(2);
const short = (s, n=14) => { s = String(s); return s.length > n ? s.slice(0, 6) + "…" + s.slice(-5) : s; }; const short = (s, n=14) => { s = String(s); return s.length > n ? s.slice(0, 6) + "…" + s.slice(-5) : s; };
async function fetchJson(path) { async function fetchJson(path) {
try { try {
const r = await fetch(path); const headers = {};
const token = localStorage.getItem("meshnet_session");
if (token) headers["Authorization"] = "Bearer " + token;
const r = await fetch(path, { headers });
if (!r.ok) return null; if (!r.ok) return null;
return await r.json(); return await r.json();
} catch { return null; } } catch { return null; }
@@ -113,16 +196,17 @@ function renderNodes(map) {
} }
let html = ""; let html = "";
for (const [model, group] of Object.entries(byModel)) { for (const [model, group] of Object.entries(byModel)) {
html += `<div><b>${esc(model)}</b> <span class="dim">(${group.length} node${group.length===1?"":"s"})</span></div>`; const supply = group.find(n => n.model_supply && n.model_supply.served_model_copies !== undefined);
html += table(["node", "shard", "tps (1h)", "queue", "health"], group.map(n => { const served = supply && supply.model_supply && supply.model_supply.served_model_copies;
html += `<div><b>${esc(model)}</b> <span class="dim">(${group.length} node${group.length===1?"":"s"} · ${esc(copies(served))} served)</span></div>`;
html += table(["node", "shard", "tps (1h)", "queue", "served"], group.map(n => {
const modelStats = (n.throughput && (n.throughput[n.hf_repo] || n.throughput[n.model])) || {}; const modelStats = (n.throughput && (n.throughput[n.hf_repo] || n.throughput[n.model])) || {};
return [ return [
esc(short(n.node_id || "?")), esc(short(n.node_id || "?")),
esc(`${n.shard_start ?? "?"}-${n.shard_end ?? "?"}`), esc(`${n.shard_start ?? "?"}-${n.shard_end ?? "?"}`),
`<span class="num">${esc(tps(modelStats.tokens_per_sec_last_hour))}</span>`, `<span class="num">${esc(tps(modelStats.tokens_per_sec_last_hour))}</span>`,
esc(String((n.stats && n.stats.queue_depth) ?? 0)), esc(String((n.stats && n.stats.queue_depth) ?? 0)),
(n.stats && (n.stats.alive === false || n.stats.healthy === false)) `<span class="num">${esc(copies(n.model_supply && n.model_supply.served_model_copies))}</span>`,
? '<span class="bad">down</span>' : '<span class="ok">up</span>',
]; })); ]; }));
} }
$("nodes").innerHTML = html; $("nodes").innerHTML = html;
@@ -193,7 +277,7 @@ function renderStats(stats) {
$("stats").innerHTML = table(["model", "rpm (1h)", "rpm (24h)", "rpm (30d)"], rows); $("stats").innerHTML = table(["model", "rpm (1h)", "rpm (24h)", "rpm (30d)"], rows);
} }
function renderThroughput(stats) { function renderThroughputHtml(stats) {
const nodes = (stats && stats.nodes) || {}; const nodes = (stats && stats.nodes) || {};
const rows = []; const rows = [];
for (const [nodeId, nodeStats] of Object.entries(nodes)) { for (const [nodeId, nodeStats] of Object.entries(nodes)) {
@@ -206,17 +290,406 @@ function renderThroughput(stats) {
]); ]);
} }
} }
$("throughput").innerHTML = table(["node", "model", "tps (1h)", "samples"], rows); if (!rows.length) return '<div class="empty">no throughput samples yet</div>';
return table(["node", "model", "tps (1h)", "samples"], rows);
}
function hiveThroughputSummary(stats) {
const nodes = (stats && stats.nodes) || {};
let totalTps = 0;
let samples = 0;
for (const nodeStats of Object.values(nodes)) {
for (const s of Object.values((nodeStats && nodeStats.models) || {})) {
const t = Number(s.tokens_per_sec_last_hour);
if (Number.isFinite(t)) totalTps += t;
samples += Number(s.sample_count_last_hour || 0);
}
}
return { totalTps, samples };
}
function buildCallWallStates(events) {
const byId = new Map();
for (const e of events) {
const f = e.fields || {};
const id = f.request_id;
if (!id) continue;
let rec = byId.get(id);
if (!rec) {
rec = { id, events: [] };
byId.set(id, rec);
}
rec.events.push(e);
const msg = e.message;
if (msg === "proxy route selected") {
rec.status = "pending";
rec.started = e.ts;
rec.model = f.model || f.route_model || "?";
rec.route = f.route || f.nodes;
rec.nodes = f.nodes;
rec.stream = f.stream;
} else if (msg === "proxy via relay" || msg === "proxy connected") {
rec.status = "processing";
if (!rec.started) rec.started = e.ts;
rec.model = rec.model || f.model || f.route_model || "?";
} else if (msg === "proxy progress") {
rec.status = "processing";
rec.model = rec.model || f.model || f.route_model || "?";
rec.tokens = f.tokens;
rec.tps = f.tokens_per_sec;
rec.elapsed = f.elapsed_seconds;
rec.stream = f.stream;
} else if (msg === "relay proxy failed, trying direct") {
rec.status = "processing";
rec.warn = "relay failed, trying direct";
} else if (msg === "proxy complete") {
rec.status = "complete";
rec.model = rec.model || f.model || f.route_model || "?";
rec.tokens = f.tokens;
rec.tps = f.tokens_per_sec;
rec.elapsed = f.elapsed_seconds;
rec.stream = f.stream;
rec.terminal = e;
} else if (msg === "proxy failed" || msg === "direct proxy failed after relay") {
rec.status = "failed";
rec.model = rec.model || f.model || f.route_model || "?";
rec.error = f.error || msg;
rec.terminal = e;
}
}
return byId;
}
function callWallAgeSeconds(rec, nowSec) {
const start = rec.started || (rec.events[0] && rec.events[0].ts) || nowSec;
return Math.max(0, nowSec - start);
}
function callWallMaxQueue(rec) {
const nodes = rec.nodes || [];
const nodeQueues = Array.isArray(nodes) ? nodes.map(n => Number(n.queue_depth || 0)) : [];
return nodeQueues.length ? Math.max(...nodeQueues) : 0;
}
function renderCallWall(consoleData, stats) {
const events = (consoleData && consoleData.events) || [];
const nowSec = Date.now() / 1000;
const states = buildCallWallStates(events);
const active = [];
const terminal = [];
for (const rec of states.values()) {
if (rec.status === "pending" || rec.status === "processing") active.push(rec);
else if (rec.status === "complete" || rec.status === "failed") terminal.push(rec);
}
active.sort((a, b) => (a.started || 0) - (b.started || 0));
terminal.sort((a, b) => (b.terminal && b.terminal.ts) - (a.terminal && a.terminal.ts));
const hive = hiveThroughputSummary(stats);
const pending = active.filter(r => r.status === "pending").length;
const processing = active.filter(r => r.status === "processing").length;
const failedRecent = terminal.filter(r => r.status === "failed").length;
let queuedEstimate = 0;
for (const rec of active) queuedEstimate += Math.max(0, callWallMaxQueue(rec) - 1);
let html =
`<div class="dim" style="margin-bottom:6px">` +
`hive tps (1h): <b>${esc(tps(hive.totalTps))}</b> · samples: <b>${hive.samples}</b> · ` +
`active: <span class="status-processing">${processing}</span> processing · ` +
`<span class="status-pending">${pending}</span> pending` +
(queuedEstimate ? ` · queued estimate: <b>${queuedEstimate}</b>` : "") +
(failedRecent ? ` · <span class="status-failed">${failedRecent} recent failures</span>` : "") +
`</div>`;
if (active.length) {
html += table(["status", "age", "model", "request", "live tps", "tokens", "queue", "route / note"], active.map(rec => {
const statusCls = rec.status === "pending" ? "status-pending" : "status-processing";
const note = rec.warn || (rec.route ? short(String(rec.route), 28) : "");
return [
`<span class="${statusCls}">${esc(rec.status)}</span>`,
`<span class="num">${esc(callWallAgeSeconds(rec, nowSec).toFixed(1))}s</span>`,
esc(short(rec.model || "?", 28)),
esc(short(rec.id, 18)),
`<span class="num">${esc(tps(rec.tps))}</span>`,
`<span class="num">${esc(String(rec.tokens ?? "—"))}</span>`,
`<span class="num">${esc(String(callWallMaxQueue(rec)))}</span>`,
esc(note),
];
}));
} else {
html += '<div class="empty">no in-flight requests</div>';
}
const historyRows = terminal.slice(0, 40).map(rec => {
const e = rec.terminal || {};
const f = e.fields || {};
const statusCls = rec.status === "failed" ? "status-failed" : "status-complete";
const detail = rec.status === "failed"
? esc(short(rec.error || "?", 40))
: (f.stream ? "stream" : "json");
return [
new Date((e.ts || 0) * 1000).toLocaleTimeString(),
`<span class="${statusCls}">${esc(rec.status)}</span>`,
esc(short(rec.model || "?", 28)),
esc(short(rec.id, 18)),
`<span class="num">${esc(tps(rec.tps ?? f.tokens_per_sec))}</span>`,
`<span class="num">${esc(String(rec.tokens ?? f.tokens ?? "?"))}</span>`,
`<span class="num">${esc(String(rec.elapsed ?? f.elapsed_seconds ?? "?"))}</span>`,
detail,
];
});
html += '<div style="margin-top:8px"><b class="dim">recent completed / failed</b></div>';
html += historyRows.length
? table(["time", "status", "model", "request", "tps", "tokens", "sec", "detail"], historyRows)
: '<div class="empty">no completed requests yet</div>';
$("call-wall").innerHTML = html;
}
function startOfLocalDay(tsSec) {
const d = new Date(tsSec * 1000);
d.setHours(0, 0, 0, 0);
return d.getTime() / 1000;
}
function formatUsageDayLabel(tsSec) {
return new Date(tsSec * 1000).toLocaleDateString();
}
function summarizeUsageBuckets(records) {
const now = Date.now() / 1000;
const todayStart = startOfLocalDay(now);
const daySec = 86400;
const empty = () => ({ requests: 0, tokens: 0, cost: 0 });
const daily = [0, 1, 2].map(offset => ({
label: offset === 0 ? "Today" : offset === 1 ? "Yesterday" : formatUsageDayLabel(todayStart - offset * daySec),
...empty(),
}));
const last7 = { label: "Last 7 days", ...empty() };
const last30 = { label: "Last 30 days", ...empty() };
const total = { label: "All time", ...empty() };
for (const u of records) {
const ts = Number(u.ts || 0);
const tokens = Number(u.total_tokens || 0);
const cost = Number(u.cost || 0);
total.requests += 1;
total.tokens += tokens;
total.cost += cost;
if (ts >= now - 30 * daySec) {
last30.requests += 1;
last30.tokens += tokens;
last30.cost += cost;
}
if (ts >= now - 7 * daySec) {
last7.requests += 1;
last7.tokens += tokens;
last7.cost += cost;
}
for (let offset = 0; offset < 3; offset++) {
const start = todayStart - offset * daySec;
const end = start + daySec;
if (ts >= start && ts < end) {
daily[offset].requests += 1;
daily[offset].tokens += tokens;
daily[offset].cost += cost;
}
}
}
return [...daily, last7, last30, total];
}
function renderUsageSummary(records) {
const el = $("usage-summary");
if (!el) return;
if (!sessionToken) {
el.innerHTML = '<div class="empty">login required</div>';
return;
}
if (!records.length) {
el.innerHTML = '<div class="empty">no billed requests yet</div>';
return;
}
const rows = summarizeUsageBuckets(records).map(b => [
esc(b.label),
`<span class="num">${b.requests}</span>`,
`<span class="num">${esc(String(b.tokens))}</span>`,
`<span class="num">${usdt(b.cost)}</span>`,
]);
el.innerHTML =
'<div class="dim" style="margin-bottom:6px">per-request detail on Request history below</div>' +
table(["period", "requests", "tokens", "cost (USDT)"], rows);
}
function renderNodeThroughput(stats) {
const el = $("node-throughput");
if (!el) return;
if (!sessionToken) {
el.innerHTML = '<div class="empty">login required</div>';
return;
}
el.innerHTML = renderThroughputHtml(stats);
}
function renderBillingUsage(records) {
const el = $("billing-usage");
if (!el) return;
if (!sessionToken) {
el.innerHTML = '<div class="empty">login required</div>';
return;
}
if (!records.length) {
el.innerHTML = '<div class="empty">no billed requests yet</div>';
return;
}
const rows = records.slice().reverse().map(u => [
new Date((u.ts || 0) * 1000).toLocaleString(),
esc(short(u.model || "?", 28)),
esc(short(u.api_key || "?", 14)),
`<span class="num">${esc(String(u.total_tokens))}</span>`,
`<span class="num">${usdt(u.cost)}</span>`,
]);
el.innerHTML = `<div class="dim" style="margin-bottom:6px">${records.length} request${records.length === 1 ? "" : "s"}</div>` +
table(["time", "model", "api key", "tokens", "cost (USDT)"], rows);
}
function renderConsole(data) {
const events = (data && data.events) || [];
if (!events.length) {
$("console").innerHTML = '<div class="empty">no console events</div>';
return;
}
$("console").innerHTML = events.slice(-120).map(e => {
const level = String(e.level || "info");
const cls = level === "error" ? "console-level-error" : level === "warn" ? "console-level-warn" : "console-level-info";
const fields = e.fields && Object.keys(e.fields).length ? " " + JSON.stringify(e.fields) : "";
return `<div class="console-line"><span class="console-time">${new Date((e.ts || 0) * 1000).toLocaleTimeString()}</span> ` +
`<span class="${cls}">${esc(level.toUpperCase())}</span> ${esc(e.message || "")}${esc(fields)}</div>`;
}).join("");
} }
// ---- account panel (registration / login / balance / usage / API keys) ---- // ---- account panel (registration / login / balance / usage / API keys) ----
let sessionToken = localStorage.getItem("meshnet_session") || null; let sessionToken = localStorage.getItem("meshnet_session") || null;
let authTab = "login"; let authTab = "login";
let dashboardTab = "overview";
let isAdmin = false;
let isLoggedIn = false;
let accountApiKeys = [];
let accountUsageRecords = [];
let lastStats = null;
let availableModels = [];
let chatHistory = [];
let chatBusy = false;
let selectedChatModel = localStorage.getItem("meshnet_chat_model") || "";
async function apiCall(path, method, body) { function switchDashboardTab(name) {
if (name === "admin" && !isAdmin) name = "overview";
if (name === "billing" && !isLoggedIn) name = "overview";
dashboardTab = name;
updateSectionVisibility();
for (const tabName of ["overview", "chat", "billing", "admin"]) {
const button = $("tab-" + tabName);
if (button) button.classList.toggle("active", tabName === dashboardTab);
}
}
function updateSectionVisibility() {
for (const section of document.querySelectorAll("main section[data-tab]")) {
const onTab = section.dataset.tab === dashboardTab;
const adminOnly = section.hasAttribute("data-admin-only");
const loggedInOnly = section.hasAttribute("data-logged-in-only");
section.hidden = !onTab || (adminOnly && !isAdmin) || (loggedInOnly && !isLoggedIn);
}
}
function renderChatStatus(text) {
$("chat-status").textContent = text;
}
function renderChatHistory() {
const history = $("chat-history");
if (!chatHistory.length) {
history.classList.add("empty");
history.innerHTML = "no messages yet";
return;
}
history.classList.remove("empty");
history.innerHTML = chatHistory.map(msg => {
const roleClass = msg.role === "user" ? "chat-role-user" : msg.role === "assistant" ? "chat-role-assistant" : "chat-role-error";
const label = msg.role === "user" ? "user" : msg.role === "assistant" ? "assistant" : "error";
const meta = msg.model ? ` <span class="dim">· ${esc(short(msg.model, 24))}</span>` : "";
return `<div class="chat-message"><div class="chat-role ${roleClass}">${label}${meta}</div><div>${esc(msg.content)}</div></div>`;
}).join("");
history.scrollTop = history.scrollHeight;
}
function renderChatModels() {
const select = $("chat-model");
if (!select) return;
const models = availableModels.slice();
if (!models.length) {
select.innerHTML = '<option value="">no models available</option>';
select.disabled = true;
return;
}
select.disabled = false;
const preferred = models.find(m => m.id === selectedChatModel)
|| models[0];
selectedChatModel = preferred.id;
localStorage.setItem("meshnet_chat_model", selectedChatModel);
select.innerHTML = models.map(model => {
const label = model.name && model.name !== model.id
? `${model.name} (${model.id})`
: model.id;
const suffix = model.recommended ? " [recommended]" : "";
return `<option value="${esc(model.id)}"${model.id === selectedChatModel ? " selected" : ""}>${esc(label + suffix)}</option>`;
}).join("");
select.value = selectedChatModel;
}
function selectChatModel(value) {
selectedChatModel = value || "";
localStorage.setItem("meshnet_chat_model", selectedChatModel);
}
function clearChatHistory() {
chatHistory = [];
renderChatHistory();
renderChatStatus("history cleared");
}
function chatAuthToken() {
if (accountApiKeys.length) return accountApiKeys[0];
return null;
}
function setAdminMode(enabled) {
isAdmin = enabled;
$("tab-admin").style.display = enabled ? "" : "none";
if (!enabled && dashboardTab === "admin") {
switchDashboardTab("overview");
} else {
updateSectionVisibility();
}
}
function setLoggedInMode(enabled) {
isLoggedIn = enabled;
$("tab-billing").style.display = enabled ? "" : "none";
if (!enabled) {
accountUsageRecords = [];
renderBillingUsage([]);
renderUsageSummary([]);
renderNodeThroughput(null);
if (dashboardTab === "billing") switchDashboardTab("overview");
} else {
updateSectionVisibility();
}
}
async function apiCall(path, method, body, bearerToken) {
const headers = { "Content-Type": "application/json" }; const headers = { "Content-Type": "application/json" };
if (sessionToken) headers["Authorization"] = "Bearer " + sessionToken; const token = bearerToken === undefined ? sessionToken : bearerToken;
if (token) headers["Authorization"] = "Bearer " + token;
try { try {
const r = await fetch(path, { const r = await fetch(path, {
method: method || "GET", method: method || "GET",
@@ -252,7 +725,10 @@ function renderAuthForms(errorMsg) {
$("account").innerHTML = $("account").innerHTML =
`<div class="tabs">${tab("login", "Log in")}${tab("register", "Register")}</div>` + `<div class="tabs">${tab("login", "Log in")}${tab("register", "Register")}</div>` +
form + `<div class="error-msg">${errorMsg ? esc(errorMsg) : ""}</div>`; form + `<div class="error-msg">${errorMsg ? esc(errorMsg) : ""}</div>`;
$("admin-section").style.display = "none"; accountApiKeys = [];
renderChatAuthHint();
setLoggedInMode(false);
setAdminMode(false);
} }
function switchAuthTab(name) { authTab = name; renderAuthForms(); } function switchAuthTab(name) { authTab = name; renderAuthForms(); }
@@ -294,15 +770,88 @@ async function revokeKey(key) {
await renderAccountPanel(); await renderAccountPanel();
} }
async function topupKey(key) {
const r = await apiCall("/v1/account/topup", "POST", { api_key: key });
if (!r.ok) alert(r.data.error || "top-up failed");
await renderAccountPanel();
}
const COPY_TOOLTIP_MS = 2000;
function showCopiedTooltip(anchor) {
const box = (anchor && anchor.closest && anchor.closest(".keybox")) || anchor;
if (!box) return;
const existing = box.querySelector(".copy-tooltip");
if (existing) existing.remove();
const tip = document.createElement("span");
tip.className = "copy-tooltip";
tip.textContent = "Copied!";
tip.setAttribute("role", "status");
box.appendChild(tip);
setTimeout(() => tip.remove(), COPY_TOOLTIP_MS);
}
async function copyApiKeyText(text, anchor) {
try {
await navigator.clipboard.writeText(text);
} catch {
const ta = document.createElement("textarea");
ta.value = text;
ta.style.position = "fixed";
ta.style.left = "-9999px";
document.body.appendChild(ta);
ta.select();
try { document.execCommand("copy"); } catch { /* ignore */ }
document.body.removeChild(ta);
}
if (anchor) showCopiedTooltip(anchor);
}
function selectApiKeyText(el) {
const range = document.createRange();
range.selectNodeContents(el);
const sel = window.getSelection();
if (!sel) return;
sel.removeAllRanges();
sel.addRange(range);
}
function copyApiKeyFromTextEl(el) {
const key = el.dataset.key || el.textContent || "";
return copyApiKeyText(key, el);
}
function copyApiKeyFromButton(button) {
const el = button.closest(".keybox") && button.closest(".keybox").querySelector(".key-text");
const key = (el && el.dataset.key) || "";
return copyApiKeyText(key, button);
}
function renderChatAuthHint() {
if (chatAuthToken()) {
renderChatStatus("ready to send with your active API key");
} else if (sessionToken) {
renderChatStatus("create an API key in Account to use chat on a billing-enabled tracker");
} else {
renderChatStatus("log in if this tracker requires an API key");
}
}
async function renderAccountPanel() { async function renderAccountPanel() {
const r = await apiCall("/v1/account"); const r = await apiCall("/v1/account");
if (r.status === 404) { // accounts disabled on this tracker if (r.status === 404) { // accounts disabled on this tracker
$("account-section").style.display = "none"; $("account-section").style.display = "none";
$("admin-section").style.display = "none"; accountApiKeys = [];
accountUsageRecords = [];
renderChatAuthHint();
setLoggedInMode(false);
setAdminMode(false);
return; return;
} }
if (!r.ok) { setSession(null); renderAuthForms(); return; } if (!r.ok) { setSession(null); renderAuthForms(); return; }
const { account, api_keys, balances, total_balance, usage } = r.data; const { account, api_keys, balances, total_balance, usage, topup_amount } = r.data;
accountApiKeys = Array.isArray(api_keys) ? api_keys.slice() : [];
accountUsageRecords = (usage && (usage.records || usage.recent)) || [];
const who = account.email || account.wallet || account.account_id; const who = account.email || account.wallet || account.account_id;
let html = let html =
`<div><b>${esc(who)}</b> <span class="pill">${esc(account.role)}</span> ` + `<div><b>${esc(who)}</b> <span class="pill">${esc(account.role)}</span> ` +
@@ -314,31 +863,86 @@ async function renderAccountPanel() {
'<button class="small" onclick="createKey()">+ new key</button></div>'; '<button class="small" onclick="createKey()">+ new key</button></div>';
if (api_keys.length) { if (api_keys.length) {
for (const key of api_keys) { for (const key of api_keys) {
html += `<div class="keybox">${esc(key)}` + html += `<div class="keybox">` +
` <span class="dim">(${usdt(balances[key] ?? 0)} USDT)</span>` + `<span class="key-text" data-key="${esc(key)}" onclick="selectApiKeyText(this)" ondblclick="copyApiKeyFromTextEl(this)">${esc(key)}</span>` +
`<span class="dim">(${usdt(balances[key] ?? 0)} USDT)</span>` +
`<button class="small" type="button" onclick="copyApiKeyFromButton(this)">copy</button>` +
(topup_amount > 0
? ` <button class="small" onclick="topupKey('${esc(key)}')">+${usdt(topup_amount)} (devnet)</button>`
: "") +
` <button class="small" onclick="revokeKey('${esc(key)}')">revoke</button></div>`; ` <button class="small" onclick="revokeKey('${esc(key)}')">revoke</button></div>`;
} }
} else { } else {
html += '<div class="empty">no active keys</div>'; html += '<div class="empty">no active keys</div>';
} }
if (usage.recent && usage.recent.length) {
html += '<div style="margin-top:6px"><b class="dim">recent usage</b></div>' +
table(["time", "model", "tokens", "cost"], usage.recent.slice().reverse().map(u => [
new Date(u.ts * 1000).toLocaleTimeString(),
esc(short(u.model || "?", 24)),
`<span class="num">${esc(String(u.total_tokens))}</span>`,
`<span class="num">${usdt(u.cost)}</span>`,
]));
}
$("account").innerHTML = html; $("account").innerHTML = html;
renderUsageSummary(accountUsageRecords);
renderNodeThroughput(lastStats);
renderBillingUsage(accountUsageRecords);
renderChatAuthHint();
renderChatModels();
renderChatHistory();
setLoggedInMode(true);
setAdminMode(account.role === "admin");
if (account.role === "admin") await renderAdminPanel(); if (account.role === "admin") await renderAdminPanel();
else $("admin-section").style.display = "none"; }
async function sendChat() {
const promptEl = $("chat-prompt");
const prompt = promptEl.value.trim();
if (!prompt || chatBusy) return;
if (!selectedChatModel) {
renderChatStatus("select a model first");
return;
}
const bearerToken = chatAuthToken();
const body = {
model: selectedChatModel,
messages: [
...chatHistory
.filter(msg => msg.role === "user" || msg.role === "assistant")
.map(msg => ({ role: msg.role, content: msg.content })),
{ role: "user", content: prompt },
],
stream: false,
max_tokens: 256,
};
chatBusy = true;
$("chat-send").disabled = true;
promptEl.value = "";
chatHistory.push({ role: "user", content: prompt, model: selectedChatModel });
renderChatHistory();
renderChatStatus("sending request…");
const r = await apiCall("/v1/chat/completions", "POST", body, bearerToken);
chatBusy = false;
$("chat-send").disabled = false;
if (!r.ok) {
const error = r.data && r.data.error
? (typeof r.data.error === "string" ? r.data.error : r.data.error.message || "request failed")
: "request failed";
chatHistory.push({ role: "error", content: error, model: selectedChatModel });
renderChatHistory();
renderChatStatus(error);
promptEl.focus();
return;
}
const reply = (r.data && r.data.choices && r.data.choices[0] && r.data.choices[0].message && r.data.choices[0].message.content) || "";
const usage = r.data && r.data.usage;
chatHistory.push({
role: "assistant",
content: reply || "(empty response)",
model: selectedChatModel,
});
renderChatHistory();
renderChatStatus(usage
? `done: ${usage.total_tokens ?? "?"} tokens`
: "done");
promptEl.focus();
} }
async function renderAdminPanel() { async function renderAdminPanel() {
const r = await apiCall("/v1/admin/accounts"); const r = await apiCall("/v1/admin/accounts");
if (!r.ok) { $("admin-section").style.display = "none"; return; } if (!r.ok) { setAdminMode(false); return; }
$("admin-section").style.display = "";
const rows = (r.data.accounts || []).map(a => { const rows = (r.data.accounts || []).map(a => {
const balance = Object.values(a.balances || {}).reduce((x, y) => x + y, 0); const balance = Object.values(a.balances || {}).reduce((x, y) => x + y, 0);
return [ return [
@@ -354,25 +958,44 @@ async function renderAdminPanel() {
async function refresh() { async function refresh() {
$("self-url").textContent = location.host; $("self-url").textContent = location.host;
const [raft, map, summary, settlements, wallets, stats] = await Promise.all([ const [raft, map, stats, models, consoleData, adminData] = await Promise.all([
fetchJson("/v1/raft/status"), fetchJson("/v1/raft/status"),
fetchJson("/v1/network/map"), fetchJson("/v1/network/map"),
fetchJson("/v1/billing/summary"),
fetchJson("/v1/billing/settlements"),
fetchJson("/v1/registry/wallets"),
fetchJson("/v1/stats"), fetchJson("/v1/stats"),
fetchJson("/v1/models"),
fetchJson("/v1/console"),
isAdmin ? Promise.all([
fetchJson("/v1/billing/summary"),
fetchJson("/v1/billing/settlements"),
fetchJson("/v1/registry/wallets"),
]) : Promise.resolve([null, null, null]),
]); ]);
const [summary, settlements, wallets] = adminData;
lastStats = stats;
availableModels = ((models && models.data) || []).map(model => ({
id: model.id,
name: model.name || model.id,
recommended: Boolean(model.recommended),
aliases: model.aliases || [],
})).filter(model => model.id);
renderHive(raft); renderHive(raft);
renderNodes(map); renderNodes(map);
renderBilling(summary); renderBilling(summary);
renderSettlements(settlements); renderSettlements(settlements);
renderFraud(wallets, summary); renderFraud(wallets, summary);
renderStats(stats); renderStats(stats);
renderThroughput(stats); renderCallWall(consoleData, stats);
renderConsole(consoleData);
renderNodeThroughput(stats);
renderChatModels();
renderChatHistory();
$("refreshed").textContent = "refreshed " + new Date().toLocaleTimeString(); $("refreshed").textContent = "refreshed " + new Date().toLocaleTimeString();
} }
refresh(); refresh();
renderAccountPanel(); renderAccountPanel();
renderChatModels();
renderChatHistory();
renderChatAuthHint();
setInterval(refresh, 4000); setInterval(refresh, 4000);
setInterval(() => { if (sessionToken) renderAccountPanel(); }, 8000); setInterval(() => { if (sessionToken) renderAccountPanel(); }, 8000);
</script> </script>

View File

@@ -0,0 +1,318 @@
"""Dynamic per-model pricing benchmarked against HuggingFace inference rates (issue 23).
Client-facing price per model tracks the market: 80% of the cheapest
comparable provider rate on HuggingFace's inference marketplace
(https://huggingface.co/inference/models), refreshed daily. Nodes are
unaffected — this only ever calls ``BillingLedger.set_price`` (the ledger's
existing write path), never touches node payouts (ADR-0015's 90/10 split
still applies to whatever price is charged).
Confirmed 2026-07-06: the pricing table is server-rendered into the initial
HTML response (SvelteKit SSR) — a plain stdlib ``urllib.request`` GET plus
HTML parsing is sufficient. No headless-browser fetch is required. Each
table row carries an anchor whose href is
``/<org>/<repo>/?inference_api=true&inference_provider=<provider>``, which is
a cheaper and more stable extraction anchor than the display text (which
duplicates the repo id at two responsive breakpoints).
"""
from __future__ import annotations
import json
import re
import sqlite3
import threading
import time
import urllib.parse
import urllib.request
from dataclasses import dataclass
from html.parser import HTMLParser
from typing import Callable
HF_INFERENCE_MODELS_URL = "https://huggingface.co/inference/models"
DEFAULT_HF_PRICING_LOG_DB_PATH = "hf_pricing_log.sqlite"
DEFAULT_CLIENT_PRICE_FRACTION = 0.80 # charge 80% of the cheapest comparable rate
_ROW_HREF_RE = re.compile(
r"^/(?P<repo>[^/]+/[^/?]+)/\?inference_api=true&inference_provider=(?P<provider>[^&\"]+)"
)
_PRICE_RE = re.compile(r"^\$[\d,]*\.?\d+$")
@dataclass(frozen=True)
class HfPriceQuote:
"""One (model, provider) row from the HF inference pricing table."""
repo_id: str
provider: str
input_per_1m: float
output_per_1m: float
def blended_price_per_1k_tokens(self) -> float:
"""Average of input/output $-per-1M-token rates, converted to $/1k.
The tracker bills a single per-1k-token rate (``BillingLedger``
doesn't distinguish prompt vs. completion tokens), so this is the
simplest fair proxy for "this provider's rate" in that unit.
"""
return (self.input_per_1m + self.output_per_1m) / 2.0 / 1000.0
def alias_keys(self) -> tuple[str, str]:
"""Both the bare-repo and repo::provider forms an ``hf_aliases`` entry may use."""
return (self.repo_id.lower(), f"{self.repo_id.lower()}::{self.provider.lower()}")
class _HfPricingTableParser(HTMLParser):
"""Extracts (repo_id, provider, input$/1M, output$/1M) rows from the raw HTML."""
def __init__(self) -> None:
super().__init__()
self._in_tr = False
self._row_match: tuple[str, str] | None = None
self._row_prices: list[float] = []
self._in_td = False
self._td_text: list[str] = []
self.quotes: list[HfPriceQuote] = []
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
if tag == "tr":
self._in_tr = True
self._row_match = None
self._row_prices = []
elif tag == "a" and self._in_tr and self._row_match is None:
href = dict(attrs).get("href") or ""
m = _ROW_HREF_RE.match(href)
if m:
self._row_match = (
urllib.parse.unquote(m.group("repo")),
urllib.parse.unquote(m.group("provider")),
)
elif tag == "td":
self._in_td = True
self._td_text = []
def handle_data(self, data: str) -> None:
if self._in_td:
self._td_text.append(data)
def handle_endtag(self, tag: str) -> None:
if tag == "td":
self._in_td = False
text = "".join(self._td_text).strip()
if _PRICE_RE.match(text):
self._row_prices.append(float(text.replace("$", "").replace(",", "")))
elif tag == "tr":
self._in_tr = False
if self._row_match and len(self._row_prices) >= 2:
repo_id, provider = self._row_match
self.quotes.append(
HfPriceQuote(
repo_id=repo_id,
provider=provider,
input_per_1m=self._row_prices[0],
output_per_1m=self._row_prices[1],
)
)
self._row_match = None
self._row_prices = []
def parse_hf_pricing_table(html: str) -> list[HfPriceQuote]:
"""Pure parsing function — no network I/O, so it's directly unit-testable."""
parser = _HfPricingTableParser()
parser.feed(html)
return parser.quotes
def _default_fetch_html(url: str, *, timeout: float) -> str:
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
with urllib.request.urlopen(req, timeout=timeout) as resp:
return resp.read().decode("utf-8", errors="replace")
def fetch_hf_price_quotes(
search_term: str,
*,
fetch_html: Callable[[str], str] | None = None,
timeout: float = 15.0,
) -> list[HfPriceQuote]:
"""Fetch and parse the HF inference pricing table filtered by ``search_term``.
``fetch_html`` is the test injection point (mirrors the ``backend=``
convention used elsewhere in this package) — it takes the full URL and
returns the raw HTML text, so tests never hit the network.
"""
url = f"{HF_INFERENCE_MODELS_URL}?{urllib.parse.urlencode({'search': search_term})}"
if fetch_html is not None:
html = fetch_html(url)
else:
html = _default_fetch_html(url, timeout=timeout)
return parse_hf_pricing_table(html)
def cheapest_matching_quote(
quotes: list[HfPriceQuote], aliases: list[str]
) -> HfPriceQuote | None:
"""Cheapest quote whose repo (optionally ``repo::provider``) is in ``aliases``.
An alias of ``"org/repo"`` matches that repo under any provider; an
alias of ``"org/repo::provider"`` matches only that specific provider —
useful when only one provider's deployment has been human-verified as a
fair comparable (matching quantization/params).
"""
alias_set = {a.strip().lower() for a in aliases if isinstance(a, str) and a.strip()}
if not alias_set:
return None
matches = [q for q in quotes if alias_set & set(q.alias_keys())]
if not matches:
return None
return min(matches, key=lambda q: q.blended_price_per_1k_tokens())
class HfPricingLog:
"""Thread-safe SQLite-backed audit log of dynamic price changes (issue 23).
Every price change (old, new, source alias/provider, timestamp) is
recorded here so a client dispute over a charge can be reconciled
against exactly what the market-tracking job did and when — mirrors
``calibration.py``'s persistence shape.
"""
def __init__(self, db_path: str | None = None) -> None:
self._db_path = db_path
self._lock = threading.Lock()
self._changes: list[dict] = []
if self._db_path:
self._init_db()
self._load_from_db()
def record_change(
self,
*,
model: str,
old_price_per_1k: float,
new_price_per_1k: float,
source_repo_id: str,
source_provider: str,
ts: float | None = None,
) -> dict:
change = {
"model": model,
"old_price_per_1k": old_price_per_1k,
"new_price_per_1k": new_price_per_1k,
"source_repo_id": source_repo_id,
"source_provider": source_provider,
"ts": ts if ts is not None else time.time(),
}
with self._lock:
self._changes.append(change)
self._save_change(change)
return change
def history(self, model: str | None = None, *, limit: int = 200) -> list[dict]:
with self._lock:
changes = list(self._changes)
if model is not None:
changes = [c for c in changes if c["model"] == model]
return changes[-limit:]
# ---- persistence (billing.py / calibration.py pattern) ----
def _init_db(self) -> None:
con = sqlite3.connect(self._db_path) # type: ignore[arg-type]
con.execute(
"CREATE TABLE IF NOT EXISTS hf_price_changes "
"(id INTEGER PRIMARY KEY AUTOINCREMENT, model TEXT NOT NULL, "
"payload TEXT NOT NULL, ts REAL NOT NULL)"
)
con.commit()
con.close()
def _load_from_db(self) -> None:
con = sqlite3.connect(self._db_path) # type: ignore[arg-type]
rows = con.execute(
"SELECT payload FROM hf_price_changes ORDER BY ts, id"
).fetchall()
con.close()
for (payload,) in rows:
try:
self._changes.append(json.loads(payload))
except json.JSONDecodeError:
continue
def _save_change(self, change: dict) -> None:
if not self._db_path:
return
con = sqlite3.connect(self._db_path) # type: ignore[arg-type]
con.execute(
"INSERT INTO hf_price_changes (model, payload, ts) VALUES (?, ?, ?)",
(change["model"], json.dumps(change), float(change["ts"])),
)
con.commit()
con.close()
def hf_search_term(preset: dict, model_name: str) -> str:
"""Best-effort search term for the HF pricing page's ``?search=`` filter."""
hf_repo = preset.get("hf_repo")
if isinstance(hf_repo, str) and hf_repo:
return hf_repo.rsplit("/", 1)[-1]
return model_name
def refresh_preset_price(
*,
model_name: str,
preset: dict,
current_price: float,
fetch_html: Callable[[str], str] | None = None,
price_fraction: float = DEFAULT_CLIENT_PRICE_FRACTION,
) -> dict | None:
"""Compute the new price for one preset, or None if nothing should change.
Never raises — any fetch/parse failure or absence of a verified match is
treated identically: keep the static default (deliverable's fallback
requirement). Callers are responsible for actually applying the result
(``BillingLedger.set_price`` + logging), so this function stays a pure
"what should the new price be" computation and is trivially unit-testable.
"""
aliases = preset.get("hf_aliases")
if not aliases:
return None
try:
quotes = fetch_hf_price_quotes(
hf_search_term(preset, model_name), fetch_html=fetch_html
)
quote = cheapest_matching_quote(quotes, aliases)
except Exception:
return None
if quote is None:
return None
new_price = round(quote.blended_price_per_1k_tokens() * price_fraction, 6)
if new_price <= 0:
return None
return {
"model": model_name,
"old_price_per_1k": current_price,
"new_price_per_1k": new_price,
# US-045: per-side rates (per 1k tokens) so the ledger bills input
# and output at the provider's actual asymmetry, not the average.
"new_input_price_per_1k": round(quote.input_per_1m * price_fraction / 1000.0, 6),
"new_output_price_per_1k": round(quote.output_per_1m * price_fraction / 1000.0, 6),
"source_repo_id": quote.repo_id,
"source_provider": quote.provider,
}
__all__ = [
"HF_INFERENCE_MODELS_URL",
"DEFAULT_HF_PRICING_LOG_DB_PATH",
"DEFAULT_CLIENT_PRICE_FRACTION",
"HfPriceQuote",
"HfPricingLog",
"parse_hf_pricing_table",
"fetch_hf_price_quotes",
"cheapest_matching_quote",
"hf_search_term",
"refresh_preset_price",
]

View File

@@ -0,0 +1,172 @@
"""Helpers for serving layer-scoped model files from tracker-local snapshots."""
from __future__ import annotations
import json
import re
from pathlib import Path
from typing import Any
INDEX_FILENAME = "model.safetensors.index.json"
_LAYER_RE = re.compile(
r"(?:^|\.)"
r"(?:model\.layers|layers|h|blocks|decoder\.layers|encoder\.layers)"
r"\.(\d+)(?:\.|$)"
)
_METADATA_FILENAMES = {
INDEX_FILENAME,
"config.json",
"generation_config.json",
"preprocessor_config.json",
"special_tokens_map.json",
"tokenizer.json",
"tokenizer.model",
"tokenizer_config.json",
"vocab.json",
"merges.txt",
"added_tokens.json",
}
_METADATA_PREFIXES = ("config.", "tokenizer.", "tokenizer_", "vocab.")
_HEAD_MARKERS = ("embed", "embedding", "embed_tokens", "wte", "wpe")
_TAIL_EXACT = {
"lm_head.weight",
"lm_head.bias",
"model.norm.weight",
"model.norm.bias",
"transformer.ln_f.weight",
"transformer.ln_f.bias",
"decoder.final_layer_norm.weight",
"decoder.final_layer_norm.bias",
}
_TAIL_MARKERS = (".lm_head.", ".norm.", ".ln_f.", ".final_layer_norm.")
def snapshot_dir_for_repo(models_dir: Path, repo_id: str) -> Path | None:
"""Return the most likely local HF snapshot directory for *repo_id*."""
candidates = [
models_dir / repo_id,
models_dir / repo_id.replace("/", "--"),
models_dir / f"models--{repo_id.replace('/', '--')}",
]
for candidate in candidates:
if (candidate / "snapshots").is_dir():
snapshots = sorted(p for p in (candidate / "snapshots").iterdir() if p.is_dir())
if snapshots:
return snapshots[-1]
if candidate.is_dir():
return candidate
return None
def files_for_layer_range(snapshot_dir: Path, shard_start: int, shard_end: int) -> list[str]:
"""Select files needed to load a conservative safetensors shard subset."""
return select_safetensors_files_for_layers(snapshot_dir, shard_start, shard_end)
def select_safetensors_files_for_layers(
model_dir: str | Path,
start_layer: int,
end_layer: int,
*,
total_layers: int | None = None,
) -> list[str]:
if start_layer < 0:
raise ValueError("start_layer must be non-negative")
if end_layer < start_layer:
raise ValueError("end_layer must be greater than or equal to start_layer")
root = Path(model_dir)
index_path = root / INDEX_FILENAME
try:
index = json.loads(index_path.read_text(encoding="utf-8"))
except FileNotFoundError:
return sorted(p.name for p in root.glob("*.safetensors") if p.is_file())
weight_map = index.get("weight_map")
if not isinstance(weight_map, dict):
raise ValueError(f"{INDEX_FILENAME} must contain a weight_map object")
inferred_total_layers = total_layers if total_layers is not None else _read_total_layers(root)
selected = _metadata_files(root)
for tensor_name, rel_file in weight_map.items():
if not isinstance(tensor_name, str) or not isinstance(rel_file, str):
continue
if _tensor_belongs_to_range(tensor_name, start_layer, end_layer, inferred_total_layers):
selected.add(_normalise_relative_file(rel_file))
return sorted(rel for rel in selected if (root / rel).is_file())
def _tensor_belongs_to_range(
tensor_name: str,
start_layer: int,
end_layer: int,
total_layers: int | None,
) -> bool:
layer = _layer_index(tensor_name)
if layer is not None:
return start_layer <= layer <= end_layer
if start_layer == 0 and _is_head_tensor(tensor_name):
return True
if total_layers is not None and end_layer >= total_layers - 1 and _is_tail_tensor(tensor_name):
return True
return False
def _layer_index(tensor_name: str) -> int | None:
match = _LAYER_RE.search(tensor_name)
return int(match.group(1)) if match else None
def _is_head_tensor(tensor_name: str) -> bool:
lowered = tensor_name.lower()
return any(marker in lowered for marker in _HEAD_MARKERS)
def _is_tail_tensor(tensor_name: str) -> bool:
lowered = tensor_name.lower()
return lowered in _TAIL_EXACT or any(marker in lowered for marker in _TAIL_MARKERS)
def _metadata_files(root: Path) -> set[str]:
files = {INDEX_FILENAME}
for path in root.iterdir():
if not path.is_file():
continue
name = path.name
if name in _METADATA_FILENAMES or name.startswith(_METADATA_PREFIXES):
files.add(name)
return files
def _read_total_layers(root: Path) -> int | None:
config_path = root / "config.json"
if not config_path.exists():
return None
config = json.loads(config_path.read_text(encoding="utf-8"))
return _layers_from_config(config)
def _layers_from_config(config: dict[str, Any]) -> int | None:
for key in ("num_hidden_layers", "num_layers", "n_layer", "n_layers"):
value = config.get(key)
if isinstance(value, int) and value > 0:
return value
text_config = config.get("text_config")
if isinstance(text_config, dict):
return _layers_from_config(text_config)
return None
def _normalise_relative_file(rel_file: str) -> str:
path = Path(rel_file)
if path.is_absolute() or ".." in path.parts:
raise ValueError(f"unsafe relative file in {INDEX_FILENAME}: {rel_file}")
return path.as_posix()

View File

@@ -11,9 +11,13 @@
], ],
"recommended": true, "recommended": true,
"deployment_status": "recommended", "deployment_status": "recommended",
"hf_aliases": [],
"hf_verified_match_note": "Pending human curation (issue 23) \u2014 no HF inference-marketplace listing has been confirmed as a comparable params/quantization match for this preset yet. Leave empty until a human signs off; an empty hf_aliases list keeps this model on the static default price.",
"required_model_bytes": 638876385280, "required_model_bytes": 638876385280,
"download_size_bytes": 638876385280, "download_size_bytes": 638876385280,
"native_quantization": "int4", "native_quantization": "int4",
"canonical_audit_dtype": "bfloat16",
"canonical_audit_quantization": "bfloat16",
"bytes_per_layer": { "bytes_per_layer": {
"int4": 10473383366 "int4": 10473383366
}, },
@@ -24,6 +28,8 @@
"num_layers": 61, "num_layers": 61,
"context_length": 256000, "context_length": 256000,
"native_quantization": "int4", "native_quantization": "int4",
"canonical_audit_dtype": "bfloat16",
"canonical_audit_quantization": "bfloat16",
"download_size_gb": 595, "download_size_gb": 595,
"recommended_short_name": "kimi-k2.7", "recommended_short_name": "kimi-k2.7",
"recommended_engines": [ "recommended_engines": [
@@ -32,6 +38,43 @@
"KTransformers" "KTransformers"
] ]
} }
},
"qwen3.6-35b-a3b": {
"layers_start": 0,
"layers_end": 39,
"hf_repo": "unsloth/Qwen3.6-35B-A3B",
"aliases": [
"qwen3.6-35b-a3b",
"Qwen3.6-35B-A3B",
"unsloth/Qwen3.6-35B-A3B",
"Qwen/Qwen3.6-35B-A3B"
],
"recommended": true,
"deployment_status": "recommended",
"price_per_1k_tokens": 0.00044,
"hf_aliases": [
"qwen/qwen3.6-35b-a3b"
],
"hf_verified_match_note": "Verified 2026-07-06: unsloth/Qwen3.6-35B-A3B is a bf16 mirror of Qwen/Qwen3.6-35B-A3B; deepinfra and featherless-ai serve the official weights on the HF inference marketplace, so their rates are a fair comparable. Rates are 80% of deepinfra: input 0.00012/1k ($0.15/1M), output 0.00076/1k ($0.95/1M); price_per_1k_tokens keeps the blended 0.00044 for display/back-compat. The nightly refresher tracks both sides.",
"required_model_bytes": 71903776776,
"download_size_bytes": 71903776776,
"native_quantization": "bfloat16",
"canonical_audit_dtype": "bfloat16",
"canonical_audit_quantization": "bfloat16",
"bytes_per_layer": {
"bfloat16": 1797594419
},
"metadata": {
"architecture": "Mixture-of-Experts (MoE, hybrid linear attention)",
"total_parameters": "35B",
"activated_parameters": "3B",
"num_layers": 40,
"context_length": 262144,
"native_quantization": "bfloat16",
"download_size_gb": 72
},
"input_price_per_1k_tokens": 0.00012,
"output_price_per_1k_tokens": 0.00076
} }
} }
} }

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,49 @@
"""Ed25519 proof-of-ownership for client wallet binding (ADR-0017 §5, issue C6).
Wallet addresses are base58-encoded Solana ed25519 public keys, the same
format used by ``packages/node/meshnet_node/wallet.py``. Binding a wallet to
an API key requires a signature over a message that embeds the api_key, so a
captured (wallet, signature) pair cannot be replayed to bind a different key.
No Solana RPC dependency is needed for verification, so this stays on plain
``cryptography`` rather than pulling in ``solders`` on the tracker.
"""
from __future__ import annotations
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
_B58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
_B58_INDEX = {char: index for index, char in enumerate(_B58_ALPHABET)}
def b58decode(value: str) -> bytes:
"""Decode a base58 string (Solana/Bitcoin alphabet) to bytes."""
n = 0
for char in value:
digit = _B58_INDEX.get(char)
if digit is None:
raise ValueError(f"invalid base58 character: {char!r}")
n = n * 58 + digit
body = n.to_bytes((n.bit_length() + 7) // 8, "big") if n else b""
leading_zeros = len(value) - len(value.lstrip("1"))
return b"\x00" * leading_zeros + body
def binding_message(api_key: str, wallet: str) -> bytes:
"""Message a wallet owner must sign to bind ``wallet`` to ``api_key``."""
return f"meshnet-wallet-bind:{api_key}:{wallet}".encode()
def verify_wallet_signature(wallet: str, message: bytes, signature_hex: str) -> bool:
"""True if ``signature_hex`` is a valid ed25519 signature by ``wallet`` over ``message``."""
try:
pubkey_bytes = b58decode(wallet)
if len(pubkey_bytes) != 32:
return False
signature = bytes.fromhex(signature_hex)
Ed25519PublicKey.from_public_bytes(pubkey_bytes).verify(signature, message)
return True
except (ValueError, InvalidSignature):
return False

View File

@@ -9,6 +9,7 @@ description = "Distributed Inference Network node registry and route selection"
requires-python = ">=3.10" requires-python = ">=3.10"
dependencies = [ dependencies = [
"cryptography>=41",
"websockets>=13", "websockets>=13",
] ]

View File

@@ -2,28 +2,81 @@
Optimistic fraud detection (ADR-0003, penalty amended by ADR-0015): the Optimistic fraud detection (ADR-0003, penalty amended by ADR-0015): the
validator re-runs a random ~5% sample of completed inference requests against validator re-runs a random ~5% sample of completed inference requests against
a trusted reference node and, on divergence, submits a slash proof and a trusted reference node. Audit-capable events are checked by teacher-forcing
forfeits the node's pending balance. the claimed token sequence through the reference node and verifying the
claimed TOPLOC activation proof. Legacy events without TOPLOC metadata still
fall back to text comparison until node-side proof capture lands.
## Why the penalty deters cheating ## Why the penalty deters cheating
There is no upfront stake. Settlement is periodic (US-033), so a node always There is no upfront stake. Settlement is periodic (US-033), so a node always
has an unpaid **pending balance** — that balance *is* the collateral. has an unpaid **pending balance** — that balance *is* the collateral.
At a sampling rate `p`, a cheater is caught on average once every `1/p` At a sampling rate `p`, a cheater who gains `G` per fraudulent job and loses
fraudulent jobs, so cheating is unprofitable when: `L` when caught has expected value:
``` ```
penalty > per_job_gain / p # p = 0.05 → penalty > 20 × per_job_gain (1 - p) * G - p * L < 0
L > ((1 - p) / p) * G # p = 0.05 -> L > 19 x G
``` ```
With the production settlement period of 24h, the pending balance at any With the production settlement period of 24h, the pending balance at any
moment approximates a full day's earnings — hundreds to thousands of jobs — moment approximates a full day's earnings — hundreds to thousands of jobs —
which is far above the 20× bar. Each catch also records a strike; three which is far above the 19× bar. Each catch also records a strike; three
strikes ban the wallet (registration rejected, excluded from routes, unpaid strikes ban the wallet (registration rejected, excluded from routes, unpaid
pending never settled), and the probationary period (first N jobs unpaid) pending never settled), and the probationary period (first N jobs unpaid)
makes re-entry with a fresh wallet costly. makes re-entry with a fresh wallet costly.
## TOPLOC audit contract
The validator expects audit-capable events to carry:
- `claimed_token_ids`: the final token sequence claimed by the prover.
- `toploc_proof`: compact TOPLOC proof data built from prover activations.
On audit the validator calls the reference node's `POST /v1/audit/toploc`
endpoint with the original messages plus `claimed_token_ids`. The reference
node must run a teacher-forced prefill over exactly that token sequence and
return the activations for TOPLOC verification. It must not free-generate a
second answer for audit.
Canonical audit parameters for the current alpha preset are:
```
dtype = "bfloat16"
quantization = "bfloat16"
decode_batching_size = 32
topk = 8
skip_prefill = true
encoding = "base64"
```
`verify_activation_proofs_detailed()` (`meshnet_validator.audit`) surfaces the
raw TOPLOC divergence — `exp_intersections` (worst-case across chunks),
`mant_err_mean`, `mant_err_median` — alongside the pass/fail bool. This is
what the calibration corpus below is built from; existing callers that only
need the bool keep using `verify_activation_proofs()`.
**Do not enable production audit thresholds before issue 21 closes.**
Production audit thresholds remain gated on the honest-noise calibration
corpus in issue 21: the tracker's `POST /v1/calibration/toploc/run`
(admin/validator-only, mirrors `POST /v1/benchmark/hop-penalty`) dispatches a
fixed prompt to every solo-capable registered node, verifies each node's
on-demand commitment against a teacher-forced reference replay, and records
the divergence into a SQLite corpus (`meshnet_tracker.calibration.
ToplocCalibrationStore`) keyed by node wallet + GPU model + dtype.
`GET /v1/calibration/toploc/results` reports the corpus plus:
- `envelope`: p99 honest-noise value per metric with a 20% safety margin —
the recommended (not yet wired) tolerance constants.
- `gate_status.ready`: whether the corpus covers enough distinct hardware
profiles (`--toploc-calibration-gate-min-hardware-profiles`, default 1).
**Alpha exception:** with the hired-VPS-only launch fleet, `ready` may
legitimately mean "covers every node we currently operate" — this must be
revisited (raise the minimum) before a public/volunteer launch broadens
the hardware mix, since a new corpus is required whenever the fleet's
hardware composition changes.
Two operational notes: Two operational notes:
- Shortening the settlement period shrinks the collateral. Period changes - Shortening the settlement period shrinks the collateral. Period changes
@@ -44,3 +97,27 @@ ValidatorProcess(
Remote validators can instead call the tracker's privileged Remote validators can instead call the tracker's privileged
`POST /v1/billing/forfeit` endpoint (non-empty Authorization header). `POST /v1/billing/forfeit` endpoint (non-empty Authorization header).
## Reputation-weighted audit rate (ADR-0018 §1, §6-7)
`sample_rate` is a flat coin flip: every wallet audited at the same rate.
Pass `audit_sampler=AdaptiveAuditSampler(...)` instead to make the audit
probability a function of each wallet's tenure and reputation — newcomers
and low-reputation wallets sampled at 2030%, veterans in good standing
floor at ≥2% — while a running budget balance keeps the fleet-wide realized
rate anchored to `AuditRateConfig.target_rate` (default 5%) regardless of
the wallet mix. Passive tripwires (`detect_output_tripwire`) bump only that
one request's odds; they never strike, ban, or affect other wallets' rates.
```python
from meshnet_validator import AdaptiveAuditSampler, detect_output_tripwire
ValidatorProcess(
contracts=contracts,
reference_node_url="http://...",
audit_sampler=AdaptiveAuditSampler(random_seed=42),
)
```
When `audit_sampler` is set, `sample_rate` is ignored — the sampler decides
per event, keyed on whichever route wallet has the lowest reputation.

View File

@@ -8,6 +8,16 @@ import time
import urllib.request import urllib.request
from typing import Any from typing import Any
from .audit import (
ToplocAuditConfig,
ToplocProofClaim,
ToplocVerificationResult,
verify_activation_proofs,
verify_activation_proofs_detailed,
)
from .sampling import AdaptiveAuditSampler, AuditRateConfig
from .tripwire import detect_output_tripwire
__version__ = "0.1.0" __version__ = "0.1.0"
@@ -27,6 +37,9 @@ class ValidatorProcess:
webhook_url: str | None = None, webhook_url: str | None = None,
interval_seconds: float = 1.0, interval_seconds: float = 1.0,
billing: Any | None = None, billing: Any | None = None,
toploc_config: ToplocAuditConfig | None = None,
toploc_backend: Any | None = None,
audit_sampler: AdaptiveAuditSampler | None = None,
) -> None: ) -> None:
if not 0.0 <= sample_rate <= 1.0: if not 0.0 <= sample_rate <= 1.0:
raise ValueError("sample_rate must be between 0 and 1") raise ValueError("sample_rate must be between 0 and 1")
@@ -48,6 +61,9 @@ class ValidatorProcess:
self._strike_threshold = strike_threshold self._strike_threshold = strike_threshold
self._webhook_url = webhook_url self._webhook_url = webhook_url
self._interval_seconds = interval_seconds self._interval_seconds = interval_seconds
self._toploc_config = toploc_config or ToplocAuditConfig()
self._toploc_backend = toploc_backend
self._audit_sampler = audit_sampler
self._random = random.Random(random_seed) self._random = random.Random(random_seed)
self._last_event_index = -1 self._last_event_index = -1
self._running = False self._running = False
@@ -62,15 +78,47 @@ class ValidatorProcess:
) )
for event in events: for event in events:
self._last_event_index = max(self._last_event_index, event.index) self._last_event_index = max(self._last_event_index, event.index)
if self._random.random() >= self._sample_rate: if not self._should_sample(event):
continue continue
self.sampled_count += 1 self.sampled_count += 1
reference_output = self._run_reference(event.messages) audit_result = self._validate_event(event)
if _outputs_match(event.observed_output, reference_output, self._tolerance): if audit_result.ok:
self._record_clean_audit(event)
continue continue
receipts.extend(self._slash_route(event.route_nodes, event.observed_output, reference_output)) receipts.extend(self._slash_node(
audit_result.culprit_node,
event.observed_output,
audit_result.reference_output,
reason=audit_result.reason,
))
return receipts return receipts
def _should_sample(self, event: Any) -> bool:
"""ADR-0018 §1/§6-7: flat sample_rate stays the default; when an
AdaptiveAuditSampler is configured, the decision is reputation- and
tenure-weighted and budget-balanced against the fleet-wide target
instead of a uniform coin flip."""
if self._audit_sampler is None:
return self._random.random() < self._sample_rate
tripwire = detect_output_tripwire(_event_value(event, "observed_output") or "")
wallets = _route_wallets(event)
if not wallets:
return self._audit_sampler.should_audit(
completed_job_count=0, reputation=1.0, tripwire=tripwire,
)
# A route is only as trustworthy as its least-trusted hop -- audit
# against whichever wallet on the route looks riskiest.
riskiest = min(
(self._contracts.registry.get_wallet(wallet) for wallet in wallets),
key=lambda wallet: wallet.reputation,
)
return self._audit_sampler.should_audit(
completed_job_count=riskiest.completed_job_count,
reputation=riskiest.reputation,
tripwire=tripwire,
)
def start(self) -> None: def start(self) -> None:
if self._running: if self._running:
raise RuntimeError("ValidatorProcess is already running") raise RuntimeError("ValidatorProcess is already running")
@@ -99,14 +147,201 @@ class ValidatorProcess:
raise ValueError("reference node response did not contain text") raise ValueError("reference node response did not contain text")
return text return text
def _slash_route( def _validate_event(self, event: Any) -> "_AuditResult":
event = self._event_with_on_demand_commitments(event)
hop_commitments = _hop_commitments_from_event(event)
if hop_commitments is not None and self._commitment_expired(event):
# ADR-0018 §3: the on-demand retention window has passed — nodes
# are no longer expected to hold the boundary activations needed
# to verify this commitment, so fall back to the text-only path.
hop_commitments = None
if hop_commitments is None:
reference_output = self._run_reference(event.messages)
ok = _outputs_match(event.observed_output, reference_output, self._tolerance)
return _AuditResult(
ok=ok,
reference_output=reference_output,
reason="reference output diverged",
# Text comparison has no per-hop signal; the last hop is the
# best-effort guess (text-only fallback), never used when
# hop-boundary commitments make real bisection possible.
culprit_node=None if ok else _final_text_node(event.route_nodes),
)
if len(hop_commitments) == 1:
# Single-commitment route (AH-006 whole-route format, or a
# genuinely one-hop pipeline): reuse the original teacher-forced
# call so existing single-hop reference integrations keep working.
only = hop_commitments[0]
reference_activations_by_hop = [self._run_teacher_forced_prefill(
model=_event_value(event, "model"),
messages=_event_value(event, "messages"),
claimed_token_ids=only.token_ids,
claim=only.claim,
)]
else:
reference_activations_by_hop = self._run_teacher_forced_prefill_hops(
model=_event_value(event, "model"),
messages=_event_value(event, "messages"),
hop_commitments=hop_commitments,
)
culprit_index = _first_divergent_hop(
hop_commitments,
reference_activations_by_hop,
config=self._toploc_config,
backend=self._toploc_backend,
)
ok = culprit_index is None
return _AuditResult(
ok=ok,
reference_output=(
"TOPLOC activation proof accepted"
if ok
else f"TOPLOC activation proof mismatch at hop {culprit_index}"
),
reason="TOPLOC activation proof mismatch",
culprit_node=None if ok else hop_commitments[culprit_index].node,
)
def _event_with_on_demand_commitments(self, event: Any) -> Any:
"""Fetch missing per-hop TOPLOC commitments only after audit sampling.
Tracker validation events deliberately carry ordinary route metadata,
not a pre-announced audit flag. When this validator samples an event, it
asks each hop for its short-lived boundary commitment and splices the
returned proof into a local event copy for the bisection verifier.
"""
route_nodes = _event_value(event, "route_nodes") or []
if not isinstance(route_nodes, list) or not route_nodes:
return event
updated_nodes: list[dict] = []
changed = False
for node in route_nodes:
if not isinstance(node, dict):
updated_nodes.append(node)
continue
updated = dict(node)
if _mapping_value(updated, "toploc_proof") is None:
commitment = self._fetch_hop_commitment(event, updated)
if commitment is not None:
updated.update(commitment)
changed = True
updated_nodes.append(updated)
if not changed:
return event
if isinstance(event, dict):
copied = dict(event)
else:
copied = dict(vars(event))
copied["route_nodes"] = updated_nodes
return copied
def _fetch_hop_commitment(self, event: Any, node: dict) -> dict[str, Any] | None:
endpoint = node.get("endpoint")
if not isinstance(endpoint, str) or not endpoint:
return None
try:
response = _post_json(
f"{endpoint.rstrip('/')}/v1/audit/toploc/commitment",
{
"session_id": _event_value(event, "session_id"),
"model": _event_value(event, "model"),
"messages": _event_value(event, "messages") or [],
"shard_start": node.get("shard_start"),
"shard_end": node.get("shard_end"),
},
timeout=2.0,
)
except (OSError, ValueError, json.JSONDecodeError):
return None
proof = response.get("toploc_proof") or response.get("activation_proof")
token_ids = response.get("claimed_token_ids") or response.get("output_token_ids")
if not isinstance(proof, dict):
return None
if not isinstance(token_ids, list) or not all(isinstance(token, int) for token in token_ids):
return None
return {"toploc_proof": proof, "claimed_token_ids": token_ids}
def _commitment_expired(self, event: Any) -> bool:
ts = _event_value(event, "ts")
if ts is None:
return False
return (time.time() - float(ts)) > self._toploc_config.commitment_ttl_seconds
def _run_teacher_forced_prefill(
self, self,
route_nodes: list[dict], *,
model: str,
messages: list[dict],
claimed_token_ids: list[int],
claim: ToplocProofClaim,
) -> list[Any]:
response = _post_json(
f"{self._reference_node_url}/v1/audit/toploc",
{
"model": model,
"messages": messages,
"claimed_token_ids": claimed_token_ids,
"dtype": claim.dtype,
"quantization": claim.quantization,
"decode_batching_size": claim.decode_batching_size,
"topk": claim.topk,
"skip_prefill": claim.skip_prefill,
},
)
activations = response.get("activations")
if not isinstance(activations, list):
raise ValueError("reference node audit response did not contain activations")
return activations
def _run_teacher_forced_prefill_hops(
self,
*,
model: str,
messages: list[dict],
hop_commitments: list["_HopCommitment"],
) -> list[list[Any]]:
"""Teacher-force the claimed tokens once and collect reference
activations at every hop's boundary layer (ADR-0018 §4 / research §1.2:
one referee forward pass, compared at each cut-point)."""
reference_claim = hop_commitments[0].claim
response = _post_json(
f"{self._reference_node_url}/v1/audit/toploc",
{
"model": model,
"messages": messages,
"claimed_token_ids": hop_commitments[-1].token_ids,
"hop_boundaries": [hop.shard_end for hop in hop_commitments],
"dtype": reference_claim.dtype,
"quantization": reference_claim.quantization,
"decode_batching_size": reference_claim.decode_batching_size,
"topk": reference_claim.topk,
"skip_prefill": reference_claim.skip_prefill,
},
)
activations_by_hop = response.get("activations_by_hop")
if not isinstance(activations_by_hop, list) or len(activations_by_hop) != len(hop_commitments):
raise ValueError("reference node audit response did not contain per-hop activations")
return activations_by_hop
def _record_clean_audit(self, event: Any) -> None:
"""ADR-0018 §6: reputation derives only from tracker-verified audit
outcomes — a clean audit credits every node on the verified route."""
for wallet_address in _route_wallets(event):
if self._contracts.registry.get_wallet(wallet_address).banned:
continue
self._contracts.registry.record_audit_outcome(wallet_address, passed=True)
def _slash_node(
self,
node: dict | None,
observed_output: str, observed_output: str,
reference_output: str, reference_output: str,
*,
reason: str = "reference output diverged",
) -> list[Any]: ) -> list[Any]:
receipts: list[Any] = [] receipts: list[Any] = []
node = _final_text_node(route_nodes)
wallet_address = node.get("wallet_address") if node else None wallet_address = node.get("wallet_address") if node else None
if not wallet_address: if not wallet_address:
return receipts return receipts
@@ -117,11 +352,14 @@ class ValidatorProcess:
slash_amount=self._slash_amount, slash_amount=self._slash_amount,
strike_threshold=self._strike_threshold, strike_threshold=self._strike_threshold,
reason=( reason=(
"reference output diverged " f"{reason} "
f"(observed={observed_output!r}, reference={reference_output!r})" f"(observed={observed_output!r}, reference={reference_output!r})"
), ),
webhook_url=self._webhook_url, webhook_url=self._webhook_url,
)) ))
# ADR-0018 §6: reputation loss is separate from the strike/ban that
# submit_slash_proof already recorded above — never double-strike.
self._contracts.registry.record_audit_outcome(wallet_address, passed=False)
# ADR-0015: the pending balance is the collateral — forfeit it in the # ADR-0015: the pending balance is the collateral — forfeit it in the
# same validation cycle as the strike. # same validation cycle as the strike.
if self._billing is not None: if self._billing is not None:
@@ -134,12 +372,149 @@ class ValidatorProcess:
return receipts return receipts
def _route_wallets(event: Any) -> list[str]:
"""Unique wallet addresses across a route, in hop order."""
route_nodes = _event_value(event, "route_nodes") or []
seen: set[str] = set()
wallets: list[str] = []
for node in route_nodes:
wallet_address = node.get("wallet_address") if isinstance(node, dict) else None
if wallet_address and wallet_address not in seen:
seen.add(wallet_address)
wallets.append(wallet_address)
return wallets
def _final_text_node(route_nodes: list[dict]) -> dict | None: def _final_text_node(route_nodes: list[dict]) -> dict | None:
"""Text-only fallback blame: when the audit has no per-hop fingerprints
to bisect (free-running text comparison only), guess the last hop.
Never used once hop-boundary commitments make real bisection possible."""
if not route_nodes: if not route_nodes:
return None return None
return max(route_nodes, key=lambda node: int(node.get("shard_end", 0))) return max(route_nodes, key=lambda node: int(node.get("shard_end", 0)))
class _AuditResult:
def __init__(
self,
*,
ok: bool,
reference_output: str,
reason: str,
culprit_node: dict | None = None,
) -> None:
self.ok = ok
self.reference_output = reference_output
self.reason = reason
self.culprit_node = culprit_node
class _HopCommitment:
"""One hop's on-demand TOPLOC commitment plus the route node it blames."""
def __init__(self, node: dict | None, claim: ToplocProofClaim, token_ids: list[int]) -> None:
self.node = node
self.claim = claim
self.token_ids = token_ids
self.shard_end = int(node.get("shard_end", 0)) if node else None
def _hop_commitments_from_event(event: Any) -> list[_HopCommitment] | None:
"""Per-hop bisection commitments (ADR-0018 §3/§4): each route node reports
its own output-boundary fingerprint. Falls back to the AH-006 whole-route
commitment format (one fingerprint, no bisection) when hops don't carry
individual commitments."""
route_nodes = _event_value(event, "route_nodes") or []
per_hop_nodes = [
node for node in route_nodes
if isinstance(node, dict) and _mapping_value(node, "toploc_proof") is not None
]
if per_hop_nodes and len(per_hop_nodes) == len(route_nodes):
ordered = sorted(route_nodes, key=lambda node: int(node.get("shard_start", 0)))
default_token_ids = _event_value(event, "claimed_token_ids")
commitments = []
for node in ordered:
token_ids = node.get("claimed_token_ids", default_token_ids)
if not isinstance(token_ids, list) or not all(isinstance(t, int) for t in token_ids):
raise ValueError("TOPLOC hop commitments must include claimed_token_ids")
commitments.append(_HopCommitment(
node,
ToplocProofClaim.from_mapping(node["toploc_proof"]),
token_ids,
))
return commitments
whole_route = _toploc_audit_from_event(event)
if whole_route is None:
return None
token_ids, claim = whole_route
return [_HopCommitment(route_nodes[-1] if route_nodes else None, claim, token_ids)]
def _first_divergent_hop(
hop_commitments: list[_HopCommitment],
reference_activations_by_hop: list[Any],
*,
config: ToplocAuditConfig,
backend: Any | None,
) -> int | None:
"""First hop whose committed output fingerprint diverges from the
referee's independently-computed reference activations at that same
cut-point (research §1.2: no interactive game needed at hop granularity —
the referee checks every cut-point in one replay)."""
for index, commitment in enumerate(hop_commitments):
ok = verify_activation_proofs(
reference_activations_by_hop[index],
commitment.claim,
config=config,
backend=backend,
)
if not ok:
return index
return None
def _toploc_audit_from_event(event: Any) -> tuple[list[int], ToplocProofClaim] | None:
audit = _event_mapping(event, "audit")
claim_data = (
_event_mapping(event, "toploc_proof")
or _event_mapping(event, "activation_proof")
or _mapping_value(audit, "toploc_proof")
or _mapping_value(audit, "activation_proof")
or _mapping_value(audit, "toploc")
)
if claim_data is None:
return None
token_ids = (
_event_value(event, "claimed_token_ids")
or _event_value(event, "output_token_ids")
or _mapping_value(audit, "claimed_token_ids")
or _mapping_value(audit, "output_token_ids")
)
if not isinstance(token_ids, list) or not all(isinstance(token, int) for token in token_ids):
raise ValueError("TOPLOC audit events must include claimed_token_ids")
return token_ids, ToplocProofClaim.from_mapping(claim_data)
def _event_value(event: Any, name: str) -> Any:
if hasattr(event, name):
return getattr(event, name)
if isinstance(event, dict):
return event.get(name)
return None
def _event_mapping(event: Any, name: str) -> dict[str, Any] | None:
value = _event_value(event, name)
return value if isinstance(value, dict) else None
def _mapping_value(mapping: dict[str, Any] | None, name: str) -> Any:
if mapping is None:
return None
return mapping.get(name)
def _outputs_match(observed: str, reference: str, tolerance: float) -> bool: def _outputs_match(observed: str, reference: str, tolerance: float) -> bool:
observed_float = _parse_float(observed) observed_float = _parse_float(observed)
reference_float = _parse_float(reference) reference_float = _parse_float(reference)
@@ -167,4 +542,11 @@ def _post_json(url: str, payload: dict, timeout: float = 5.0) -> dict:
return json.loads(response.read()) return json.loads(response.read())
__all__ = ["ValidatorProcess"] __all__ = [
"ToplocAuditConfig",
"ToplocProofClaim",
"ValidatorProcess",
"AdaptiveAuditSampler",
"AuditRateConfig",
"detect_output_tripwire",
]

View File

@@ -0,0 +1,236 @@
"""TOPLOC activation proof helpers for validator-side audits."""
from __future__ import annotations
from dataclasses import dataclass
from importlib import import_module
from typing import Any, Literal
ProofEncoding = Literal["base64", "bytes"]
@dataclass(frozen=True)
class ToplocAuditConfig:
"""Canonical audit parameters for one model preset."""
dtype: str = "bfloat16"
quantization: str = "bfloat16"
decode_batching_size: int = 32
topk: int = 8
skip_prefill: bool = True
encoding: ProofEncoding = "base64"
# ADR-0018 §3: nodes retain boundary activations only briefly; a commitment
# older than this can no longer be verified against a live node and must
# fall back to the text-only audit path.
commitment_ttl_seconds: float = 30.0
@dataclass(frozen=True)
class ToplocProofClaim:
"""Prover-provided TOPLOC proof and the parameters it was built with."""
proofs: Any
dtype: str
quantization: str
decode_batching_size: int
topk: int
skip_prefill: bool = True
encoding: ProofEncoding = "base64"
@classmethod
def from_mapping(cls, value: dict[str, Any]) -> "ToplocProofClaim":
return cls(
proofs=value["proofs"],
dtype=str(value.get("dtype", "bfloat16")),
quantization=str(value.get("quantization", "bfloat16")),
decode_batching_size=int(value.get("decode_batching_size", 32)),
topk=int(value.get("topk", 8)),
skip_prefill=bool(value.get("skip_prefill", True)),
encoding=_proof_encoding(value.get("encoding", "base64")),
)
def as_mapping(self) -> dict[str, Any]:
return {
"proofs": self.proofs,
"dtype": self.dtype,
"quantization": self.quantization,
"decode_batching_size": self.decode_batching_size,
"topk": self.topk,
"skip_prefill": self.skip_prefill,
"encoding": self.encoding,
}
def build_activation_proofs(
activations: list[Any],
*,
config: ToplocAuditConfig | None = None,
backend: Any | None = None,
) -> ToplocProofClaim:
"""Build a TOPLOC proof claim from captured activation tensors."""
cfg = config or ToplocAuditConfig()
module = backend or _load_toploc()
function_name = f"build_proofs_{cfg.encoding}"
build = getattr(module, function_name)
proofs = _call_toploc(
build,
activations,
decode_batching_size=cfg.decode_batching_size,
topk=cfg.topk,
skip_prefill=cfg.skip_prefill,
)
return ToplocProofClaim(
proofs=proofs,
dtype=cfg.dtype,
quantization=cfg.quantization,
decode_batching_size=cfg.decode_batching_size,
topk=cfg.topk,
skip_prefill=cfg.skip_prefill,
encoding=cfg.encoding,
)
@dataclass(frozen=True)
class ToplocVerificationResult:
"""Verification outcome plus the raw TOPLOC divergence metric.
The `toploc` library's `verify_proofs_*` returns a bool for simple
prover/verifier config mismatches, but for a real activation comparison
it returns one `VerificationResult(exp_intersections, mant_err_mean,
mant_err_median)` per chunk (README §"What it actually is"). Historically
only `bool(result)` was kept, which is always true for a non-empty list
of results regardless of how divergent they are (AH-021 gap #1). This
dataclass surfaces the raw per-chunk metrics (aggregated: worst-case
`exp_intersections`, mean `mant_err_mean`/`mant_err_median`) so a
calibration corpus can be built before any threshold is trusted.
"""
passed: bool
exp_intersections: float | None = None
mant_err_mean: float | None = None
mant_err_median: float | None = None
chunk_count: int = 0
def verify_activation_proofs(
reference_activations: list[Any],
claim: ToplocProofClaim,
*,
config: ToplocAuditConfig | None = None,
backend: Any | None = None,
) -> bool:
"""Verify prover TOPLOC proofs against reference teacher-forced activations."""
return verify_activation_proofs_detailed(
reference_activations, claim, config=config, backend=backend,
).passed
def verify_activation_proofs_detailed(
reference_activations: list[Any],
claim: ToplocProofClaim,
*,
config: ToplocAuditConfig | None = None,
backend: Any | None = None,
) -> ToplocVerificationResult:
"""Verify prover TOPLOC proofs and surface the raw divergence metric.
Same pass/fail contract as `verify_activation_proofs` (kept as a thin
wrapper for existing call sites); this is the entry point for anything
that needs the underlying distance value, e.g. the AH-021 honest-noise
calibration corpus.
"""
cfg = config or ToplocAuditConfig(
dtype=claim.dtype,
quantization=claim.quantization,
decode_batching_size=claim.decode_batching_size,
topk=claim.topk,
skip_prefill=claim.skip_prefill,
encoding=claim.encoding,
)
if claim.dtype != cfg.dtype or claim.quantization != cfg.quantization:
return ToplocVerificationResult(passed=False)
if claim.decode_batching_size != cfg.decode_batching_size or claim.topk != cfg.topk:
return ToplocVerificationResult(passed=False)
if claim.skip_prefill != cfg.skip_prefill or claim.encoding != cfg.encoding:
return ToplocVerificationResult(passed=False)
module = backend or _load_toploc()
function_name = f"verify_proofs_{claim.encoding}"
verify = getattr(module, function_name)
raw = _call_toploc(
verify,
reference_activations,
claim.proofs,
decode_batching_size=claim.decode_batching_size,
topk=claim.topk,
skip_prefill=claim.skip_prefill,
)
divergence = _extract_divergence(raw)
return ToplocVerificationResult(passed=bool(raw), **divergence)
def _extract_divergence(raw: Any) -> dict[str, Any]:
"""Aggregate per-chunk TOPLOC `VerificationResult`s, if present.
`raw` is a plain bool for the simple fake backends used in existing unit
tests (no per-chunk metric available). The real `toploc` library returns
a list of per-chunk results; `exp_intersections` is aggregated by min
(worst honest-noise case across chunks) and the mantissa errors by mean.
"""
chunks = raw if isinstance(raw, (list, tuple)) else None
if not chunks:
return {"exp_intersections": None, "mant_err_mean": None, "mant_err_median": None, "chunk_count": 0}
exp_vals = [v for v in (_chunk_field(c, "exp_intersections") for c in chunks) if v is not None]
mean_vals = [v for v in (_chunk_field(c, "mant_err_mean") for c in chunks) if v is not None]
median_vals = [v for v in (_chunk_field(c, "mant_err_median") for c in chunks) if v is not None]
return {
"exp_intersections": min(exp_vals) if exp_vals else None,
"mant_err_mean": (sum(mean_vals) / len(mean_vals)) if mean_vals else None,
"mant_err_median": (sum(median_vals) / len(median_vals)) if median_vals else None,
"chunk_count": len(chunks),
}
def _chunk_field(chunk: Any, name: str) -> float | None:
value = chunk.get(name) if isinstance(chunk, dict) else getattr(chunk, name, None)
return float(value) if isinstance(value, (int, float)) else None
def _load_toploc() -> Any:
try:
return import_module("toploc")
except ModuleNotFoundError as exc:
raise RuntimeError(
"toploc is required for activation proof audits; install meshnet-validator with dependencies"
) from exc
def _call_toploc(function: Any, activations: list[Any], *args: Any, **kwargs: Any) -> Any:
try:
return function(activations, *args, **kwargs)
except TypeError:
if kwargs:
ordered = [
kwargs["decode_batching_size"],
kwargs["topk"],
kwargs["skip_prefill"],
]
return function(activations, *args, *ordered)
raise
def _proof_encoding(value: object) -> ProofEncoding:
if value == "bytes":
return "bytes"
return "base64"
__all__ = [
"ToplocAuditConfig",
"ToplocProofClaim",
"ToplocVerificationResult",
"build_activation_proofs",
"verify_activation_proofs",
"verify_activation_proofs_detailed",
]

View File

@@ -0,0 +1,105 @@
"""Reputation-weighted, budget-balanced audit sampling (ADR-0018 §1, §6-7).
The flat ``sample_rate`` on ``ValidatorProcess`` treats every wallet the same.
This module scores each wallet's audit probability from its tenure
(``completed_job_count``) and reputation -- newcomers and low-reputation
wallets get sampled far more than veterans in good standing, who float down
to a floor -- while a running budget balance keeps the *realized* fleet-wide
average anchored to a configured target even as the wallet population mix
drifts (research §6, §8 layers 2-4).
"""
from __future__ import annotations
import random
from dataclasses import dataclass
@dataclass(frozen=True)
class AuditRateConfig:
"""Tunable audit-rate policy. Defaults match ADR-0018 §1/§6."""
target_rate: float = 0.05
newcomer_rate: float = 0.25
veteran_floor: float = 0.02
probation_jobs: int = 50
veteran_jobs: int = 500
tripwire_multiplier: float = 3.0
# Bounds the correction the budget balancer can apply in one step so a
# short burst of skewed traffic can't swing everyone's rate wildly.
max_budget_scale: float = 20.0
def __post_init__(self) -> None:
if not 0.0 <= self.target_rate <= 1.0:
raise ValueError("target_rate must be between 0 and 1")
if not 0.0 <= self.veteran_floor <= self.newcomer_rate <= 1.0:
raise ValueError("veteran_floor must be <= newcomer_rate, both within [0, 1]")
if self.probation_jobs < 0 or self.veteran_jobs <= self.probation_jobs:
raise ValueError("veteran_jobs must be greater than probation_jobs")
if self.tripwire_multiplier < 1.0:
raise ValueError("tripwire_multiplier must be >= 1.0")
class AdaptiveAuditSampler:
"""Per-wallet audit probability + fleet-wide budget balancer.
``wallet_base_rate`` scores tenure and reputation into a rate between
``veteran_floor`` and ``newcomer_rate``. ``should_audit`` scales that rate
by a running budget-balance factor (target_rate / historical mean base
rate) so the fleet-wide realized audit rate tracks ``target_rate`` even
when the wallet mix is skewed toward veterans or newcomers, then applies
the tripwire multiplier to *that single decision only* -- a tripwire flag
never touches the shared budget-balance history, so it can't punish
other wallets' audit rate.
"""
def __init__(self, config: AuditRateConfig | None = None, *, random_seed: int | None = None) -> None:
self.config = config or AuditRateConfig()
self._random = random.Random(random_seed)
self._base_rate_total = 0.0
self._decisions = 0
def wallet_base_rate(self, *, completed_job_count: int, reputation: float) -> float:
cfg = self.config
if completed_job_count <= cfg.probation_jobs:
tenure_rate = cfg.newcomer_rate
elif completed_job_count >= cfg.veteran_jobs:
tenure_rate = cfg.veteran_floor
else:
span = cfg.veteran_jobs - cfg.probation_jobs
frac = (completed_job_count - cfg.probation_jobs) / span
tenure_rate = cfg.newcomer_rate + (cfg.veteran_floor - cfg.newcomer_rate) * frac
reputation_gap = max(0.0, min(1.0, 1.0 - reputation))
reputation_rate = cfg.veteran_floor + reputation_gap * (cfg.newcomer_rate - cfg.veteran_floor)
return max(tenure_rate, reputation_rate, cfg.veteran_floor)
def sample_rate_for(self, *, completed_job_count: int, reputation: float, tripwire: bool = False) -> float:
"""Preview the effective audit probability without recording a decision."""
base_rate = self.wallet_base_rate(completed_job_count=completed_job_count, reputation=reputation)
return self._effective_rate(base_rate, tripwire=tripwire)
def should_audit(self, *, completed_job_count: int, reputation: float, tripwire: bool = False) -> bool:
base_rate = self.wallet_base_rate(completed_job_count=completed_job_count, reputation=reputation)
effective_rate = self._effective_rate(base_rate, tripwire=tripwire)
self._base_rate_total += base_rate
self._decisions += 1
return self._random.random() < effective_rate
def _effective_rate(self, base_rate: float, *, tripwire: bool) -> float:
rate = base_rate * self._budget_scale()
if tripwire:
rate *= self.config.tripwire_multiplier
return max(self.config.veteran_floor, min(1.0, rate))
def _budget_scale(self) -> float:
if self._decisions == 0:
return 1.0
mean_base_rate = self._base_rate_total / self._decisions
if mean_base_rate <= 0:
return 1.0
return min(self.config.max_budget_scale, self.config.target_rate / mean_base_rate)
__all__ = ["AuditRateConfig", "AdaptiveAuditSampler"]

Some files were not shown because too many files have changed in this diff Show More