30 Commits

Author SHA1 Message Date
Dobromir Popov
9e70b94417 feat: sync Ralph stories with Gitea issues 2026-07-16 23:37:03 +03:00
Dobromir Popov
9db036f91a feat: DGR-018 canonical Ralph metadata schema 2026-07-16 23:01:55 +03:00
Dobromir Popov
369b2072cc chore: clean superseded GGUF scaffolding 2026-07-16 22:32:37 +03:00
Dobromir Popov
81b1fa6074 docs: define implementation-ready distributed GGUF roadmap 2026-07-16 22:19:50 +03:00
Dobromir Popov
02b3709311 feat: checkpoint batching and release-gate stories 2026-07-16 17:24:56 +03:00
Dobromir Popov
737bade989 COLIBRI RESEARCH 2026-07-16 16:22:58 +02:00
Dobromir Popov
254627629b Merge commit '47b243cd98fd94da7918cacf5725373b099208e5' into ralph/distributed-gguf-runtime 2026-07-15 23:04:52 +02:00
Dobromir Popov
1fe31ef38d feat: checkpoint distributed gguf runtime stories 2026-07-15 23:42:58 +03:00
Dobromir Popov
47b243cd98 model loading, dash 2026-07-15 13:55:38 +02:00
Dobromir Popov
2852b1f80b loading more 2026-07-15 12:54:51 +02:00
Dobromir Popov
eaf00f6add test: record public relay smoke benchmark 2026-07-15 13:42:22 +03:00
Dobromir Popov
22f28bd69a fix model load/unload 2026-07-15 12:35:32 +02:00
Dobromir Popov
97e2784b37 node registration fixes 2026-07-15 10:34:41 +02:00
Dobromir Popov
c035bad5b7 feat: wire live benchmark CLI endpoints 2026-07-15 10:34:20 +03:00
Dobromir Popov
a508768e8a feat: add live endpoint benchmark runner 2026-07-14 22:46:11 +03:00
Dobromir Popov
e6f6782995 feat: add deterministic CPU/GPU benchmark runner slice 2026-07-14 21:39:13 +03:00
Dobromir Popov
ba7c656364 node metrics 2026-07-14 20:33:02 +02:00
Dobromir Popov
b661590ac7 log window bigger 2026-07-14 17:47:20 +02:00
Dobromir Popov
5b33bf8b99 feat: compare safetensors and gguf on cpu and gpu 2026-07-14 18:45:12 +03:00
Dobromir Popov
c7554ef7d8 feat: add DGR-001 performance contract 2026-07-14 18:13:54 +03:00
Dobromir Popov
21e6c86147 fix: let admin placement recover joined nodes 2026-07-14 16:37:42 +02:00
Dobromir Popov
def47f1a42 Merge branch 'master' of https://git.d-popov.com/popov/neuron-tai 2026-07-14 16:11:26 +02:00
Dobromir Popov
8cb00e951f feat: show admin node pool capacity 2026-07-14 16:11:18 +02:00
Dobromir Popov
7b3399760e chore: wrap up completed story metadata 2026-07-14 17:09:04 +03:00
Dobromir Popov
22467f145c merge: distributed performance baseline benchmark 2026-07-14 17:01:08 +03:00
Dobromir Popov
35af1e21de fix: make model placement controls observable 2026-07-14 16:00:37 +02:00
Dobromir Popov
905ea16ce0 feat: complete route session baseline benchmark 2026-07-14 16:55:52 +03:00
Dobromir Popov
348b003d6e fix: restore responsive dashboard panel grid 2026-07-14 15:55:24 +02:00
Dobromir Popov
1e64a5b2b9 new dash update 2026-07-14 15:29:11 +02:00
Dobromir Popov
e2f3ae32b8 feat: let admins manage model placement 2026-07-14 15:16:23 +02:00
111 changed files with 8477 additions and 3241 deletions

View File

@@ -8,6 +8,15 @@ metadata:
# Project Status (2026-07-13)
## Selected-node model placement (2026-07-14)
- Admin Model placement now opens a node selector for load and release; the control-plane accepts optional `node_id` and targets only that registry assignment. Multi-model serving remains supported through `ADD_SHARD` and `max_loaded_shards`.
- Total node pool resource values are rendered from `/v1/network/map`'s `node.capacity` contract. Route selection remains assignment/capability/throughput/queue based; capacity is used for placement and falls back to tracker defaults only if a node truly omits it.
## Distributed inference performance (2026-07-14)
`DIP-001` is done in `.scratch/distributed-inference-performance/`: the deterministic two-node Route Session stub benchmark covers direct/relay plus cached/stateless prefill and decode. Its JSON and concise summary explicitly attribute model execution, activation encode/decode, compression, connection setup, relay queueing, local HTTP forwarding, and end-to-end seam latency. `PYTHONPATH=packages/node pytest -q tests/test_route_session_benchmark.py` passed (7); the fixture assertion checks output-token identity and connection attempts.
> Doc reconciliation 2026-07-13: `docs/prd.json` tracks US-001…US-050 (048 memory budget, 049 mainnet pilot, 050 Qwen demand placement). ADRs 00250026 added (TAI phase B/C, assignment ownership).
All 35 user stories in docs/prd.json are done (35/35), including the reward-system arc US-030…US-035 completed 2026-07-02:

View File

@@ -1,13 +0,0 @@
# Ralph TUI Configuration
# Generated by setup wizard
# See: ralph-tui config help
configVersion = "2.1"
tracker = "json"
agent = "codex"
model = "gpt-5.6-terra"
maxIterations = 0
autoCommit = true
[trackerOptions]
[agentOptions]

View File

@@ -12,4 +12,10 @@ Provide an opt-in, admin-only tracker Dashboard Testing tab that dynamically dis
- One active run.
- Real inference stays separately environment-gated and excluded from default suites.
## Operator workflow
See [`docs/dev/dashboard-test-runner.md`](../../docs/dev/dashboard-test-runner.md)
for launch configuration, default safe suites vs the gated real-inference suite,
and required environment variables.
See `prd.json` for executable Ralph user stories and acceptance criteria.

View File

@@ -51,15 +51,16 @@
"uv run pytest tests/test_dashboard.py tests/test_dynamic_routing.py -q passes."
],
"priority": 3,
"passes": false,
"passes": true,
"notes": "Do not reintroduce --enable-test-runner without implementing its CLI argument in US-001.",
"dependsOn": [
"US-001",
"US-002"
]
],
"completionNotes": "Completed by agent"
}
],
"metadata": {
"updatedAt": "2026-07-11T17:02:30.520Z"
"updatedAt": "2026-07-12T01:58:06.286Z"
}
}

View File

@@ -1,252 +1,714 @@
# PRD: Performant Concurrent Distributed GGUF Runtime
# PRD: Distributed GGUF Runtime
## Overview
> **Specification status:** planning artifacts only. No distributed GGUF runtime is implemented. DGR-017 cleanup is complete; no runtime implementation story has completion credit. `prd.json` is authoritative.
Build one lean native GGUF execution path that lets an Inference Route combine consumer machines to serve models larger than any one node can hold. Reuse the existing Meshnet control plane and llama.cpp/GGML execution engine. Adopt gRPC/HTTP2 and Protocol Buffers for the native Shard worker data plane rather than inventing a transport.
## Goal
The program is benchmark-gated. GGUF is not assumed faster merely because it is quantized or uses a different file format. The first story compares the current Transformers/safetensors backend against whole-model llama.cpp on controlled model/hardware/quality lanes and locks a performance contract. Native distributed work proceeds only when GGUF provides a meaningful speed or fit benefit.
Deliver benchmark-gated, concurrent, distributed GGUF inference across consumer machines through existing Meshnet control-plane behavior and a standalone native worker around upstream llama.cpp. The accepted target is DeepSeek V4 Flash, not the superseded legacy target.
## Goals
## Locked scope
- Execute one GGUF model across independently addressable contiguous Shards.
- Retain Hot KV State locally for each Shard and isolate concurrent Route Sessions.
- Batch compatible decode steps across active sessions for aggregate throughput.
- Use consumer CPU, AMD, NVIDIA, Vulkan, Metal, and mixed routes only where a real certified forward passes.
- Beat the current distributed safetensors route under a controlled performance contract or enable a larger otherwise-unroutable model at useful measured speed.
- Keep the critical path to Meshnet plus a small pinned llama.cpp fork and standalone C++ worker.
- Produce narrow upstream collaboration material for llama.cpp without placing Meshnet networking or economics inside upstream.
- Existing Meshnet Tracker routing, load balancing, billing, telemetry, relay, and provider semantics are backend-agnostic and are **not redesigned**. GGUF contributes exact compatibility, range/capacity, queue/load, seam-cost, health/reliability, and certification inputs only.
- The data plane is a standalone project-owned C++ Shard worker with gRPC/Protobuf and a project-owned `ShardEngine` boundary.
- llama.cpp is fetched at one exact commit into an ignored workspace from an in-repo manifest, then a numbered minimal patch stack is applied. There is no submodule, vendored tree, or permanent-fork dependency.
- llama.cpp owns DeepSeek V4 graphs, mHC, MoE, attention, hash routing, and kernels. Meshnet adds only range-ownership hooks, typed boundary/local-state adapters, worker integration, and parity/certification.
- Quantization and placement are dynamic recipe inputs. The 24 and 10+ stage layouts are certification scenarios, never product constants.
- Per-shard Hot KV and V4 CSA/HCA/SWA/indexer/compressor state remain local and keyed by route session/epoch. The WAN seam carries the typed mHC 4×4096 residual boundary, positions, token-ID sideband where required, and schema/cache expectations—not per-layer caches.
- Route changes use cache miss plus re-prefill/restart. There is no WAN KV or V4 auxiliary-cache migration.
- CPU/CUDA/ROCm/Vulkan/Metal compile lanes are planned; only exact real-hardware-certified backend/model/recipe lanes may be advertised.
- Alpha requires correctness and the pre-locked useful-speed gate. MTP is reserved and off for alpha; its ownership contract, implementation, and benchmark are required before beta.
## Quality Gates
## Target identities
Every story must:
- DeepSeek V4 official target SHA: `60d8d70770c6776ff598c94bb586a859a38244f1`.
- llama.cpp V4 support lineage began at PR 24162 / merge `8c146a8366304c871efc26057cc90370ccf58dad`; DGR-027 later pins one exact validated current commit.
- V4 scope: 43 main layers plus MTP; mHC 4×4096 boundary; 256 routed + 1 shared experts with six routed active; token IDs required for the first three hash-routed layers.
- Exact split-GGUF artifacts are provisioned to mounted-drive storage with a complete hashed manifest and resumable verification; no model artifact may be placed under `/home`.
- Run its targeted `pytest` tests.
- Run `python -m compileall packages tests` for Python changes.
- Run `git diff --check`.
- Keep default tests deterministic, model-download-free, API-credit-free, and GPU-free.
- Preserve existing Transformers/safetensors behavior unless the story explicitly changes a versioned compatibility contract.
## Quality gates
Stories touching the native worker must also:
The canonical gate groups live in `prd.json`. Every story explicitly requires its applicable shared gates: deterministic targeted tests, Python compile checks where applicable, native CMake/CTest and exact patch verification where applicable, real artifact/hardware provenance for opt-in lanes, `git diff --check`, and a durable evidence handoff.
- Build the pinned C++ target with CMake.
- Run focused C++/protocol tests through CTest or the documented equivalent.
- Verify the llama.cpp patch stack applies cleanly to the exact pinned commit.
## Milestones
Real-model/hardware stories must:
- **M0 — Truth and contracts (DGR-017..DGR-020):** Reconciled legacy truth, canonical metadata, immutable gates, and a controlled whole-model baseline.
- **M1 — Protocol and native substrate (DGR-021..DGR-033):** Versioned gRPC protocol, exact identities/artifacts, pinned upstream, reproducible builds, ShardEngine, and fake worker.
- **M2 — Dense vertical proof (DGR-034..DGR-043):** Dense ranged execution, parity, local state, worker integration, and GGUF inputs to existing routing.
- **M3 — DeepSeek V4 Flash alpha (DGR-044..DGR-054):** Pinned V4 adapter around upstream llama.cpp, real route certification, and pre-locked alpha decision with MTP off.
- **M4 — Performance and beta hardening (DGR-055..DGR-067):** Batching, backpressure, recovery, scale certification, optimization, MTP, and hardware matrix.
- **M5 — Release and maintenance (DGR-068..DGR-071):** Reproducible packages, upstream collaboration, beta decision, and sustainable recertification.
- Require `MESHNET_ENABLE_REAL_INFERENCE_TESTS=1`.
- Use the machine-specific mounted-drive model path and the certified runtime environment; never place model artifacts under `/home`.
- Record exact model revision, artifact hash, runtime recipe, hardware, driver/backend, commands, raw JSON metrics, and output-quality result.
- Label synthetic tests as unit coverage rather than distributed acceptance.
## User stories
Before a story is marked complete, run the full deterministic `pytest -q` suite or record the exact pre-existing unrelated failure with a clean-tree reproduction.
### DGR-017: Reconcile and clean the superseded DGR backlog
## User Stories
**Milestone:** M0 · **Mode:** AFK · **State:** complete · **Depends on:** none
### DGR-001: Lock the safetensors-versus-GGUF performance contract
**Description:** As a runtime engineer, I need a controlled baseline so that GGUF work proceeds from measured speed, memory, and quality rather than reputation.
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/017-reconcile-and-clean-the-superseded-dgr-backlog.md`, and evidence READMEs for dependencies (none) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Audit implementation reality, void inherited completion credit, and clean misleading backlog/stub baggage while preserving attributable evidence and accepted research.
**Acceptance Criteria:**
- [ ] Benchmark the same model architecture/revision, machine, prompts, context lengths, output lengths, sampling policy, and concurrency across the current Transformers/safetensors recipe and whole-model llama.cpp recipes.
- [ ] Separate correctness/quality lanes from quantized performance/fit lanes instead of claiming BF16 and Q4 are numerically equivalent.
- [ ] Report TTFT, prefill tok/s, decode tok/s, p50/p95 latency, aggregate throughput, RSS, VRAM, artifact size, failures, and output drift in machine-readable JSON.
- [ ] Add concurrency levels 1 and 4 where memory permits.
- [ ] Write a versioned performance contract consumed by later release gates, including an explicit stop condition when llama.cpp/GGUF has no meaningful speed or fit benefit.
- [x] Compare the branch, old DGR-001..016 issue/pass states, evidence, and actual runtime sources; classify each output as reusable, reference-only, blocked, obsolete, or absent.
- [x] Record an authoritative old-to-new disposition and provenance; explicitly give no completion credit to any new story and note absent implementation/evidence.
- [x] Remove or archive only artifacts the audit proves obsolete while preserving accepted ADRs, useful research, raw benchmark evidence, and attributable reusable work.
- [x] Protect ignored build workspaces, generated protobuf outputs, Ralph logs, and model artifacts from accidental commits, and document every retained legacy artifact.
- [x] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
### DGR-002: Adopt the versioned gRPC Shard protocol
**Description:** As a node developer, I need a battle-proven streaming protocol so that Python and C++ Shards communicate without a custom socket protocol.
### DGR-018: Define canonical Ralph and Gitea metadata schema
**Acceptance Criteria:**
- [ ] Add a Protocol Buffers schema for capability, health, session stream, release, and cancellation operations.
- [ ] Define one long-lived bidirectional gRPC stream per Route Session Activation Seam with deadlines, cancellation, flow control, and structured errors.
- [ ] Define bounded chunking for prefill and a small decode fast path.
- [ ] Carry schema version, request/work ID, Route Session ID, route epoch, artifact/recipe fingerprint, Shard range/effective start, phase, position, idempotency step, cache expectation, compression, and checksum.
- [ ] Define a versioned named-tensor bundle with per-tensor name, shape, dtype, byte order, and payload fragments.
- [ ] Add generated-schema round-trip and compatibility tests in Python and C++.
**Milestone:** M0 · **Mode:** AFK · **Triage:** `ready-for-agent` · **Depends on:** DGR-017
### DGR-003: Define exact Artifact and runtime recipe identity
**Description:** As the Tracker, I need exact compatibility identity so that only numerically and operationally compatible Shards form an Inference Route.
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/018-define-canonical-ralph-and-gitea-metadata-schema.md`, and evidence READMEs for dependencies (DGR-017) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Make `prd.json` the validated source from which Markdown and Gitea issues can later be generated losslessly.
**Acceptance Criteria:**
- [ ] Separate weight quantization, activation dtype, compute dtype, KV dtype/layout, tokenizer revision, architecture adapter, backend, and runtime version.
- [ ] Bind derivative or split artifacts to an exact source Model Artifact hash and Shard range.
- [ ] Produce a stable compatibility fingerprint used by capability admission and the gRPC handshake.
- [ ] Fail closed on mismatched artifact, tokenizer, architecture, range, boundary schema, activation recipe, or cache layout.
- [ ] Keep unsupported recipes registered-but-dark until a real distributed forward certifies them.
- [ ] Define fields for stable ID/title, labels, milestone, type, `dependsOn`, derived `blocks`, triage, evidence class, and hardware/model/upstream flags.
- [ ] Validate that all stories start `passes: false`, use known dependencies, and have unique stable IDs.
- [ ] Reject cycles, missing dependencies, mismatched generated `blocks`, duplicate titles/IDs, and generated artifacts claiming authority over `prd.json`.
- [ ] Add deterministic model-free tests for parse, validation, and generation round trips.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
### DGR-004: Create the reproducible pinned llama.cpp patch stack
**Description:** As a maintainer, I need a small auditable fork boundary so that upstream updates do not turn the runtime into an unmaintainable stitched codebase.
### DGR-019: Lock alpha and beta performance contracts
**Acceptance Criteria:**
- [ ] Pin one exact llama.cpp commit through a reproducible source dependency mechanism.
- [ ] Store a numbered minimal patch stack separately from Meshnet networking code.
- [ ] Add a build script that applies/checks patches and builds the standalone worker without manual source copying.
- [ ] Record upstream file/ABI assumptions and fail clearly when the pin changes.
- [ ] Preserve upstream license and attribution notices.
- [ ] Add a clean rebuild smoke test that does not download a model.
**Milestone:** M0 · **Mode:** HITL · **Triage:** `ready-for-human` · **Depends on:** DGR-017
### DGR-005: Implement dense-Llama range-aware GGUF ownership
**Description:** As a node, I need to map only my assigned dense-Llama Shard so that aggregate consumer memory can hold a model larger than one node.
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/019-lock-alpha-and-beta-performance-contracts.md`, and evidence READMEs for dependencies (DGR-017) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Freeze useful speed, correctness, memory-fit, and stop/go thresholds before implementation results are visible.
**Acceptance Criteria:**
- [ ] Register and allocate only `blk.N.*` tensors in the assigned range.
- [ ] Load embeddings only for the head and final norm/LM head only for the tail, including tied embeddings.
- [ ] Prefer range-aware mapping from one exact source GGUF; if derivative sub-GGUFs are used temporarily, verify source/slice hashes and avoid claiming final artifact semantics.
- [ ] Report authoritative loaded range and endpoint ownership from the model, not operator CLI claims.
- [ ] Demonstrate mapped/resident memory scales with owned tensors rather than full model size.
- [ ] Define controlled safetensors, whole-model GGUF, dense distributed GGUF, and V4 Flash distributed lanes with fixed prompts, context/output lengths, sampling, concurrency, hardware, and metrics.
- [ ] Alpha requires correctness plus a human-approved useful-speed threshold; beta adds concurrency, long-context, failure, and sustained-throughput thresholds.
- [ ] Separate quantization/model-fit gains from runtime, transport, batching, and kernel gains.
- [ ] Treat quants and 24/10+ stage counts only as named certification scenarios; no product logic may hardcode them.
- [ ] Lock thresholds and stop conditions in versioned machine-readable data before benchmark result ingestion.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
### DGR-006: Implement architecture-defined boundary input/output
**Description:** As a Shard, I need to consume and emit the correct transformer boundary state so that disjoint processes reproduce whole-model execution.
### DGR-020: Run the controlled whole-model GGUF baseline
**Acceptance Criteria:**
- [ ] Head accepts token IDs and owns token embedding.
- [ ] Middle/tail bypass token embedding and accept the named boundary bundle.
- [ ] Non-tail emits the unnormalized architecture-defined residual/boundary before final norm/head and before tail-only row pruning.
- [ ] Tail emits logits or token output through an explicit sampling contract.
- [ ] Dense-Llama whole-model versus two-range prefill and greedy-decode parity passes the documented tolerance.
- [ ] The adapter interface fails closed for uncertified architectures.
**Milestone:** M0 · **Mode:** HITL · **Triage:** `ready-for-human` · **Depends on:** DGR-019
### DGR-007: Add isolated concurrent local Hot KV State
**Description:** As a client, I need concurrent Route Sessions to retain independent per-Shard cache so that one request cannot clear or corrupt another.
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/020-run-the-controlled-whole-model-gguf-baseline.md`, and evidence READMEs for dependencies (DGR-019) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Execute the locked safetensors and whole-model llama.cpp lanes before distributed implementation results can influence the decision.
**Acceptance Criteria:**
- [ ] Map `(Route Session ID, route epoch)` to an isolated llama sequence or bounded context.
- [ ] Allocate KV only for owned layers.
- [ ] Support prefill append, decode append, truncate, release, TTL/LRU eviction, and explicit cache-miss response.
- [ ] Reject stale epochs and incompatible cache recipes.
- [ ] At least four concurrent sessions on a small model complete without token or KV cross-talk.
- [ ] Cancellation/release of one session leaves other sessions intact and memory returns to the configured budget.
- [ ] Run the exact DGR-019 safetensors and whole-model llama.cpp benchmark lanes with locked prompts, lengths, sampling, concurrency, hardware, and artifact/runtime identities.
- [ ] Record raw machine-readable correctness, TTFT, prefill/decode, throughput, latency, memory, artifact-size, failure, and quality-drift metrics without ingesting distributed implementation results.
- [ ] Separate quantization/model-fit effects from runtime/kernel effects and preserve failed or unavailable lanes honestly.
- [ ] Publish a threshold-based `go`, `optimize baseline`, or `stop` decision without changing the locked contract.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
### DGR-008: Build the standalone C++ gRPC Shard worker
**Description:** As a node runtime, I need one supervised native process so that llama.cpp internals remain behind a stable project-owned protocol.
### DGR-021: Define the versioned named-tensor stream envelope
**Acceptance Criteria:**
- [ ] Worker exposes capability, health, session stream, release, cancellation, and metrics services from DGR-002.
- [ ] Worker loads one exact Artifact/recipe/Shard identity and refuses mismatched requests.
- [ ] Streaming path enforces bounded messages, flow control, deadlines, idempotency, and independent session cancellation.
- [ ] Worker does not expose raw llama.cpp RPC or arbitrary GGML graph execution.
- [ ] Graceful shutdown releases sessions; crash behavior is bounded and observable.
- [ ] Python integration tests run against a fake model mode without model downloads.
**Milestone:** M1 · **Mode:** AFK · **Triage:** `ready-for-agent` · **Depends on:** DGR-018
### DGR-009: Integrate the native worker with Meshnet
**Description:** As the existing node service, I need a GGUF Shard backend adapter so that the Tracker, relay, billing, telemetry, and capability admission remain the sole control plane.
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/021-define-the-versioned-named-tensor-stream-envelope.md`, and evidence READMEs for dependencies (DGR-018) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Establish the backend-neutral protobuf envelope used by direct and relayed Shard activation traffic.
**Acceptance Criteria:**
- [ ] Implement the existing model-backend surface without changing Transformers behavior.
- [ ] Registration carries exact validated GGUF recipe, Shard, backend and concurrency/KV capacity.
- [ ] Tracker forms only complete compatible routes and keeps uncertified recipes dark.
- [ ] Direct routes use gRPC streams; relayed routes carry the same versioned protobuf frames as opaque binary through the existing relay seam.
- [ ] Existing request/work IDs, cancellation, Generation Telemetry, billing, and per-node attribution remain correlated.
- [ ] No vLLM, Nakshatra, prima.cpp, or custom-engine control plane becomes a core dependency.
- [ ] Define schema version, request/work ID, route session/epoch, shard range/effective start, phase, position, and idempotency step.
- [ ] Define named tensors with shape, dtype, byte order, bounded fragments, compression identity, and checksum.
- [ ] Reserve extensible fields for token-ID sidebands, architecture state, recurrent state, and MTP without claiming implementations.
- [ ] Add deterministic serialization, fragmentation, checksum, unknown-field, and size-limit tests.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
### DGR-010: Pass local real-model two-process acceptance
**Description:** As a release engineer, I need real local distributed parity before involving network variability.
### DGR-022: Define Shard lifecycle and structured status RPCs
**Acceptance Criteria:**
- [ ] Two local worker processes open disjoint dense-Llama ranges from the certified Artifact.
- [ ] Prefill and at least 32 greedy decode tokens match whole-model llama.cpp within the certified tolerance.
- [ ] Each worker retains only its own tensors and Hot KV State.
- [ ] Four concurrent Route Sessions pass isolation and cleanup checks.
- [ ] Report TTFT, prefill/decode throughput, seam bytes/latency, worker RSS/VRAM, KV memory, batch size, and queue time.
- [ ] Killing one worker produces a bounded structured failure rather than a deadlock.
**Milestone:** M1 · **Mode:** AFK · **Triage:** `ready-for-agent` · **Depends on:** DGR-021
### DGR-011: Pass a real heterogeneous two-machine route
**Description:** As a consumer-hardware operator, I need two physical machines to execute one GGUF model so that the distributed claim is real.
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/022-define-shard-lifecycle-and-structured-status-rpcs.md`, and evidence READMEs for dependencies (DGR-021) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Complete the gRPC contract for worker capability, health, sessions, cancellation, release, and metrics.
**Acceptance Criteria:**
- [ ] Tracker selects two physical nodes with disjoint Shards and one exact certified recipe/compatibility class.
- [ ] Actual CPU/GPU execution occurs on both nodes; synthetic workers do not satisfy acceptance.
- [ ] Prefill/decode, concurrent-session isolation, telemetry, cancellation, and cleanup pass over the real transport/relay path.
- [ ] Exact hardware, network, backend, model hash, route, commands, and raw metrics are recorded.
- [ ] A model or recipe larger than one participating node's admitted memory is exercised when available.
- [ ] Output drift is measured and incompatible mixed backends fail closed.
- [ ] Define capability, health, bidirectional session stream, cancellation, release, and metrics RPCs.
- [ ] Specify deadlines, cancellation propagation, bounded flow control, cache expectations/results, and structured error taxonomy.
- [ ] Specify TLS/auth hooks without moving Meshnet authentication or billing into the worker.
- [ ] Add compatibility tests for supported versions and fail-closed tests for unsupported versions and malformed lifecycle transitions.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
### DGR-012: Implement continuous batching and bounded admission
**Description:** As a node operator, I need active sessions batched safely so that concurrency increases aggregate throughput rather than serializing every request.
### DGR-023: Make Python and C++ protobuf generation reproducible
**Acceptance Criteria:**
- [ ] Node scheduler admits sessions against weight, KV, scratch, and queue budgets.
- [ ] Compatible decode steps from multiple sessions form llama.cpp batches while preserving per-session positions and outputs.
- [ ] Prefill does not starve decode; scheduling policy and bounds are explicit.
- [ ] Backpressure prevents unbounded queued activations or KV growth.
- [ ] Capability telemetry reports active sessions, queue depth, batch occupancy, KV pressure, prefill/decode rates, and rejected admissions.
- [ ] Concurrency 1/2/4/8 benchmark identifies saturation and shows no cross-session corruption.
**Milestone:** M1 · **Mode:** AFK · **Triage:** `ready-for-agent` · **Depends on:** DGR-021
### DGR-013: Harden failure, cancellation, and restart semantics
**Description:** As a client, I need failures to be bounded and explicit so that distributed speed does not come with hanging or corrupted generations.
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/023-make-python-and-c-protobuf-generation-reproducible.md`, and evidence READMEs for dependencies (DGR-021) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Generate identical Python/C++ protocol bindings without manual copying or checked-in build debris.
**Acceptance Criteria:**
- [ ] Deadlines and heartbeat/health loss terminate blocked stream operations.
- [ ] Cancellation propagates across every Shard and releases local KV and queued buffers.
- [ ] Duplicate steps are idempotent; uncertain mutations are never replayed silently.
- [ ] Alpha failover restarts from token zero on a newly compatible route rather than importing unverified KV.
- [ ] Worker death, stream reset, malformed bundle, stale epoch, and cache miss tests pass.
- [ ] Billing/work records distinguish completed, cancelled, failed, and unverified work.
- [ ] Pin protoc, gRPC, and plugin versions or declare a verified compatible range.
- [ ] Generate Python and C++ bindings into out-of-tree build/package locations through documented commands.
- [ ] Add Python↔C++ round-trip and descriptor compatibility tests.
- [ ] A clean checkout regenerates bindings deterministically or fails with an actionable toolchain error.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
### DGR-014: Enforce the GGUF-versus-safetensors release gate
**Description:** As the product owner, I need an end-to-end comparison so that the native runtime ships only if it advances model access or performance.
### DGR-024: Implement in-memory fake gRPC seam transport
**Acceptance Criteria:**
- [ ] Run current distributed safetensors and distributed GGUF routes on the same certified model/hardware/network scenario where technically comparable.
- [ ] Report quality, TTFT, prefill/decode throughput, aggregate concurrency throughput, p95 latency, seam cost, memory, KV pressure, failures, and cleanup.
- [ ] Evaluate against the DGR-001 performance contract without changing thresholds after seeing results.
- [ ] Ship recommendation is one of: promote GGUF, optimize a measured bottleneck with a new bounded task, or stop the native track.
- [ ] Results clearly separate quantization gains from transport/runtime gains.
**Milestone:** M1 · **Mode:** AFK · **Triage:** `ready-for-agent` · **Depends on:** DGR-022, DGR-023
### DGR-015: Add and certify a Qwen3/Qwen3-MoE adapter
**Description:** As a client seeking top models, I need a separately certified MoE-capable architecture after the dense runtime proves stable.
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/024-implement-in-memory-fake-grpc-seam-transport.md`, and evidence READMEs for dependencies (DGR-022, DGR-023) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Exercise the complete streaming protocol deterministically before a real model or worker exists.
**Acceptance Criteria:**
- [ ] Implement explicit tensor ownership, router/top-k, expert/shared-expert, Q/K normalization, boundary bundle, and cache semantics for the selected Qwen3 family recipe.
- [ ] Do not reuse the dense-Llama adapter through unchecked name substitutions.
- [ ] Whole-model versus distributed prefill/decode parity passes the architecture-specific tolerance.
- [ ] Expert memory ownership and communication are measured.
- [ ] Real consumer-hardware acceptance and capability admission pass before the recipe becomes routable.
- [ ] Provide a fake bidirectional stream supporting prefill fragments, decode fast-path frames, release, cancel, and structured errors.
- [ ] Test flow-control blocking, deadlines, malformed fragments, checksum failure, duplicates, and stale epochs.
- [ ] Verify direct and opaque-relay framing preserve identical protobuf bytes.
- [ ] Tests require no sockets outside localhost, model downloads, or native accelerator.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
### DGR-016: Produce the upstream llama.cpp collaboration package
**Description:** As a maintainer, I need narrow upstreamable proposals so that our patch burden can shrink without asking llama.cpp to own Meshnet networking.
### DGR-025: Define exact artifact and runtime recipe identity
**Acceptance Criteria:**
- [ ] Separate generic llama.cpp hooks from Meshnet protocol/control-plane code.
- [ ] Prepare minimal reproducible examples and tests for range-aware loading, boundary input/output, and layer-filtered KV.
- [ ] Compare the proposal with Nakshatra and prima.cpp evidence and explain why the API is generally useful.
- [ ] Preserve one scoped commit/patch per concern against the exact upstream pin.
- [ ] Produce an outreach document suitable for Georgi/llama.cpp maintainers; actual sending remains a human action.
**Milestone:** M1 · **Mode:** AFK · **Triage:** `ready-for-agent` · **Depends on:** DGR-018, DGR-021
## Functional Requirements
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/025-define-exact-artifact-and-runtime-recipe-identity.md`, and evidence READMEs for dependencies (DGR-018, DGR-021) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Ensure the tracker and worker only combine numerically and operationally compatible shards.
1. The public distributed primitive is an ordered Inference Route of contiguous Shards.
2. The native runtime uses llama.cpp/GGML; vLLM remains optional as a complete managed provider.
3. Native worker communication uses gRPC/HTTP2 and Protocol Buffers with one stable stream per Route Session Activation Seam.
4. Artifact identity, runtime recipe, boundary schema, activation dtype and cache layout must match exactly before routing.
5. Hot KV State remains local to the node serving the Shard.
6. Multiple Route Sessions must execute concurrently without shared-cache corruption.
7. Nodes batch compatible active decode steps and enforce bounded admission/backpressure.
8. Unsupported architectures and hardware recipes remain non-routable until real certification passes.
9. Default tests never download models or require GPUs; real tests are explicit and preserve artifacts off `/home`.
10. The release decision is based on measured performance, fit, quality, concurrency, and reliability relative to the safetensors baseline.
- [ ] Fingerprint source artifact SHA, tokenizer revision, architecture adapter/version, boundary schema, runtime pin/patch stack, backend, quant, activation/compute dtype, and KV/state layout.
- [ ] Bind each shard to an exact half-open range without hardcoding a topology or quant.
- [ ] Fail closed on any artifact, adapter, boundary, cache, backend, or runtime mismatch.
- [ ] Unsupported recipes remain registered-but-dark until real-hardware evidence certifies them.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Non-Goals
### DGR-026: Provision exact split-GGUF artifacts outside /home
- Forking vLLM or importing its PagedAttention/Torch distributed runtime.
- Adopting Nakshatra, prima.cpp, llama-gguf, LiGGUF, or GPUStack as the control plane.
- Public WAN tensor/expert parallel collectives.
- QUIC, WebRTC, or a custom socket protocol.
- Automatic KV migration or mid-generation route repair in the first release.
- Speculative decoding or disaggregated prefill before the core release gate.
- Supporting every GGUF architecture before dense Llama and Qwen3-family certification.
- A marketing-scale model demo that bypasses parity, concurrency, admission, or performance gates.
**Milestone:** M1 · **Mode:** AFK · **Triage:** `ready-for-agent` · **Depends on:** DGR-025
## Success Metrics
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/026-provision-exact-split-gguf-artifacts-outside-home.md`, and evidence READMEs for dependencies (DGR-025) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Make exact split-GGUF inputs reproducibly available from mounted-drive storage without embedding a quantization or topology assumption in product code.
- A real model larger than one admitted node can execute across consumer machines when suitable hardware/artifacts are available.
- Four or more concurrent sessions complete without cross-talk; hardware-specific saturation is measured.
- Distributed GGUF passes the locked performance/fit contract against the existing safetensors route.
- Worker and Tracker recover all resources after completion, cancellation, malformed input, and node failure.
- The critical runtime remains Meshnet plus one standalone worker and a small auditable llama.cpp patch stack.
- [ ] Create an exact manifest that binds the source artifact, tokenizer/revision, every split file name, size, range/role, and cryptographic hash.
- [ ] Provide resumable, hash-verifying download/provision tooling targeting configured mounted-drive storage; refuse paths under `/home` and incomplete or mismatched splits.
- [ ] Keep quantization and split topology as manifest/recipe inputs with no hardcoded quant, node count, or range layout.
- [ ] Add deterministic model-download-free tests using tiny local split fixtures, including interrupted resume, missing split, hash mismatch, and `/home` rejection.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Open Questions
### DGR-027: Add exact llama.cpp provenance manifest and fetch workspace
- Exact benchmark model and quantization lanes are selected by DGR-001 from currently supported, legally redistributable artifacts.
- Final hardware-specific concurrency and useful-speed thresholds are locked by measured baselines rather than guessed globally.
- Upstream llama.cpp acceptance is desirable but not a prerequisite for the first narrow pinned fork.
**Milestone:** M1 · **Mode:** AFK · **Triage:** `ready-for-agent` · **Depends on:** DGR-017
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/027-add-exact-llama-cpp-provenance-manifest-and-fetch-workspace.md`, and evidence READMEs for dependencies (DGR-017) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Pin llama.cpp exactly through an in-repo manifest while fetching source only into an ignored build workspace.
- [ ] Manifest records upstream URL, exact commit, expected source archive/tree hash, license, and retrieval method.
- [ ] Fetch tooling verifies identity before use and refuses an unpinned branch/tag.
- [ ] Source is fetched into an ignored build workspace; no submodule, vendored source tree, or permanent fork is introduced.
- [ ] Offline reuse is supported only after the cached trees exact identity is verified.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
### DGR-028: Implement numbered patch-stack apply and verification
**Milestone:** M1 · **Mode:** AFK · **Triage:** `ready-for-agent` · **Depends on:** DGR-027
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/028-implement-numbered-patch-stack-apply-and-verification.md`, and evidence READMEs for dependencies (DGR-027) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Maintain a minimal auditable llama.cpp delta with one numbered patch per concern.
- [ ] Add deterministic apply/check/reverse verification against the exact manifest pin.
- [ ] Separate range loading, boundary I/O, filtered state, and worker hooks into scoped patches.
- [ ] Record upstream file/API assumptions and fail with the first incompatible patch when the pin changes.
- [ ] Verify license/attribution and prove no Meshnet routing, billing, relay, or authentication code enters the patch stack.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
### DGR-029: Create the native CMake skeleton and deterministic CPU lane
**Milestone:** M1 · **Mode:** AFK · **Triage:** `ready-for-agent` · **Depends on:** DGR-027, DGR-028
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/029-create-the-native-cmake-skeleton-and-deterministic-cpu-lane.md`, and evidence READMEs for dependencies (DGR-027, DGR-028) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Establish an out-of-tree standalone native build with a deterministic CPU lane before accelerator matrix work.
- [ ] Create the standalone native CMake target/skeleton and isolated out-of-tree configure/build preset for CPU.
- [ ] Build and run a deterministic model-free CPU smoke/CTest lane from a clean checkout with actionable toolchain failures.
- [ ] Keep fetched upstream sources, generated bindings, and all build outputs ignored and out of tree.
- [ ] Ensure build success alone does not advertise any backend/model/recipe capability.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
### DGR-030: Add accelerator build presets and native CI matrix
**Milestone:** M1 · **Mode:** AFK · **Triage:** `ready-for-agent` · **Depends on:** DGR-029
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/030-add-accelerator-build-presets-and-native-ci-matrix.md`, and evidence READMEs for dependencies (DGR-029) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Compile all required accelerator lanes reproducibly while keeping untested real-hardware capabilities registered-dark.
- [ ] Add isolated out-of-tree presets for CUDA, ROCm, Vulkan, and Metal without changing the deterministic CPU default.
- [ ] Add a native CI/build matrix that reports unavailable SDKs as explicit unavailable/skipped lanes rather than false success.
- [ ] Compile each available lane and preserve exact compiler, SDK, upstream pin, patch-stack, and build-option evidence.
- [ ] Keep every backend/model/recipe lane registered-dark until a separate real-hardware certification record exists.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
### DGR-031: Introduce the project-owned `ShardEngine` interface
**Milestone:** M1 · **Mode:** AFK · **Triage:** `ready-for-agent` · **Depends on:** DGR-021, DGR-025
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/031-introduce-the-project-owned-shardengine-interface.md`, and evidence READMEs for dependencies (DGR-021, DGR-025) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Isolate worker/protocol code from llama.cpp internals behind a stable project-owned engine contract.
- [ ] Define load, capabilities, prefill/decode, boundary/logits result, cancel, release, health, and metrics operations.
- [ ] Use project-owned request/result/state types; expose no `ggml_tensor`, llama context, scheduler, or ABI-owned structure.
- [ ] Reserve typed MTP and architecture auxiliary-state hooks without enabling them.
- [ ] Add contract tests proving fake and future llama implementations obey identical lifecycle semantics.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
### DGR-032: Implement deterministic fake `ShardEngine`
**Milestone:** M1 · **Mode:** AFK · **Triage:** `ready-for-agent` · **Depends on:** DGR-031
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/032-implement-deterministic-fake-shardengine.md`, and evidence READMEs for dependencies (DGR-031) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Provide an engine fixture that deterministically transforms typed boundary bundles and session state.
- [ ] Support head, middle, tail, prefill, decode, cancellation, and release with deterministic outputs.
- [ ] Model isolated session/epoch state and deterministic cache-miss/stale-epoch failures.
- [ ] Support configurable delay, memory pressure, malformed output, and crash injection.
- [ ] Contract tests distinguish fixture evidence from real-model certification.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
### DGR-033: Build a standalone fake C++ gRPC Shard worker
**Milestone:** M1 · **Mode:** AFK · **Triage:** `ready-for-agent` · **Depends on:** DGR-022, DGR-024, DGR-032
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/033-build-a-standalone-fake-c-grpc-shard-worker.md`, and evidence READMEs for dependencies (DGR-022, DGR-024, DGR-032) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Prove the standalone worker process, stream, lifecycle, and supervision shape before llama.cpp integration.
- [ ] A standalone C++ executable serves the complete lifecycle and stream RPC contract using the fake engine.
- [ ] Python integration tests cover startup, health, capability, fragmented prefill, decode, release, cancellation, and graceful shutdown.
- [ ] Bounded messages, deadlines, flow control, and independent session cancellation are enforced.
- [ ] The worker exposes neither llama.cpp RPC nor arbitrary graph execution.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
### DGR-034: Implement dense-Llama range-aware GGUF ownership
**Milestone:** M2 · **Mode:** AFK · **Triage:** `ready-for-agent` · **Depends on:** DGR-028, DGR-029, DGR-031
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/034-implement-dense-llama-range-aware-gguf-ownership.md`, and evidence READMEs for dependencies (DGR-028, DGR-029, DGR-031) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Load only the dense-Llama tensors owned by a shard range.
- [ ] Load only `blk.N.*` tensors in the assigned range, embeddings only at the head, and norm/output or tied output only at the tail.
- [ ] Derive authoritative range and endpoint ownership from the loaded engine state.
- [ ] Reject invalid/gapped/out-of-model ranges and unexpected required tensors.
- [ ] Real-model evidence shows mapped/resident memory scales with owned tensors rather than full artifact size.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
### DGR-035: Implement dense architecture boundary input/output
**Milestone:** M2 · **Mode:** AFK · **Triage:** `ready-for-agent` · **Depends on:** DGR-021, DGR-031, DGR-034
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/035-implement-dense-architecture-boundary-input-output.md`, and evidence READMEs for dependencies (DGR-021, DGR-031, DGR-034) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Execute dense head/middle/tail ranges through an architecture-defined residual boundary.
- [ ] Head accepts token IDs and owns embedding; middle/tail bypass embedding and accept a named boundary bundle.
- [ ] Non-tail returns the unnormalized residual before final norm/head and before tail-only row pruning.
- [ ] Tail returns logits or sampled-token output under an explicit contract.
- [ ] Uncertified architectures and incompatible boundary schemas fail closed.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
### DGR-036: Prove dense fixture and real-model range parity
**Milestone:** M2 · **Mode:** AFK · **Triage:** `ready-for-agent` · **Depends on:** DGR-033, DGR-035
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/036-prove-dense-fixture-and-real-model-range-parity.md`, and evidence READMEs for dependencies (DGR-033, DGR-035) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Prove the engine/protocol seam before adding session concurrency.
- [ ] Model-free two-stage tests pass through two fake worker processes with disjoint ranges.
- [ ] A small real dense GGUF passes whole-model versus two-range prefill parity.
- [ ] At least 32 greedy decode tokens match the locked tolerance.
- [ ] Evidence distinguishes deterministic fixture proof from opt-in real-model proof.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
### DGR-037: Bind llama.cpp to the standalone worker
**Milestone:** M2 · **Mode:** AFK · **Triage:** `ready-for-agent` · **Depends on:** DGR-022, DGR-023, DGR-031, DGR-034, DGR-035
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/037-bind-llama-cpp-to-the-standalone-worker.md`, and evidence READMEs for dependencies (DGR-022, DGR-023, DGR-031, DGR-034, DGR-035) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Replace the fake engine with the pinned llama.cpp `ShardEngine` implementation without changing the public worker contract.
- [ ] Worker loads exactly one artifact/recipe/range identity and rejects mismatched stream requests.
- [ ] All execution passes through `ShardEngine`; llama.cpp implementation types remain private.
- [ ] Health and metrics expose loaded identity, authoritative ownership, memory, and execution state.
- [ ] Graceful shutdown releases model/session resources; injected process death is observable and bounded.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
### DGR-038: Implement isolated shard-local Hot KV State
**Milestone:** M2 · **Mode:** AFK · **Triage:** `ready-for-agent` · **Depends on:** DGR-037
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/038-implement-isolated-shard-local-hot-kv-state.md`, and evidence READMEs for dependencies (DGR-037) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Map each route session and epoch to isolated state containing only locally owned layers.
- [ ] Map `(route_session_id, route_epoch)` to an isolated llama sequence or bounded context.
- [ ] Support prefill/decode append, truncate, release, TTL/LRU eviction, cache miss, and stale-epoch rejection.
- [ ] Four concurrent sessions complete without token, KV, position, or cancellation cross-talk.
- [ ] Release/eviction returns memory to the configured budget without affecting other sessions.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
### DGR-039: Pass local two-process dense acceptance
**Milestone:** M2 · **Mode:** AFK · **Triage:** `ready-for-agent` · **Depends on:** DGR-036, DGR-037, DGR-038
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/039-pass-local-two-process-dense-acceptance.md`, and evidence READMEs for dependencies (DGR-036, DGR-037, DGR-038) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Establish the first real, independently executing distributed GGUF route on one host.
- [ ] Two worker processes open disjoint dense ranges and both execute real prefill/decode work.
- [ ] Whole-model parity, 32-token greedy decode, four-session isolation, cancellation, and cleanup pass.
- [ ] Record TTFT, prefill/decode rates, seam bytes/latency, RSS/VRAM, KV, queue, and failure metrics.
- [ ] Killing one worker returns a bounded structured failure rather than hanging.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
### DGR-040: Add node-side native worker supervision
**Milestone:** M2 · **Mode:** AFK · **Triage:** `ready-for-agent` · **Depends on:** DGR-033, DGR-037
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/040-add-node-side-native-worker-supervision.md`, and evidence READMEs for dependencies (DGR-033, DGR-037) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Let the existing node service safely start, probe, stop, and restart the standalone worker.
- [ ] Supervision owns process startup, readiness, log capture, graceful shutdown, and bounded forced termination.
- [ ] Startup verifies worker binary, artifact identity, recipe, and range before registration.
- [ ] Crashes or health loss make the capability unavailable without corrupting the Transformers backend.
- [ ] Tests use the fake worker and deterministic crash injection.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
### DGR-041: Register native Shard capabilities without redesigning Meshnet
**Milestone:** M2 · **Mode:** AFK · **Triage:** `ready-for-agent` · **Depends on:** DGR-025, DGR-040
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/041-register-native-shard-capabilities-without-redesigning-meshnet.md`, and evidence READMEs for dependencies (DGR-025, DGR-040) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Adapt native worker identity and capacity to existing backend-agnostic capability admission.
- [ ] Registration carries exact recipe fingerprint, authoritative range, backend, memory/KV capacity, concurrency, and certification status.
- [ ] Existing tracker, billing, routing, telemetry, and provider semantics remain backend-agnostic.
- [ ] Uncertified backend/model/recipe combinations are visible but unroutable.
- [ ] Existing Transformers registration and route tests remain unchanged in behavior.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
### DGR-042: Carry native frames through direct and existing relay seams
**Milestone:** M2 · **Mode:** AFK · **Triage:** `ready-for-agent` · **Depends on:** DGR-024, DGR-040
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/042-carry-native-frames-through-direct-and-existing-relay-seams.md`, and evidence READMEs for dependencies (DGR-024, DGR-040) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Use direct gRPC where available and the existing relay as opaque protobuf transport without redesigning relay behavior.
- [ ] Direct paths use the long-lived gRPC activation stream.
- [ ] Relayed paths carry byte-identical versioned protobuf frames through the existing relay contract.
- [ ] Request/work identity, cancellation, deadlines, telemetry, billing correlation, and per-node attribution survive both paths.
- [ ] Fake-worker tests cover direct, relay, disconnect, cancellation, and bounded buffering.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
### DGR-043: Expose GGUF compatibility and measured cost inputs to existing routing
**Milestone:** M2 · **Mode:** AFK · **Triage:** `ready-for-agent` · **Depends on:** DGR-041
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/043-expose-gguf-compatibility-and-measured-cost-inputs-to-existing-routing.md`, and evidence READMEs for dependencies (DGR-041) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Adapt exact GGUF recipe/range compatibility and measured capacity, queue, seam-cost, health, and reliability data into the existing backend-agnostic routing inputs without redesigning routing or load balancing.
- [ ] Expose exact recipe, range coverage, capacity, queue/load, seam-cost, health, reliability, backend, and certification measurements through existing tracker input contracts.
- [ ] Prove existing routing forms complete compatible coverage and excludes dark or mismatched candidates using its current backend-agnostic mechanisms.
- [ ] Regression-test unchanged Transformers behavior and unchanged tracker routing, load-balancing, billing, relay, and provider semantics.
- [ ] Regression-test that no quant, stage count, fixed split, architecture, backend sequence, or DeepSeek-specific policy is hardcoded.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
### DGR-044: Pin the DeepSeek V4 Flash target contract
**Milestone:** M3 · **Mode:** AFK · **Triage:** `ready-for-agent` · **Depends on:** DGR-019, DGR-025, DGR-026, DGR-027
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/044-pin-the-deepseek-v4-flash-target-contract.md`, and evidence READMEs for dependencies (DGR-019, DGR-025, DGR-026, DGR-027) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Fix the alpha/beta model identity and upstream maturity assumptions before implementing the adapter.
- [ ] Pin Hugging Face target SHA `60d8d70770c6776ff598c94bb586a859a38244f1`.
- [ ] Record the selected GGUF provenance and exact source binding without assuming one quant.
- [ ] Record that llama.cpp support began with PR 24162/commit `8c146a8` and remains maturing; the build manifest still pins one exact validated upstream commit.
- [ ] Record 43 main layers plus MTP and all known architecture-specific state obligations.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
### DGR-045: Inventory V4 GGUF tensors and layer ownership
**Milestone:** M3 · **Mode:** AFK · **Triage:** `ready-for-agent` · **Depends on:** DGR-026, DGR-044
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/045-inventory-v4-gguf-tensors-and-layer-ownership.md`, and evidence READMEs for dependencies (DGR-026, DGR-044) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Derive exact head, repeated-layer, tail, expert, auxiliary-state, and MTP ownership from the pinned artifact.
- [ ] Produce a machine-readable inventory tied to the target SHA and exact GGUF artifact.
- [ ] Classify embeddings, 43 main layers, final head, MTP, mHC, attention variants, indexer/compressor, and MoE tensors.
- [ ] Validate half-open range ownership and fail on unclassified required tensors.
- [ ] Inventory tooling works across quants without embedding quant names in architecture logic.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
### DGR-046: Define the V4 typed architecture boundary schema
**Milestone:** M3 · **Mode:** AFK · **Triage:** `ready-for-agent` · **Depends on:** DGR-021, DGR-045
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/046-define-the-v4-typed-architecture-boundary-schema.md`, and evidence READMEs for dependencies (DGR-021, DGR-045) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Define the exact cross-stage V4 architecture boundary while keeping per-layer attention and auxiliary caches shard-local.
- [ ] Define a versioned named bundle for the mHC 4×4096 residual boundary, positions, token-ID sideband where required, and schema/cache expectations.
- [ ] Explicitly exclude per-layer CSA, HCA, SWA, indexer, compressor, KV, and MTP caches/state from the WAN boundary; those remain local to the owning shard and session/epoch.
- [ ] Reserve typed MTP boundary fields but mark MTP execution unsupported and unroutable for alpha.
- [ ] Fingerprint independently of quant/topology and fail closed on missing, incompatible, incorrectly shaped, or stale boundary/cache expectations.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
### DGR-047: Adapt the upstream V4 mHC boundary for ranged ownership
**Milestone:** M3 · **Mode:** AFK · **Triage:** `ready-for-agent` · **Depends on:** DGR-045, DGR-046
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/047-adapt-the-upstream-v4-mhc-boundary-for-ranged-ownership.md`, and evidence READMEs for dependencies (DGR-045, DGR-046) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Add range-boundary adapters around upstream llama.cpp V4 mHC execution without reimplementing the V4 graph or kernels.
- [ ] Represent and validate the upstream V4 4×4096 mHC boundary without flattening semantic axes.
- [ ] Add only head/intermediate/tail range ownership and boundary conversion hooks around the pinned upstream llama.cpp graph.
- [ ] Compare deterministic fixture vectors and single-process ranged outputs with upstream whole-model execution.
- [ ] Document that llama.cpp owns V4 mHC graph/kernels and that quantized storage does not alter the logical boundary schema.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
### DGR-048: Carry token-ID sideband through the first three hash-routed layers
**Milestone:** M3 · **Mode:** AFK · **Triage:** `ready-for-agent` · **Depends on:** DGR-046, DGR-047
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/048-carry-token-id-sideband-through-the-first-three-hash-routed-layers.md`, and evidence READMEs for dependencies (DGR-046, DGR-047) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Ensure any stage containing the first three hash-routed layers receives exact token identities.
- [ ] Head emits token IDs in the typed sideband for boundaries that require them.
- [ ] Intermediate stages preserve or consume the sideband according to their layer range.
- [ ] Routes splitting before, within, and after the first three layers pass deterministic partition tests.
- [ ] Missing or mismatched token IDs fail closed rather than silently selecting incorrect experts.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
### DGR-049: Keep V4 attention and auxiliary state shard-local
**Milestone:** M3 · **Mode:** AFK · **Triage:** `ready-for-agent` · **Depends on:** DGR-046, DGR-047
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/049-keep-v4-attention-and-auxiliary-state-shard-local.md`, and evidence READMEs for dependencies (DGR-046, DGR-047) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Bind V4 CSA/HCA/SWA/indexer/compressor and KV state to the owning shard session/epoch rather than transferring caches over the WAN.
- [ ] Map CSA, HCA, SWA, indexer, compressor, and KV ownership from the pinned upstream graph to each owned layer range.
- [ ] Key all such caches/state by route session and epoch with bounded lifecycle, memory accounting, stale-epoch rejection, release, and eviction.
- [ ] Prove cross-stage messages carry only the typed architecture boundary and cache expectations, never per-layer cache contents.
- [ ] On route change or state loss, use explicit cache miss and re-prefill/restart; do not migrate V4 caches across workers.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
### DGR-050: Validate upstream V4 MoE and hash-routing execution under ranged ownership
**Milestone:** M3 · **Mode:** AFK · **Triage:** `ready-for-agent` · **Depends on:** DGR-045, DGR-047
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/050-validate-upstream-v4-moe-and-hash-routing-execution-under-ranged-ownership.md`, and evidence READMEs for dependencies (DGR-045, DGR-047) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Validate the pinned upstream llama.cpp V4 MoE and hash-routing graph when layers are range-owned, without reimplementing routing or expert kernels in Meshnet.
- [ ] Load range-owned tensors for 256 routed plus one shared expert and validate upstream execution activates six routed experts where specified.
- [ ] Validate the first three upstream hash-routed layers receive exact token-ID sideband across splits before, within, and after them.
- [ ] Compare upstream whole-model and ranged router/expert outputs, shared-expert contribution, and malformed sideband failures.
- [ ] Document that llama.cpp owns V4 MoE, attention, hash routing, graph, and kernels; no expert-parallel WAN collective or Meshnet reimplementation is introduced.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
### DGR-051: Assemble the DeepSeek V4 Flash `ShardEngine` adapter
**Milestone:** M3 · **Mode:** AFK · **Triage:** `ready-for-agent` · **Depends on:** DGR-034, DGR-037, DGR-047, DGR-048, DGR-049, DGR-050
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/051-assemble-the-deepseek-v4-flash-shardengine-adapter.md`, and evidence READMEs for dependencies (DGR-034, DGR-037, DGR-047, DGR-048, DGR-049, DGR-050) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Assemble range ownership hooks and boundary/local-state adapters around upstream llama.cpp V4 execution behind the stable ShardEngine interface.
- [ ] Support valid head, middle, tail, and whole-model ranges over all 43 main layers using the pinned upstream llama.cpp V4 graph/kernels.
- [ ] Integrate exact range ownership, mHC boundary, positions, required token-ID sideband, and shard-local session/epoch state adapters.
- [ ] Report MTP reserved-but-not-executable for alpha and reject unsupported split points or cache expectations.
- [ ] Include exact adapter/schema/runtime/artifact identity and valid split restrictions without reimplementing V4 MoE, attention, mHC, or hash routing.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
### DGR-052: Pass local V4 whole-model versus ranged parity
**Milestone:** M3 · **Mode:** AFK · **Triage:** `ready-for-agent` · **Depends on:** DGR-038, DGR-051
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/052-pass-local-v4-whole-model-versus-ranged-parity.md`, and evidence READMEs for dependencies (DGR-038, DGR-051) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Prove V4 prefill and decode correctness locally before network certification.
- [ ] Compare pinned whole-model llama.cpp with at least two valid ranged partitions.
- [ ] Prefill intermediates and locked-length greedy decode pass architecture-specific tolerances.
- [ ] Test splits around the first three hash-routed layers and at least one CSA/HCA/SWA/indexer/compressor transition.
- [ ] Four concurrent sessions pass KV/state isolation and cleanup.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
### DGR-053: Certify a real 24-stage V4 route
**Milestone:** M3 · **Mode:** HITL · **Triage:** `ready-for-human` · **Depends on:** DGR-030, DGR-043, DGR-052
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/053-certify-a-real-2-4-stage-v4-route.md`, and evidence READMEs for dependencies (DGR-030, DGR-043, DGR-052) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Prove real Tracker-selected V4 execution across physical machines before alpha.
- [ ] Run one documented 24-stage certification scenario using exact compatible artifacts/recipes; the count and chosen quant are evidence inputs, not product constants.
- [ ] Actual CPU/GPU work executes on every stage; fake workers do not satisfy acceptance.
- [ ] Record parity, TTFT, prefill/decode speed, seam cost, memory, cache/state isolation, cancellation, and cleanup.
- [ ] Tracker selection remains dynamic and rejects an injected incompatible backend/recipe.
- [ ] Only the exact real-hardware lanes exercised become eligible for advertisement.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
### DGR-054: Enforce the DeepSeek V4 Flash alpha gate
**Milestone:** M3 · **Mode:** HITL · **Triage:** `ready-for-human` · **Depends on:** DGR-017, DGR-019, DGR-020, DGR-039, DGR-042, DGR-043, DGR-052, DGR-053
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/054-enforce-the-deepseek-v4-flash-alpha-gate.md`, and evidence READMEs for dependencies (DGR-017, DGR-019, DGR-020, DGR-039, DGR-042, DGR-043, DGR-052, DGR-053) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Release alpha only when V4 is correct and clears the pre-locked useful-speed requirement.
- [ ] Evaluate correctness, model fit, TTFT, prefill/decode speed, seam cost, memory, and failure rate against DGF-004 without changing thresholds.
- [ ] Separate quant/model-fit gains from runtime/transport gains.
- [ ] Decision is `alpha`, `optimize measured bottleneck`, or `stop`; failures cannot be relabeled as certification.
- [ ] Alpha documentation states MTP is reserved but not implemented and identifies every dark hardware lane.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
### DGR-055: Implement compatible continuous decode batching
**Milestone:** M4 · **Mode:** AFK · **Triage:** `ready-for-agent` · **Depends on:** DGR-038, DGR-040, DGR-054
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/055-implement-compatible-continuous-decode-batching.md`, and evidence READMEs for dependencies (DGR-038, DGR-040, DGR-054) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Batch compatible active sessions without violating route, recipe, position, or architecture state.
- [ ] Batch only sessions with compatible engine, recipe, phase, boundary schema, and state layout.
- [ ] Preserve per-session positions, sequence IDs, outputs, cancellation, and accounting.
- [ ] Decode receives bounded service while prefill remains schedulable.
- [ ] Deterministic 1/2/4/8 concurrency tests show no cross-session corruption.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
### DGR-056: Enforce bounded admission, queues, and backpressure
**Milestone:** M4 · **Mode:** AFK · **Triage:** `ready-for-agent` · **Depends on:** DGR-055
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/056-enforce-bounded-admission-queues-and-backpressure.md`, and evidence READMEs for dependencies (DGR-055) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Prevent weight, KV, state, scratch, and stream buffers from exceeding admitted capacity.
- [ ] Admission accounts separately for weights, KV/state, scratch, in-flight fragments, and queue slots.
- [ ] Queue and stream limits produce structured retryable or terminal responses.
- [ ] Prefill cannot starve decode and one route session cannot monopolize queue capacity.
- [ ] Telemetry reports active sessions, queue depth/time, batch occupancy, memory pressure, and rejects.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
### DGR-057: Benchmark batching saturation and fairness
**Milestone:** M4 · **Mode:** AFK · **Triage:** `ready-for-agent` · **Depends on:** DGR-055, DGR-056
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/057-benchmark-batching-saturation-and-fairness.md`, and evidence READMEs for dependencies (DGR-055, DGR-056) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Identify useful concurrency and saturation points without assuming one global batch size.
- [ ] Run controlled concurrency 1/2/4/8 and record aggregate throughput, per-request p50/p95, TTFT, queue time, occupancy, and memory.
- [ ] Measure dense and V4 lanes separately where hardware permits.
- [ ] Verify bounded fairness and no prefill/decode starvation.
- [ ] Produce machine-readable saturation recommendations consumed by capability reporting, not hardcoded constants.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
### DGR-058: Harden worker and stream failure semantics
**Milestone:** M4 · **Mode:** AFK · **Triage:** `ready-for-agent` · **Depends on:** DGR-040, DGR-042, DGR-056
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/058-harden-worker-and-stream-failure-semantics.md`, and evidence READMEs for dependencies (DGR-040, DGR-042, DGR-056) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Ensure malformed input, process death, transport reset, and cancellation terminate cleanly.
- [ ] Test worker death, stream reset, malformed bundle, checksum failure, deadline, cache miss, stale epoch, and partial fragment loss.
- [ ] Cancellation propagates across all stages and releases KV/state, queue entries, and fragment buffers.
- [ ] Duplicate steps are idempotent; uncertain mutations are never silently replayed.
- [ ] Billing/work outcomes distinguish completed, cancelled, failed, and unverified work.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
### DGR-059: Implement alpha-safe route recovery
**Milestone:** M4 · **Mode:** AFK · **Triage:** `ready-for-agent` · **Depends on:** DGR-043, DGR-058
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/059-implement-alpha-safe-route-recovery.md`, and evidence READMEs for dependencies (DGR-043, DGR-058) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Recover from route loss without importing or continuing unverified state.
- [ ] On route loss or local-state cache miss, restart from token zero or re-prefill on a newly compatible route according to the locked alpha contract.
- [ ] Never import KV, CSA, HCA, SWA, indexer, compressor, recurrent, or MTP cache/state across workers.
- [ ] Keep exact same-route duplicate delivery idempotent while cross-route continuation fails closed.
- [ ] Test direct/relay loss, cache miss, replacement selection, client cancellation, and billing reconciliation.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
### DGR-060: Certify V4 long-context state correctness
**Milestone:** M4 · **Mode:** AFK · **Triage:** `ready-for-agent` · **Depends on:** DGR-051, DGR-056, DGR-058
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/060-certify-v4-long-context-state-correctness.md`, and evidence READMEs for dependencies (DGR-051, DGR-056, DGR-058) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Prove V4s KV and auxiliary state remain correct and bounded at long contexts.
- [ ] Exercise pre-locked context lengths covering multiple prefill chunks and sustained decode.
- [ ] Validate KV plus CSA/HCA/SWA/indexer/compressor state positions across every stage.
- [ ] Measure memory growth, fragment sizes, TTFT, decode degradation, cancellation latency, and cleanup.
- [ ] Cache mismatch, truncation, and context-limit behavior fail deterministically.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
### DGR-061: Certify existing routing with 10+ GGUF stage candidates
**Milestone:** M4 · **Mode:** AFK · **Triage:** `ready-for-agent` · **Depends on:** DGR-043, DGR-057, DGR-058
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/061-certify-existing-routing-with-10-gguf-stage-candidates.md`, and evidence READMEs for dependencies (DGR-043, DGR-057, DGR-058) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Certify that existing backend-agnostic routing consumes GGUF compatibility and measured-cost inputs for a 10+ candidate scenario without algorithm or policy redesign.
- [ ] Generate deterministic pools with 10+ compatible GGUF stage candidates plus slower, overloaded, unhealthy, and incompatible alternatives.
- [ ] Run the existing routing implementation unchanged and verify complete coverage, compatibility, acyclicity, and use of measured inputs.
- [ ] Regression-test that no stage count, quant, fixed split, architecture, or backend sequence is encoded in production routing policy.
- [ ] Verify existing route recomputation reacts to measured load/failure while tracker, load-balancing, billing, relay, and provider semantics remain unchanged.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
### DGR-062: Certify a dynamic real 10+ stage V4 scenario
**Milestone:** M4 · **Mode:** HITL · **Triage:** `ready-for-human` · **Depends on:** DGR-053, DGR-060, DGR-061
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/062-certify-a-dynamic-real-10-stage-v4-scenario.md`, and evidence READMEs for dependencies (DGR-053, DGR-060, DGR-061) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Demonstrate that a large real route can be dynamically selected and usefully execute V4.
- [ ] Run one real 10+-stage V4 certification scenario; stage count, quant, and split remain scenario metadata only.
- [ ] Every selected stage proves real work, exact compatible identity, local state ownership, and bounded resources.
- [ ] Record end-to-end and per-stage TTFT, prefill/decode, seam cost, queueing, memory, failures, and cleanup.
- [ ] Inject at least one incompatible or degraded candidate and verify dynamic exclusion/reselection.
- [ ] The scenario must meet its pre-locked usefulness threshold or remain failed evidence.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
### DGR-063: Profile and optimize the critical seam
**Milestone:** M4 · **Mode:** AFK · **Triage:** `ready-for-agent` · **Depends on:** DGR-057, DGR-061
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/063-profile-and-optimize-the-critical-seam.md`, and evidence READMEs for dependencies (DGR-057, DGR-061) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Optimize only the measured dominant compute, serialization, copy, or transport bottleneck.
- [ ] Profile worker compute, tensor conversion, copies, protobuf framing, compression, relay/direct transport, queueing, and synchronization.
- [ ] Select one dominant bottleneck from evidence and lock its before/after benchmark.
- [ ] Implement one bounded optimization without weakening correctness or protocol identity.
- [ ] Report whether the optimization changes TTFT, prefill, decode, throughput, or memory and preserve raw data.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
### DGR-064: Add negotiated activation compression
**Milestone:** M4 · **Mode:** AFK · **Triage:** `ready-for-agent` · **Depends on:** DGR-060, DGR-063
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/064-add-negotiated-activation-compression.md`, and evidence READMEs for dependencies (DGR-060, DGR-063) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Reduce V4 seam cost only when a certified compression recipe improves end-to-end performance acceptably.
- [ ] Negotiate compression through recipe identity; unnegotiated or mismatched compression fails closed.
- [ ] Preserve names, shapes, semantic axes, token-ID sideband, and checksums.
- [ ] Measure quality drift, encode/decode cost, bytes, TTFT, and throughput against uncompressed boundaries.
- [ ] Compression remains dark unless it meets pre-locked quality and speed thresholds.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
### DGR-065: Define V4 MTP ownership and distributed state contract
**Milestone:** M4 · **Mode:** AFK · **Triage:** `ready-for-agent` · **Depends on:** DGR-051, DGR-054, DGR-060
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/065-define-v4-mtp-ownership-and-distributed-state-contract.md`, and evidence READMEs for dependencies (DGR-051, DGR-054, DGR-060) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Lock MTP tensor, execution, boundary, acceptance/rejection, and session-state ownership before implementation while keeping MTP disabled for alpha.
- [ ] Derive exact MTP tensor and execution ownership from the pinned V4 target and upstream llama.cpp graph, distinguishing main-layer, tail, and MTP responsibilities.
- [ ] Define typed MTP inputs/outputs plus accepted-token, rejection, rollback/truncation, position, cache, and session/epoch lifecycle semantics.
- [ ] Specify which MTP state remains shard-local and which typed boundary values cross a seam; prohibit WAN migration of KV or V4 auxiliary caches.
- [ ] Keep every MTP recipe disabled and unroutable for alpha, with fail-closed capability negotiation and deterministic contract fixtures.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
### DGR-066: Implement and benchmark V4 MTP
**Milestone:** M4 · **Mode:** AFK · **Triage:** `ready-for-agent` · **Depends on:** DGR-054, DGR-060, DGR-064, DGR-065
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/066-implement-and-benchmark-v4-mtp.md`, and evidence READMEs for dependencies (DGR-054, DGR-060, DGR-064, DGR-065) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Implement the locked MTP contract around upstream llama.cpp before beta, without making MTP an alpha prerequisite.
- [ ] Implement the exact DGR-065 MTP ownership and typed state contract against the pinned upstream V4 graph while preserving shard-local caches.
- [ ] Pass whole-model versus ranged MTP correctness, accepted-token, rejection, rollback/truncation, and session-isolation tests.
- [ ] Benchmark MTP-off versus MTP-on quality, accepted-token rate, TTFT, decode speed, seam bytes, and memory on the locked lane.
- [ ] Distinguish implemented, certified, disabled, and unsupported MTP recipes in fail-closed capability advertisement.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
### DGR-067: Certify the backend capability matrix
**Milestone:** M4 · **Mode:** HITL · **Triage:** `ready-for-human` · **Depends on:** DGR-030, DGR-053, DGR-062, DGR-066
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/067-certify-the-backend-capability-matrix.md`, and evidence READMEs for dependencies (DGR-030, DGR-053, DGR-062, DGR-066) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Publish only backend/model/recipe lanes proven on actual CPU, CUDA, ROCm, Vulkan, or Metal hardware.
- [ ] Maintain independent build and certification status for CPU, CUDA, ROCm, Vulkan, and Metal.
- [ ] Each advertised lane includes real hardware/driver/runtime/model evidence for parity, concurrency, cancellation, cleanup, and useful speed.
- [ ] Build success alone never makes a lane routable; unavailable hardware remains explicitly dark.
- [ ] Tracker admission consumes signed/versioned certification records rather than backend-name allowlists.
- [ ] Mixed-backend routes require exact compatibility evidence and fail closed otherwise.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
### DGR-068: Package reproducible native worker releases
**Milestone:** M5 · **Mode:** AFK · **Triage:** `ready-for-agent` · **Depends on:** DGR-030, DGR-054, DGR-067
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/068-package-reproducible-native-worker-releases.md`, and evidence READMEs for dependencies (DGR-030, DGR-054, DGR-067) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Produce installable worker packages that preserve exact source, patch, protocol, and certification identity.
- [ ] Package worker binaries/configuration for supported host/backend combinations without bundling an unverified llama.cpp tree.
- [ ] Embed protocol, engine, upstream pin, patch-stack, build-toolchain, and certification fingerprints.
- [ ] Installation/startup refuses mismatched artifacts, runtime recipes, or unsupported hardware lanes.
- [ ] Produce checksums, SBOM/license attribution, reproducible build instructions, and smoke tests.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
### DGR-069: Prepare narrow upstream llama.cpp collaboration patches
**Milestone:** M5 · **Mode:** HITL · **Triage:** `ready-for-human` · **Depends on:** DGR-028, DGR-035, DGR-038, DGR-051
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/069-prepare-narrow-upstream-llama-cpp-collaboration-patches.md`, and evidence READMEs for dependencies (DGR-028, DGR-035, DGR-038, DGR-051) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Reduce long-term patch burden through generic upstreamable hooks without asking llama.cpp to own Meshnet.
- [ ] Separate generic range loading, boundary I/O, and filtered state hooks from project worker/protocol code.
- [ ] Provide one scoped patch, focused test, and minimal reproducer per concern against the exact upstream pin.
- [ ] Compare the proposal with prior-art evidence and current upstream V4 support/maturity.
- [ ] Prepare human-ready design/outreach text; actual issue/PR submission remains a human action.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
### DGR-070: Enforce the DeepSeek V4 Flash beta gate
**Milestone:** M5 · **Mode:** HITL · **Triage:** `ready-for-human` · **Depends on:** DGR-057, DGR-059, DGR-060, DGR-062, DGR-064, DGR-066, DGR-067, DGR-068
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/070-enforce-the-deepseek-v4-flash-beta-gate.md`, and evidence READMEs for dependencies (DGR-057, DGR-059, DGR-060, DGR-062, DGR-064, DGR-066, DGR-067, DGR-068) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Promote beta only after concurrency, resilience, long-context, MTP, scale, packaging, and speed gates pass.
- [ ] Evaluate all beta metrics against DGF-004 without changing thresholds after observing results.
- [ ] Require V4 parity, batching/fairness, bounded backpressure, failure recovery, long-context correctness, MTP evidence, and dynamic 10+ stage evidence.
- [ ] Publish the exact certified hardware/backend/recipe matrix; all other lanes remain dark.
- [ ] Decision is `beta`, `targeted optimization`, or `stop/rollback`, with unresolved failures listed explicitly.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
### DGR-071: Establish upstream pin, patch, and certification maintenance
**Milestone:** M5 · **Mode:** AFK · **Triage:** `ready-for-agent` · **Depends on:** DGR-069, DGR-070
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/071-establish-upstream-pin-patch-and-certification-maintenance.md`, and evidence READMEs for dependencies (DGR-069, DGR-070) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Keep beta reproducible and detect upstream/model/hardware drift before it reaches routable nodes.
- [ ] Add a documented update procedure for llama.cpp pin, numbered patches, protocol/engine versions, V4 target revision, and certification records.
- [ ] A candidate pin update must apply/build/test in isolation and cannot replace the production pin automatically.
- [ ] Any changed graph, tensor inventory, boundary, cache/state layout, backend behavior, or performance invalidates affected certification.
- [ ] Add scheduled model-free checks plus opt-in real-hardware recertification instructions and rollback procedure.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Non-goals
- Replacing or redesigning Tracker routing/load-balancing, billing, relay, or provider policy.
- Reimplementing DeepSeek V4 architecture graphs or kernels in Meshnet.
- Hardcoding a quant, stage count, node count, split, architecture, or backend sequence.
- WAN migration of KV or V4 auxiliary caches.
- Advertising a compile-only or fixture-only hardware lane.
- Making MTP an alpha dependency.

View File

@@ -1,309 +1,57 @@
# Ralph execution context: Performant Concurrent Distributed GGUF Runtime
# Ralph context: Distributed GGUF Runtime
Status: authoritative context for every fresh Ralph iteration
Last updated: 2026-07-13
> **Specification status:** planning artifacts only. No distributed GGUF runtime is implemented. DGR-017 cleanup is complete; no runtime implementation story has completion credit. `prd.json` is authoritative.
## Mandatory startup sequence
## Mandatory startup for every fresh story
Before changing code, every Ralph agent must:
1. Read this file and authoritative `prd.json` completely.
2. Read the generated source issue named in the selected story description.
3. Read every dependency evidence README; legacy DGR-001..016 evidence is provenance only.
4. Read `docs/adr/0024-distributed-gguf-runtime.md`, root `CONTEXT.md`, `.claude/memory/MEMORY.md`, and relevant live source/tests.
5. Inspect `git status`; preserve unrelated work. Never infer implementation from planning text or old pass states.
6. If blocked or oversized, keep `passes: false` and write an honest `BLOCKED.md`/`DECOMPOSITION.md`; never weaken criteria or fabricate evidence.
1. Read this file completely.
2. Read the selected issue under `.scratch/distributed-gguf-runtime/issues/`.
3. Read `docs/adr/0024-distributed-gguf-runtime.md` and the relevant part of `architecture.md`.
4. Read `.claude/memory/MEMORY.md` and root `CONTEXT.md` for current project vocabulary and constraints.
5. Inspect the current implementation and tests; do not assume historical scratch text describes live code.
6. Read the evidence/handoff directories for every declared dependency.
7. Inspect `git status` and preserve all pre-existing working-tree changes.
## Locked scope
A fresh Ralph iteration has no conversational memory. These files are the context contract.
- Existing Meshnet Tracker routing, load balancing, billing, telemetry, relay, and provider semantics are backend-agnostic and are **not redesigned**. GGUF contributes exact compatibility, range/capacity, queue/load, seam-cost, health/reliability, and certification inputs only.
- The data plane is a standalone project-owned C++ Shard worker with gRPC/Protobuf and a project-owned `ShardEngine` boundary.
- llama.cpp is fetched at one exact commit into an ignored workspace from an in-repo manifest, then a numbered minimal patch stack is applied. There is no submodule, vendored tree, or permanent-fork dependency.
- llama.cpp owns DeepSeek V4 graphs, mHC, MoE, attention, hash routing, and kernels. Meshnet adds only range-ownership hooks, typed boundary/local-state adapters, worker integration, and parity/certification.
- Quantization and placement are dynamic recipe inputs. The 24 and 10+ stage layouts are certification scenarios, never product constants.
- Per-shard Hot KV and V4 CSA/HCA/SWA/indexer/compressor state remain local and keyed by route session/epoch. The WAN seam carries the typed mHC 4×4096 residual boundary, positions, token-ID sideband where required, and schema/cache expectations—not per-layer caches.
- Route changes use cache miss plus re-prefill/restart. There is no WAN KV or V4 auxiliary-cache migration.
- CPU/CUDA/ROCm/Vulkan/Metal compile lanes are planned; only exact real-hardware-certified backend/model/recipe lanes may be advertised.
- Alpha requires correctness and the pre-locked useful-speed gate. MTP is reserved and off for alpha; its ownership contract, implementation, and benchmark are required before beta.
## Story sizing and interruption rule
## Target identities
Each story is intended to fit one focused Ralph context. Before implementation, estimate whether every acceptance criterion can be completed and verified in the current iteration.
- DeepSeek V4 official target SHA: `60d8d70770c6776ff598c94bb586a859a38244f1`.
- llama.cpp V4 support lineage began at PR 24162 / merge `8c146a8366304c871efc26057cc90370ccf58dad`; DGR-027 later pins one exact validated current commit.
- V4 scope: 43 main layers plus MTP; mHC 4×4096 boundary; 256 routed + 1 shared experts with six routed active; token IDs required for the first three hash-routed layers.
- Exact split-GGUF artifacts are provisioned to mounted-drive storage with a complete hashed manifest and resumable verification; no model artifact may be placed under `/home`.
If the story is too large, an external dependency is unavailable, or the context/provider limit prevents completion:
## Control/data-plane contract
- Do not weaken criteria.
- Do not mark the issue done or set `passes: true`.
- Avoid leaving an unverified cross-cutting partial implementation when a smaller safe spike is possible.
- Write `evidence/<TASK-ID>/DECOMPOSITION.md` or `BLOCKED.md` with the exact blocker, current verified state, proposed child stories, dependency graph and rollback/continuation instructions.
- Stop for supervised review.
Meshnet continues to own registration, coverage, existing route selection/load balancing, route epochs/sessions, direct/relay behavior, capability admission, cancellation, telemetry, billing, validation, and attribution. The GGUF adapter exposes measured inputs to those existing mechanisms. Direct seams use long-lived gRPC streams; relay seams carry byte-identical protobuf frames opaquely.
If interrupted after code changes, record every changed file, command result and unresolved invariant so the next fresh loop can verify rather than guess.
The project-owned `ShardEngine` hides llama.cpp internals. A worker loads one exact artifact/recipe/range identity. Default tests use fake/tiny fixtures. Real runs are opt-in, preserve raw metrics, and never download models under `/home`.
## Product objective
## Gitea issue synchronization
Build performant, concurrent distributed inference that combines consumer machines to serve top open models that exceed one node's RAM/VRAM.
Gitea is a projection of `prd.json`, never a competing source of truth. Before and after every supervised Ralph run, invoke:
A distributed demo is not success. The product must provide:
- Useful measured prefill and decode speed.
- Multiple concurrent Route Sessions.
- No KV/token cross-talk.
- Bounded memory, queues, cancellation and failures.
- Real execution on every participating node.
- A model-fit or performance advantage over the current Transformers/safetensors route.
## Critical-path architecture
```text
Existing Meshnet control plane
|
Versioned Protobuf over gRPC/HTTP2
|
Project-owned standalone C++ Shard worker
|
Small exact-commit llama.cpp patch stack
```bash
python3 scripts/ralph_gitea_sync.py sync
```
Meshnet remains the only control plane and owns:
For a complete Ralph invocation with automatic state reconciliation, use:
- Tracker registration, Coverage Map, route selection and route epochs.
- Route Sessions and Activation Seams.
- Direct/relay routing.
- Capability admission.
- Cancellation, Generation Telemetry and backpressure.
- Billing, validation and per-node work attribution.
Do not introduce another scheduler/control plane from vLLM, Nakshatra, prima.cpp, llama-gguf, GPUStack or another project.
## Runtime decisions that are not open
1. Public-network Shards are contiguous transformer layer ranges.
2. llama.cpp/GGML is the native GGUF execution substrate.
3. The project owns a small standalone worker and a narrow pinned llama.cpp patch stack.
4. The native Shard protocol is Protocol Buffers over gRPC/HTTP2.
5. One long-lived bidirectional stream serves one Route Session Activation Seam.
6. The public activation boundary is a versioned named-tensor bundle.
7. Hot KV State remains local to the node serving the Shard.
8. `(Route Session ID, route epoch)` maps to an isolated llama sequence or bounded context.
9. Concurrency uses continuous batching of compatible active sessions inside each node.
10. Transformers/safetensors remains the correctness and performance baseline.
11. vLLM may be an optional complete managed provider and concept donor; it is not forked into public Shards.
12. Tensor/expert collectives are deferred to a trusted composite provider, not public WAN routes.
13. Unsupported architectures/backends remain registered-but-dark until real certification passes.
14. Alpha failure retries from token zero; unverified KV is never migrated silently.
15. Model artifacts must remain on mounted-drive storage and never under `/home`.
Changing one of these requires an explicit ADR update and human review, not an incidental story implementation.
## Performance discipline
GGUF performance is a hypothesis. Never write “GGUF is faster” without measurements.
DGR-001 locks controlled benchmark lanes and thresholds. DGR-014 enforces the final distributed comparison.
Always distinguish:
- Weight quantization from activation/compute/KV dtype.
- Runtime/kernel gains from quantization/model-fit gains.
- Single-request latency from aggregate concurrency throughput.
- Synthetic unit coverage from real distributed acceptance.
Required metrics where applicable:
```text
TTFT
prefill tokens/sec
decode tokens/sec
aggregate throughput
p50/p95 latency
seam bytes and latency
queue and batch occupancy
RSS and VRAM
KV pressure
output-quality drift
failures and cleanup
```bash
scripts/ralph-gitea-run.sh ralph-tui run --prd .scratch/distributed-gguf-runtime/prd.json --agent claude --model sonnet --iterations 1 --no-tui --no-setup --direct-merge --no-sandbox
```
Do not weaken or move performance thresholds after seeing implementation results.
The sync creates/reconciles one Gitea issue per `DGR-*` story, creates missing labels/milestones, closes issues whose `passes` is true, marks the selected next eligible story `status:in-progress`, and marks blocked stories `status:blocked`. `gitea-issues.json` is a derived mapping only.
## Transport discipline
## Evidence and completion
Do not invent a raw TCP protocol, new WebSocket protocol, QUIC layer or bespoke binary control format.
The `.proto` schema is the semantic contract. Direct transport uses gRPC. Existing relay infrastructure may carry the same serialized protobuf frames as opaque binary.
Protocol requirements:
- Schema/version negotiation.
- Request/work ID.
- Route Session ID and route epoch.
- Exact Model Artifact/runtime recipe fingerprint.
- Shard range and effective overlap-safe start.
- Prefill/decode/release/cancel phases.
- Position/token range and idempotency step.
- Named tensors with shape, dtype, byte order and bounded fragments.
- Compression/checksum.
- Cache expectation/result.
- Deadlines, cancellation, flow control and structured status.
Avoid per-token channel creation and unbounded unary payloads. Generated code and build tooling must be reproducible; do not require manual copying.
## Native runtime discipline
Reuse llama.cpp for GGUF, mmap, kernels, architecture graphs, tokenizer, KV, sequences and heterogeneous backends.
The project patch stack is limited to:
- Range-aware tensor registration/loading.
- Endpoint-specific embedding/final head ownership.
- Architecture-defined intermediate input/output.
- Intermediate output before final norm/head.
- Layer-filtered KV and session mapping.
Do not place Meshnet routing, transport, billing or authentication inside llama.cpp. Keep patches numbered, scoped, pinned and upstreamable.
Dense Llama-family is first. Qwen3/Qwen3-MoE is a separate adapter after the dense release gate. Do not generalize through unchecked tensor-name substitutions.
## Existing code seams to inspect first
- `packages/node/meshnet_node/model_backend.py` — backend abstraction.
- `packages/node/meshnet_node/torch_server.py` — reference ranged execution and session behavior.
- `packages/node/meshnet_node/activation_compression.py` — current activation framing/compression.
- `packages/node/meshnet_node/route_session_benchmark.py` — existing benchmark infrastructure.
- `packages/tracker/meshnet_tracker/server.py` — registration, route and proxy behavior.
- `packages/tracker/meshnet_tracker/capability.py` — fail-closed capability admission.
- `tests/test_real_model_backend.py` — real backend coverage.
- `tests/test_tracker_routing.py` — route/session behavior.
- `tests/test_tracker_capability_admission.py` — recipe admission.
- `tests/test_route_session_benchmark.py` and `tests/test_manual_route_benchmark.py` — benchmark patterns.
- `docs/adr/0008-binary-activation-wire-format.md` — existing wire compatibility.
- `docs/adr/0012-start-layer-overlapping-shards.md` — effective start semantics.
- `docs/adr/0022-sharded-per-node-kv-cache.md` — Hot KV State contract.
- `docs/adr/0023-model-agnostic-node-capability-admission.md` — certification/admission.
Do not edit generated `build/`, `__pycache__`, egg-info, Ralph logs or unrelated scratch features.
## Planned source layout
Use these paths unless current code inspection proves a better project-consistent location. If changed, document the reason in task evidence.
```text
packages/node/native/
proto/shard_runtime.proto
cmake/
llama/
UPSTREAM_COMMIT
patches/
gguf_worker/
tests/
packages/node/meshnet_node/
native_protocol/
gguf_backend.py
runtime_recipe.py
.scratch/distributed-gguf-runtime/evidence/<TASK-ID>/
README.md
commands.txt
results.json or other machine-readable evidence
```
Generated protobuf/C++ build outputs belong in build directories unless packaging explicitly requires checked-in generated Python modules. The story must document the generation command and version.
## Story output map
| Story | Required durable outputs |
|---|---|
| DGR-001 | benchmark harness/tests; `evidence/DGR-001/performance-contract.json`; raw/summary benchmark evidence |
| DGR-002 | `packages/node/native/proto/shard_runtime.proto`; reproducible Python/C++ generation/build wiring; protocol round-trip/compatibility tests; `evidence/DGR-002/` |
| DGR-003 | exact runtime-recipe/fingerprint implementation and admission tests; `evidence/DGR-003/` |
| DGR-004 | exact upstream pin, numbered patch series, reproducible fetch/apply/build smoke; `evidence/DGR-004/` |
| DGR-005 | dense-Llama range ownership loader and memory evidence; `evidence/DGR-005/` |
| DGR-006 | architecture boundary adapter/parity tests and results; `evidence/DGR-006/` |
| DGR-007 | concurrent session/KV manager, isolation/cleanup tests; `evidence/DGR-007/` |
| DGR-008 | standalone C++ gRPC worker, fake-model integration tests, lifecycle evidence; `evidence/DGR-008/` |
| DGR-009 | Meshnet backend/registration/relay integration and tests; `evidence/DGR-009/` |
| DGR-010 | real local two-process commands, raw metrics and parity report; `evidence/DGR-010/` |
| DGR-011 | two-machine configuration, commands, hardware/network manifest and raw results; `evidence/DGR-011/` |
| DGR-012 | continuous scheduler/admission implementation and 1/2/4/8 concurrency report; `evidence/DGR-012/` |
| DGR-013 | failure/cancel/restart test matrix and resource-cleanup evidence; `evidence/DGR-013/` |
| DGR-014 | immutable final comparison against DGR-001 thresholds and ship/stop recommendation; `evidence/DGR-014/` |
| DGR-015 | Qwen3-family adapter, architecture-specific parity/admission/performance evidence; `evidence/DGR-015/` |
| DGR-016 | narrow upstream patches/tests, design note and human-ready outreach package; `evidence/DGR-016/` |
## Dependency handoff rule
For every dependency listed by Ralph:
1. Confirm its `passes` state in `prd.json`.
2. Read `.scratch/distributed-gguf-runtime/evidence/<DEPENDENCY-ID>/README.md`.
3. Verify referenced source paths and commands still exist.
4. Do not repeat completed work unless verification exposes a concrete defect.
5. If dependency evidence is missing or contradictory, stop and repair the dependency instead of guessing.
## Testing and hardware rules
Default tests must be deterministic, GPU-free, model-download-free and API-credit-free.
Real model tests require:
```text
MESHNET_ENABLE_REAL_INFERENCE_TESTS=1
```
On this machine:
- Use `.venv-rocm` for real Radeon 8060S ROCm execution.
- The default Python 3.14 `.venv` is unsuitable for real ROCm inference.
- Resolve model storage through the machine-specific `.env.<hostname>` configuration.
- Never download model artifacts under `/home`.
- Real acceptance must exercise actual Tracker-routed CPU/GPU computation; synthetic workers are only unit tests.
Record exact:
- Model/revision and Artifact hash.
- Quantization and runtime recipe.
- Host/hardware/backend/driver.
- Commands and environment names without secrets.
- Raw output and metrics.
- Whether the evidence is synthetic, local-real, or multi-machine-real.
## Worktree and commit discipline
This repository may contain pre-existing changes from research or another feature.
- Inspect `git status` before editing.
- Never reset, checkout over, stash, delete or reformat unrelated changes.
- Stage only files belonging to the selected story.
- Exclude `.ralph-tui`, iteration logs, caches, generated builds, FUSE artifacts and unrelated scratch work.
- Keep one scoped commit per completed story when the supervising loop requests commits.
- Do not modify `passes` for another story.
## Mandatory finish/handoff sequence
Before emitting `<promise>COMPLETE</promise>`:
1. Verify every acceptance criterion with real command output or file evidence.
2. Run story-specific gates and repository quality gates.
3. Write `.scratch/distributed-gguf-runtime/evidence/<TASK-ID>/README.md` containing:
- Summary of changes.
- Exact files changed.
- Commands run and their real results.
- Performance/correctness evidence.
- Known limitations and deferred work.
- Compatibility or migration notes.
- Clear handoff for dependent stories.
4. Save machine-readable evidence beside it when the story produces metrics or schemas.
5. Update the source issue status to `done` only after all gates pass.
6. Preserve failures honestly. Never fabricate model, benchmark, test or hardware output.
## Authoritative references
Active decisions:
- `.scratch/distributed-gguf-runtime/README.md`
- `.scratch/distributed-gguf-runtime/implementation-strategy.md`
- `.scratch/distributed-gguf-runtime/architecture.md`
- `docs/adr/0024-distributed-gguf-runtime.md`
- `.scratch/distributed-gguf-runtime/PRD.md`
- `.scratch/distributed-gguf-runtime/prd.json`
Source research:
- `docs/research/distributed-gguf-landscape.md`
- `docs/research/distributed-gguf-github-followup.md`
- `docs/research/vllm-distributed-gguf-assessment.md`
If historical notes conflict with these files, the active decisions above win.
Each story writes `/run/media/popov/d/DEV/repos/d-popov.com/AI/.claude/worktrees/distributed-gguf-runtime/.scratch/distributed-gguf-runtime/evidence/<DGR-ID>/README.md` with exact files, commands/results, limitations, identities, and dependent-story handoff. Only `prd.json` may record `passes`; DGR-017 and DGR-018 are complete and DGR-019 onward remain false. Generated Markdown and Gitea issues cannot override it. One scoped commit per story is expected during future execution.

View File

@@ -1,46 +1,32 @@
# Performant concurrent distributed GGUF runtime
# Distributed GGUF Runtime planning workspace
Status: active benchmark-gated implementation program.
> **Specification status:** planning artifacts only. No distributed GGUF runtime is implemented. DGR-017 cleanup is complete; no runtime implementation story has completion credit. `prd.json` is authoritative.
## Objective
Serve top open models across consumer machines with useful performance and concurrent Route Sessions while keeping the runtime lean.
## Locked scope
## Critical path
- Existing Meshnet Tracker routing, load balancing, billing, telemetry, relay, and provider semantics are backend-agnostic and are **not redesigned**. GGUF contributes exact compatibility, range/capacity, queue/load, seam-cost, health/reliability, and certification inputs only.
- The data plane is a standalone project-owned C++ Shard worker with gRPC/Protobuf and a project-owned `ShardEngine` boundary.
- llama.cpp is fetched at one exact commit into an ignored workspace from an in-repo manifest, then a numbered minimal patch stack is applied. There is no submodule, vendored tree, or permanent-fork dependency.
- llama.cpp owns DeepSeek V4 graphs, mHC, MoE, attention, hash routing, and kernels. Meshnet adds only range-ownership hooks, typed boundary/local-state adapters, worker integration, and parity/certification.
- Quantization and placement are dynamic recipe inputs. The 24 and 10+ stage layouts are certification scenarios, never product constants.
- Per-shard Hot KV and V4 CSA/HCA/SWA/indexer/compressor state remain local and keyed by route session/epoch. The WAN seam carries the typed mHC 4×4096 residual boundary, positions, token-ID sideband where required, and schema/cache expectations—not per-layer caches.
- Route changes use cache miss plus re-prefill/restart. There is no WAN KV or V4 auxiliary-cache migration.
- CPU/CUDA/ROCm/Vulkan/Metal compile lanes are planned; only exact real-hardware-certified backend/model/recipe lanes may be advertised.
- Alpha requires correctness and the pre-locked useful-speed gate. MTP is reserved and off for alpha; its ownership contract, implementation, and benchmark are required before beta.
```text
Meshnet control plane
-> versioned gRPC/Protobuf Shard protocol
-> project-owned standalone C++ worker
-> small pinned llama.cpp patch stack
```
## Target identities
Transformers/safetensors remains the correctness baseline. vLLM remains an optional complete managed provider and a design donor; it is not forked into the public mesh.
- DeepSeek V4 official target SHA: `60d8d70770c6776ff598c94bb586a859a38244f1`.
- llama.cpp V4 support lineage began at PR 24162 / merge `8c146a8366304c871efc26057cc90370ccf58dad`; DGR-027 later pins one exact validated current commit.
- V4 scope: 43 main layers plus MTP; mHC 4×4096 boundary; 256 routed + 1 shared experts with six routed active; token IDs required for the first three hash-routed layers.
- Exact split-GGUF artifacts are provisioned to mounted-drive storage with a complete hashed manifest and resumable verification; no model artifact may be placed under `/home`.
## Planning artifacts
## Navigation
- **[Mandatory Ralph context](RALPH-CONTEXT.md)** — read first in every fresh iteration
- [Task evidence contract](evidence/README.md)
- [Implementation strategy](implementation-strategy.md)
- [Current architecture](architecture.md)
- [PRD](PRD.md)
- [Ralph backlog](prd.json)
- [ADR-0024](../../docs/adr/0024-distributed-gguf-runtime.md)
- [Milestones](milestones.md)
- [Issues](issues/)
- [Distributed GGUF research](../../docs/research/distributed-gguf-landscape.md)
- [GitHub follow-up](../../docs/research/distributed-gguf-github-followup.md)
- [vLLM assessment](../../docs/research/vllm-distributed-gguf-assessment.md)
## Ralph execution
Use supervised one-story iterations for this high-risk runtime:
```bash
ralph-tui run \
--prd .scratch/distributed-gguf-runtime/prd.json \
--agent claude --model opus \
--iterations 1 --no-tui --no-setup --verify
```
Inspect the diff, run the story gates, and commit one verified story before the next iteration. Real-model stories require the explicit environment gate and mounted-drive model storage.
- [`prd.json`](prd.json) — sole authoritative 55-story backlog, DGR-017..071.
- [`PRD.md`](PRD.md) — human-readable projection of goals, gates, and all stories.
- [`RALPH-CONTEXT.md`](RALPH-CONTEXT.md) — mandatory fresh-session context.
- [`architecture.md`](architecture.md), [`implementation-strategy.md`](implementation-strategy.md), [`milestones.md`](milestones.md) — design and execution sequence.
- [`issues/`](issues/) — generated story specs; files 01..16 are retained legacy artifacts pending DGR-017.
- [`evidence/`](evidence/) — provenance and future per-story handoffs.

View File

@@ -1,259 +1,45 @@
# Performant Concurrent Distributed GGUF Architecture
# Distributed GGUF Runtime architecture
Status: current target architecture
Last updated: 2026-07-13
> **Specification status:** planning artifacts only. No distributed GGUF runtime is implemented. DGR-017 cleanup is complete; no runtime implementation story has completion credit. `prd.json` is authoritative.
## Product invariant
The system exists to serve high-quality models that exceed one consumer node's memory while retaining useful interactive speed and aggregate concurrency. A feature that only produces a distributed demo but is slower, globally serialized, or impossible to operate on consumer hardware is not complete.
## Locked scope
## Existing control plane
- Existing Meshnet Tracker routing, load balancing, billing, telemetry, relay, and provider semantics are backend-agnostic and are **not redesigned**. GGUF contributes exact compatibility, range/capacity, queue/load, seam-cost, health/reliability, and certification inputs only.
- The data plane is a standalone project-owned C++ Shard worker with gRPC/Protobuf and a project-owned `ShardEngine` boundary.
- llama.cpp is fetched at one exact commit into an ignored workspace from an in-repo manifest, then a numbered minimal patch stack is applied. There is no submodule, vendored tree, or permanent-fork dependency.
- llama.cpp owns DeepSeek V4 graphs, mHC, MoE, attention, hash routing, and kernels. Meshnet adds only range-ownership hooks, typed boundary/local-state adapters, worker integration, and parity/certification.
- Quantization and placement are dynamic recipe inputs. The 24 and 10+ stage layouts are certification scenarios, never product constants.
- Per-shard Hot KV and V4 CSA/HCA/SWA/indexer/compressor state remain local and keyed by route session/epoch. The WAN seam carries the typed mHC 4×4096 residual boundary, positions, token-ID sideband where required, and schema/cache expectations—not per-layer caches.
- Route changes use cache miss plus re-prefill/restart. There is no WAN KV or V4 auxiliary-cache migration.
- CPU/CUDA/ROCm/Vulkan/Metal compile lanes are planned; only exact real-hardware-certified backend/model/recipe lanes may be advertised.
- Alpha requires correctness and the pre-locked useful-speed gate. MTP is reserved and off for alpha; its ownership contract, implementation, and benchmark are required before beta.
Meshnet remains the only public control plane:
## Target identities
- Tracker registration, Coverage Map, route scoring and assignment.
- Contiguous Shards and overlap-safe effective starts.
- Stable Route Sessions and route epochs.
- Local per-Shard Hot KV State in the reference backend.
- Direct/relay transport, cancellation and backpressure.
- Generation Telemetry, billing, validation and per-node attribution.
- Model-agnostic capability admission.
- DeepSeek V4 official target SHA: `60d8d70770c6776ff598c94bb586a859a38244f1`.
- llama.cpp V4 support lineage began at PR 24162 / merge `8c146a8366304c871efc26057cc90370ccf58dad`; DGR-027 later pins one exact validated current commit.
- V4 scope: 43 main layers plus MTP; mHC 4×4096 boundary; 256 routed + 1 shared experts with six routed active; token IDs required for the first three hash-routed layers.
- Exact split-GGUF artifacts are provisioned to mounted-drive storage with a complete hashed manifest and resumable verification; no model artifact may be placed under `/home`.
No external engine replaces these responsibilities.
## Runtime topology
## Topology
```text
OpenAI-compatible client
|
Gateway / Tracker Node
|
ordered Inference Route
|
+-- head Shard: tokenizer/embedding + early layers
| local weights and Hot KV State
|
+-- middle Shard(s): architecture boundary + owned layers
| local weights and Hot KV State
|
+-- tail Shard: final layers + norm/head/sampling
local weights and Hot KV State
existing Meshnet Tracker/control plane
-> existing backend-agnostic route/load-balancing decision
-> direct gRPC or existing opaque relay
-> project-owned standalone C++ Shard worker
-> project-owned ShardEngine
-> pinned upstream llama.cpp + numbered range/boundary/state hook patches
-> GGUF mmap, upstream V4 graph/kernels, local per-shard state
```
Weights never move in the per-request hot path. Every node opens and verifies its local Model Artifact before becoming routable.
A route is ordered contiguous half-open ranges. Head owns token embedding; tail owns final norm/head/sampling. Compatibility fingerprints bind source/split hashes, tokenizer, architecture adapter, typed boundary, runtime pin/patches, backend, quant, activation/compute/KV layout, range, and certification.
## Primary execution substrate
## V4 boundary and state
```text
project-owned C++ Shard worker
|
small exact-commit llama.cpp patch stack
|
GGUF mmap, quantized kernels, architecture graphs,
KV/sequence operations, CPU/CUDA/HIP/Vulkan/Metal backends
```
The inter-stage boundary is semantic and versioned: mHC 4×4096 residual, positions, token IDs only where the first three hash-routed layers require them, and cache/schema expectations. CSA/HCA/SWA/indexer/compressor/KV state belongs to upstream layer execution on the owning worker and is isolated by `(route_session_id, route_epoch)`. On loss, return cache miss and re-prefill/restart. Never serialize those caches into the WAN bundle.
The patch stack adds only the missing local execution seam:
## Concurrency, failure, and admission
1. Range-aware tensor registration/loading.
2. Endpoint-specific embedding and final head ownership.
3. Architecture-defined intermediate input.
4. Architecture-defined pre-tail boundary output.
5. Layer-filtered KV and external session mapping.
The worker owns protocol translation and process lifecycle. llama.cpp never receives Tracker, relay, billing or volunteer-network code.
## Shard data plane
Use Protocol Buffers and gRPC over HTTP/2.
### Service shape
- Unary capability and health.
- Bidirectional Route Session stream.
- Explicit release and cancellation.
- Metrics suitable for capability admission and route scoring.
### Session stream
One long-lived stream represents one Route Session Activation Seam. It amortizes connection setup and inherits HTTP/2 flow control. Every message carries enough identity to reject stale or incompatible work.
```text
schema version
request/work id
Route Session id
route epoch
Model Artifact hash
runtime recipe fingerprint
Shard begin/end and effective start
prefill/decode/release/cancel phase
position and token range
idempotency step id
cache expectation/result
named tensor bundle
compression/checksum
```
Prefill tensors are split into bounded ordered frames. Decode messages carry one-step architecture boundary bundles and remain small.
Direct nodes use gRPC. Nodes requiring the existing relay carry the same protobuf frames as opaque binary through the relay session. This preserves one semantic protocol instead of maintaining separate direct and relay payload contracts.
## Architecture boundary
The public boundary is a versioned named-tensor bundle:
```text
bundle schema/version
architecture adapter and boundary point
named tensors
per-tensor shape, dtype and byte order
payload fragments
compression/checksum
```
Dense Llama may use one residual tensor. Other adapters may require more. vLLM's Llama and Qwen3-MoE PP paths demonstrate a boundary with both `hidden_states` and `residual`; therefore the generic protocol must not assume one anonymous tensor.
Only the head owns token embedding. Only the tail owns final normalization, LM head and sampling. Middle Shards exchange the architecture-defined pre-tail boundary, not final normalized embeddings.
## Hot KV State and concurrency
```text
(Route Session id, route epoch)
-> local llama sequence or bounded context
-> KV for owned layers only
-> lease, memory accounting and lifecycle
```
Required operations:
- Prefill append.
- Decode append.
- Truncate after rejected speculative positions if later enabled.
- Explicit release.
- TTL/LRU eviction.
- Cache-miss response.
- Stale-epoch rejection.
A node must not clear global KV on a new stream or serialize all requests behind one logical serving sequence.
## Continuous batching
Autoregressive dependencies remain sequential inside one Route Session. Aggregate throughput comes from batching compatible decode steps across active sessions:
```text
time 0: session A token 1 + session B token 8 + session C token 3
-> one llama batch for this Shard
time 1: next ready positions from active sessions
-> next llama batch
```
The node scheduler:
- Admits work against weight, KV, scratch and queue budgets.
- Keeps per-session token positions and outputs separate.
- Prevents long prefill from starving decode.
- Applies bounded backpressure.
- Reports active sessions, queue depth, batch occupancy, KV pressure and throughput.
The initial deterministic gate is four concurrent sessions on a small model without cross-talk. Hardware-specific limits are measured and advertised through capability admission.
## Parallelism boundaries
| Mechanism | First-runtime use |
|---|---|
| Layer/pipeline parallelism | Public Inference Route across contiguous Shards |
| Continuous batching | Inside every node across active Route Sessions |
| Data parallelism | Multiple complete routes for independent requests |
| Tensor parallelism | Deferred to a trusted composite node/managed cluster |
| Expert parallelism | Deferred to a trusted composite node/managed cluster |
| Disaggregated prefill | Deferred until core route performance passes |
| Speculative decoding | Deferred optimization |
Public WAN tensor/expert collectives are rejected for the first runtime because their per-layer communication and static rank assumptions conflict with heterogeneous volunteer nodes.
## Optional providers
### Transformers/safetensors
Remains:
- Correctness/reference backend.
- Fallback for unsupported architectures.
- Baseline for performance and output quality.
### vLLM
May run unmodified as a complete model or managed TP/PP/EP cluster represented as one logical provider. Its internal ranks are not independently routed or rewarded.
Borrow only concepts such as named bundles, continuous batching, typed compatibility fingerprints, explicit transfer lifecycle and load telemetry.
### Whole-model llama.cpp
Provides a local proxy backend, correctness oracle and performance baseline. It is not the native distributed milestone.
## Artifact and recipe compatibility
A routable recipe identifies separately:
- Source Model Artifact hash and optional derivative/slice hash.
- Architecture and adapter version.
- Tokenizer revision and vocabulary.
- Weight quantization.
- Activation interchange dtype/schema.
- Backend compute dtype and backend implementation.
- KV dtype/layout.
- RoPE/context parameters.
- llama.cpp commit and project patch version.
- Shard range and endpoint ownership.
Compatibility fails closed. Similar quantization labels or model names are not enough.
## Admission and failure
A recipe becomes routable only after a real local and distributed forward passes. Synthetic tests remain unit coverage.
Alpha failure behavior:
- Deadline or node loss cancels the Route Session.
- Every node releases KV and queued buffers.
- Uncertain mutations are not replayed silently.
- Retry starts from token zero on a newly compatible route.
- No cross-node KV import is trusted until a later signed/compatible snapshot protocol exists.
## Performance release contract
Before native development proceeds, compare the current Transformers/safetensors backend with whole-model llama.cpp under controlled model/hardware/quality lanes.
Final release compares distributed GGUF with distributed safetensors using thresholds locked before seeing final results.
Required measurements:
- TTFT.
- Prefill and decode tokens/sec.
- Aggregate concurrency throughput.
- p50/p95 latency.
- Seam bytes and latency.
- Queue/batch occupancy.
- RSS, VRAM and KV pressure.
- Output-quality drift.
- Cancellation/failure cleanup.
The GGUF path ships only if it is faster at acceptable quality or enables a larger otherwise-unroutable model at useful measured speed.
## Implementation sequence
1. Lock benchmark/performance contract.
2. Define gRPC/protobuf and exact recipe identity.
3. Pin llama.cpp and create the minimal patch stack.
4. Implement dense-Llama range loading and boundary parity.
5. Implement concurrent local KV.
6. Build and integrate the standalone worker.
7. Pass local two-process real-model acceptance.
8. Pass real heterogeneous two-machine acceptance.
9. Add continuous batching and failure hardening.
10. Enforce the GGUF-versus-safetensors release gate.
11. Add Qwen3/Qwen3-MoE as a separately certified adapter.
12. Prepare narrow upstream collaboration patches/tests.
See [the Ralph backlog](prd.json) and [implementation strategy](implementation-strategy.md).
Compatible sessions may be continuously batched within a worker while retaining isolated positions/state. Admission bounds weights, local state/KV, scratch, fragments, and queues. Uncertain cross-route mutation is not replayed. Registration can show an uncertified lane, but existing admission keeps it unroutable until signed/versioned real-hardware evidence exists.

View File

@@ -1,270 +1,40 @@
# Distributed GGUF Decision Framework
> **Superseded for active implementation decisions.** The grill was resolved on 2026-07-13. Use [implementation-strategy.md](implementation-strategy.md), [architecture.md](architecture.md), [ADR-0024](../../docs/adr/0024-distributed-gguf-runtime.md), and [prd.json](prd.json). This file remains as historical decision rationale.
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.
# Distributed GGUF Runtime decision framework
> **Specification status:** planning artifacts only. No distributed GGUF runtime is implemented. DGR-017 cleanup is complete; no runtime implementation story has completion credit. `prd.json` is authoritative.
## Decision order
1. DGR-019 locks comparable lanes and thresholds before results.
2. DGR-020 runs safetensors and whole-model llama.cpp only, then returns `go`, `optimize baseline`, or `stop`.
3. Dense and V4 work must prove parity, independent per-stage execution, local-state isolation, bounded failure, and measured resources.
4. DGR-054 returns `alpha`, `optimize measured bottleneck`, or `stop`; MTP is explicitly off.
5. Post-alpha optimizations must be selected from profiles, not assumptions.
6. DGR-070 returns `beta`, `targeted optimization`, or `stop/rollback`, and requires MTP and the exact certified hardware/recipe matrix.
## Interpretation rules
- Quant/model-fit gains are separate from runtime/kernel/transport gains.
- Fixture, real-model, real-hardware, and release evidence are never interchangeable.
- 24 and 10+ stages are certification scenarios only.
- Existing routing policy is certified, not redesigned.
- Build success is not hardware certification; dark lanes remain unroutable.
- Route loss uses cache miss and re-prefill/restart, never WAN cache migration.
## Locked scope
- Existing Meshnet Tracker routing, load balancing, billing, telemetry, relay, and provider semantics are backend-agnostic and are **not redesigned**. GGUF contributes exact compatibility, range/capacity, queue/load, seam-cost, health/reliability, and certification inputs only.
- The data plane is a standalone project-owned C++ Shard worker with gRPC/Protobuf and a project-owned `ShardEngine` boundary.
- llama.cpp is fetched at one exact commit into an ignored workspace from an in-repo manifest, then a numbered minimal patch stack is applied. There is no submodule, vendored tree, or permanent-fork dependency.
- llama.cpp owns DeepSeek V4 graphs, mHC, MoE, attention, hash routing, and kernels. Meshnet adds only range-ownership hooks, typed boundary/local-state adapters, worker integration, and parity/certification.
- Quantization and placement are dynamic recipe inputs. The 24 and 10+ stage layouts are certification scenarios, never product constants.
- Per-shard Hot KV and V4 CSA/HCA/SWA/indexer/compressor state remain local and keyed by route session/epoch. The WAN seam carries the typed mHC 4×4096 residual boundary, positions, token-ID sideband where required, and schema/cache expectations—not per-layer caches.
- Route changes use cache miss plus re-prefill/restart. There is no WAN KV or V4 auxiliary-cache migration.
- CPU/CUDA/ROCm/Vulkan/Metal compile lanes are planned; only exact real-hardware-certified backend/model/recipe lanes may be advertised.
- Alpha requires correctness and the pre-locked useful-speed gate. MTP is reserved and off for alpha; its ownership contract, implementation, and benchmark are required before beta.
## Target identities
- DeepSeek V4 official target SHA: `60d8d70770c6776ff598c94bb586a859a38244f1`.
- llama.cpp V4 support lineage began at PR 24162 / merge `8c146a8366304c871efc26057cc90370ccf58dad`; DGR-027 later pins one exact validated current commit.
- V4 scope: 43 main layers plus MTP; mHC 4×4096 boundary; 256 routed + 1 shared experts with six routed active; token IDs required for the first three hash-routed layers.
- Exact split-GGUF artifacts are provisioned to mounted-drive storage with a complete hashed manifest and resumable verification; no model artifact may be placed under `/home`.

View File

@@ -0,0 +1,114 @@
# DGR-017 evidence — superseded backlog cleanup
**Completed:** 2026-07-16
**Branch:** `ralph/distributed-gguf-runtime`
**Planning checkpoint before cleanup:** `81b1fa6`
**Authority:** `.scratch/distributed-gguf-runtime/prd.json`
## Outcome
The old DGR-001…016 completion claims and active artifacts were reconciled against the live branch. No old pass state transferred to the new implementation roadmap.
The active `packages/` and `tests/` trees were restored exactly to `origin/master`. The branch therefore no longer exposes a nominal GGUF startup path backed by unimplemented transport methods, a protobuf-only native scaffold, or isolated synthetic scheduler/cache/failure modules as if they were a working distributed GGUF runtime.
## Classification and disposition
### Retained
- Accepted ADRs and repository research, including `docs/research/colibri-implementation-audit.md`.
- The authoritative 55-story roadmap `DGR-017…071` and its generated issue specifications.
- The real public-relay smoke benchmark, moved with provenance to `legacy-public-relay-smoke-benchmark.json`.
- Git history containing the complete superseded implementation/reference work.
### Removed from the active tree
- Legacy issue specifications DGR-001…016 and their stale/blocked/synthetic evidence directories.
- The nonfunctional `gguf_backend` startup path whose gRPC execution methods raised not-implemented errors.
- Synthetic/reference-only boundary, Hot KV, scheduler, failure, recipe, ownership, and native-protocol modules that were not a real llama.cpp Shard runtime.
- The protobuf round-trip-only native scaffold, placeholder llama.cpp patch, generated bindings/build workspace, and associated tests.
- Tracker/admission/source modifications coupled to that superseded scaffold.
### Confirmed absent and still required
- Real standalone C++ gRPC Shard worker.
- Exact pinned llama.cpp manifest and verified patch stack.
- Range-aware GGUF tensor ownership and real ranged execution.
- Real Shard-local llama.cpp KV/V4 auxiliary state.
- DeepSeek V4 boundary adapter and ranged parity.
- Real multi-machine DeepSeek V4 alpha or beta acceptance.
These remain `passes: false` in DGR-018…071.
## Before-cleanup baseline
Command:
```bash
.venv-rocm/bin/python -m pytest -q \
tests/test_performance_contract.py tests/test_native_shard_protocol.py \
tests/test_gguf_ownership.py tests/test_boundary_adapter.py \
tests/test_hot_kv_state.py tests/test_gguf_backend.py \
tests/test_batch_scheduler.py tests/test_failure_semantics.py \
tests/test_llama_worker_build.py tests/test_node_admission.py \
tests/test_node_capability.py tests/test_tracker_capability_admission.py
```
Result:
```text
216 passed, 2 skipped, 1 failed, 1 warning
```
The failure was a synthetic capability-test helper `KeyError: 'compatibility_fingerprint'`. The warning was a pre-existing heartbeat-thread `SystemExit` warning.
## Cleanup verification
### Source equality
Command:
```bash
git diff --quiet origin/master -- packages tests
```
Result:
```text
packages_tests_match_origin_master=yes
```
The staged cleanup removes approximately 15.3k obsolete source/test/evidence lines from the active branch.
### Cleanup-relevant regression suite
Command:
```bash
.venv-rocm/bin/python -m pytest -q \
tests/test_node_admission.py tests/test_node_capability.py \
tests/test_tracker_capability_admission.py \
tests/test_kv_cache_distributed.py tests/test_real_distributed_inference.py
```
Result:
```text
119 passed, 2 skipped, 1 warning in 15.90s
```
The warning is the same pre-existing heartbeat-thread `SystemExit` warning.
### Known `origin/master` limitations
The wider routing run produced `210 passed, 2 skipped, 4 failed, 1 warning`. Each failure reproduced individually while `packages/` and `tests/` matched `origin/master` exactly:
- `test_tracker_models_endpoint_lists_registered_hf_repo_and_short_name_alias`
- `test_torch_node_applies_tracker_load_shard_directive`
- `test_shard_heal_cycle_surviving_node_covers_dead_peers_gap`
- `test_a_node_with_an_unusable_precision_covers_no_layers`
They are recorded as pre-existing baseline defects and were not repaired or hidden by this cleanup story.
## Dependency handoff
DGR-018 and later stories must start from the cleaned upstream-equivalent runtime tree. Reuse concepts from superseded commits only by explicitly porting the smallest verified slice under the new storys contracts, tests, and evidence gates. Git history is provenance, not completion evidence.

View File

@@ -0,0 +1,83 @@
{
"schema_version": 1,
"executed_at_utc": "2026-07-15T10:41:14Z",
"test_kind": "public-relay-single-node-streaming-smoke-benchmark",
"target": {
"public_chat_endpoint": "https://meshnet.2.d-popov.com/v1/chat/completions",
"relay_url": "wss://meshnet.2.d-popov.com/ws",
"model": "qwen2.5-0.5b-instruct",
"quantization": "bfloat16"
},
"recovery": {
"problem": "The local node's capability proof had expired and its port-7000 HTTP server had wedged with CLOSE-WAIT sockets.",
"action": "Gracefully restarted the local public-tracker meshnet-node process on port 7000.",
"startup_validation": {
"device": "cuda",
"capability_proof_ms": 336,
"node_id": "7j77FsPY-b32476219492",
"relay_addr": "wss://meshnet.2.d-popov.com/rpc/7j77FsPY1evV8tuf-7000"
}
},
"tracker_admission_after_recovery": {
"node_id": "7j77FsPY-b32476219492",
"alive": true,
"status": "ready",
"capability_state": "admitted",
"routable": true,
"route_hops": 1
},
"client_measurements": {
"warmup": {
"http_status": 200,
"ttft_ms": 420.8,
"elapsed_ms": 610.23,
"response_text": "MeshNet Relay Benchmark Passed"
},
"runs": [
{
"run": 1,
"ttft_ms": 376.04,
"elapsed_ms": 458.65,
"response_text": "relay benchmark pass"
},
{
"run": 2,
"ttft_ms": 258.33,
"elapsed_ms": 336.71,
"response_text": "relay benchmark pass"
},
{
"run": 3,
"ttft_ms": 288.26,
"elapsed_ms": 363.2,
"response_text": "relay benchmark pass"
}
],
"p50_ttft_ms": 288.26,
"p50_elapsed_ms": 363.2
},
"tracker_relay_evidence": [
{
"status": 200,
"relay": true,
"node_id": "7j77FsPY-b32476219492",
"tokens": 11,
"elapsed_seconds": 0.1686,
"tokens_per_sec": 65.2541
},
{
"status": 200,
"relay": true,
"node_id": "7j77FsPY-b32476219492",
"tokens": 11,
"elapsed_seconds": 0.1891,
"tokens_per_sec": 58.1799
}
],
"scope_and_remaining_work": {
"validated": "Public HTTPS chat endpoint routed a streaming request through the tracker relay to the local CUDA node and completed with HTTP 200.",
"not_validated": "Two-node shard routing was not run because the remote node 5gMLrmyB-88f5cba044d0 still had an expired capability proof and was not routable.",
"next_gate": "Refresh the remote node capability proof, then load a multi-node-compatible assignment and repeat the benchmark through the public tracker relay."
},
"reproduction": "Use a valid bearer API key with the public /v1/chat/completions endpoint and stream a short qwen2.5-0.5b-instruct request. Do not connect directly to private node HTTP endpoints; the tracker relay is the required path."
}

View File

@@ -0,0 +1,204 @@
# DGR-018 evidence — canonical Ralph and Gitea metadata schema
**Completed:** 2026-07-16
**Branch:** `ralph/distributed-gguf-runtime`
**Authority:** `.scratch/distributed-gguf-runtime/prd.json`
**Dependency:** DGR-017 (`evidence/DGR-017/README.md`) — cleaned backlog reconciled to `origin/master`; no old pass state transferred.
## Objective
Make `prd.json` the validated source from which Markdown (and, later, Gitea) issues
can be generated losslessly, per
`.scratch/distributed-gguf-runtime/issues/018-define-canonical-ralph-and-gitea-metadata-schema.md`.
## Pre-existing state found (not caused by this story)
Before any change in this session, `git status` showed `.scratch/distributed-gguf-runtime/prd.json`
already modified in the working tree relative to `HEAD` (commit `369b207`), with no corresponding
progress-log entry. Diffing against `HEAD` showed the working copy had **dropped** prd.json's
top-level `sourceOfTruth`, `qualityGates`, `metadataSchema`, `milestones`, and `supersededStories`
objects, while `userStories` itself was byte-identical to `HEAD`. This looked like an abandoned,
uncommitted partial edit from a prior session, not intentional current work — those fields are
exactly the schema/quality-gate/audit-provenance content this story depends on, and their loss
wasn't explained by any acceptance criterion. They were restored (see "Changes" below) rather than
silently accepted or discarded, per the instruction to investigate unexplained working-tree state
before building on top of it.
## Changes
### `scripts/ralph_prd_schema.py` (new)
Single module providing:
- **Parse:** `load_prd(path)` — JSON load with clear `PrdValidationError`s for missing file /
invalid JSON / non-object document.
- **Canonical schema registry:** `STORY_FIELDS` (name → required/type), `EXECUTION_MODES`,
`EVIDENCE_CLASSES`, `HARDWARE_FLAGS`, `UPSTREAM_FLAGS`, `TRIAGE_VALUES`. Covers every field named
in the acceptance criteria: stable `id`/`title`, `labels`, `milestone`, derived `type`
(`derive_type`), `dependsOn`, derived `blocks`, `triage`, `evidenceClass`, and
`hardware`/`model`/`upstream` flags.
- **Structural validation:** `validate_schema(data)` — required fields, types, enum membership,
ID convention, `type:`/`priority:` label cardinality, non-empty `acceptanceCriteria`.
- **Semantic validation:** `validate_semantics(data)` — unique IDs, unique titles, `dependsOn`
resolves to known stories (no self-dependency), dependency graph is acyclic (with a reported
cycle path on failure), `blocks` matches the dependency graph exactly (sorted set equality, not
superset), and `evidencePath` matches the per-story convention.
- **Fresh vs. in-progress backlog:** `validate_fresh_backlog(data)` additionally requires every
story to start `passes: false` (for a backlog that hasn't started execution yet);
`validate_backlog(data)` is the composed check for a real, in-flight backlog where some stories
have legitimately completed.
- **Self-consistency check:** `validate_metadata_schema_consistency(data)` — when prd.json declares
its own `metadataSchema`/`qualityGates` (as this one now does), verifies that self-documentation
hasn't drifted from what the validator actually enforces (enum sets, required/optional field
lists, presence of `qualityGates` and `generatedArtifactDisclaimer`). This is a no-op for minimal
fixture PRDs that don't carry that documentation.
- **Generation (one-directional, prd.json → artifact):** `render_issue_markdown(story, data)`
renders the exact Markdown convention already used by
`.scratch/distributed-gguf-runtime/issues/*.md`, sourcing the "Shared quality gates" bullets from
`data["qualityGates"]` and the leading disclaimer from
`data["metadataSchema"]["generatedArtifactDisclaimer"]` (falling back to a module default only
when `data` omits them) — not from a duplicated Python string literal.
`to_gitea_issue_payload(story, data)` wraps the same body into a Gitea create-issue-shaped payload
(`title`, `body`, `labels`, `milestone`).
- **Authority guard:** `check_generated_markdown_authority(text, disclaimer=...)` rejects generated
Markdown that's missing the disclaimer or that contains a conflicting authority claim (e.g. "this
file is authoritative"). There is deliberately no Markdown → prd.json parser, so a generated
artifact structurally cannot feed `passes` (or anything else) back into the authoritative source.
- CLI: `python scripts/ralph_prd_schema.py validate <prd.json> [--fresh]` and
`... render <prd.json> <STORY-ID>`.
### `.scratch/distributed-gguf-runtime/prd.json`
- Restored the top-level `sourceOfTruth`, `qualityGates`, `milestones`, and `supersededStories`
objects to their `HEAD` content (see "Pre-existing state" above); `userStories` was already
identical to `HEAD` and is unchanged in content.
- Extended `metadataSchema` (previously incomplete for this story's own acceptance criteria) with:
`requiredStoryFields` now also lists `notes` and `blocks` (present on all 55 stories); new
`optionalStoryFields: ["completionNotes"]`; new `hardwareValues`/`upstreamValues` enums (`model`
is documented as an open convention, not a closed enum, since quantization/model targets are
dynamic recipe inputs per `RALPH-CONTEXT.md`); new `typeDerivation` and `labelConventions`
(reserved prefixes, cardinality); new `generatedArtifactDisclaimer` (the exact string generated
artifacts must start with); extended `dependencyRules`/`authorityRule` prose to match what the
validator enforces.
- Reworded `sourceOfTruth`'s stale "All stories are unimplemented ... passes=false" clause, which
was no longer accurate once DGR-017 completed.
- Marked `DGR-018.passes = true` with `completionNotes` recording this story's outcome.
### `.scratch/distributed-gguf-runtime/issues/018-define-canonical-ralph-and-gitea-metadata-schema.md`
Regenerated via `render_issue_markdown` to reflect `passes: true` (checked acceptance criteria,
"completed" status line, "Verified evidence" handoff line) — matching the same convention DGR-017's
issue file already used for a completed story.
### `tests/test_ralph_prd_schema.py` (new)
108 deterministic, model-download-free, GPU-free tests:
- **Parse** (4 tests): real backlog parses to 55 stories; missing file, invalid JSON, and
non-object documents raise `PrdValidationError`.
- **Structural/semantic validation against the real backlog** (7 tests): passes `validate_schema`,
`validate_semantics`, and the composed `validate_backlog`; unique IDs/titles; all `dependsOn`
resolve; `blocks` matches the derived dependency graph for all 55 stories; no cycle; every
`passes: true` story carries `completionNotes` and an existing evidence README (a durable
invariant, not a hardcoded list of which stories have completed — that list will keep growing).
- **Structural/semantic failure-mode fixtures** (13 tests): missing required field, bad enum, wrong
type, empty `acceptanceCriteria`, multiple `type:` labels, duplicate ID, duplicate title, unknown
dependency, self-dependency, dependency cycle, mismatched `blocks`, bad `evidencePath`.
- **Fresh-backlog invariant** (3 tests): accepts all-`false`, rejects a premature `passes: true`,
and confirms `validate_backlog` (the in-progress variant) permits completed stories.
- **prd.json-as-source-of-truth for boilerplate** (9 tests): `qualityGates`/`metadataSchema`
self-consistency checks (no-op without them, catches a drifted enum, catches a missing
`qualityGates`), `quality_gate_bullets` flattening order, `authority_disclaimer` precedence and
fallback, and 3 tests asserting the real backlog's declared schema matches the code, its 7
quality-gate bullets are intact, and its disclaimer matches the module default.
- **`derive_type`** (4 tests): label-derived type, release-gate synthetic type for HITL gate
stories, `None` when absent, and confirmation that the real backlog's two release-gate stories
(`DGR-054`, `DGR-070`) derive `release-gate`.
- **Markdown generation round trips** (55 parametrized + 6 tests): `render_issue_markdown` for
every story `DGR-017`..`DGR-071` is byte-for-byte identical to the corresponding file already in
`.scratch/distributed-gguf-runtime/issues/`; determinism; leading disclaimer; `Blocks (derived)`
rendering (`None` vs. listed); checkbox reflects `passes`; filename convention.
- **Authority-claim rejection** (4 tests): accepts real generated text, rejects a missing
disclaimer, rejects an overriding claim, and confirms every committed issue file in
`.scratch/distributed-gguf-runtime/issues/` passes the check.
- **Gitea payload generation** (3 tests): payload shape, body carries no information beyond what's
in prd.json, and every real story's payload is well-formed and authority-clean.
## Commands and results
```bash
python3 -m pytest -q tests/test_ralph_prd_schema.py
```
```text
108 passed in 0.16s
```
```bash
python3 -m compileall -q packages tests
```
Exit code 0, no output (all files compile).
```bash
git diff --check
```
Exit code 0 (no whitespace errors).
```bash
python3 scripts/ralph_prd_schema.py validate .scratch/distributed-gguf-runtime/prd.json
```
```text
OK: 55 stories validated.
```
```bash
python3 scripts/ralph_prd_schema.py validate .scratch/distributed-gguf-runtime/prd.json --fresh
```
```text
ERROR: DGR-017: fresh backlog requires passes=false, got True
ERROR: DGR-018: fresh backlog requires passes=false, got True
2 validation error(s).
```
Expected: `--fresh` is the invariant for a backlog that hasn't started execution; this backlog has
legitimately completed two stories, so it correctly fails that stricter check while passing the
plain (in-progress) `validate` command above.
### Baseline: full repository suite (ad hoc `python3`, not a project venv)
```bash
python3 -m pytest -q
```
```text
20 failed, 776 passed, 13 skipped, 2 warnings in 244.17s (0:04:04)
```
None of the failures touch `scripts/ralph_prd_schema.py` or `tests/test_ralph_prd_schema.py`
(neither file existed before this story; this story adds no changes to `packages/`). Four of the
20 failures reproduce exactly the pre-existing baseline defects DGR-017's evidence already recorded
(`test_tracker_models_endpoint_lists_registered_hf_repo_and_short_name_alias`,
`test_torch_node_applies_tracker_load_shard_directive`,
`test_shard_heal_cycle_surviving_node_covers_dead_peers_gap`,
`test_a_node_with_an_unusable_precision_covers_no_layers`). The remaining 16 (activation
compression, dynamic routing, gossip/relay, manual route benchmark, openai gateway, TOPLoC
calibration dispatch, tracker control plane) include a `ModuleNotFoundError: langchain` failure,
indicating this ad hoc `python3` lacks the project's `dev` extras (`langchain-openai`, etc.) rather
than a real regression; this environment has no project virtualenv (e.g. no `.venv-rocm`) to run
against instead. Not investigated further as out of scope for this story.
## Limitations
- No real Gitea instance or API integration exists; `to_gitea_issue_payload` defines the payload
shape (title/body/labels/milestone) only. Creating issues against a live Gitea server is future
work, not claimed here.
- `model` is intentionally validated as an open string, not a closed enum, per
`RALPH-CONTEXT.md`'s "Quantization and placement are dynamic recipe inputs" constraint; the schema
documents (`metadataSchema.modelConvention`) but does not restrict its value set.
- Validation and generation were exercised only against this feature's `prd.json`
(`.scratch/distributed-gguf-runtime/prd.json`); `docs/prd.json` and other `.scratch/*/prd.json`
files in this repo use a materially different (simpler) shape and are out of scope.
## Dependency handoff
DGR-021 and DGR-025 (this story's derived `blocks`) may treat `prd.json`'s `metadataSchema`,
`qualityGates`, and this validator/generator as stable. Any future field addition to a story shape
must extend `STORY_FIELDS` in `scripts/ralph_prd_schema.py` and the corresponding
`metadataSchema.requiredStoryFields`/`optionalStoryFields` in `prd.json` together —
`validate_metadata_schema_consistency` fails closed if they drift apart.

View File

@@ -1,15 +1,15 @@
# Ralph task evidence
# Distributed GGUF Runtime evidence
Each completed story creates `evidence/<TASK-ID>/README.md`. Fresh dependent iterations must read it before coding.
> **Specification status:** planning artifacts only. No distributed GGUF runtime is implemented. DGR-017 cleanup is complete; no runtime implementation story has completion credit. `prd.json` is authoritative.
Required README sections:
## Authority and classes
1. Summary and acceptance decision.
2. Exact files changed.
3. Commands run and real exit/results.
4. Correctness, performance and hardware evidence classification.
5. Known limitations and deferred work.
6. Compatibility/migration notes.
7. Explicit handoff for each dependent story.
Evidence supports but never overrides `prd.json`. Valid classes are `model-free`, `fixture`, `real-model`, `real-hardware`, and `release`; lower classes cannot satisfy higher-class acceptance. Legacy DGR-001..016 directories remain unchanged for DGR-017 provenance audit and confer no completion credit.
Store raw machine-readable metrics, manifests and protocol artifacts beside the README. Never store secrets, model weights, build outputs or Ralph iteration logs here.
## Future story layout
Each DGR-017..071 story writes `evidence/<ID>/README.md` with summary, exact changed files, exact commands and real outputs, limitations, compatibility/migration notes, and dependent-story handoff. Machine-readable contracts, manifests, metrics, and raw logs live beside it. Never fabricate output.
Real runs record exact model SHA and all split hashes, tokenizer, quant/recipe, llama.cpp pin+patch identity, backend/driver/toolchain, host/hardware/network, commands/environment (without secrets), raw parity/performance/resource results, and evidence class. Models live on configured mounted-drive storage, never `/home`.
Routing certification records prove only the exact exercised backend/model/recipe lane. Compile-only, fixture, failed, or unavailable lanes remain registered-dark. V4 cache/state evidence must show KV and CSA/HCA/SWA/indexer/compressor data remain shard-local/session-keyed; route recovery evidence must show cache miss plus re-prefill/restart, not migration.

View File

@@ -0,0 +1,335 @@
{
"repository": "https://git.d-popov.com/popov/neuron-tai",
"stories": {
"DGR-017": {
"number": 1,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/1",
"state": "closed",
"status": "completed"
},
"DGR-018": {
"number": 2,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/2",
"state": "closed",
"status": "completed"
},
"DGR-019": {
"number": 3,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/3",
"state": "open",
"status": "ready"
},
"DGR-020": {
"number": 4,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/4",
"state": "open",
"status": "blocked"
},
"DGR-021": {
"number": 5,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/5",
"state": "open",
"status": "in-progress"
},
"DGR-022": {
"number": 6,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/6",
"state": "open",
"status": "blocked"
},
"DGR-023": {
"number": 7,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/7",
"state": "open",
"status": "blocked"
},
"DGR-024": {
"number": 8,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/8",
"state": "open",
"status": "blocked"
},
"DGR-025": {
"number": 9,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/9",
"state": "open",
"status": "blocked"
},
"DGR-026": {
"number": 10,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/10",
"state": "open",
"status": "blocked"
},
"DGR-027": {
"number": 11,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/11",
"state": "open",
"status": "ready"
},
"DGR-028": {
"number": 12,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/12",
"state": "open",
"status": "blocked"
},
"DGR-029": {
"number": 13,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/13",
"state": "open",
"status": "blocked"
},
"DGR-030": {
"number": 14,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/14",
"state": "open",
"status": "blocked"
},
"DGR-031": {
"number": 15,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/15",
"state": "open",
"status": "blocked"
},
"DGR-032": {
"number": 16,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/16",
"state": "open",
"status": "blocked"
},
"DGR-033": {
"number": 17,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/17",
"state": "open",
"status": "blocked"
},
"DGR-034": {
"number": 18,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/18",
"state": "open",
"status": "blocked"
},
"DGR-035": {
"number": 19,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/19",
"state": "open",
"status": "blocked"
},
"DGR-036": {
"number": 20,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/20",
"state": "open",
"status": "blocked"
},
"DGR-037": {
"number": 21,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/21",
"state": "open",
"status": "blocked"
},
"DGR-038": {
"number": 22,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/22",
"state": "open",
"status": "blocked"
},
"DGR-039": {
"number": 23,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/23",
"state": "open",
"status": "blocked"
},
"DGR-040": {
"number": 24,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/24",
"state": "open",
"status": "blocked"
},
"DGR-041": {
"number": 25,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/25",
"state": "open",
"status": "blocked"
},
"DGR-042": {
"number": 26,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/26",
"state": "open",
"status": "blocked"
},
"DGR-043": {
"number": 27,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/27",
"state": "open",
"status": "blocked"
},
"DGR-044": {
"number": 28,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/28",
"state": "open",
"status": "blocked"
},
"DGR-045": {
"number": 29,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/29",
"state": "open",
"status": "blocked"
},
"DGR-046": {
"number": 30,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/30",
"state": "open",
"status": "blocked"
},
"DGR-047": {
"number": 31,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/31",
"state": "open",
"status": "blocked"
},
"DGR-048": {
"number": 32,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/32",
"state": "open",
"status": "blocked"
},
"DGR-049": {
"number": 33,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/33",
"state": "open",
"status": "blocked"
},
"DGR-050": {
"number": 34,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/34",
"state": "open",
"status": "blocked"
},
"DGR-051": {
"number": 35,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/35",
"state": "open",
"status": "blocked"
},
"DGR-052": {
"number": 36,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/36",
"state": "open",
"status": "blocked"
},
"DGR-053": {
"number": 37,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/37",
"state": "open",
"status": "blocked"
},
"DGR-054": {
"number": 38,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/38",
"state": "open",
"status": "blocked"
},
"DGR-055": {
"number": 39,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/39",
"state": "open",
"status": "blocked"
},
"DGR-056": {
"number": 40,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/40",
"state": "open",
"status": "blocked"
},
"DGR-057": {
"number": 41,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/41",
"state": "open",
"status": "blocked"
},
"DGR-058": {
"number": 42,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/42",
"state": "open",
"status": "blocked"
},
"DGR-059": {
"number": 43,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/43",
"state": "open",
"status": "blocked"
},
"DGR-060": {
"number": 44,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/44",
"state": "open",
"status": "blocked"
},
"DGR-061": {
"number": 45,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/45",
"state": "open",
"status": "blocked"
},
"DGR-062": {
"number": 46,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/46",
"state": "open",
"status": "blocked"
},
"DGR-063": {
"number": 47,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/47",
"state": "open",
"status": "blocked"
},
"DGR-064": {
"number": 48,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/48",
"state": "open",
"status": "blocked"
},
"DGR-065": {
"number": 49,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/49",
"state": "open",
"status": "blocked"
},
"DGR-066": {
"number": 50,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/50",
"state": "open",
"status": "blocked"
},
"DGR-067": {
"number": 51,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/51",
"state": "open",
"status": "blocked"
},
"DGR-068": {
"number": 52,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/52",
"state": "open",
"status": "blocked"
},
"DGR-069": {
"number": 53,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/53",
"state": "open",
"status": "blocked"
},
"DGR-070": {
"number": 54,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/54",
"state": "open",
"status": "blocked"
},
"DGR-071": {
"number": 55,
"url": "https://git.d-popov.com/popov/neuron-tai/issues/55",
"state": "open",
"status": "blocked"
}
}
}

View File

@@ -1,241 +1,40 @@
# Focused implementation strategy: performant concurrent distributed inference
# Distributed GGUF Runtime implementation strategy
Status: Accepted planning direction
Last updated: 2026-07-13
> **Specification status:** planning artifacts only. No distributed GGUF runtime is implemented. DGR-017 cleanup is complete; no runtime implementation story has completion credit. `prd.json` is authoritative.
## Product objective
## Execution model
Enable clients to run top open models that do not fit on one consumer machine by combining independently owned model Shards into performant, concurrent Inference Routes.
Execute one numerically ordered, dependency-ready story per fresh Ralph context. Read `RALPH-CONTEXT.md`, source issue, and dependency evidence first; use TDD/fixture-first verification; finish with exact evidence. `prd.json` is the only state authority.
The project is not trying to reproduce every vLLM feature or support every inference engine. It is optimizing for:
## Sequence
1. Models larger than one node's RAM/VRAM.
2. Useful interactive decode speed on consumer CPU, AMD, NVIDIA, Vulkan, and mixed routes where certified.
3. Multiple concurrent Route Sessions without cache corruption or global serialization.
4. A lean runtime with one control plane and one primary GGUF engine.
5. Measured improvement over the existing Transformers/safetensors implementation.
1. **M0 DGR-017..020:** reconcile legacy reality, lock metadata/performance contracts, and run the independent whole-model baseline.
2. **M1 DGR-021..033:** protocol/lifecycle/codegen, exact identities and split artifacts, pinned upstream/patches, CPU then accelerator builds, `ShardEngine`, fixtures, fake worker.
3. **M2 DGR-034..043:** dense ranged ownership/boundary/parity/local state, worker integration, supervision/direct-relay, and measured GGUF inputs to unchanged routing.
4. **M3 DGR-044..054:** pin/inventory V4, adapt upstream boundary/local state/MoE/hash execution, pass parity and real 24 scenario, then enforce alpha with MTP off.
5. **M4 DGR-055..067:** batching/backpressure/failure/recovery/long-context, existing-routing 10+ certification, real scale, measured optimization/compression, MTP contract+implementation, hardware certification.
6. **M5 DGR-068..071:** packages, human upstream collaboration, beta gate (including MTP), and pin/patch/certification maintenance.
## Current reality
## Guardrails
The existing project already owns the differentiating distributed control plane:
- Tracker-selected contiguous Shards.
- Stable Route Sessions.
- Local per-Shard Hot KV State in the Transformers reference backend.
- Binary Activation Seams.
- Relay/direct routing, cancellation, telemetry, billing, and capability admission.
- Persistent relay and direct transport optimizations.
## Locked scope
The missing production path is a native GGUF execution worker that can load and execute only an assigned layer range while retaining local Hot KV State for concurrent Route Sessions.
- Existing Meshnet Tracker routing, load balancing, billing, telemetry, relay, and provider semantics are backend-agnostic and are **not redesigned**. GGUF contributes exact compatibility, range/capacity, queue/load, seam-cost, health/reliability, and certification inputs only.
- The data plane is a standalone project-owned C++ Shard worker with gRPC/Protobuf and a project-owned `ShardEngine` boundary.
- llama.cpp is fetched at one exact commit into an ignored workspace from an in-repo manifest, then a numbered minimal patch stack is applied. There is no submodule, vendored tree, or permanent-fork dependency.
- llama.cpp owns DeepSeek V4 graphs, mHC, MoE, attention, hash routing, and kernels. Meshnet adds only range-ownership hooks, typed boundary/local-state adapters, worker integration, and parity/certification.
- Quantization and placement are dynamic recipe inputs. The 24 and 10+ stage layouts are certification scenarios, never product constants.
- Per-shard Hot KV and V4 CSA/HCA/SWA/indexer/compressor state remain local and keyed by route session/epoch. The WAN seam carries the typed mHC 4×4096 residual boundary, positions, token-ID sideband where required, and schema/cache expectations—not per-layer caches.
- Route changes use cache miss plus re-prefill/restart. There is no WAN KV or V4 auxiliary-cache migration.
- CPU/CUDA/ROCm/Vulkan/Metal compile lanes are planned; only exact real-hardware-certified backend/model/recipe lanes may be advertised.
- Alpha requires correctness and the pre-locked useful-speed gate. MTP is reserved and off for alpha; its ownership contract, implementation, and benchmark are required before beta.
Whole-model llama.cpp, vLLM, and existing Transformers serving remain baselines or optional route kinds. They are not substitutes for native distributed Shards.
## Target identities
## Performance hypothesis—not an assumption
- DeepSeek V4 official target SHA: `60d8d70770c6776ff598c94bb586a859a38244f1`.
- llama.cpp V4 support lineage began at PR 24162 / merge `8c146a8366304c871efc26057cc90370ccf58dad`; DGR-027 later pins one exact validated current commit.
- V4 scope: 43 main layers plus MTP; mHC 4×4096 boundary; 256 routed + 1 shared experts with six routed active; token IDs required for the first three hash-routed layers.
- Exact split-GGUF artifacts are provisioned to mounted-drive storage with a complete hashed manifest and resumable verification; no model artifact may be placed under `/home`.
GGUF itself is a format. Performance comes from llama.cpp/GGML's quantized kernels, memory layout, mmap, backend scheduling, and reduced working set.
Quantized GGUF may be faster or may merely fit a larger model. Comparisons against safetensors must report both speed and quality because BF16 safetensors and Q4/Q8 GGUF are not numerically equivalent.
Before expensive native work, establish controlled lanes:
- Same model architecture and upstream revision.
- Same machine, prompt set, context, output length, sampling policy, and concurrency.
- Transformers/safetensors BF16 or the current production recipe.
- llama.cpp GGUF F16/BF16 or Q8 correctness lane where available.
- Q4_K_M or selected production quantization performance/fit lane.
- TTFT, prefill tok/s, decode tok/s, p50/p95 latency, RSS, VRAM, artifact size, energy where available, and output-quality drift.
The program proceeds only if llama.cpp/GGUF provides at least one meaningful advantage recorded in a machine-readable performance contract:
- Better decode or aggregate throughput at acceptable quality; or
- Materially lower memory that makes the target model routable while preserving useful throughput.
## Parallelism we will use
### Public Inference Route: layer/pipeline parallelism
Each node independently executes one contiguous Shard. Activations cross seams; weights and Hot KV State remain local.
This is the only public cross-machine model-parallel primitive in the first runtime.
### Per-node continuous batching
Autoregressive tokens remain sequential within one generation. Throughput comes from batching decode steps from multiple active Route Sessions inside each node using llama.cpp batches and sequence IDs or bounded context pools.
This is essential. A worker that globally serializes sessions is not production-ready.
### Multiple complete routes: data parallelism
The Tracker may select multiple complete routes for independent requests. This increases network throughput and availability without requiring collectives between routes.
### Trusted composite node: optional tensor/expert parallelism
Tensor parallelism and expert parallelism require frequent collectives and tight compatibility. They may be used later inside one operator-controlled composite node or managed cluster exposed as one logical provider. They are not public WAN routing primitives.
### Deferred mechanisms
- Disaggregated prefill and KV transfer.
- Speculative decoding.
- Cross-route prefix snapshots.
- Route repair with KV migration.
- Public tensor/expert parallel collectives.
They remain out of the critical path until the native layer route passes performance and concurrency gates.
## Reuse decisions
### llama.cpp/GGML: primary runtime substrate
Reuse:
- GGUF parsing and mmap.
- Quantized kernels.
- CPU, CUDA, HIP/ROCm, Vulkan, Metal, and other supported backends.
- Tokenizer and model architecture implementations.
- KV and sequence operations.
- Backend scheduler and graph execution.
Maintain a small exact-commit fork only for the missing local seam:
- Range-aware tensor ownership/loading.
- Architecture-defined boundary input/output.
- Intermediate boundary output without tail normalization.
- Layer-filtered KV and sequence mapping.
Keep networking, Tracker logic, billing, and public protocol outside llama.cpp. Upstream generic hooks where possible.
### vLLM: concepts and optional managed backend
Use unmodified vLLM only as:
- A whole-model node backend.
- A managed TP/PP/EP cluster represented as one logical provider.
- A performance/correctness baseline.
Adapt concepts, not runtime code:
- Named intermediate tensor bundles.
- Continuous batching and request-owner maps.
- Versioned KV-transfer compatibility fingerprints.
- Explicit send/receive/abort/failure lifecycle.
- Load telemetry and unbiased route selection.
Do not fork vLLM for public Shards and do not transplant PagedAttention, Torch process groups, or GGUF-plugin kernels into the llama.cpp worker.
### Nakshatra, prima.cpp, llama-gguf, LiGGUF, GPUStack
Use as source and test donors only:
- Nakshatra: partial-GGUF patches, daemon concepts, replay cases.
- prima.cpp: selected tensor ownership and local-layer KV evidence.
- llama-gguf: small protocol and integration-test patterns.
- LiGGUF: Q8 activation transport and tensor-reduction reference.
- historical GPUStack: resource preflight and role-oriented placement.
Do not adopt or fork their repositories wholesale.
## Battle-proven transport decision
Use gRPC over HTTP/2 with Protocol Buffers for the native C++ Shard worker protocol.
Why:
- Mature Python and C++ implementations.
- Bidirectional streaming.
- HTTP/2 flow control and connection reuse.
- Deadlines, cancellation, status codes, TLS, authentication interceptors, and generated schemas.
- Avoids inventing a socket protocol.
Scope boundary:
- OpenAI-compatible client/Gateway APIs remain HTTP/SSE.
- Tracker/control APIs remain existing project interfaces.
- One long-lived bidirectional gRPC stream serves one Route Session Activation Seam.
- Existing relay/WebSocket infrastructure may carry the same versioned protobuf frames as opaque binary when direct gRPC reachability is unavailable.
- Large prefill tensors are chunked into bounded frames; decode bundles stay small.
- No QUIC/WebRTC/custom transport in this milestone.
The public boundary uses a versioned named-tensor bundle rather than one anonymous tensor because architecture boundaries can require more than `hidden_states`.
Minimum identity:
```text
schema version
request/work id
Route Session id and route epoch
Model Artifact and runtime recipe fingerprint
Shard range and effective start
phase: prefill/decode/release/cancel
position/token range
named tensors with shape/dtype/byte order
compression and checksum
idempotency step id
cache expectation/result
```
## Concurrency model
A native worker must not use one global serving sequence or one lock around all model execution.
Required ownership:
```text
(Route Session id, route epoch)
-> local sequence/context
-> Shard-local Hot KV State
-> bounded lease and memory accounting
```
The node scheduler:
- Admits sessions against model memory and KV budget.
- Forms compatible decode batches from active sessions.
- Preserves per-session position and route order.
- Applies bounded queues and backpressure.
- Cancels/releases independently.
- Reports queue, batch, KV, prefill, decode, and seam telemetry.
Initial deterministic gate: at least four concurrent sessions on a small certified model with no token/KV cross-talk. Final concurrency targets are hardware/recipe-specific and recorded by capability admission rather than hardcoded globally.
## Stage gates
### Gate A: performance hypothesis
Controlled safetensors-versus-GGUF benchmark produces a signed/reproducible report and locks thresholds. Stop native work if there is no meaningful speed or fit benefit.
### Gate B: local range parity
Two local processes own disjoint GGUF ranges and match whole-model llama.cpp within the certified numerical tolerance for prefill and greedy decode.
### Gate C: concurrent KV
Multiple Route Sessions prefill/decode concurrently with isolated local KV, bounded memory, cancellation, and release.
### Gate D: real distributed route
Two physical machines execute one model that uses both Shards. Synthetic activation tests do not satisfy this gate.
### Gate E: consumer-hardware performance
On certified consumer hardware, the GGUF route beats the current distributed safetensors route under the locked performance contract or enables a larger otherwise-unroutable model at useful measured speed.
### Gate F: architecture expansion
Only after dense Llama-family gates pass, add an explicit Qwen3/Qwen3-MoE adapter and certify it independently.
## Scope discipline
The following do not block the first production candidate:
- New cryptocurrency/economics work.
- New artifact P2P protocol.
- QUIC or WebRTC.
- vLLM fork.
- Whole-repository Nakshatra/prima adoption.
- Every GGUF architecture.
- Automatic route repair.
- Prefix snapshot migration.
- Speculative decoding.
- A large-model marketing demo before small-model parity and concurrency pass.
Every optimization must preserve output contract, session isolation, cancellation, resource cleanup, capability admission, and per-node attribution.
DGR-020 cannot use distributed results. DGR-054 does not depend on MTP. DGR-070 depends on DGR-066. Compile support and scenario success never imply general routability.

View File

@@ -1,59 +0,0 @@
# 01 — Lock the safetensors-versus-GGUF performance contract
Status: ready-for-agent
## Mandatory fresh-session context
- Read [RALPH-CONTEXT.md](../RALPH-CONTEXT.md) completely before changing code.
- This issue is `DGR-001` in [prd.json](../prd.json).
- Read the evidence README for every dependency listed below.
- Inspect current code and `git status`; historical text and previous agent claims are not evidence.
## Description
As a runtime engineer, I need a controlled baseline so that GGUF work proceeds from measured speed, memory, and quality rather than reputation.
## Expected durable outputs
- Benchmark harness and deterministic tests
- evidence/DGR-001/performance-contract.json
- Raw and summarized safetensors/GGUF benchmark evidence
## Acceptance criteria
- [ ] Benchmark the same model architecture/revision, machine, prompts, context lengths, output lengths, sampling policy, and concurrency across the current Transformers/safetensors recipe and whole-model llama.cpp recipes.
- [ ] Separate correctness/quality lanes from quantized performance/fit lanes instead of claiming BF16 and Q4 are numerically equivalent.
- [ ] Report TTFT, prefill tok/s, decode tok/s, p50/p95 latency, aggregate throughput, RSS, VRAM, artifact size, failures, and output drift in machine-readable JSON.
- [ ] Add concurrency levels 1 and 4 where memory permits.
- [ ] Write a versioned performance contract consumed by later release gates, including an explicit stop condition when llama.cpp/GGUF has no meaningful speed or fit benefit.
- [ ] Targeted pytest tests pass
- [ ] python -m compileall packages tests passes for Python changes
- [ ] git diff --check passes
- [ ] Default tests remain deterministic, model-download-free, API-credit-free, and GPU-free
- [ ] Full deterministic pytest -q passes, or the exact pre-existing unrelated failure is recorded with a clean-tree reproduction
- [ ] Real-model execution is opt-in through MESHNET_ENABLE_REAL_INFERENCE_TESTS=1 and records exact artifact/runtime/hardware evidence
- [ ] Model artifacts remain on the configured mounted-drive storage and never under /home
- [ ] Read .scratch/distributed-gguf-runtime/RALPH-CONTEXT.md and this story issue completely before changing code
- [ ] Read and verify every dependency evidence README before relying on dependency behavior
- [ ] Preserve all pre-existing working-tree changes and stage only files belonging to this story
- [ ] Write .scratch/distributed-gguf-runtime/evidence/DGR-001/README.md with files changed, exact commands and real results, limitations, compatibility notes, and dependent-story handoff
- [ ] Update only this story issue to Status: done after every acceptance criterion and quality gate passes
## Dependency handoff
- None. This story may start immediately.
## Finish contract
- Create the task evidence directory and durable handoff required above.
- Preserve real failures and blockers; never fabricate benchmark, model, test or hardware output.
- Change this issue to `Status: done` only after all criteria pass.
- Emit `<promise>COMPLETE</promise>` only after the evidence handoff exists.
## References
- [Ralph execution context](../RALPH-CONTEXT.md)
- [PRD](../PRD.md)
- [Implementation strategy](../implementation-strategy.md)
- [Current architecture](../architecture.md)
- [Architecture decision](../../docs/adr/0024-distributed-gguf-runtime.md)

View File

@@ -0,0 +1,39 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-017: Reconcile and clean the superseded DGR backlog
- **Status / triage:** completed; `passes: true`
- **Execution mode:** `AFK`
- **Milestone:** `M0`
- **Dependencies:** None
- **Blocks (derived):** `DGR-018`, `DGR-019`, `DGR-027`, `DGR-054`
- **Labels:** `area:provenance`, `area:cleanup`, `type:audit`, `priority:p0`, `ready-for-agent`
- **Evidence class:** `model-free`
- **Hardware:** `none`
- **Model:** `generic`
- **Upstream:** `no`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/017-reconcile-and-clean-the-superseded-dgr-backlog.md`, and evidence READMEs for dependencies (none) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Audit implementation reality, void inherited completion credit, and clean misleading backlog/stub baggage while preserving attributable evidence and accepted research.
## Acceptance criteria
- [x] Compare the branch, old DGR-001..016 issue/pass states, evidence, and actual runtime sources; classify each output as reusable, reference-only, blocked, obsolete, or absent.
- [x] Record an authoritative old-to-new disposition and provenance; explicitly give no completion credit to any new story and note absent implementation/evidence.
- [x] Remove or archive only artifacts the audit proves obsolete while preserving accepted ADRs, useful research, raw benchmark evidence, and attributable reusable work.
- [x] Protect ignored build workspaces, generated protobuf outputs, Ralph logs, and model artifacts from accidental commits, and document every retained legacy artifact.
- [x] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Verified evidence: `.scratch/distributed-gguf-runtime/evidence/DGR-017/README.md`. Legacy evidence remains provenance only and grants no implementation completion credit.

View File

@@ -0,0 +1,39 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-018: Define canonical Ralph and Gitea metadata schema
- **Status / triage:** completed; `passes: true`
- **Execution mode:** `AFK`
- **Milestone:** `M0`
- **Dependencies:** `DGR-017`
- **Blocks (derived):** `DGR-021`, `DGR-025`
- **Labels:** `area:planning`, `area:gitea`, `type:infrastructure`, `priority:p0`, `ready-for-agent`
- **Evidence class:** `model-free`
- **Hardware:** `none`
- **Model:** `generic`
- **Upstream:** `no`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/018-define-canonical-ralph-and-gitea-metadata-schema.md`, and evidence READMEs for dependencies (DGR-017) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Make `prd.json` the validated source from which Markdown and Gitea issues can later be generated losslessly.
## Acceptance criteria
- [x] Define fields for stable ID/title, labels, milestone, type, `dependsOn`, derived `blocks`, triage, evidence class, and hardware/model/upstream flags.
- [x] Validate that all stories start `passes: false`, use known dependencies, and have unique stable IDs.
- [x] Reject cycles, missing dependencies, mismatched generated `blocks`, duplicate titles/IDs, and generated artifacts claiming authority over `prd.json`.
- [x] Add deterministic model-free tests for parse, validation, and generation round trips.
- [x] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Verified evidence: `.scratch/distributed-gguf-runtime/evidence/DGR-018/README.md`. Legacy evidence remains provenance only and grants no implementation completion credit.

View File

@@ -0,0 +1,40 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-019: Lock alpha and beta performance contracts
- **Status / triage:** specification only; `ready-for-human`; `passes: false`
- **Execution mode:** `HITL`
- **Milestone:** `M0`
- **Dependencies:** `DGR-017`
- **Blocks (derived):** `DGR-020`, `DGR-044`, `DGR-054`
- **Labels:** `area:performance`, `type:contract`, `priority:p0`, `gate:hitl`, `ready-for-human`
- **Evidence class:** `release`
- **Hardware:** `required`
- **Model:** `generic+deepseek-v4`
- **Upstream:** `no`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/019-lock-alpha-and-beta-performance-contracts.md`, and evidence READMEs for dependencies (DGR-017) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Freeze useful speed, correctness, memory-fit, and stop/go thresholds before implementation results are visible.
## Acceptance criteria
- [ ] Define controlled safetensors, whole-model GGUF, dense distributed GGUF, and V4 Flash distributed lanes with fixed prompts, context/output lengths, sampling, concurrency, hardware, and metrics.
- [ ] Alpha requires correctness plus a human-approved useful-speed threshold; beta adds concurrency, long-context, failure, and sustained-throughput thresholds.
- [ ] Separate quantization/model-fit gains from runtime, transport, batching, and kernel gains.
- [ ] Treat quants and 24/10+ stage counts only as named certification scenarios; no product logic may hardcode them.
- [ ] Lock thresholds and stop conditions in versioned machine-readable data before benchmark result ingestion.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Write and verify `.scratch/distributed-gguf-runtime/evidence/DGR-019/README.md`. Until every criterion and applicable gate has real evidence, this story remains `passes: false`. Legacy evidence is provenance only, not completion credit.

View File

@@ -1,59 +0,0 @@
# 02 — Adopt the versioned gRPC Shard protocol
Status: ready-for-agent
## Mandatory fresh-session context
- Read [RALPH-CONTEXT.md](../RALPH-CONTEXT.md) completely before changing code.
- This issue is `DGR-002` in [prd.json](../prd.json).
- Read the evidence README for every dependency listed below.
- Inspect current code and `git status`; historical text and previous agent claims are not evidence.
## Description
As a node developer, I need a battle-proven streaming protocol so that Python and C++ Shards communicate without a custom socket protocol.
## Expected durable outputs
- packages/node/native/proto/shard_runtime.proto
- Reproducible Python/C++ schema generation and build wiring
- Protocol round-trip and compatibility tests
- evidence/DGR-002/README.md
## Acceptance criteria
- [ ] Add a Protocol Buffers schema for capability, health, session stream, release, and cancellation operations.
- [ ] Define one long-lived bidirectional gRPC stream per Route Session Activation Seam with deadlines, cancellation, flow control, and structured errors.
- [ ] Define bounded chunking for prefill and a small decode fast path.
- [ ] Carry schema version, request/work ID, Route Session ID, route epoch, artifact/recipe fingerprint, Shard range/effective start, phase, position, idempotency step, cache expectation, compression, and checksum.
- [ ] Define a versioned named-tensor bundle with per-tensor name, shape, dtype, byte order, and payload fragments.
- [ ] Add generated-schema round-trip and compatibility tests in Python and C++.
- [ ] Targeted pytest tests pass
- [ ] python -m compileall packages tests passes for Python changes
- [ ] git diff --check passes
- [ ] Default tests remain deterministic, model-download-free, API-credit-free, and GPU-free
- [ ] Full deterministic pytest -q passes, or the exact pre-existing unrelated failure is recorded with a clean-tree reproduction
- [ ] Read .scratch/distributed-gguf-runtime/RALPH-CONTEXT.md and this story issue completely before changing code
- [ ] Read and verify every dependency evidence README before relying on dependency behavior
- [ ] Preserve all pre-existing working-tree changes and stage only files belonging to this story
- [ ] Write .scratch/distributed-gguf-runtime/evidence/DGR-002/README.md with files changed, exact commands and real results, limitations, compatibility notes, and dependent-story handoff
- [ ] Update only this story issue to Status: done after every acceptance criterion and quality gate passes
## Dependency handoff
- None. This story may start immediately.
## Finish contract
- Create the task evidence directory and durable handoff required above.
- Preserve real failures and blockers; never fabricate benchmark, model, test or hardware output.
- Change this issue to `Status: done` only after all criteria pass.
- Emit `<promise>COMPLETE</promise>` only after the evidence handoff exists.
## References
- [Ralph execution context](../RALPH-CONTEXT.md)
- [PRD](../PRD.md)
- [Implementation strategy](../implementation-strategy.md)
- [Current architecture](../architecture.md)
- [Architecture decision](../../docs/adr/0024-distributed-gguf-runtime.md)

View File

@@ -0,0 +1,39 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-020: Run the controlled whole-model GGUF baseline
- **Status / triage:** specification only; `ready-for-human`; `passes: false`
- **Execution mode:** `HITL`
- **Milestone:** `M0`
- **Dependencies:** `DGR-019`
- **Blocks (derived):** `DGR-054`
- **Labels:** `area:performance`, `type:benchmark`, `priority:p0`, `gate:hitl`, `ready-for-human`
- **Evidence class:** `real-hardware`
- **Hardware:** `required`
- **Model:** `generic`
- **Upstream:** `no`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/020-run-the-controlled-whole-model-gguf-baseline.md`, and evidence READMEs for dependencies (DGR-019) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Execute the locked safetensors and whole-model llama.cpp lanes before distributed implementation results can influence the decision.
## Acceptance criteria
- [ ] Run the exact DGR-019 safetensors and whole-model llama.cpp benchmark lanes with locked prompts, lengths, sampling, concurrency, hardware, and artifact/runtime identities.
- [ ] Record raw machine-readable correctness, TTFT, prefill/decode, throughput, latency, memory, artifact-size, failure, and quality-drift metrics without ingesting distributed implementation results.
- [ ] Separate quantization/model-fit effects from runtime/kernel effects and preserve failed or unavailable lanes honestly.
- [ ] Publish a threshold-based `go`, `optimize baseline`, or `stop` decision without changing the locked contract.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Write and verify `.scratch/distributed-gguf-runtime/evidence/DGR-020/README.md`. Until every criterion and applicable gate has real evidence, this story remains `passes: false`. Legacy evidence is provenance only, not completion credit.

View File

@@ -0,0 +1,39 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-021: Define the versioned named-tensor stream envelope
- **Status / triage:** specification only; `ready-for-agent`; `passes: false`
- **Execution mode:** `AFK`
- **Milestone:** `M1`
- **Dependencies:** `DGR-018`
- **Blocks (derived):** `DGR-022`, `DGR-023`, `DGR-025`, `DGR-031`, `DGR-035`, `DGR-046`
- **Labels:** `area:protocol`, `type:infrastructure`, `priority:p0`, `ready-for-agent`
- **Evidence class:** `model-free`
- **Hardware:** `none`
- **Model:** `generic`
- **Upstream:** `no`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/021-define-the-versioned-named-tensor-stream-envelope.md`, and evidence READMEs for dependencies (DGR-018) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Establish the backend-neutral protobuf envelope used by direct and relayed Shard activation traffic.
## Acceptance criteria
- [ ] Define schema version, request/work ID, route session/epoch, shard range/effective start, phase, position, and idempotency step.
- [ ] Define named tensors with shape, dtype, byte order, bounded fragments, compression identity, and checksum.
- [ ] Reserve extensible fields for token-ID sidebands, architecture state, recurrent state, and MTP without claiming implementations.
- [ ] Add deterministic serialization, fragmentation, checksum, unknown-field, and size-limit tests.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Write and verify `.scratch/distributed-gguf-runtime/evidence/DGR-021/README.md`. Until every criterion and applicable gate has real evidence, this story remains `passes: false`. Legacy evidence is provenance only, not completion credit.

View File

@@ -0,0 +1,39 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-022: Define Shard lifecycle and structured status RPCs
- **Status / triage:** specification only; `ready-for-agent`; `passes: false`
- **Execution mode:** `AFK`
- **Milestone:** `M1`
- **Dependencies:** `DGR-021`
- **Blocks (derived):** `DGR-024`, `DGR-033`, `DGR-037`
- **Labels:** `area:protocol`, `area:lifecycle`, `type:infrastructure`, `priority:p0`, `ready-for-agent`
- **Evidence class:** `model-free`
- **Hardware:** `none`
- **Model:** `generic`
- **Upstream:** `no`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/022-define-shard-lifecycle-and-structured-status-rpcs.md`, and evidence READMEs for dependencies (DGR-021) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Complete the gRPC contract for worker capability, health, sessions, cancellation, release, and metrics.
## Acceptance criteria
- [ ] Define capability, health, bidirectional session stream, cancellation, release, and metrics RPCs.
- [ ] Specify deadlines, cancellation propagation, bounded flow control, cache expectations/results, and structured error taxonomy.
- [ ] Specify TLS/auth hooks without moving Meshnet authentication or billing into the worker.
- [ ] Add compatibility tests for supported versions and fail-closed tests for unsupported versions and malformed lifecycle transitions.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Write and verify `.scratch/distributed-gguf-runtime/evidence/DGR-022/README.md`. Until every criterion and applicable gate has real evidence, this story remains `passes: false`. Legacy evidence is provenance only, not completion credit.

View File

@@ -0,0 +1,39 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-023: Make Python and C++ protobuf generation reproducible
- **Status / triage:** specification only; `ready-for-agent`; `passes: false`
- **Execution mode:** `AFK`
- **Milestone:** `M1`
- **Dependencies:** `DGR-021`
- **Blocks (derived):** `DGR-024`, `DGR-037`
- **Labels:** `area:protocol`, `area:build`, `type:tooling`, `priority:p0`, `ready-for-agent`
- **Evidence class:** `model-free`
- **Hardware:** `none`
- **Model:** `generic`
- **Upstream:** `no`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/023-make-python-and-c-protobuf-generation-reproducible.md`, and evidence READMEs for dependencies (DGR-021) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Generate identical Python/C++ protocol bindings without manual copying or checked-in build debris.
## Acceptance criteria
- [ ] Pin protoc, gRPC, and plugin versions or declare a verified compatible range.
- [ ] Generate Python and C++ bindings into out-of-tree build/package locations through documented commands.
- [ ] Add Python↔C++ round-trip and descriptor compatibility tests.
- [ ] A clean checkout regenerates bindings deterministically or fails with an actionable toolchain error.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Write and verify `.scratch/distributed-gguf-runtime/evidence/DGR-023/README.md`. Until every criterion and applicable gate has real evidence, this story remains `passes: false`. Legacy evidence is provenance only, not completion credit.

View File

@@ -0,0 +1,39 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-024: Implement in-memory fake gRPC seam transport
- **Status / triage:** specification only; `ready-for-agent`; `passes: false`
- **Execution mode:** `AFK`
- **Milestone:** `M1`
- **Dependencies:** `DGR-022`, `DGR-023`
- **Blocks (derived):** `DGR-033`, `DGR-042`
- **Labels:** `area:protocol`, `area:testing`, `type:vertical-slice`, `priority:p0`, `ready-for-agent`
- **Evidence class:** `fixture`
- **Hardware:** `none`
- **Model:** `fake`
- **Upstream:** `no`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/024-implement-in-memory-fake-grpc-seam-transport.md`, and evidence READMEs for dependencies (DGR-022, DGR-023) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Exercise the complete streaming protocol deterministically before a real model or worker exists.
## Acceptance criteria
- [ ] Provide a fake bidirectional stream supporting prefill fragments, decode fast-path frames, release, cancel, and structured errors.
- [ ] Test flow-control blocking, deadlines, malformed fragments, checksum failure, duplicates, and stale epochs.
- [ ] Verify direct and opaque-relay framing preserve identical protobuf bytes.
- [ ] Tests require no sockets outside localhost, model downloads, or native accelerator.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Write and verify `.scratch/distributed-gguf-runtime/evidence/DGR-024/README.md`. Until every criterion and applicable gate has real evidence, this story remains `passes: false`. Legacy evidence is provenance only, not completion credit.

View File

@@ -0,0 +1,39 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-025: Define exact artifact and runtime recipe identity
- **Status / triage:** specification only; `ready-for-agent`; `passes: false`
- **Execution mode:** `AFK`
- **Milestone:** `M1`
- **Dependencies:** `DGR-018`, `DGR-021`
- **Blocks (derived):** `DGR-026`, `DGR-031`, `DGR-041`, `DGR-044`
- **Labels:** `area:identity`, `area:admission`, `type:domain`, `priority:p0`, `ready-for-agent`
- **Evidence class:** `model-free`
- **Hardware:** `none`
- **Model:** `generic`
- **Upstream:** `no`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/025-define-exact-artifact-and-runtime-recipe-identity.md`, and evidence READMEs for dependencies (DGR-018, DGR-021) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Ensure the tracker and worker only combine numerically and operationally compatible shards.
## Acceptance criteria
- [ ] Fingerprint source artifact SHA, tokenizer revision, architecture adapter/version, boundary schema, runtime pin/patch stack, backend, quant, activation/compute dtype, and KV/state layout.
- [ ] Bind each shard to an exact half-open range without hardcoding a topology or quant.
- [ ] Fail closed on any artifact, adapter, boundary, cache, backend, or runtime mismatch.
- [ ] Unsupported recipes remain registered-but-dark until real-hardware evidence certifies them.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Write and verify `.scratch/distributed-gguf-runtime/evidence/DGR-025/README.md`. Until every criterion and applicable gate has real evidence, this story remains `passes: false`. Legacy evidence is provenance only, not completion credit.

View File

@@ -0,0 +1,39 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-026: Provision exact split-GGUF artifacts outside /home
- **Status / triage:** specification only; `ready-for-agent`; `passes: false`
- **Execution mode:** `AFK`
- **Milestone:** `M1`
- **Dependencies:** `DGR-025`
- **Blocks (derived):** `DGR-044`, `DGR-045`
- **Labels:** `area:artifacts`, `area:provenance`, `type:tooling`, `priority:p0`, `ready-for-agent`
- **Evidence class:** `fixture`
- **Hardware:** `none`
- **Model:** `generic`
- **Upstream:** `no`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/026-provision-exact-split-gguf-artifacts-outside-home.md`, and evidence READMEs for dependencies (DGR-025) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Make exact split-GGUF inputs reproducibly available from mounted-drive storage without embedding a quantization or topology assumption in product code.
## Acceptance criteria
- [ ] Create an exact manifest that binds the source artifact, tokenizer/revision, every split file name, size, range/role, and cryptographic hash.
- [ ] Provide resumable, hash-verifying download/provision tooling targeting configured mounted-drive storage; refuse paths under `/home` and incomplete or mismatched splits.
- [ ] Keep quantization and split topology as manifest/recipe inputs with no hardcoded quant, node count, or range layout.
- [ ] Add deterministic model-download-free tests using tiny local split fixtures, including interrupted resume, missing split, hash mismatch, and `/home` rejection.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Write and verify `.scratch/distributed-gguf-runtime/evidence/DGR-026/README.md`. Until every criterion and applicable gate has real evidence, this story remains `passes: false`. Legacy evidence is provenance only, not completion credit.

View File

@@ -0,0 +1,39 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-027: Add exact llama.cpp provenance manifest and fetch workspace
- **Status / triage:** specification only; `ready-for-agent`; `passes: false`
- **Execution mode:** `AFK`
- **Milestone:** `M1`
- **Dependencies:** `DGR-017`
- **Blocks (derived):** `DGR-028`, `DGR-029`, `DGR-044`
- **Labels:** `area:upstream`, `area:build`, `type:provenance`, `priority:p0`, `ready-for-agent`
- **Evidence class:** `model-free`
- **Hardware:** `none`
- **Model:** `generic`
- **Upstream:** `yes`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/027-add-exact-llama-cpp-provenance-manifest-and-fetch-workspace.md`, and evidence READMEs for dependencies (DGR-017) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Pin llama.cpp exactly through an in-repo manifest while fetching source only into an ignored build workspace.
## Acceptance criteria
- [ ] Manifest records upstream URL, exact commit, expected source archive/tree hash, license, and retrieval method.
- [ ] Fetch tooling verifies identity before use and refuses an unpinned branch/tag.
- [ ] Source is fetched into an ignored build workspace; no submodule, vendored source tree, or permanent fork is introduced.
- [ ] Offline reuse is supported only after the cached trees exact identity is verified.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Write and verify `.scratch/distributed-gguf-runtime/evidence/DGR-027/README.md`. Until every criterion and applicable gate has real evidence, this story remains `passes: false`. Legacy evidence is provenance only, not completion credit.

View File

@@ -0,0 +1,39 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-028: Implement numbered patch-stack apply and verification
- **Status / triage:** specification only; `ready-for-agent`; `passes: false`
- **Execution mode:** `AFK`
- **Milestone:** `M1`
- **Dependencies:** `DGR-027`
- **Blocks (derived):** `DGR-029`, `DGR-034`, `DGR-069`
- **Labels:** `area:upstream`, `area:patches`, `type:tooling`, `priority:p0`, `ready-for-agent`
- **Evidence class:** `model-free`
- **Hardware:** `none`
- **Model:** `generic`
- **Upstream:** `yes`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/028-implement-numbered-patch-stack-apply-and-verification.md`, and evidence READMEs for dependencies (DGR-027) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Maintain a minimal auditable llama.cpp delta with one numbered patch per concern.
## Acceptance criteria
- [ ] Add deterministic apply/check/reverse verification against the exact manifest pin.
- [ ] Separate range loading, boundary I/O, filtered state, and worker hooks into scoped patches.
- [ ] Record upstream file/API assumptions and fail with the first incompatible patch when the pin changes.
- [ ] Verify license/attribution and prove no Meshnet routing, billing, relay, or authentication code enters the patch stack.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Write and verify `.scratch/distributed-gguf-runtime/evidence/DGR-028/README.md`. Until every criterion and applicable gate has real evidence, this story remains `passes: false`. Legacy evidence is provenance only, not completion credit.

View File

@@ -0,0 +1,39 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-029: Create the native CMake skeleton and deterministic CPU lane
- **Status / triage:** specification only; `ready-for-agent`; `passes: false`
- **Execution mode:** `AFK`
- **Milestone:** `M1`
- **Dependencies:** `DGR-027`, `DGR-028`
- **Blocks (derived):** `DGR-030`, `DGR-034`
- **Labels:** `area:build`, `type:toolchain`, `priority:p0`, `ready-for-agent`
- **Evidence class:** `model-free`
- **Hardware:** `none`
- **Model:** `generic`
- **Upstream:** `yes`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/029-create-the-native-cmake-skeleton-and-deterministic-cpu-lane.md`, and evidence READMEs for dependencies (DGR-027, DGR-028) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Establish an out-of-tree standalone native build with a deterministic CPU lane before accelerator matrix work.
## Acceptance criteria
- [ ] Create the standalone native CMake target/skeleton and isolated out-of-tree configure/build preset for CPU.
- [ ] Build and run a deterministic model-free CPU smoke/CTest lane from a clean checkout with actionable toolchain failures.
- [ ] Keep fetched upstream sources, generated bindings, and all build outputs ignored and out of tree.
- [ ] Ensure build success alone does not advertise any backend/model/recipe capability.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Write and verify `.scratch/distributed-gguf-runtime/evidence/DGR-029/README.md`. Until every criterion and applicable gate has real evidence, this story remains `passes: false`. Legacy evidence is provenance only, not completion credit.

View File

@@ -1,57 +0,0 @@
# 03 — Define exact Artifact and runtime recipe identity
Status: ready-for-agent
## Mandatory fresh-session context
- Read [RALPH-CONTEXT.md](../RALPH-CONTEXT.md) completely before changing code.
- This issue is `DGR-003` in [prd.json](../prd.json).
- Read the evidence README for every dependency listed below.
- Inspect current code and `git status`; historical text and previous agent claims are not evidence.
## Description
As the Tracker, I need exact compatibility identity so that only numerically and operationally compatible Shards form an Inference Route.
## Expected durable outputs
- Exact runtime recipe/fingerprint implementation
- Tracker/node fail-closed admission tests
- evidence/DGR-003/README.md
## Acceptance criteria
- [ ] Separate weight quantization, activation dtype, compute dtype, KV dtype/layout, tokenizer revision, architecture adapter, backend, and runtime version.
- [ ] Bind derivative or split artifacts to an exact source Model Artifact hash and Shard range.
- [ ] Produce a stable compatibility fingerprint used by capability admission and the gRPC handshake.
- [ ] Fail closed on mismatched artifact, tokenizer, architecture, range, boundary schema, activation recipe, or cache layout.
- [ ] Keep unsupported recipes registered-but-dark until a real distributed forward certifies them.
- [ ] Targeted pytest tests pass
- [ ] python -m compileall packages tests passes for Python changes
- [ ] git diff --check passes
- [ ] Default tests remain deterministic, model-download-free, API-credit-free, and GPU-free
- [ ] Full deterministic pytest -q passes, or the exact pre-existing unrelated failure is recorded with a clean-tree reproduction
- [ ] Read .scratch/distributed-gguf-runtime/RALPH-CONTEXT.md and this story issue completely before changing code
- [ ] Read and verify every dependency evidence README before relying on dependency behavior
- [ ] Preserve all pre-existing working-tree changes and stage only files belonging to this story
- [ ] Write .scratch/distributed-gguf-runtime/evidence/DGR-003/README.md with files changed, exact commands and real results, limitations, compatibility notes, and dependent-story handoff
- [ ] Update only this story issue to Status: done after every acceptance criterion and quality gate passes
## Dependency handoff
- `DGR-002` must have `passes: true`; read `../evidence/DGR-002/README.md` and verify its referenced files/commands.
## Finish contract
- Create the task evidence directory and durable handoff required above.
- Preserve real failures and blockers; never fabricate benchmark, model, test or hardware output.
- Change this issue to `Status: done` only after all criteria pass.
- Emit `<promise>COMPLETE</promise>` only after the evidence handoff exists.
## References
- [Ralph execution context](../RALPH-CONTEXT.md)
- [PRD](../PRD.md)
- [Implementation strategy](../implementation-strategy.md)
- [Current architecture](../architecture.md)
- [Architecture decision](../../docs/adr/0024-distributed-gguf-runtime.md)

View File

@@ -0,0 +1,39 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-030: Add accelerator build presets and native CI matrix
- **Status / triage:** specification only; `ready-for-agent`; `passes: false`
- **Execution mode:** `AFK`
- **Milestone:** `M1`
- **Dependencies:** `DGR-029`
- **Blocks (derived):** `DGR-053`, `DGR-067`, `DGR-068`
- **Labels:** `area:build`, `area:hardware`, `type:toolchain`, `priority:p0`, `ready-for-agent`
- **Evidence class:** `model-free`
- **Hardware:** `optional`
- **Model:** `generic`
- **Upstream:** `yes`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/030-add-accelerator-build-presets-and-native-ci-matrix.md`, and evidence READMEs for dependencies (DGR-029) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Compile all required accelerator lanes reproducibly while keeping untested real-hardware capabilities registered-dark.
## Acceptance criteria
- [ ] Add isolated out-of-tree presets for CUDA, ROCm, Vulkan, and Metal without changing the deterministic CPU default.
- [ ] Add a native CI/build matrix that reports unavailable SDKs as explicit unavailable/skipped lanes rather than false success.
- [ ] Compile each available lane and preserve exact compiler, SDK, upstream pin, patch-stack, and build-option evidence.
- [ ] Keep every backend/model/recipe lane registered-dark until a separate real-hardware certification record exists.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Write and verify `.scratch/distributed-gguf-runtime/evidence/DGR-030/README.md`. Until every criterion and applicable gate has real evidence, this story remains `passes: false`. Legacy evidence is provenance only, not completion credit.

View File

@@ -0,0 +1,39 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-031: Introduce the project-owned `ShardEngine` interface
- **Status / triage:** specification only; `ready-for-agent`; `passes: false`
- **Execution mode:** `AFK`
- **Milestone:** `M1`
- **Dependencies:** `DGR-021`, `DGR-025`
- **Blocks (derived):** `DGR-032`, `DGR-034`, `DGR-035`, `DGR-037`
- **Labels:** `area:engine`, `type:architecture`, `priority:p0`, `ready-for-agent`
- **Evidence class:** `model-free`
- **Hardware:** `none`
- **Model:** `generic`
- **Upstream:** `no`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/031-introduce-the-project-owned-shardengine-interface.md`, and evidence READMEs for dependencies (DGR-021, DGR-025) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Isolate worker/protocol code from llama.cpp internals behind a stable project-owned engine contract.
## Acceptance criteria
- [ ] Define load, capabilities, prefill/decode, boundary/logits result, cancel, release, health, and metrics operations.
- [ ] Use project-owned request/result/state types; expose no `ggml_tensor`, llama context, scheduler, or ABI-owned structure.
- [ ] Reserve typed MTP and architecture auxiliary-state hooks without enabling them.
- [ ] Add contract tests proving fake and future llama implementations obey identical lifecycle semantics.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Write and verify `.scratch/distributed-gguf-runtime/evidence/DGR-031/README.md`. Until every criterion and applicable gate has real evidence, this story remains `passes: false`. Legacy evidence is provenance only, not completion credit.

View File

@@ -0,0 +1,39 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-032: Implement deterministic fake `ShardEngine`
- **Status / triage:** specification only; `ready-for-agent`; `passes: false`
- **Execution mode:** `AFK`
- **Milestone:** `M1`
- **Dependencies:** `DGR-031`
- **Blocks (derived):** `DGR-033`
- **Labels:** `area:engine`, `area:testing`, `type:fixture`, `priority:p0`, `ready-for-agent`
- **Evidence class:** `fixture`
- **Hardware:** `none`
- **Model:** `fake`
- **Upstream:** `no`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/032-implement-deterministic-fake-shardengine.md`, and evidence READMEs for dependencies (DGR-031) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Provide an engine fixture that deterministically transforms typed boundary bundles and session state.
## Acceptance criteria
- [ ] Support head, middle, tail, prefill, decode, cancellation, and release with deterministic outputs.
- [ ] Model isolated session/epoch state and deterministic cache-miss/stale-epoch failures.
- [ ] Support configurable delay, memory pressure, malformed output, and crash injection.
- [ ] Contract tests distinguish fixture evidence from real-model certification.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Write and verify `.scratch/distributed-gguf-runtime/evidence/DGR-032/README.md`. Until every criterion and applicable gate has real evidence, this story remains `passes: false`. Legacy evidence is provenance only, not completion credit.

View File

@@ -0,0 +1,39 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-033: Build a standalone fake C++ gRPC Shard worker
- **Status / triage:** specification only; `ready-for-agent`; `passes: false`
- **Execution mode:** `AFK`
- **Milestone:** `M1`
- **Dependencies:** `DGR-022`, `DGR-024`, `DGR-032`
- **Blocks (derived):** `DGR-036`, `DGR-040`
- **Labels:** `area:worker`, `area:grpc`, `type:vertical-slice`, `priority:p0`, `ready-for-agent`
- **Evidence class:** `fixture`
- **Hardware:** `none`
- **Model:** `fake`
- **Upstream:** `no`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/033-build-a-standalone-fake-c-grpc-shard-worker.md`, and evidence READMEs for dependencies (DGR-022, DGR-024, DGR-032) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Prove the standalone worker process, stream, lifecycle, and supervision shape before llama.cpp integration.
## Acceptance criteria
- [ ] A standalone C++ executable serves the complete lifecycle and stream RPC contract using the fake engine.
- [ ] Python integration tests cover startup, health, capability, fragmented prefill, decode, release, cancellation, and graceful shutdown.
- [ ] Bounded messages, deadlines, flow control, and independent session cancellation are enforced.
- [ ] The worker exposes neither llama.cpp RPC nor arbitrary graph execution.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Write and verify `.scratch/distributed-gguf-runtime/evidence/DGR-033/README.md`. Until every criterion and applicable gate has real evidence, this story remains `passes: false`. Legacy evidence is provenance only, not completion credit.

View File

@@ -0,0 +1,39 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-034: Implement dense-Llama range-aware GGUF ownership
- **Status / triage:** specification only; `ready-for-agent`; `passes: false`
- **Execution mode:** `AFK`
- **Milestone:** `M2`
- **Dependencies:** `DGR-028`, `DGR-029`, `DGR-031`
- **Blocks (derived):** `DGR-035`, `DGR-037`, `DGR-051`
- **Labels:** `area:llama`, `area:weights`, `type:runtime`, `priority:p0`, `ready-for-agent`
- **Evidence class:** `real-model`
- **Hardware:** `optional`
- **Model:** `dense-llama`
- **Upstream:** `yes`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/034-implement-dense-llama-range-aware-gguf-ownership.md`, and evidence READMEs for dependencies (DGR-028, DGR-029, DGR-031) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Load only the dense-Llama tensors owned by a shard range.
## Acceptance criteria
- [ ] Load only `blk.N.*` tensors in the assigned range, embeddings only at the head, and norm/output or tied output only at the tail.
- [ ] Derive authoritative range and endpoint ownership from the loaded engine state.
- [ ] Reject invalid/gapped/out-of-model ranges and unexpected required tensors.
- [ ] Real-model evidence shows mapped/resident memory scales with owned tensors rather than full artifact size.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Write and verify `.scratch/distributed-gguf-runtime/evidence/DGR-034/README.md`. Until every criterion and applicable gate has real evidence, this story remains `passes: false`. Legacy evidence is provenance only, not completion credit.

View File

@@ -0,0 +1,39 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-035: Implement dense architecture boundary input/output
- **Status / triage:** specification only; `ready-for-agent`; `passes: false`
- **Execution mode:** `AFK`
- **Milestone:** `M2`
- **Dependencies:** `DGR-021`, `DGR-031`, `DGR-034`
- **Blocks (derived):** `DGR-036`, `DGR-037`, `DGR-069`
- **Labels:** `area:llama`, `area:boundary`, `type:runtime`, `priority:p0`, `ready-for-agent`
- **Evidence class:** `real-model`
- **Hardware:** `optional`
- **Model:** `dense-llama`
- **Upstream:** `yes`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/035-implement-dense-architecture-boundary-input-output.md`, and evidence READMEs for dependencies (DGR-021, DGR-031, DGR-034) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Execute dense head/middle/tail ranges through an architecture-defined residual boundary.
## Acceptance criteria
- [ ] Head accepts token IDs and owns embedding; middle/tail bypass embedding and accept a named boundary bundle.
- [ ] Non-tail returns the unnormalized residual before final norm/head and before tail-only row pruning.
- [ ] Tail returns logits or sampled-token output under an explicit contract.
- [ ] Uncertified architectures and incompatible boundary schemas fail closed.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Write and verify `.scratch/distributed-gguf-runtime/evidence/DGR-035/README.md`. Until every criterion and applicable gate has real evidence, this story remains `passes: false`. Legacy evidence is provenance only, not completion credit.

View File

@@ -0,0 +1,39 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-036: Prove dense fixture and real-model range parity
- **Status / triage:** specification only; `ready-for-agent`; `passes: false`
- **Execution mode:** `AFK`
- **Milestone:** `M2`
- **Dependencies:** `DGR-033`, `DGR-035`
- **Blocks (derived):** `DGR-039`
- **Labels:** `area:parity`, `area:testing`, `type:certification`, `priority:p0`, `ready-for-agent`
- **Evidence class:** `real-model`
- **Hardware:** `optional`
- **Model:** `dense-llama`
- **Upstream:** `yes`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/036-prove-dense-fixture-and-real-model-range-parity.md`, and evidence READMEs for dependencies (DGR-033, DGR-035) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Prove the engine/protocol seam before adding session concurrency.
## Acceptance criteria
- [ ] Model-free two-stage tests pass through two fake worker processes with disjoint ranges.
- [ ] A small real dense GGUF passes whole-model versus two-range prefill parity.
- [ ] At least 32 greedy decode tokens match the locked tolerance.
- [ ] Evidence distinguishes deterministic fixture proof from opt-in real-model proof.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Write and verify `.scratch/distributed-gguf-runtime/evidence/DGR-036/README.md`. Until every criterion and applicable gate has real evidence, this story remains `passes: false`. Legacy evidence is provenance only, not completion credit.

View File

@@ -0,0 +1,39 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-037: Bind llama.cpp to the standalone worker
- **Status / triage:** specification only; `ready-for-agent`; `passes: false`
- **Execution mode:** `AFK`
- **Milestone:** `M2`
- **Dependencies:** `DGR-022`, `DGR-023`, `DGR-031`, `DGR-034`, `DGR-035`
- **Blocks (derived):** `DGR-038`, `DGR-039`, `DGR-040`, `DGR-051`
- **Labels:** `area:worker`, `area:llama`, `type:vertical-slice`, `priority:p0`, `ready-for-agent`
- **Evidence class:** `real-model`
- **Hardware:** `optional`
- **Model:** `dense-llama`
- **Upstream:** `yes`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/037-bind-llama-cpp-to-the-standalone-worker.md`, and evidence READMEs for dependencies (DGR-022, DGR-023, DGR-031, DGR-034, DGR-035) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Replace the fake engine with the pinned llama.cpp `ShardEngine` implementation without changing the public worker contract.
## Acceptance criteria
- [ ] Worker loads exactly one artifact/recipe/range identity and rejects mismatched stream requests.
- [ ] All execution passes through `ShardEngine`; llama.cpp implementation types remain private.
- [ ] Health and metrics expose loaded identity, authoritative ownership, memory, and execution state.
- [ ] Graceful shutdown releases model/session resources; injected process death is observable and bounded.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Write and verify `.scratch/distributed-gguf-runtime/evidence/DGR-037/README.md`. Until every criterion and applicable gate has real evidence, this story remains `passes: false`. Legacy evidence is provenance only, not completion credit.

View File

@@ -0,0 +1,39 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-038: Implement isolated shard-local Hot KV State
- **Status / triage:** specification only; `ready-for-agent`; `passes: false`
- **Execution mode:** `AFK`
- **Milestone:** `M2`
- **Dependencies:** `DGR-037`
- **Blocks (derived):** `DGR-039`, `DGR-052`, `DGR-055`, `DGR-069`
- **Labels:** `area:kv-cache`, `area:concurrency`, `type:runtime`, `priority:p0`, `ready-for-agent`
- **Evidence class:** `real-model`
- **Hardware:** `optional`
- **Model:** `dense-llama`
- **Upstream:** `yes`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/038-implement-isolated-shard-local-hot-kv-state.md`, and evidence READMEs for dependencies (DGR-037) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Map each route session and epoch to isolated state containing only locally owned layers.
## Acceptance criteria
- [ ] Map `(route_session_id, route_epoch)` to an isolated llama sequence or bounded context.
- [ ] Support prefill/decode append, truncate, release, TTL/LRU eviction, cache miss, and stale-epoch rejection.
- [ ] Four concurrent sessions complete without token, KV, position, or cancellation cross-talk.
- [ ] Release/eviction returns memory to the configured budget without affecting other sessions.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Write and verify `.scratch/distributed-gguf-runtime/evidence/DGR-038/README.md`. Until every criterion and applicable gate has real evidence, this story remains `passes: false`. Legacy evidence is provenance only, not completion credit.

View File

@@ -0,0 +1,39 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-039: Pass local two-process dense acceptance
- **Status / triage:** specification only; `ready-for-agent`; `passes: false`
- **Execution mode:** `AFK`
- **Milestone:** `M2`
- **Dependencies:** `DGR-036`, `DGR-037`, `DGR-038`
- **Blocks (derived):** `DGR-054`
- **Labels:** `area:integration`, `area:parity`, `type:certification`, `priority:p0`, `ready-for-agent`
- **Evidence class:** `real-model`
- **Hardware:** `optional`
- **Model:** `dense-llama`
- **Upstream:** `yes`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/039-pass-local-two-process-dense-acceptance.md`, and evidence READMEs for dependencies (DGR-036, DGR-037, DGR-038) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Establish the first real, independently executing distributed GGUF route on one host.
## Acceptance criteria
- [ ] Two worker processes open disjoint dense ranges and both execute real prefill/decode work.
- [ ] Whole-model parity, 32-token greedy decode, four-session isolation, cancellation, and cleanup pass.
- [ ] Record TTFT, prefill/decode rates, seam bytes/latency, RSS/VRAM, KV, queue, and failure metrics.
- [ ] Killing one worker returns a bounded structured failure rather than hanging.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Write and verify `.scratch/distributed-gguf-runtime/evidence/DGR-039/README.md`. Until every criterion and applicable gate has real evidence, this story remains `passes: false`. Legacy evidence is provenance only, not completion credit.

View File

@@ -1,61 +0,0 @@
# 04 — Create the reproducible pinned llama.cpp patch stack
Status: ready-for-agent
## Mandatory fresh-session context
- Read [RALPH-CONTEXT.md](../RALPH-CONTEXT.md) completely before changing code.
- This issue is `DGR-004` in [prd.json](../prd.json).
- Read the evidence README for every dependency listed below.
- Inspect current code and `git status`; historical text and previous agent claims are not evidence.
## Description
As a maintainer, I need a small auditable fork boundary so that upstream updates do not turn the runtime into an unmaintainable stitched codebase.
## Expected durable outputs
- Exact llama.cpp upstream pin
- Numbered minimal patch stack
- Reproducible fetch/apply/build smoke
- evidence/DGR-004/README.md
## Acceptance criteria
- [ ] Pin one exact llama.cpp commit through a reproducible source dependency mechanism.
- [ ] Store a numbered minimal patch stack separately from Meshnet networking code.
- [ ] Add a build script that applies/checks patches and builds the standalone worker without manual source copying.
- [ ] Record upstream file/ABI assumptions and fail clearly when the pin changes.
- [ ] Preserve upstream license and attribution notices.
- [ ] Add a clean rebuild smoke test that does not download a model.
- [ ] Targeted pytest tests pass
- [ ] python -m compileall packages tests passes for Python changes
- [ ] git diff --check passes
- [ ] Default tests remain deterministic, model-download-free, API-credit-free, and GPU-free
- [ ] Full deterministic pytest -q passes, or the exact pre-existing unrelated failure is recorded with a clean-tree reproduction
- [ ] Pinned native C++ target builds and focused CTest/protocol tests pass where native code is touched
- [ ] llama.cpp patch stack applies cleanly to the exact pinned commit where patch code is touched
- [ ] Read .scratch/distributed-gguf-runtime/RALPH-CONTEXT.md and this story issue completely before changing code
- [ ] Read and verify every dependency evidence README before relying on dependency behavior
- [ ] Preserve all pre-existing working-tree changes and stage only files belonging to this story
- [ ] Write .scratch/distributed-gguf-runtime/evidence/DGR-004/README.md with files changed, exact commands and real results, limitations, compatibility notes, and dependent-story handoff
- [ ] Update only this story issue to Status: done after every acceptance criterion and quality gate passes
## Dependency handoff
- `DGR-001` must have `passes: true`; read `../evidence/DGR-001/README.md` and verify its referenced files/commands.
## Finish contract
- Create the task evidence directory and durable handoff required above.
- Preserve real failures and blockers; never fabricate benchmark, model, test or hardware output.
- Change this issue to `Status: done` only after all criteria pass.
- Emit `<promise>COMPLETE</promise>` only after the evidence handoff exists.
## References
- [Ralph execution context](../RALPH-CONTEXT.md)
- [PRD](../PRD.md)
- [Implementation strategy](../implementation-strategy.md)
- [Current architecture](../architecture.md)
- [Architecture decision](../../docs/adr/0024-distributed-gguf-runtime.md)

View File

@@ -0,0 +1,39 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-040: Add node-side native worker supervision
- **Status / triage:** specification only; `ready-for-agent`; `passes: false`
- **Execution mode:** `AFK`
- **Milestone:** `M2`
- **Dependencies:** `DGR-033`, `DGR-037`
- **Blocks (derived):** `DGR-041`, `DGR-042`, `DGR-055`, `DGR-058`
- **Labels:** `area:node`, `area:supervision`, `type:integration`, `priority:p0`, `ready-for-agent`
- **Evidence class:** `fixture`
- **Hardware:** `none`
- **Model:** `generic`
- **Upstream:** `no`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/040-add-node-side-native-worker-supervision.md`, and evidence READMEs for dependencies (DGR-033, DGR-037) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Let the existing node service safely start, probe, stop, and restart the standalone worker.
## Acceptance criteria
- [ ] Supervision owns process startup, readiness, log capture, graceful shutdown, and bounded forced termination.
- [ ] Startup verifies worker binary, artifact identity, recipe, and range before registration.
- [ ] Crashes or health loss make the capability unavailable without corrupting the Transformers backend.
- [ ] Tests use the fake worker and deterministic crash injection.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Write and verify `.scratch/distributed-gguf-runtime/evidence/DGR-040/README.md`. Until every criterion and applicable gate has real evidence, this story remains `passes: false`. Legacy evidence is provenance only, not completion credit.

View File

@@ -0,0 +1,39 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-041: Register native Shard capabilities without redesigning Meshnet
- **Status / triage:** specification only; `ready-for-agent`; `passes: false`
- **Execution mode:** `AFK`
- **Milestone:** `M2`
- **Dependencies:** `DGR-025`, `DGR-040`
- **Blocks (derived):** `DGR-043`
- **Labels:** `area:meshnet`, `area:admission`, `type:integration`, `priority:p0`, `ready-for-agent`
- **Evidence class:** `model-free`
- **Hardware:** `none`
- **Model:** `generic`
- **Upstream:** `no`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/041-register-native-shard-capabilities-without-redesigning-meshnet.md`, and evidence READMEs for dependencies (DGR-025, DGR-040) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Adapt native worker identity and capacity to existing backend-agnostic capability admission.
## Acceptance criteria
- [ ] Registration carries exact recipe fingerprint, authoritative range, backend, memory/KV capacity, concurrency, and certification status.
- [ ] Existing tracker, billing, routing, telemetry, and provider semantics remain backend-agnostic.
- [ ] Uncertified backend/model/recipe combinations are visible but unroutable.
- [ ] Existing Transformers registration and route tests remain unchanged in behavior.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Write and verify `.scratch/distributed-gguf-runtime/evidence/DGR-041/README.md`. Until every criterion and applicable gate has real evidence, this story remains `passes: false`. Legacy evidence is provenance only, not completion credit.

View File

@@ -0,0 +1,39 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-042: Carry native frames through direct and existing relay seams
- **Status / triage:** specification only; `ready-for-agent`; `passes: false`
- **Execution mode:** `AFK`
- **Milestone:** `M2`
- **Dependencies:** `DGR-024`, `DGR-040`
- **Blocks (derived):** `DGR-054`, `DGR-058`
- **Labels:** `area:meshnet`, `area:relay`, `area:grpc`, `type:integration`, `priority:p0`, `ready-for-agent`
- **Evidence class:** `fixture`
- **Hardware:** `none`
- **Model:** `generic`
- **Upstream:** `no`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/042-carry-native-frames-through-direct-and-existing-relay-seams.md`, and evidence READMEs for dependencies (DGR-024, DGR-040) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Use direct gRPC where available and the existing relay as opaque protobuf transport without redesigning relay behavior.
## Acceptance criteria
- [ ] Direct paths use the long-lived gRPC activation stream.
- [ ] Relayed paths carry byte-identical versioned protobuf frames through the existing relay contract.
- [ ] Request/work identity, cancellation, deadlines, telemetry, billing correlation, and per-node attribution survive both paths.
- [ ] Fake-worker tests cover direct, relay, disconnect, cancellation, and bounded buffering.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Write and verify `.scratch/distributed-gguf-runtime/evidence/DGR-042/README.md`. Until every criterion and applicable gate has real evidence, this story remains `passes: false`. Legacy evidence is provenance only, not completion credit.

View File

@@ -0,0 +1,39 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-043: Expose GGUF compatibility and measured cost inputs to existing routing
- **Status / triage:** specification only; `ready-for-agent`; `passes: false`
- **Execution mode:** `AFK`
- **Milestone:** `M2`
- **Dependencies:** `DGR-041`
- **Blocks (derived):** `DGR-053`, `DGR-054`, `DGR-059`, `DGR-061`
- **Labels:** `area:tracker`, `area:routing`, `type:integration`, `priority:p0`, `ready-for-agent`
- **Evidence class:** `model-free`
- **Hardware:** `none`
- **Model:** `generic`
- **Upstream:** `no`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/043-expose-gguf-compatibility-and-measured-cost-inputs-to-existing-routing.md`, and evidence READMEs for dependencies (DGR-041) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Adapt exact GGUF recipe/range compatibility and measured capacity, queue, seam-cost, health, and reliability data into the existing backend-agnostic routing inputs without redesigning routing or load balancing.
## Acceptance criteria
- [ ] Expose exact recipe, range coverage, capacity, queue/load, seam-cost, health, reliability, backend, and certification measurements through existing tracker input contracts.
- [ ] Prove existing routing forms complete compatible coverage and excludes dark or mismatched candidates using its current backend-agnostic mechanisms.
- [ ] Regression-test unchanged Transformers behavior and unchanged tracker routing, load-balancing, billing, relay, and provider semantics.
- [ ] Regression-test that no quant, stage count, fixed split, architecture, backend sequence, or DeepSeek-specific policy is hardcoded.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Write and verify `.scratch/distributed-gguf-runtime/evidence/DGR-043/README.md`. Until every criterion and applicable gate has real evidence, this story remains `passes: false`. Legacy evidence is provenance only, not completion credit.

View File

@@ -0,0 +1,39 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-044: Pin the DeepSeek V4 Flash target contract
- **Status / triage:** specification only; `ready-for-agent`; `passes: false`
- **Execution mode:** `AFK`
- **Milestone:** `M3`
- **Dependencies:** `DGR-019`, `DGR-025`, `DGR-026`, `DGR-027`
- **Blocks (derived):** `DGR-045`
- **Labels:** `area:deepseek-v4`, `area:provenance`, `type:contract`, `priority:p0`, `ready-for-agent`
- **Evidence class:** `model-free`
- **Hardware:** `none`
- **Model:** `deepseek-v4-flash`
- **Upstream:** `yes`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/044-pin-the-deepseek-v4-flash-target-contract.md`, and evidence READMEs for dependencies (DGR-019, DGR-025, DGR-026, DGR-027) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Fix the alpha/beta model identity and upstream maturity assumptions before implementing the adapter.
## Acceptance criteria
- [ ] Pin Hugging Face target SHA `60d8d70770c6776ff598c94bb586a859a38244f1`.
- [ ] Record the selected GGUF provenance and exact source binding without assuming one quant.
- [ ] Record that llama.cpp support began with PR 24162/commit `8c146a8` and remains maturing; the build manifest still pins one exact validated upstream commit.
- [ ] Record 43 main layers plus MTP and all known architecture-specific state obligations.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Write and verify `.scratch/distributed-gguf-runtime/evidence/DGR-044/README.md`. Until every criterion and applicable gate has real evidence, this story remains `passes: false`. Legacy evidence is provenance only, not completion credit.

View File

@@ -0,0 +1,39 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-045: Inventory V4 GGUF tensors and layer ownership
- **Status / triage:** specification only; `ready-for-agent`; `passes: false`
- **Execution mode:** `AFK`
- **Milestone:** `M3`
- **Dependencies:** `DGR-026`, `DGR-044`
- **Blocks (derived):** `DGR-046`, `DGR-047`, `DGR-050`
- **Labels:** `area:deepseek-v4`, `area:weights`, `type:research-spike`, `priority:p0`, `ready-for-agent`
- **Evidence class:** `real-model`
- **Hardware:** `none`
- **Model:** `deepseek-v4-flash`
- **Upstream:** `yes`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/045-inventory-v4-gguf-tensors-and-layer-ownership.md`, and evidence READMEs for dependencies (DGR-026, DGR-044) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Derive exact head, repeated-layer, tail, expert, auxiliary-state, and MTP ownership from the pinned artifact.
## Acceptance criteria
- [ ] Produce a machine-readable inventory tied to the target SHA and exact GGUF artifact.
- [ ] Classify embeddings, 43 main layers, final head, MTP, mHC, attention variants, indexer/compressor, and MoE tensors.
- [ ] Validate half-open range ownership and fail on unclassified required tensors.
- [ ] Inventory tooling works across quants without embedding quant names in architecture logic.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Write and verify `.scratch/distributed-gguf-runtime/evidence/DGR-045/README.md`. Until every criterion and applicable gate has real evidence, this story remains `passes: false`. Legacy evidence is provenance only, not completion credit.

View File

@@ -0,0 +1,39 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-046: Define the V4 typed architecture boundary schema
- **Status / triage:** specification only; `ready-for-agent`; `passes: false`
- **Execution mode:** `AFK`
- **Milestone:** `M3`
- **Dependencies:** `DGR-021`, `DGR-045`
- **Blocks (derived):** `DGR-047`, `DGR-048`, `DGR-049`
- **Labels:** `area:deepseek-v4`, `area:boundary`, `type:protocol`, `priority:p0`, `ready-for-agent`
- **Evidence class:** `model-free`
- **Hardware:** `none`
- **Model:** `deepseek-v4-flash`
- **Upstream:** `yes`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/046-define-the-v4-typed-architecture-boundary-schema.md`, and evidence READMEs for dependencies (DGR-021, DGR-045) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Define the exact cross-stage V4 architecture boundary while keeping per-layer attention and auxiliary caches shard-local.
## Acceptance criteria
- [ ] Define a versioned named bundle for the mHC 4×4096 residual boundary, positions, token-ID sideband where required, and schema/cache expectations.
- [ ] Explicitly exclude per-layer CSA, HCA, SWA, indexer, compressor, KV, and MTP caches/state from the WAN boundary; those remain local to the owning shard and session/epoch.
- [ ] Reserve typed MTP boundary fields but mark MTP execution unsupported and unroutable for alpha.
- [ ] Fingerprint independently of quant/topology and fail closed on missing, incompatible, incorrectly shaped, or stale boundary/cache expectations.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Write and verify `.scratch/distributed-gguf-runtime/evidence/DGR-046/README.md`. Until every criterion and applicable gate has real evidence, this story remains `passes: false`. Legacy evidence is provenance only, not completion credit.

View File

@@ -0,0 +1,39 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-047: Adapt the upstream V4 mHC boundary for ranged ownership
- **Status / triage:** specification only; `ready-for-agent`; `passes: false`
- **Execution mode:** `AFK`
- **Milestone:** `M3`
- **Dependencies:** `DGR-045`, `DGR-046`
- **Blocks (derived):** `DGR-048`, `DGR-049`, `DGR-050`, `DGR-051`
- **Labels:** `area:deepseek-v4`, `area:mhc`, `type:runtime`, `priority:p0`, `ready-for-agent`
- **Evidence class:** `real-model`
- **Hardware:** `optional`
- **Model:** `deepseek-v4-flash`
- **Upstream:** `yes`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/047-adapt-the-upstream-v4-mhc-boundary-for-ranged-ownership.md`, and evidence READMEs for dependencies (DGR-045, DGR-046) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Add range-boundary adapters around upstream llama.cpp V4 mHC execution without reimplementing the V4 graph or kernels.
## Acceptance criteria
- [ ] Represent and validate the upstream V4 4×4096 mHC boundary without flattening semantic axes.
- [ ] Add only head/intermediate/tail range ownership and boundary conversion hooks around the pinned upstream llama.cpp graph.
- [ ] Compare deterministic fixture vectors and single-process ranged outputs with upstream whole-model execution.
- [ ] Document that llama.cpp owns V4 mHC graph/kernels and that quantized storage does not alter the logical boundary schema.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Write and verify `.scratch/distributed-gguf-runtime/evidence/DGR-047/README.md`. Until every criterion and applicable gate has real evidence, this story remains `passes: false`. Legacy evidence is provenance only, not completion credit.

View File

@@ -0,0 +1,39 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-048: Carry token-ID sideband through the first three hash-routed layers
- **Status / triage:** specification only; `ready-for-agent`; `passes: false`
- **Execution mode:** `AFK`
- **Milestone:** `M3`
- **Dependencies:** `DGR-046`, `DGR-047`
- **Blocks (derived):** `DGR-051`
- **Labels:** `area:deepseek-v4`, `area:routing-state`, `type:runtime`, `priority:p0`, `ready-for-agent`
- **Evidence class:** `real-model`
- **Hardware:** `optional`
- **Model:** `deepseek-v4-flash`
- **Upstream:** `yes`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/048-carry-token-id-sideband-through-the-first-three-hash-routed-layers.md`, and evidence READMEs for dependencies (DGR-046, DGR-047) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Ensure any stage containing the first three hash-routed layers receives exact token identities.
## Acceptance criteria
- [ ] Head emits token IDs in the typed sideband for boundaries that require them.
- [ ] Intermediate stages preserve or consume the sideband according to their layer range.
- [ ] Routes splitting before, within, and after the first three layers pass deterministic partition tests.
- [ ] Missing or mismatched token IDs fail closed rather than silently selecting incorrect experts.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Write and verify `.scratch/distributed-gguf-runtime/evidence/DGR-048/README.md`. Until every criterion and applicable gate has real evidence, this story remains `passes: false`. Legacy evidence is provenance only, not completion credit.

View File

@@ -0,0 +1,39 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-049: Keep V4 attention and auxiliary state shard-local
- **Status / triage:** specification only; `ready-for-agent`; `passes: false`
- **Execution mode:** `AFK`
- **Milestone:** `M3`
- **Dependencies:** `DGR-046`, `DGR-047`
- **Blocks (derived):** `DGR-051`
- **Labels:** `area:deepseek-v4`, `area:attention`, `type:runtime`, `priority:p0`, `ready-for-agent`
- **Evidence class:** `real-model`
- **Hardware:** `optional`
- **Model:** `deepseek-v4-flash`
- **Upstream:** `yes`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/049-keep-v4-attention-and-auxiliary-state-shard-local.md`, and evidence READMEs for dependencies (DGR-046, DGR-047) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Bind V4 CSA/HCA/SWA/indexer/compressor and KV state to the owning shard session/epoch rather than transferring caches over the WAN.
## Acceptance criteria
- [ ] Map CSA, HCA, SWA, indexer, compressor, and KV ownership from the pinned upstream graph to each owned layer range.
- [ ] Key all such caches/state by route session and epoch with bounded lifecycle, memory accounting, stale-epoch rejection, release, and eviction.
- [ ] Prove cross-stage messages carry only the typed architecture boundary and cache expectations, never per-layer cache contents.
- [ ] On route change or state loss, use explicit cache miss and re-prefill/restart; do not migrate V4 caches across workers.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Write and verify `.scratch/distributed-gguf-runtime/evidence/DGR-049/README.md`. Until every criterion and applicable gate has real evidence, this story remains `passes: false`. Legacy evidence is provenance only, not completion credit.

View File

@@ -1,61 +0,0 @@
# 05 — Implement dense-Llama range-aware GGUF ownership
Status: ready-for-agent
## Mandatory fresh-session context
- Read [RALPH-CONTEXT.md](../RALPH-CONTEXT.md) completely before changing code.
- This issue is `DGR-005` in [prd.json](../prd.json).
- Read the evidence README for every dependency listed below.
- Inspect current code and `git status`; historical text and previous agent claims are not evidence.
## Description
As a node, I need to map only my assigned dense-Llama Shard so that aggregate consumer memory can hold a model larger than one node.
## Expected durable outputs
- Dense-Llama range-aware ownership implementation
- Authoritative loaded-range introspection
- Mapped/resident memory evidence
- evidence/DGR-005/README.md
## Acceptance criteria
- [ ] Register and allocate only `blk.N.*` tensors in the assigned range.
- [ ] Load embeddings only for the head and final norm/LM head only for the tail, including tied embeddings.
- [ ] Prefer range-aware mapping from one exact source GGUF; if derivative sub-GGUFs are used temporarily, verify source/slice hashes and avoid claiming final artifact semantics.
- [ ] Report authoritative loaded range and endpoint ownership from the model, not operator CLI claims.
- [ ] Demonstrate mapped/resident memory scales with owned tensors rather than full model size.
- [ ] Targeted pytest tests pass
- [ ] python -m compileall packages tests passes for Python changes
- [ ] git diff --check passes
- [ ] Default tests remain deterministic, model-download-free, API-credit-free, and GPU-free
- [ ] Full deterministic pytest -q passes, or the exact pre-existing unrelated failure is recorded with a clean-tree reproduction
- [ ] Pinned native C++ target builds and focused CTest/protocol tests pass where native code is touched
- [ ] llama.cpp patch stack applies cleanly to the exact pinned commit where patch code is touched
- [ ] Read .scratch/distributed-gguf-runtime/RALPH-CONTEXT.md and this story issue completely before changing code
- [ ] Read and verify every dependency evidence README before relying on dependency behavior
- [ ] Preserve all pre-existing working-tree changes and stage only files belonging to this story
- [ ] Write .scratch/distributed-gguf-runtime/evidence/DGR-005/README.md with files changed, exact commands and real results, limitations, compatibility notes, and dependent-story handoff
- [ ] Update only this story issue to Status: done after every acceptance criterion and quality gate passes
## Dependency handoff
- `DGR-003` must have `passes: true`; read `../evidence/DGR-003/README.md` and verify its referenced files/commands.
- `DGR-004` must have `passes: true`; read `../evidence/DGR-004/README.md` and verify its referenced files/commands.
## Finish contract
- Create the task evidence directory and durable handoff required above.
- Preserve real failures and blockers; never fabricate benchmark, model, test or hardware output.
- Change this issue to `Status: done` only after all criteria pass.
- Emit `<promise>COMPLETE</promise>` only after the evidence handoff exists.
## References
- [Ralph execution context](../RALPH-CONTEXT.md)
- [PRD](../PRD.md)
- [Implementation strategy](../implementation-strategy.md)
- [Current architecture](../architecture.md)
- [Architecture decision](../../docs/adr/0024-distributed-gguf-runtime.md)

View File

@@ -0,0 +1,39 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-050: Validate upstream V4 MoE and hash-routing execution under ranged ownership
- **Status / triage:** specification only; `ready-for-agent`; `passes: false`
- **Execution mode:** `AFK`
- **Milestone:** `M3`
- **Dependencies:** `DGR-045`, `DGR-047`
- **Blocks (derived):** `DGR-051`
- **Labels:** `area:deepseek-v4`, `area:moe`, `type:runtime`, `priority:p0`, `ready-for-agent`
- **Evidence class:** `real-model`
- **Hardware:** `optional`
- **Model:** `deepseek-v4-flash`
- **Upstream:** `yes`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/050-validate-upstream-v4-moe-and-hash-routing-execution-under-ranged-ownership.md`, and evidence READMEs for dependencies (DGR-045, DGR-047) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Validate the pinned upstream llama.cpp V4 MoE and hash-routing graph when layers are range-owned, without reimplementing routing or expert kernels in Meshnet.
## Acceptance criteria
- [ ] Load range-owned tensors for 256 routed plus one shared expert and validate upstream execution activates six routed experts where specified.
- [ ] Validate the first three upstream hash-routed layers receive exact token-ID sideband across splits before, within, and after them.
- [ ] Compare upstream whole-model and ranged router/expert outputs, shared-expert contribution, and malformed sideband failures.
- [ ] Document that llama.cpp owns V4 MoE, attention, hash routing, graph, and kernels; no expert-parallel WAN collective or Meshnet reimplementation is introduced.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Write and verify `.scratch/distributed-gguf-runtime/evidence/DGR-050/README.md`. Until every criterion and applicable gate has real evidence, this story remains `passes: false`. Legacy evidence is provenance only, not completion credit.

View File

@@ -0,0 +1,39 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-051: Assemble the DeepSeek V4 Flash `ShardEngine` adapter
- **Status / triage:** specification only; `ready-for-agent`; `passes: false`
- **Execution mode:** `AFK`
- **Milestone:** `M3`
- **Dependencies:** `DGR-034`, `DGR-037`, `DGR-047`, `DGR-048`, `DGR-049`, `DGR-050`
- **Blocks (derived):** `DGR-052`, `DGR-060`, `DGR-065`, `DGR-069`
- **Labels:** `area:deepseek-v4`, `area:engine`, `type:vertical-slice`, `priority:p0`, `ready-for-agent`
- **Evidence class:** `real-model`
- **Hardware:** `optional`
- **Model:** `deepseek-v4-flash`
- **Upstream:** `yes`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/051-assemble-the-deepseek-v4-flash-shardengine-adapter.md`, and evidence READMEs for dependencies (DGR-034, DGR-037, DGR-047, DGR-048, DGR-049, DGR-050) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Assemble range ownership hooks and boundary/local-state adapters around upstream llama.cpp V4 execution behind the stable ShardEngine interface.
## Acceptance criteria
- [ ] Support valid head, middle, tail, and whole-model ranges over all 43 main layers using the pinned upstream llama.cpp V4 graph/kernels.
- [ ] Integrate exact range ownership, mHC boundary, positions, required token-ID sideband, and shard-local session/epoch state adapters.
- [ ] Report MTP reserved-but-not-executable for alpha and reject unsupported split points or cache expectations.
- [ ] Include exact adapter/schema/runtime/artifact identity and valid split restrictions without reimplementing V4 MoE, attention, mHC, or hash routing.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Write and verify `.scratch/distributed-gguf-runtime/evidence/DGR-051/README.md`. Until every criterion and applicable gate has real evidence, this story remains `passes: false`. Legacy evidence is provenance only, not completion credit.

View File

@@ -0,0 +1,39 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-052: Pass local V4 whole-model versus ranged parity
- **Status / triage:** specification only; `ready-for-agent`; `passes: false`
- **Execution mode:** `AFK`
- **Milestone:** `M3`
- **Dependencies:** `DGR-038`, `DGR-051`
- **Blocks (derived):** `DGR-053`, `DGR-054`
- **Labels:** `area:deepseek-v4`, `area:parity`, `type:certification`, `priority:p0`, `ready-for-agent`
- **Evidence class:** `real-model`
- **Hardware:** `optional`
- **Model:** `deepseek-v4-flash`
- **Upstream:** `yes`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/052-pass-local-v4-whole-model-versus-ranged-parity.md`, and evidence READMEs for dependencies (DGR-038, DGR-051) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Prove V4 prefill and decode correctness locally before network certification.
## Acceptance criteria
- [ ] Compare pinned whole-model llama.cpp with at least two valid ranged partitions.
- [ ] Prefill intermediates and locked-length greedy decode pass architecture-specific tolerances.
- [ ] Test splits around the first three hash-routed layers and at least one CSA/HCA/SWA/indexer/compressor transition.
- [ ] Four concurrent sessions pass KV/state isolation and cleanup.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Write and verify `.scratch/distributed-gguf-runtime/evidence/DGR-052/README.md`. Until every criterion and applicable gate has real evidence, this story remains `passes: false`. Legacy evidence is provenance only, not completion credit.

View File

@@ -0,0 +1,40 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-053: Certify a real 24-stage V4 route
- **Status / triage:** specification only; `ready-for-human`; `passes: false`
- **Execution mode:** `HITL`
- **Milestone:** `M3`
- **Dependencies:** `DGR-030`, `DGR-043`, `DGR-052`
- **Blocks (derived):** `DGR-054`, `DGR-062`, `DGR-067`
- **Labels:** `area:deepseek-v4`, `area:hardware`, `type:certification`, `priority:p0`, `gate:hitl`, `ready-for-human`
- **Evidence class:** `real-hardware`
- **Hardware:** `required`
- **Model:** `deepseek-v4-flash`
- **Upstream:** `yes`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/053-certify-a-real-2-4-stage-v4-route.md`, and evidence READMEs for dependencies (DGR-030, DGR-043, DGR-052) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Prove real Tracker-selected V4 execution across physical machines before alpha.
## Acceptance criteria
- [ ] Run one documented 24-stage certification scenario using exact compatible artifacts/recipes; the count and chosen quant are evidence inputs, not product constants.
- [ ] Actual CPU/GPU work executes on every stage; fake workers do not satisfy acceptance.
- [ ] Record parity, TTFT, prefill/decode speed, seam cost, memory, cache/state isolation, cancellation, and cleanup.
- [ ] Tracker selection remains dynamic and rejects an injected incompatible backend/recipe.
- [ ] Only the exact real-hardware lanes exercised become eligible for advertisement.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Write and verify `.scratch/distributed-gguf-runtime/evidence/DGR-053/README.md`. Until every criterion and applicable gate has real evidence, this story remains `passes: false`. Legacy evidence is provenance only, not completion credit.

View File

@@ -0,0 +1,39 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-054: Enforce the DeepSeek V4 Flash alpha gate
- **Status / triage:** specification only; `ready-for-human`; `passes: false`
- **Execution mode:** `HITL`
- **Milestone:** `M3`
- **Dependencies:** `DGR-017`, `DGR-019`, `DGR-020`, `DGR-039`, `DGR-042`, `DGR-043`, `DGR-052`, `DGR-053`
- **Blocks (derived):** `DGR-055`, `DGR-065`, `DGR-066`, `DGR-068`
- **Labels:** `area:deepseek-v4`, `area:release`, `milestone:alpha`, `priority:p0`, `gate:hitl`, `ready-for-human`
- **Evidence class:** `release`
- **Hardware:** `required`
- **Model:** `deepseek-v4-flash`
- **Upstream:** `yes`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/054-enforce-the-deepseek-v4-flash-alpha-gate.md`, and evidence READMEs for dependencies (DGR-017, DGR-019, DGR-020, DGR-039, DGR-042, DGR-043, DGR-052, DGR-053) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Release alpha only when V4 is correct and clears the pre-locked useful-speed requirement.
## Acceptance criteria
- [ ] Evaluate correctness, model fit, TTFT, prefill/decode speed, seam cost, memory, and failure rate against DGF-004 without changing thresholds.
- [ ] Separate quant/model-fit gains from runtime/transport gains.
- [ ] Decision is `alpha`, `optimize measured bottleneck`, or `stop`; failures cannot be relabeled as certification.
- [ ] Alpha documentation states MTP is reserved but not implemented and identifies every dark hardware lane.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Write and verify `.scratch/distributed-gguf-runtime/evidence/DGR-054/README.md`. Until every criterion and applicable gate has real evidence, this story remains `passes: false`. Legacy evidence is provenance only, not completion credit.

View File

@@ -0,0 +1,39 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-055: Implement compatible continuous decode batching
- **Status / triage:** specification only; `ready-for-agent`; `passes: false`
- **Execution mode:** `AFK`
- **Milestone:** `M4`
- **Dependencies:** `DGR-038`, `DGR-040`, `DGR-054`
- **Blocks (derived):** `DGR-056`, `DGR-057`
- **Labels:** `area:scheduler`, `area:batching`, `type:performance`, `priority:p1`, `ready-for-agent`
- **Evidence class:** `fixture`
- **Hardware:** `none`
- **Model:** `generic`
- **Upstream:** `no`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/055-implement-compatible-continuous-decode-batching.md`, and evidence READMEs for dependencies (DGR-038, DGR-040, DGR-054) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Batch compatible active sessions without violating route, recipe, position, or architecture state.
## Acceptance criteria
- [ ] Batch only sessions with compatible engine, recipe, phase, boundary schema, and state layout.
- [ ] Preserve per-session positions, sequence IDs, outputs, cancellation, and accounting.
- [ ] Decode receives bounded service while prefill remains schedulable.
- [ ] Deterministic 1/2/4/8 concurrency tests show no cross-session corruption.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Write and verify `.scratch/distributed-gguf-runtime/evidence/DGR-055/README.md`. Until every criterion and applicable gate has real evidence, this story remains `passes: false`. Legacy evidence is provenance only, not completion credit.

View File

@@ -0,0 +1,39 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-056: Enforce bounded admission, queues, and backpressure
- **Status / triage:** specification only; `ready-for-agent`; `passes: false`
- **Execution mode:** `AFK`
- **Milestone:** `M4`
- **Dependencies:** `DGR-055`
- **Blocks (derived):** `DGR-057`, `DGR-058`, `DGR-060`
- **Labels:** `area:scheduler`, `area:backpressure`, `type:performance`, `priority:p1`, `ready-for-agent`
- **Evidence class:** `fixture`
- **Hardware:** `none`
- **Model:** `generic`
- **Upstream:** `no`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/056-enforce-bounded-admission-queues-and-backpressure.md`, and evidence READMEs for dependencies (DGR-055) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Prevent weight, KV, state, scratch, and stream buffers from exceeding admitted capacity.
## Acceptance criteria
- [ ] Admission accounts separately for weights, KV/state, scratch, in-flight fragments, and queue slots.
- [ ] Queue and stream limits produce structured retryable or terminal responses.
- [ ] Prefill cannot starve decode and one route session cannot monopolize queue capacity.
- [ ] Telemetry reports active sessions, queue depth/time, batch occupancy, memory pressure, and rejects.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Write and verify `.scratch/distributed-gguf-runtime/evidence/DGR-056/README.md`. Until every criterion and applicable gate has real evidence, this story remains `passes: false`. Legacy evidence is provenance only, not completion credit.

View File

@@ -0,0 +1,39 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-057: Benchmark batching saturation and fairness
- **Status / triage:** specification only; `ready-for-agent`; `passes: false`
- **Execution mode:** `AFK`
- **Milestone:** `M4`
- **Dependencies:** `DGR-055`, `DGR-056`
- **Blocks (derived):** `DGR-061`, `DGR-063`, `DGR-070`
- **Labels:** `area:performance`, `area:batching`, `type:benchmark`, `priority:p1`, `ready-for-agent`
- **Evidence class:** `real-hardware`
- **Hardware:** `required`
- **Model:** `dense-llama+deepseek-v4`
- **Upstream:** `no`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/057-benchmark-batching-saturation-and-fairness.md`, and evidence READMEs for dependencies (DGR-055, DGR-056) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Identify useful concurrency and saturation points without assuming one global batch size.
## Acceptance criteria
- [ ] Run controlled concurrency 1/2/4/8 and record aggregate throughput, per-request p50/p95, TTFT, queue time, occupancy, and memory.
- [ ] Measure dense and V4 lanes separately where hardware permits.
- [ ] Verify bounded fairness and no prefill/decode starvation.
- [ ] Produce machine-readable saturation recommendations consumed by capability reporting, not hardcoded constants.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Write and verify `.scratch/distributed-gguf-runtime/evidence/DGR-057/README.md`. Until every criterion and applicable gate has real evidence, this story remains `passes: false`. Legacy evidence is provenance only, not completion credit.

View File

@@ -0,0 +1,39 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-058: Harden worker and stream failure semantics
- **Status / triage:** specification only; `ready-for-agent`; `passes: false`
- **Execution mode:** `AFK`
- **Milestone:** `M4`
- **Dependencies:** `DGR-040`, `DGR-042`, `DGR-056`
- **Blocks (derived):** `DGR-059`, `DGR-060`, `DGR-061`
- **Labels:** `area:reliability`, `area:failure`, `type:hardening`, `priority:p1`, `ready-for-agent`
- **Evidence class:** `fixture`
- **Hardware:** `none`
- **Model:** `generic`
- **Upstream:** `no`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/058-harden-worker-and-stream-failure-semantics.md`, and evidence READMEs for dependencies (DGR-040, DGR-042, DGR-056) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Ensure malformed input, process death, transport reset, and cancellation terminate cleanly.
## Acceptance criteria
- [ ] Test worker death, stream reset, malformed bundle, checksum failure, deadline, cache miss, stale epoch, and partial fragment loss.
- [ ] Cancellation propagates across all stages and releases KV/state, queue entries, and fragment buffers.
- [ ] Duplicate steps are idempotent; uncertain mutations are never silently replayed.
- [ ] Billing/work outcomes distinguish completed, cancelled, failed, and unverified work.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Write and verify `.scratch/distributed-gguf-runtime/evidence/DGR-058/README.md`. Until every criterion and applicable gate has real evidence, this story remains `passes: false`. Legacy evidence is provenance only, not completion credit.

View File

@@ -0,0 +1,39 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-059: Implement alpha-safe route recovery
- **Status / triage:** specification only; `ready-for-agent`; `passes: false`
- **Execution mode:** `AFK`
- **Milestone:** `M4`
- **Dependencies:** `DGR-043`, `DGR-058`
- **Blocks (derived):** `DGR-070`
- **Labels:** `area:recovery`, `area:routing`, `type:hardening`, `priority:p1`, `ready-for-agent`
- **Evidence class:** `fixture`
- **Hardware:** `none`
- **Model:** `generic`
- **Upstream:** `no`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/059-implement-alpha-safe-route-recovery.md`, and evidence READMEs for dependencies (DGR-043, DGR-058) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Recover from route loss without importing or continuing unverified state.
## Acceptance criteria
- [ ] On route loss or local-state cache miss, restart from token zero or re-prefill on a newly compatible route according to the locked alpha contract.
- [ ] Never import KV, CSA, HCA, SWA, indexer, compressor, recurrent, or MTP cache/state across workers.
- [ ] Keep exact same-route duplicate delivery idempotent while cross-route continuation fails closed.
- [ ] Test direct/relay loss, cache miss, replacement selection, client cancellation, and billing reconciliation.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Write and verify `.scratch/distributed-gguf-runtime/evidence/DGR-059/README.md`. Until every criterion and applicable gate has real evidence, this story remains `passes: false`. Legacy evidence is provenance only, not completion credit.

View File

@@ -1,61 +0,0 @@
# 06 — Implement architecture-defined boundary input/output
Status: ready-for-agent
## Mandatory fresh-session context
- Read [RALPH-CONTEXT.md](../RALPH-CONTEXT.md) completely before changing code.
- This issue is `DGR-006` in [prd.json](../prd.json).
- Read the evidence README for every dependency listed below.
- Inspect current code and `git status`; historical text and previous agent claims are not evidence.
## Description
As a Shard, I need to consume and emit the correct transformer boundary state so that disjoint processes reproduce whole-model execution.
## Expected durable outputs
- Architecture boundary adapter
- Whole-model/two-range parity tests and results
- evidence/DGR-006/README.md
## Acceptance criteria
- [ ] Head accepts token IDs and owns token embedding.
- [ ] Middle/tail bypass token embedding and accept the named boundary bundle.
- [ ] Non-tail emits the unnormalized architecture-defined residual/boundary before final norm/head and before tail-only row pruning.
- [ ] Tail emits logits or token output through an explicit sampling contract.
- [ ] Dense-Llama whole-model versus two-range prefill and greedy-decode parity passes the documented tolerance.
- [ ] The adapter interface fails closed for uncertified architectures.
- [ ] Targeted pytest tests pass
- [ ] python -m compileall packages tests passes for Python changes
- [ ] git diff --check passes
- [ ] Default tests remain deterministic, model-download-free, API-credit-free, and GPU-free
- [ ] Full deterministic pytest -q passes, or the exact pre-existing unrelated failure is recorded with a clean-tree reproduction
- [ ] Pinned native C++ target builds and focused CTest/protocol tests pass where native code is touched
- [ ] llama.cpp patch stack applies cleanly to the exact pinned commit where patch code is touched
- [ ] Read .scratch/distributed-gguf-runtime/RALPH-CONTEXT.md and this story issue completely before changing code
- [ ] Read and verify every dependency evidence README before relying on dependency behavior
- [ ] Preserve all pre-existing working-tree changes and stage only files belonging to this story
- [ ] Write .scratch/distributed-gguf-runtime/evidence/DGR-006/README.md with files changed, exact commands and real results, limitations, compatibility notes, and dependent-story handoff
- [ ] Update only this story issue to Status: done after every acceptance criterion and quality gate passes
## Dependency handoff
- `DGR-002` must have `passes: true`; read `../evidence/DGR-002/README.md` and verify its referenced files/commands.
- `DGR-005` must have `passes: true`; read `../evidence/DGR-005/README.md` and verify its referenced files/commands.
## Finish contract
- Create the task evidence directory and durable handoff required above.
- Preserve real failures and blockers; never fabricate benchmark, model, test or hardware output.
- Change this issue to `Status: done` only after all criteria pass.
- Emit `<promise>COMPLETE</promise>` only after the evidence handoff exists.
## References
- [Ralph execution context](../RALPH-CONTEXT.md)
- [PRD](../PRD.md)
- [Implementation strategy](../implementation-strategy.md)
- [Current architecture](../architecture.md)
- [Architecture decision](../../docs/adr/0024-distributed-gguf-runtime.md)

View File

@@ -0,0 +1,39 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-060: Certify V4 long-context state correctness
- **Status / triage:** specification only; `ready-for-agent`; `passes: false`
- **Execution mode:** `AFK`
- **Milestone:** `M4`
- **Dependencies:** `DGR-051`, `DGR-056`, `DGR-058`
- **Blocks (derived):** `DGR-062`, `DGR-064`, `DGR-065`, `DGR-066`, `DGR-070`
- **Labels:** `area:deepseek-v4`, `area:long-context`, `type:certification`, `priority:p1`, `ready-for-agent`
- **Evidence class:** `real-hardware`
- **Hardware:** `required`
- **Model:** `deepseek-v4-flash`
- **Upstream:** `yes`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/060-certify-v4-long-context-state-correctness.md`, and evidence READMEs for dependencies (DGR-051, DGR-056, DGR-058) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Prove V4s KV and auxiliary state remain correct and bounded at long contexts.
## Acceptance criteria
- [ ] Exercise pre-locked context lengths covering multiple prefill chunks and sustained decode.
- [ ] Validate KV plus CSA/HCA/SWA/indexer/compressor state positions across every stage.
- [ ] Measure memory growth, fragment sizes, TTFT, decode degradation, cancellation latency, and cleanup.
- [ ] Cache mismatch, truncation, and context-limit behavior fail deterministically.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Write and verify `.scratch/distributed-gguf-runtime/evidence/DGR-060/README.md`. Until every criterion and applicable gate has real evidence, this story remains `passes: false`. Legacy evidence is provenance only, not completion credit.

View File

@@ -0,0 +1,39 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-061: Certify existing routing with 10+ GGUF stage candidates
- **Status / triage:** specification only; `ready-for-agent`; `passes: false`
- **Execution mode:** `AFK`
- **Milestone:** `M4`
- **Dependencies:** `DGR-043`, `DGR-057`, `DGR-058`
- **Blocks (derived):** `DGR-062`, `DGR-063`
- **Labels:** `area:tracker`, `area:scale`, `type:simulation`, `priority:p1`, `ready-for-agent`
- **Evidence class:** `fixture`
- **Hardware:** `none`
- **Model:** `generic`
- **Upstream:** `no`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/061-certify-existing-routing-with-10-gguf-stage-candidates.md`, and evidence READMEs for dependencies (DGR-043, DGR-057, DGR-058) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Certify that existing backend-agnostic routing consumes GGUF compatibility and measured-cost inputs for a 10+ candidate scenario without algorithm or policy redesign.
## Acceptance criteria
- [ ] Generate deterministic pools with 10+ compatible GGUF stage candidates plus slower, overloaded, unhealthy, and incompatible alternatives.
- [ ] Run the existing routing implementation unchanged and verify complete coverage, compatibility, acyclicity, and use of measured inputs.
- [ ] Regression-test that no stage count, quant, fixed split, architecture, or backend sequence is encoded in production routing policy.
- [ ] Verify existing route recomputation reacts to measured load/failure while tracker, load-balancing, billing, relay, and provider semantics remain unchanged.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Write and verify `.scratch/distributed-gguf-runtime/evidence/DGR-061/README.md`. Until every criterion and applicable gate has real evidence, this story remains `passes: false`. Legacy evidence is provenance only, not completion credit.

View File

@@ -0,0 +1,40 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-062: Certify a dynamic real 10+ stage V4 scenario
- **Status / triage:** specification only; `ready-for-human`; `passes: false`
- **Execution mode:** `HITL`
- **Milestone:** `M4`
- **Dependencies:** `DGR-053`, `DGR-060`, `DGR-061`
- **Blocks (derived):** `DGR-067`, `DGR-070`
- **Labels:** `area:deepseek-v4`, `area:scale`, `area:hardware`, `type:certification`, `priority:p1`, `gate:hitl`, `ready-for-human`
- **Evidence class:** `real-hardware`
- **Hardware:** `required`
- **Model:** `deepseek-v4-flash`
- **Upstream:** `yes`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/062-certify-a-dynamic-real-10-stage-v4-scenario.md`, and evidence READMEs for dependencies (DGR-053, DGR-060, DGR-061) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Demonstrate that a large real route can be dynamically selected and usefully execute V4.
## Acceptance criteria
- [ ] Run one real 10+-stage V4 certification scenario; stage count, quant, and split remain scenario metadata only.
- [ ] Every selected stage proves real work, exact compatible identity, local state ownership, and bounded resources.
- [ ] Record end-to-end and per-stage TTFT, prefill/decode, seam cost, queueing, memory, failures, and cleanup.
- [ ] Inject at least one incompatible or degraded candidate and verify dynamic exclusion/reselection.
- [ ] The scenario must meet its pre-locked usefulness threshold or remain failed evidence.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Write and verify `.scratch/distributed-gguf-runtime/evidence/DGR-062/README.md`. Until every criterion and applicable gate has real evidence, this story remains `passes: false`. Legacy evidence is provenance only, not completion credit.

View File

@@ -0,0 +1,39 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-063: Profile and optimize the critical seam
- **Status / triage:** specification only; `ready-for-agent`; `passes: false`
- **Execution mode:** `AFK`
- **Milestone:** `M4`
- **Dependencies:** `DGR-057`, `DGR-061`
- **Blocks (derived):** `DGR-064`
- **Labels:** `area:performance`, `type:optimization`, `priority:p1`, `ready-for-agent`
- **Evidence class:** `real-hardware`
- **Hardware:** `required`
- **Model:** `generic`
- **Upstream:** `conditional`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/063-profile-and-optimize-the-critical-seam.md`, and evidence READMEs for dependencies (DGR-057, DGR-061) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Optimize only the measured dominant compute, serialization, copy, or transport bottleneck.
## Acceptance criteria
- [ ] Profile worker compute, tensor conversion, copies, protobuf framing, compression, relay/direct transport, queueing, and synchronization.
- [ ] Select one dominant bottleneck from evidence and lock its before/after benchmark.
- [ ] Implement one bounded optimization without weakening correctness or protocol identity.
- [ ] Report whether the optimization changes TTFT, prefill, decode, throughput, or memory and preserve raw data.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Write and verify `.scratch/distributed-gguf-runtime/evidence/DGR-063/README.md`. Until every criterion and applicable gate has real evidence, this story remains `passes: false`. Legacy evidence is provenance only, not completion credit.

View File

@@ -0,0 +1,39 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-064: Add negotiated activation compression
- **Status / triage:** specification only; `ready-for-agent`; `passes: false`
- **Execution mode:** `AFK`
- **Milestone:** `M4`
- **Dependencies:** `DGR-060`, `DGR-063`
- **Blocks (derived):** `DGR-066`, `DGR-070`
- **Labels:** `area:protocol`, `area:compression`, `type:optimization`, `priority:p1`, `ready-for-agent`
- **Evidence class:** `real-hardware`
- **Hardware:** `required`
- **Model:** `deepseek-v4-flash`
- **Upstream:** `no`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/064-add-negotiated-activation-compression.md`, and evidence READMEs for dependencies (DGR-060, DGR-063) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Reduce V4 seam cost only when a certified compression recipe improves end-to-end performance acceptably.
## Acceptance criteria
- [ ] Negotiate compression through recipe identity; unnegotiated or mismatched compression fails closed.
- [ ] Preserve names, shapes, semantic axes, token-ID sideband, and checksums.
- [ ] Measure quality drift, encode/decode cost, bytes, TTFT, and throughput against uncompressed boundaries.
- [ ] Compression remains dark unless it meets pre-locked quality and speed thresholds.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Write and verify `.scratch/distributed-gguf-runtime/evidence/DGR-064/README.md`. Until every criterion and applicable gate has real evidence, this story remains `passes: false`. Legacy evidence is provenance only, not completion credit.

View File

@@ -0,0 +1,39 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-065: Define V4 MTP ownership and distributed state contract
- **Status / triage:** specification only; `ready-for-agent`; `passes: false`
- **Execution mode:** `AFK`
- **Milestone:** `M4`
- **Dependencies:** `DGR-051`, `DGR-054`, `DGR-060`
- **Blocks (derived):** `DGR-066`
- **Labels:** `area:deepseek-v4`, `area:mtp`, `type:contract`, `priority:p1`, `ready-for-agent`
- **Evidence class:** `fixture`
- **Hardware:** `none`
- **Model:** `deepseek-v4-flash`
- **Upstream:** `yes`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/065-define-v4-mtp-ownership-and-distributed-state-contract.md`, and evidence READMEs for dependencies (DGR-051, DGR-054, DGR-060) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Lock MTP tensor, execution, boundary, acceptance/rejection, and session-state ownership before implementation while keeping MTP disabled for alpha.
## Acceptance criteria
- [ ] Derive exact MTP tensor and execution ownership from the pinned V4 target and upstream llama.cpp graph, distinguishing main-layer, tail, and MTP responsibilities.
- [ ] Define typed MTP inputs/outputs plus accepted-token, rejection, rollback/truncation, position, cache, and session/epoch lifecycle semantics.
- [ ] Specify which MTP state remains shard-local and which typed boundary values cross a seam; prohibit WAN migration of KV or V4 auxiliary caches.
- [ ] Keep every MTP recipe disabled and unroutable for alpha, with fail-closed capability negotiation and deterministic contract fixtures.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Write and verify `.scratch/distributed-gguf-runtime/evidence/DGR-065/README.md`. Until every criterion and applicable gate has real evidence, this story remains `passes: false`. Legacy evidence is provenance only, not completion credit.

View File

@@ -0,0 +1,39 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-066: Implement and benchmark V4 MTP
- **Status / triage:** specification only; `ready-for-agent`; `passes: false`
- **Execution mode:** `AFK`
- **Milestone:** `M4`
- **Dependencies:** `DGR-054`, `DGR-060`, `DGR-064`, `DGR-065`
- **Blocks (derived):** `DGR-067`, `DGR-070`
- **Labels:** `area:deepseek-v4`, `area:mtp`, `type:runtime`, `priority:p1`, `ready-for-agent`
- **Evidence class:** `real-hardware`
- **Hardware:** `required`
- **Model:** `deepseek-v4-flash`
- **Upstream:** `yes`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/066-implement-and-benchmark-v4-mtp.md`, and evidence READMEs for dependencies (DGR-054, DGR-060, DGR-064, DGR-065) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Implement the locked MTP contract around upstream llama.cpp before beta, without making MTP an alpha prerequisite.
## Acceptance criteria
- [ ] Implement the exact DGR-065 MTP ownership and typed state contract against the pinned upstream V4 graph while preserving shard-local caches.
- [ ] Pass whole-model versus ranged MTP correctness, accepted-token, rejection, rollback/truncation, and session-isolation tests.
- [ ] Benchmark MTP-off versus MTP-on quality, accepted-token rate, TTFT, decode speed, seam bytes, and memory on the locked lane.
- [ ] Distinguish implemented, certified, disabled, and unsupported MTP recipes in fail-closed capability advertisement.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Write and verify `.scratch/distributed-gguf-runtime/evidence/DGR-066/README.md`. Until every criterion and applicable gate has real evidence, this story remains `passes: false`. Legacy evidence is provenance only, not completion credit.

View File

@@ -0,0 +1,40 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-067: Certify the backend capability matrix
- **Status / triage:** specification only; `ready-for-human`; `passes: false`
- **Execution mode:** `HITL`
- **Milestone:** `M4`
- **Dependencies:** `DGR-030`, `DGR-053`, `DGR-062`, `DGR-066`
- **Blocks (derived):** `DGR-068`, `DGR-070`
- **Labels:** `area:hardware`, `area:admission`, `type:certification`, `priority:p1`, `gate:hitl`, `ready-for-human`
- **Evidence class:** `real-hardware`
- **Hardware:** `required`
- **Model:** `deepseek-v4-flash`
- **Upstream:** `yes`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/067-certify-the-backend-capability-matrix.md`, and evidence READMEs for dependencies (DGR-030, DGR-053, DGR-062, DGR-066) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Publish only backend/model/recipe lanes proven on actual CPU, CUDA, ROCm, Vulkan, or Metal hardware.
## Acceptance criteria
- [ ] Maintain independent build and certification status for CPU, CUDA, ROCm, Vulkan, and Metal.
- [ ] Each advertised lane includes real hardware/driver/runtime/model evidence for parity, concurrency, cancellation, cleanup, and useful speed.
- [ ] Build success alone never makes a lane routable; unavailable hardware remains explicitly dark.
- [ ] Tracker admission consumes signed/versioned certification records rather than backend-name allowlists.
- [ ] Mixed-backend routes require exact compatibility evidence and fail closed otherwise.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Write and verify `.scratch/distributed-gguf-runtime/evidence/DGR-067/README.md`. Until every criterion and applicable gate has real evidence, this story remains `passes: false`. Legacy evidence is provenance only, not completion credit.

View File

@@ -0,0 +1,39 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-068: Package reproducible native worker releases
- **Status / triage:** specification only; `ready-for-agent`; `passes: false`
- **Execution mode:** `AFK`
- **Milestone:** `M5`
- **Dependencies:** `DGR-030`, `DGR-054`, `DGR-067`
- **Blocks (derived):** `DGR-070`
- **Labels:** `area:packaging`, `area:release`, `type:delivery`, `priority:p1`, `ready-for-agent`
- **Evidence class:** `release`
- **Hardware:** `optional`
- **Model:** `generic`
- **Upstream:** `yes`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/068-package-reproducible-native-worker-releases.md`, and evidence READMEs for dependencies (DGR-030, DGR-054, DGR-067) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Produce installable worker packages that preserve exact source, patch, protocol, and certification identity.
## Acceptance criteria
- [ ] Package worker binaries/configuration for supported host/backend combinations without bundling an unverified llama.cpp tree.
- [ ] Embed protocol, engine, upstream pin, patch-stack, build-toolchain, and certification fingerprints.
- [ ] Installation/startup refuses mismatched artifacts, runtime recipes, or unsupported hardware lanes.
- [ ] Produce checksums, SBOM/license attribution, reproducible build instructions, and smoke tests.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Write and verify `.scratch/distributed-gguf-runtime/evidence/DGR-068/README.md`. Until every criterion and applicable gate has real evidence, this story remains `passes: false`. Legacy evidence is provenance only, not completion credit.

View File

@@ -0,0 +1,39 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-069: Prepare narrow upstream llama.cpp collaboration patches
- **Status / triage:** specification only; `ready-for-human`; `passes: false`
- **Execution mode:** `HITL`
- **Milestone:** `M5`
- **Dependencies:** `DGR-028`, `DGR-035`, `DGR-038`, `DGR-051`
- **Blocks (derived):** `DGR-071`
- **Labels:** `area:upstream`, `area:patches`, `type:collaboration`, `priority:p2`, `gate:hitl`, `ready-for-human`
- **Evidence class:** `release`
- **Hardware:** `none`
- **Model:** `generic+deepseek-v4`
- **Upstream:** `yes`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/069-prepare-narrow-upstream-llama-cpp-collaboration-patches.md`, and evidence READMEs for dependencies (DGR-028, DGR-035, DGR-038, DGR-051) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Reduce long-term patch burden through generic upstreamable hooks without asking llama.cpp to own Meshnet.
## Acceptance criteria
- [ ] Separate generic range loading, boundary I/O, and filtered state hooks from project worker/protocol code.
- [ ] Provide one scoped patch, focused test, and minimal reproducer per concern against the exact upstream pin.
- [ ] Compare the proposal with prior-art evidence and current upstream V4 support/maturity.
- [ ] Prepare human-ready design/outreach text; actual issue/PR submission remains a human action.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Write and verify `.scratch/distributed-gguf-runtime/evidence/DGR-069/README.md`. Until every criterion and applicable gate has real evidence, this story remains `passes: false`. Legacy evidence is provenance only, not completion credit.

View File

@@ -1,60 +0,0 @@
# 07 — Add isolated concurrent local Hot KV State
Status: ready-for-agent
## Mandatory fresh-session context
- Read [RALPH-CONTEXT.md](../RALPH-CONTEXT.md) completely before changing code.
- This issue is `DGR-007` in [prd.json](../prd.json).
- Read the evidence README for every dependency listed below.
- Inspect current code and `git status`; historical text and previous agent claims are not evidence.
## Description
As a client, I need concurrent Route Sessions to retain independent per-Shard cache so that one request cannot clear or corrupt another.
## Expected durable outputs
- Concurrent local KV/session manager
- Isolation, eviction, cancellation and cleanup tests
- evidence/DGR-007/README.md
## Acceptance criteria
- [ ] Map `(Route Session ID, route epoch)` to an isolated llama sequence or bounded context.
- [ ] Allocate KV only for owned layers.
- [ ] Support prefill append, decode append, truncate, release, TTL/LRU eviction, and explicit cache-miss response.
- [ ] Reject stale epochs and incompatible cache recipes.
- [ ] At least four concurrent sessions on a small model complete without token or KV cross-talk.
- [ ] Cancellation/release of one session leaves other sessions intact and memory returns to the configured budget.
- [ ] Targeted pytest tests pass
- [ ] python -m compileall packages tests passes for Python changes
- [ ] git diff --check passes
- [ ] Default tests remain deterministic, model-download-free, API-credit-free, and GPU-free
- [ ] Full deterministic pytest -q passes, or the exact pre-existing unrelated failure is recorded with a clean-tree reproduction
- [ ] Pinned native C++ target builds and focused CTest/protocol tests pass where native code is touched
- [ ] llama.cpp patch stack applies cleanly to the exact pinned commit where patch code is touched
- [ ] Read .scratch/distributed-gguf-runtime/RALPH-CONTEXT.md and this story issue completely before changing code
- [ ] Read and verify every dependency evidence README before relying on dependency behavior
- [ ] Preserve all pre-existing working-tree changes and stage only files belonging to this story
- [ ] Write .scratch/distributed-gguf-runtime/evidence/DGR-007/README.md with files changed, exact commands and real results, limitations, compatibility notes, and dependent-story handoff
- [ ] Update only this story issue to Status: done after every acceptance criterion and quality gate passes
## Dependency handoff
- `DGR-006` must have `passes: true`; read `../evidence/DGR-006/README.md` and verify its referenced files/commands.
## Finish contract
- Create the task evidence directory and durable handoff required above.
- Preserve real failures and blockers; never fabricate benchmark, model, test or hardware output.
- Change this issue to `Status: done` only after all criteria pass.
- Emit `<promise>COMPLETE</promise>` only after the evidence handoff exists.
## References
- [Ralph execution context](../RALPH-CONTEXT.md)
- [PRD](../PRD.md)
- [Implementation strategy](../implementation-strategy.md)
- [Current architecture](../architecture.md)
- [Architecture decision](../../docs/adr/0024-distributed-gguf-runtime.md)

View File

@@ -0,0 +1,39 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-070: Enforce the DeepSeek V4 Flash beta gate
- **Status / triage:** specification only; `ready-for-human`; `passes: false`
- **Execution mode:** `HITL`
- **Milestone:** `M5`
- **Dependencies:** `DGR-057`, `DGR-059`, `DGR-060`, `DGR-062`, `DGR-064`, `DGR-066`, `DGR-067`, `DGR-068`
- **Blocks (derived):** `DGR-071`
- **Labels:** `area:deepseek-v4`, `area:release`, `milestone:beta`, `priority:p0`, `gate:hitl`, `ready-for-human`
- **Evidence class:** `release`
- **Hardware:** `required`
- **Model:** `deepseek-v4-flash`
- **Upstream:** `yes`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/070-enforce-the-deepseek-v4-flash-beta-gate.md`, and evidence READMEs for dependencies (DGR-057, DGR-059, DGR-060, DGR-062, DGR-064, DGR-066, DGR-067, DGR-068) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Promote beta only after concurrency, resilience, long-context, MTP, scale, packaging, and speed gates pass.
## Acceptance criteria
- [ ] Evaluate all beta metrics against DGF-004 without changing thresholds after observing results.
- [ ] Require V4 parity, batching/fairness, bounded backpressure, failure recovery, long-context correctness, MTP evidence, and dynamic 10+ stage evidence.
- [ ] Publish the exact certified hardware/backend/recipe matrix; all other lanes remain dark.
- [ ] Decision is `beta`, `targeted optimization`, or `stop/rollback`, with unresolved failures listed explicitly.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Write and verify `.scratch/distributed-gguf-runtime/evidence/DGR-070/README.md`. Until every criterion and applicable gate has real evidence, this story remains `passes: false`. Legacy evidence is provenance only, not completion credit.

View File

@@ -0,0 +1,39 @@
<!-- GENERATED FROM prd.json — DO NOT EDIT AS AN INDEPENDENT SOURCE. prd.json IS AUTHORITATIVE. -->
# DGR-071: Establish upstream pin, patch, and certification maintenance
- **Status / triage:** specification only; `ready-for-agent`; `passes: false`
- **Execution mode:** `AFK`
- **Milestone:** `M5`
- **Dependencies:** `DGR-069`, `DGR-070`
- **Blocks (derived):** None
- **Labels:** `area:maintenance`, `area:upstream`, `area:certification`, `type:operations`, `priority:p2`, `ready-for-agent`
- **Evidence class:** `release`
- **Hardware:** `optional`
- **Model:** `deepseek-v4-flash`
- **Upstream:** `yes`
## Objective / description
Fresh Ralph session: read `.scratch/distributed-gguf-runtime/RALPH-CONTEXT.md`, source issue `.scratch/distributed-gguf-runtime/issues/071-establish-upstream-pin-patch-and-certification-maintenance.md`, and evidence READMEs for dependencies (DGR-069, DGR-070) before changing code. Inspect live source/tests rather than trusting legacy pass states. Objective: Keep beta reproducible and detect upstream/model/hardware drift before it reaches routable nodes.
## Acceptance criteria
- [ ] Add a documented update procedure for llama.cpp pin, numbered patches, protocol/engine versions, V4 target revision, and certification records.
- [ ] A candidate pin update must apply/build/test in isolation and cannot replace the production pin automatically.
- [ ] Any changed graph, tensor inventory, boundary, cache/state layout, backend behavior, or performance invalidates affected certification.
- [ ] Add scheduled model-free checks plus opt-in real-hardware recertification instructions and rollback procedure.
- [ ] Applicable shared quality gates in `prd.json` pass, and the evidence handoff records exact commands/results, changed files, limitations, and dependency handoff.
## Shared quality gates
- Targeted deterministic tests pass; Python changes also pass `python -m compileall packages tests`.
- `git diff --check` passes.
- Default tests are model-download-free, API-credit-free, and GPU-free.
- Evidence README records exact changed files, commands/results, limitations, and dependency handoff; no fabricated evidence or inherited completion credit.
- Native changes pass focused out-of-tree CMake build and CTest; patch changes verify clean apply/check/reverse against the exact llama.cpp pin.
- Runs are opt-in and record exact artifact/split hashes, runtime/upstream pin, backend/driver, hardware, network, commands, and raw metrics. Model artifacts use configured mounted-drive storage and never `/home`.
- Preserve existing Transformers behavior and backend-agnostic Tracker routing/load balancing/billing/relay semantics unless an explicit versioned contract says otherwise. One scoped story commit is expected during execution, but this specification-materialization change is not committed.
## Evidence handoff
Write and verify `.scratch/distributed-gguf-runtime/evidence/DGR-071/README.md`. Until every criterion and applicable gate has real evidence, this story remains `passes: false`. Legacy evidence is provenance only, not completion credit.

View File

@@ -1,65 +0,0 @@
# 08 — Build the standalone C++ gRPC Shard worker
Status: ready-for-agent
## Mandatory fresh-session context
- Read [RALPH-CONTEXT.md](../RALPH-CONTEXT.md) completely before changing code.
- This issue is `DGR-008` in [prd.json](../prd.json).
- Read the evidence README for every dependency listed below.
- Inspect current code and `git status`; historical text and previous agent claims are not evidence.
## Description
As a node runtime, I need one supervised native process so that llama.cpp internals remain behind a stable project-owned protocol.
## Expected durable outputs
- Standalone C++ gRPC worker
- Fake-model Python/C++ integration tests
- Lifecycle and bounded-failure evidence
- evidence/DGR-008/README.md
## Acceptance criteria
- [ ] Worker exposes capability, health, session stream, release, cancellation, and metrics services from DGR-002.
- [ ] Worker loads one exact Artifact/recipe/Shard identity and refuses mismatched requests.
- [ ] Streaming path enforces bounded messages, flow control, deadlines, idempotency, and independent session cancellation.
- [ ] Worker does not expose raw llama.cpp RPC or arbitrary GGML graph execution.
- [ ] Graceful shutdown releases sessions; crash behavior is bounded and observable.
- [ ] Python integration tests run against a fake model mode without model downloads.
- [ ] Targeted pytest tests pass
- [ ] python -m compileall packages tests passes for Python changes
- [ ] git diff --check passes
- [ ] Default tests remain deterministic, model-download-free, API-credit-free, and GPU-free
- [ ] Full deterministic pytest -q passes, or the exact pre-existing unrelated failure is recorded with a clean-tree reproduction
- [ ] Pinned native C++ target builds and focused CTest/protocol tests pass where native code is touched
- [ ] llama.cpp patch stack applies cleanly to the exact pinned commit where patch code is touched
- [ ] Read .scratch/distributed-gguf-runtime/RALPH-CONTEXT.md and this story issue completely before changing code
- [ ] Read and verify every dependency evidence README before relying on dependency behavior
- [ ] Preserve all pre-existing working-tree changes and stage only files belonging to this story
- [ ] Write .scratch/distributed-gguf-runtime/evidence/DGR-008/README.md with files changed, exact commands and real results, limitations, compatibility notes, and dependent-story handoff
- [ ] Update only this story issue to Status: done after every acceptance criterion and quality gate passes
## Dependency handoff
- `DGR-002` must have `passes: true`; read `../evidence/DGR-002/README.md` and verify its referenced files/commands.
- `DGR-003` must have `passes: true`; read `../evidence/DGR-003/README.md` and verify its referenced files/commands.
- `DGR-004` must have `passes: true`; read `../evidence/DGR-004/README.md` and verify its referenced files/commands.
- `DGR-006` must have `passes: true`; read `../evidence/DGR-006/README.md` and verify its referenced files/commands.
- `DGR-007` must have `passes: true`; read `../evidence/DGR-007/README.md` and verify its referenced files/commands.
## Finish contract
- Create the task evidence directory and durable handoff required above.
- Preserve real failures and blockers; never fabricate benchmark, model, test or hardware output.
- Change this issue to `Status: done` only after all criteria pass.
- Emit `<promise>COMPLETE</promise>` only after the evidence handoff exists.
## References
- [Ralph execution context](../RALPH-CONTEXT.md)
- [PRD](../PRD.md)
- [Implementation strategy](../implementation-strategy.md)
- [Current architecture](../architecture.md)
- [Architecture decision](../../docs/adr/0024-distributed-gguf-runtime.md)

View File

@@ -1,61 +0,0 @@
# 09 — Integrate the native worker with Meshnet
Status: ready-for-agent
## Mandatory fresh-session context
- Read [RALPH-CONTEXT.md](../RALPH-CONTEXT.md) completely before changing code.
- This issue is `DGR-009` in [prd.json](../prd.json).
- Read the evidence README for every dependency listed below.
- Inspect current code and `git status`; historical text and previous agent claims are not evidence.
## Description
As the existing node service, I need a GGUF Shard backend adapter so that the Tracker, relay, billing, telemetry, and capability admission remain the sole control plane.
## Expected durable outputs
- Meshnet GGUF backend adapter
- Registration, routing, relay, telemetry and billing tests
- evidence/DGR-009/README.md
## Acceptance criteria
- [ ] Implement the existing model-backend surface without changing Transformers behavior.
- [ ] Registration carries exact validated GGUF recipe, Shard, backend and concurrency/KV capacity.
- [ ] Tracker forms only complete compatible routes and keeps uncertified recipes dark.
- [ ] Direct routes use gRPC streams; relayed routes carry the same versioned protobuf frames as opaque binary through the existing relay seam.
- [ ] Existing request/work IDs, cancellation, Generation Telemetry, billing, and per-node attribution remain correlated.
- [ ] No vLLM, Nakshatra, prima.cpp, or custom-engine control plane becomes a core dependency.
- [ ] Targeted pytest tests pass
- [ ] python -m compileall packages tests passes for Python changes
- [ ] git diff --check passes
- [ ] Default tests remain deterministic, model-download-free, API-credit-free, and GPU-free
- [ ] Full deterministic pytest -q passes, or the exact pre-existing unrelated failure is recorded with a clean-tree reproduction
- [ ] Pinned native C++ target builds and focused CTest/protocol tests pass where native code is touched
- [ ] llama.cpp patch stack applies cleanly to the exact pinned commit where patch code is touched
- [ ] Read .scratch/distributed-gguf-runtime/RALPH-CONTEXT.md and this story issue completely before changing code
- [ ] Read and verify every dependency evidence README before relying on dependency behavior
- [ ] Preserve all pre-existing working-tree changes and stage only files belonging to this story
- [ ] Write .scratch/distributed-gguf-runtime/evidence/DGR-009/README.md with files changed, exact commands and real results, limitations, compatibility notes, and dependent-story handoff
- [ ] Update only this story issue to Status: done after every acceptance criterion and quality gate passes
## Dependency handoff
- `DGR-003` must have `passes: true`; read `../evidence/DGR-003/README.md` and verify its referenced files/commands.
- `DGR-008` must have `passes: true`; read `../evidence/DGR-008/README.md` and verify its referenced files/commands.
## Finish contract
- Create the task evidence directory and durable handoff required above.
- Preserve real failures and blockers; never fabricate benchmark, model, test or hardware output.
- Change this issue to `Status: done` only after all criteria pass.
- Emit `<promise>COMPLETE</promise>` only after the evidence handoff exists.
## References
- [Ralph execution context](../RALPH-CONTEXT.md)
- [PRD](../PRD.md)
- [Implementation strategy](../implementation-strategy.md)
- [Current architecture](../architecture.md)
- [Architecture decision](../../docs/adr/0024-distributed-gguf-runtime.md)

View File

@@ -1,62 +0,0 @@
# 10 — Pass local real-model two-process acceptance
Status: ready-for-agent
## Mandatory fresh-session context
- Read [RALPH-CONTEXT.md](../RALPH-CONTEXT.md) completely before changing code.
- This issue is `DGR-010` in [prd.json](../prd.json).
- Read the evidence README for every dependency listed below.
- Inspect current code and `git status`; historical text and previous agent claims are not evidence.
## Description
As a release engineer, I need real local distributed parity before involving network variability.
## Expected durable outputs
- Real local two-process commands and configuration
- Raw parity, memory and performance results
- evidence/DGR-010/README.md
## Acceptance criteria
- [ ] Two local worker processes open disjoint dense-Llama ranges from the certified Artifact.
- [ ] Prefill and at least 32 greedy decode tokens match whole-model llama.cpp within the certified tolerance.
- [ ] Each worker retains only its own tensors and Hot KV State.
- [ ] Four concurrent Route Sessions pass isolation and cleanup checks.
- [ ] Report TTFT, prefill/decode throughput, seam bytes/latency, worker RSS/VRAM, KV memory, batch size, and queue time.
- [ ] Killing one worker produces a bounded structured failure rather than a deadlock.
- [ ] Targeted pytest tests pass
- [ ] python -m compileall packages tests passes for Python changes
- [ ] git diff --check passes
- [ ] Default tests remain deterministic, model-download-free, API-credit-free, and GPU-free
- [ ] Full deterministic pytest -q passes, or the exact pre-existing unrelated failure is recorded with a clean-tree reproduction
- [ ] Pinned native C++ target builds and focused CTest/protocol tests pass where native code is touched
- [ ] llama.cpp patch stack applies cleanly to the exact pinned commit where patch code is touched
- [ ] Real-model execution is opt-in through MESHNET_ENABLE_REAL_INFERENCE_TESTS=1 and records exact artifact/runtime/hardware evidence
- [ ] Model artifacts remain on the configured mounted-drive storage and never under /home
- [ ] Read .scratch/distributed-gguf-runtime/RALPH-CONTEXT.md and this story issue completely before changing code
- [ ] Read and verify every dependency evidence README before relying on dependency behavior
- [ ] Preserve all pre-existing working-tree changes and stage only files belonging to this story
- [ ] Write .scratch/distributed-gguf-runtime/evidence/DGR-010/README.md with files changed, exact commands and real results, limitations, compatibility notes, and dependent-story handoff
- [ ] Update only this story issue to Status: done after every acceptance criterion and quality gate passes
## Dependency handoff
- `DGR-009` must have `passes: true`; read `../evidence/DGR-009/README.md` and verify its referenced files/commands.
## Finish contract
- Create the task evidence directory and durable handoff required above.
- Preserve real failures and blockers; never fabricate benchmark, model, test or hardware output.
- Change this issue to `Status: done` only after all criteria pass.
- Emit `<promise>COMPLETE</promise>` only after the evidence handoff exists.
## References
- [Ralph execution context](../RALPH-CONTEXT.md)
- [PRD](../PRD.md)
- [Implementation strategy](../implementation-strategy.md)
- [Current architecture](../architecture.md)
- [Architecture decision](../../docs/adr/0024-distributed-gguf-runtime.md)

View File

@@ -1,62 +0,0 @@
# 11 — Pass a real heterogeneous two-machine route
Status: ready-for-agent
## Mandatory fresh-session context
- Read [RALPH-CONTEXT.md](../RALPH-CONTEXT.md) completely before changing code.
- This issue is `DGR-011` in [prd.json](../prd.json).
- Read the evidence README for every dependency listed below.
- Inspect current code and `git status`; historical text and previous agent claims are not evidence.
## Description
As a consumer-hardware operator, I need two physical machines to execute one GGUF model so that the distributed claim is real.
## Expected durable outputs
- Two-machine hardware/network/runtime manifest
- Raw real-route metrics and output evidence
- evidence/DGR-011/README.md
## Acceptance criteria
- [ ] Tracker selects two physical nodes with disjoint Shards and one exact certified recipe/compatibility class.
- [ ] Actual CPU/GPU execution occurs on both nodes; synthetic workers do not satisfy acceptance.
- [ ] Prefill/decode, concurrent-session isolation, telemetry, cancellation, and cleanup pass over the real transport/relay path.
- [ ] Exact hardware, network, backend, model hash, route, commands, and raw metrics are recorded.
- [ ] A model or recipe larger than one participating node's admitted memory is exercised when available.
- [ ] Output drift is measured and incompatible mixed backends fail closed.
- [ ] Targeted pytest tests pass
- [ ] python -m compileall packages tests passes for Python changes
- [ ] git diff --check passes
- [ ] Default tests remain deterministic, model-download-free, API-credit-free, and GPU-free
- [ ] Full deterministic pytest -q passes, or the exact pre-existing unrelated failure is recorded with a clean-tree reproduction
- [ ] Pinned native C++ target builds and focused CTest/protocol tests pass where native code is touched
- [ ] llama.cpp patch stack applies cleanly to the exact pinned commit where patch code is touched
- [ ] Real-model execution is opt-in through MESHNET_ENABLE_REAL_INFERENCE_TESTS=1 and records exact artifact/runtime/hardware evidence
- [ ] Model artifacts remain on the configured mounted-drive storage and never under /home
- [ ] Read .scratch/distributed-gguf-runtime/RALPH-CONTEXT.md and this story issue completely before changing code
- [ ] Read and verify every dependency evidence README before relying on dependency behavior
- [ ] Preserve all pre-existing working-tree changes and stage only files belonging to this story
- [ ] Write .scratch/distributed-gguf-runtime/evidence/DGR-011/README.md with files changed, exact commands and real results, limitations, compatibility notes, and dependent-story handoff
- [ ] Update only this story issue to Status: done after every acceptance criterion and quality gate passes
## Dependency handoff
- `DGR-010` must have `passes: true`; read `../evidence/DGR-010/README.md` and verify its referenced files/commands.
## Finish contract
- Create the task evidence directory and durable handoff required above.
- Preserve real failures and blockers; never fabricate benchmark, model, test or hardware output.
- Change this issue to `Status: done` only after all criteria pass.
- Emit `<promise>COMPLETE</promise>` only after the evidence handoff exists.
## References
- [Ralph execution context](../RALPH-CONTEXT.md)
- [PRD](../PRD.md)
- [Implementation strategy](../implementation-strategy.md)
- [Current architecture](../architecture.md)
- [Architecture decision](../../docs/adr/0024-distributed-gguf-runtime.md)

View File

@@ -1,63 +0,0 @@
# 12 — Implement continuous batching and bounded admission
Status: ready-for-agent
## Mandatory fresh-session context
- Read [RALPH-CONTEXT.md](../RALPH-CONTEXT.md) completely before changing code.
- This issue is `DGR-012` in [prd.json](../prd.json).
- Read the evidence README for every dependency listed below.
- Inspect current code and `git status`; historical text and previous agent claims are not evidence.
## Description
As a node operator, I need active sessions batched safely so that concurrency increases aggregate throughput rather than serializing every request.
## Expected durable outputs
- Continuous batching/admission scheduler
- Concurrency 1/2/4/8 report
- Queue, batch and KV-pressure evidence
- evidence/DGR-012/README.md
## Acceptance criteria
- [ ] Node scheduler admits sessions against weight, KV, scratch, and queue budgets.
- [ ] Compatible decode steps from multiple sessions form llama.cpp batches while preserving per-session positions and outputs.
- [ ] Prefill does not starve decode; scheduling policy and bounds are explicit.
- [ ] Backpressure prevents unbounded queued activations or KV growth.
- [ ] Capability telemetry reports active sessions, queue depth, batch occupancy, KV pressure, prefill/decode rates, and rejected admissions.
- [ ] Concurrency 1/2/4/8 benchmark identifies saturation and shows no cross-session corruption.
- [ ] Targeted pytest tests pass
- [ ] python -m compileall packages tests passes for Python changes
- [ ] git diff --check passes
- [ ] Default tests remain deterministic, model-download-free, API-credit-free, and GPU-free
- [ ] Full deterministic pytest -q passes, or the exact pre-existing unrelated failure is recorded with a clean-tree reproduction
- [ ] Pinned native C++ target builds and focused CTest/protocol tests pass where native code is touched
- [ ] llama.cpp patch stack applies cleanly to the exact pinned commit where patch code is touched
- [ ] Read .scratch/distributed-gguf-runtime/RALPH-CONTEXT.md and this story issue completely before changing code
- [ ] Read and verify every dependency evidence README before relying on dependency behavior
- [ ] Preserve all pre-existing working-tree changes and stage only files belonging to this story
- [ ] Write .scratch/distributed-gguf-runtime/evidence/DGR-012/README.md with files changed, exact commands and real results, limitations, compatibility notes, and dependent-story handoff
- [ ] Update only this story issue to Status: done after every acceptance criterion and quality gate passes
## Dependency handoff
- `DGR-007` must have `passes: true`; read `../evidence/DGR-007/README.md` and verify its referenced files/commands.
- `DGR-009` must have `passes: true`; read `../evidence/DGR-009/README.md` and verify its referenced files/commands.
- `DGR-010` must have `passes: true`; read `../evidence/DGR-010/README.md` and verify its referenced files/commands.
## Finish contract
- Create the task evidence directory and durable handoff required above.
- Preserve real failures and blockers; never fabricate benchmark, model, test or hardware output.
- Change this issue to `Status: done` only after all criteria pass.
- Emit `<promise>COMPLETE</promise>` only after the evidence handoff exists.
## References
- [Ralph execution context](../RALPH-CONTEXT.md)
- [PRD](../PRD.md)
- [Implementation strategy](../implementation-strategy.md)
- [Current architecture](../architecture.md)
- [Architecture decision](../../docs/adr/0024-distributed-gguf-runtime.md)

View File

@@ -1,62 +0,0 @@
# 13 — Harden failure, cancellation, and restart semantics
Status: ready-for-agent
## Mandatory fresh-session context
- Read [RALPH-CONTEXT.md](../RALPH-CONTEXT.md) completely before changing code.
- This issue is `DGR-013` in [prd.json](../prd.json).
- Read the evidence README for every dependency listed below.
- Inspect current code and `git status`; historical text and previous agent claims are not evidence.
## Description
As a client, I need failures to be bounded and explicit so that distributed speed does not come with hanging or corrupted generations.
## Expected durable outputs
- Failure/cancel/restart test matrix
- Resource cleanup and billing-state evidence
- evidence/DGR-013/README.md
## Acceptance criteria
- [ ] Deadlines and heartbeat/health loss terminate blocked stream operations.
- [ ] Cancellation propagates across every Shard and releases local KV and queued buffers.
- [ ] Duplicate steps are idempotent; uncertain mutations are never replayed silently.
- [ ] Alpha failover restarts from token zero on a newly compatible route rather than importing unverified KV.
- [ ] Worker death, stream reset, malformed bundle, stale epoch, and cache miss tests pass.
- [ ] Billing/work records distinguish completed, cancelled, failed, and unverified work.
- [ ] Targeted pytest tests pass
- [ ] python -m compileall packages tests passes for Python changes
- [ ] git diff --check passes
- [ ] Default tests remain deterministic, model-download-free, API-credit-free, and GPU-free
- [ ] Full deterministic pytest -q passes, or the exact pre-existing unrelated failure is recorded with a clean-tree reproduction
- [ ] Pinned native C++ target builds and focused CTest/protocol tests pass where native code is touched
- [ ] llama.cpp patch stack applies cleanly to the exact pinned commit where patch code is touched
- [ ] Read .scratch/distributed-gguf-runtime/RALPH-CONTEXT.md and this story issue completely before changing code
- [ ] Read and verify every dependency evidence README before relying on dependency behavior
- [ ] Preserve all pre-existing working-tree changes and stage only files belonging to this story
- [ ] Write .scratch/distributed-gguf-runtime/evidence/DGR-013/README.md with files changed, exact commands and real results, limitations, compatibility notes, and dependent-story handoff
- [ ] Update only this story issue to Status: done after every acceptance criterion and quality gate passes
## Dependency handoff
- `DGR-008` must have `passes: true`; read `../evidence/DGR-008/README.md` and verify its referenced files/commands.
- `DGR-009` must have `passes: true`; read `../evidence/DGR-009/README.md` and verify its referenced files/commands.
- `DGR-012` must have `passes: true`; read `../evidence/DGR-012/README.md` and verify its referenced files/commands.
## Finish contract
- Create the task evidence directory and durable handoff required above.
- Preserve real failures and blockers; never fabricate benchmark, model, test or hardware output.
- Change this issue to `Status: done` only after all criteria pass.
- Emit `<promise>COMPLETE</promise>` only after the evidence handoff exists.
## References
- [Ralph execution context](../RALPH-CONTEXT.md)
- [PRD](../PRD.md)
- [Implementation strategy](../implementation-strategy.md)
- [Current architecture](../architecture.md)
- [Architecture decision](../../docs/adr/0024-distributed-gguf-runtime.md)

View File

@@ -1,65 +0,0 @@
# 14 — Enforce the GGUF-versus-safetensors release gate
Status: ready-for-agent
## Mandatory fresh-session context
- Read [RALPH-CONTEXT.md](../RALPH-CONTEXT.md) completely before changing code.
- This issue is `DGR-014` in [prd.json](../prd.json).
- Read the evidence README for every dependency listed below.
- Inspect current code and `git status`; historical text and previous agent claims are not evidence.
## Description
As the product owner, I need an end-to-end comparison so that the native runtime ships only if it advances model access or performance.
## Expected durable outputs
- Immutable comparison against DGR-001 thresholds
- Machine-readable final report
- Ship/optimize/stop recommendation
- evidence/DGR-014/README.md
## Acceptance criteria
- [ ] Run current distributed safetensors and distributed GGUF routes on the same certified model/hardware/network scenario where technically comparable.
- [ ] Report quality, TTFT, prefill/decode throughput, aggregate concurrency throughput, p95 latency, seam cost, memory, KV pressure, failures, and cleanup.
- [ ] Evaluate against the DGR-001 performance contract without changing thresholds after seeing results.
- [ ] Ship recommendation is one of: promote GGUF, optimize a measured bottleneck with a new bounded task, or stop the native track.
- [ ] Results clearly separate quantization gains from transport/runtime gains.
- [ ] Targeted pytest tests pass
- [ ] python -m compileall packages tests passes for Python changes
- [ ] git diff --check passes
- [ ] Default tests remain deterministic, model-download-free, API-credit-free, and GPU-free
- [ ] Full deterministic pytest -q passes, or the exact pre-existing unrelated failure is recorded with a clean-tree reproduction
- [ ] Pinned native C++ target builds and focused CTest/protocol tests pass where native code is touched
- [ ] llama.cpp patch stack applies cleanly to the exact pinned commit where patch code is touched
- [ ] Real-model execution is opt-in through MESHNET_ENABLE_REAL_INFERENCE_TESTS=1 and records exact artifact/runtime/hardware evidence
- [ ] Model artifacts remain on the configured mounted-drive storage and never under /home
- [ ] Read .scratch/distributed-gguf-runtime/RALPH-CONTEXT.md and this story issue completely before changing code
- [ ] Read and verify every dependency evidence README before relying on dependency behavior
- [ ] Preserve all pre-existing working-tree changes and stage only files belonging to this story
- [ ] Write .scratch/distributed-gguf-runtime/evidence/DGR-014/README.md with files changed, exact commands and real results, limitations, compatibility notes, and dependent-story handoff
- [ ] Update only this story issue to Status: done after every acceptance criterion and quality gate passes
## Dependency handoff
- `DGR-001` must have `passes: true`; read `../evidence/DGR-001/README.md` and verify its referenced files/commands.
- `DGR-011` must have `passes: true`; read `../evidence/DGR-011/README.md` and verify its referenced files/commands.
- `DGR-012` must have `passes: true`; read `../evidence/DGR-012/README.md` and verify its referenced files/commands.
- `DGR-013` must have `passes: true`; read `../evidence/DGR-013/README.md` and verify its referenced files/commands.
## Finish contract
- Create the task evidence directory and durable handoff required above.
- Preserve real failures and blockers; never fabricate benchmark, model, test or hardware output.
- Change this issue to `Status: done` only after all criteria pass.
- Emit `<promise>COMPLETE</promise>` only after the evidence handoff exists.
## References
- [Ralph execution context](../RALPH-CONTEXT.md)
- [PRD](../PRD.md)
- [Implementation strategy](../implementation-strategy.md)
- [Current architecture](../architecture.md)
- [Architecture decision](../../docs/adr/0024-distributed-gguf-runtime.md)

View File

@@ -1,61 +0,0 @@
# 15 — Add and certify a Qwen3/Qwen3-MoE adapter
Status: ready-for-agent
## Mandatory fresh-session context
- Read [RALPH-CONTEXT.md](../RALPH-CONTEXT.md) completely before changing code.
- This issue is `DGR-015` in [prd.json](../prd.json).
- Read the evidence README for every dependency listed below.
- Inspect current code and `git status`; historical text and previous agent claims are not evidence.
## Description
As a client seeking top models, I need a separately certified MoE-capable architecture after the dense runtime proves stable.
## Expected durable outputs
- Qwen3-family architecture adapter
- Architecture-specific parity/admission/performance results
- evidence/DGR-015/README.md
## Acceptance criteria
- [ ] Implement explicit tensor ownership, router/top-k, expert/shared-expert, Q/K normalization, boundary bundle, and cache semantics for the selected Qwen3 family recipe.
- [ ] Do not reuse the dense-Llama adapter through unchecked name substitutions.
- [ ] Whole-model versus distributed prefill/decode parity passes the architecture-specific tolerance.
- [ ] Expert memory ownership and communication are measured.
- [ ] Real consumer-hardware acceptance and capability admission pass before the recipe becomes routable.
- [ ] Targeted pytest tests pass
- [ ] python -m compileall packages tests passes for Python changes
- [ ] git diff --check passes
- [ ] Default tests remain deterministic, model-download-free, API-credit-free, and GPU-free
- [ ] Full deterministic pytest -q passes, or the exact pre-existing unrelated failure is recorded with a clean-tree reproduction
- [ ] Pinned native C++ target builds and focused CTest/protocol tests pass where native code is touched
- [ ] llama.cpp patch stack applies cleanly to the exact pinned commit where patch code is touched
- [ ] Real-model execution is opt-in through MESHNET_ENABLE_REAL_INFERENCE_TESTS=1 and records exact artifact/runtime/hardware evidence
- [ ] Model artifacts remain on the configured mounted-drive storage and never under /home
- [ ] Read .scratch/distributed-gguf-runtime/RALPH-CONTEXT.md and this story issue completely before changing code
- [ ] Read and verify every dependency evidence README before relying on dependency behavior
- [ ] Preserve all pre-existing working-tree changes and stage only files belonging to this story
- [ ] Write .scratch/distributed-gguf-runtime/evidence/DGR-015/README.md with files changed, exact commands and real results, limitations, compatibility notes, and dependent-story handoff
- [ ] Update only this story issue to Status: done after every acceptance criterion and quality gate passes
## Dependency handoff
- `DGR-014` must have `passes: true`; read `../evidence/DGR-014/README.md` and verify its referenced files/commands.
## Finish contract
- Create the task evidence directory and durable handoff required above.
- Preserve real failures and blockers; never fabricate benchmark, model, test or hardware output.
- Change this issue to `Status: done` only after all criteria pass.
- Emit `<promise>COMPLETE</promise>` only after the evidence handoff exists.
## References
- [Ralph execution context](../RALPH-CONTEXT.md)
- [PRD](../PRD.md)
- [Implementation strategy](../implementation-strategy.md)
- [Current architecture](../architecture.md)
- [Architecture decision](../../docs/adr/0024-distributed-gguf-runtime.md)

View File

@@ -1,60 +0,0 @@
# 16 — Produce the upstream llama.cpp collaboration package
Status: ready-for-agent
## Mandatory fresh-session context
- Read [RALPH-CONTEXT.md](../RALPH-CONTEXT.md) completely before changing code.
- This issue is `DGR-016` in [prd.json](../prd.json).
- Read the evidence README for every dependency listed below.
- Inspect current code and `git status`; historical text and previous agent claims are not evidence.
## Description
As a maintainer, I need narrow upstreamable proposals so that our patch burden can shrink without asking llama.cpp to own Meshnet networking.
## Expected durable outputs
- Narrow upstream patches/tests
- Generic API design note
- Human-ready llama.cpp outreach package
- evidence/DGR-016/README.md
## Acceptance criteria
- [ ] Separate generic llama.cpp hooks from Meshnet protocol/control-plane code.
- [ ] Prepare minimal reproducible examples and tests for range-aware loading, boundary input/output, and layer-filtered KV.
- [ ] Compare the proposal with Nakshatra and prima.cpp evidence and explain why the API is generally useful.
- [ ] Preserve one scoped commit/patch per concern against the exact upstream pin.
- [ ] Produce an outreach document suitable for Georgi/llama.cpp maintainers; actual sending remains a human action.
- [ ] Targeted pytest tests pass
- [ ] python -m compileall packages tests passes for Python changes
- [ ] git diff --check passes
- [ ] Default tests remain deterministic, model-download-free, API-credit-free, and GPU-free
- [ ] Full deterministic pytest -q passes, or the exact pre-existing unrelated failure is recorded with a clean-tree reproduction
- [ ] Pinned native C++ target builds and focused CTest/protocol tests pass where native code is touched
- [ ] llama.cpp patch stack applies cleanly to the exact pinned commit where patch code is touched
- [ ] Read .scratch/distributed-gguf-runtime/RALPH-CONTEXT.md and this story issue completely before changing code
- [ ] Read and verify every dependency evidence README before relying on dependency behavior
- [ ] Preserve all pre-existing working-tree changes and stage only files belonging to this story
- [ ] Write .scratch/distributed-gguf-runtime/evidence/DGR-016/README.md with files changed, exact commands and real results, limitations, compatibility notes, and dependent-story handoff
- [ ] Update only this story issue to Status: done after every acceptance criterion and quality gate passes
## Dependency handoff
- `DGR-010` must have `passes: true`; read `../evidence/DGR-010/README.md` and verify its referenced files/commands.
## Finish contract
- Create the task evidence directory and durable handoff required above.
- Preserve real failures and blockers; never fabricate benchmark, model, test or hardware output.
- Change this issue to `Status: done` only after all criteria pass.
- Emit `<promise>COMPLETE</promise>` only after the evidence handoff exists.
## References
- [Ralph execution context](../RALPH-CONTEXT.md)
- [PRD](../PRD.md)
- [Implementation strategy](../implementation-strategy.md)
- [Current architecture](../architecture.md)
- [Architecture decision](../../docs/adr/0024-distributed-gguf-runtime.md)

View File

@@ -1,35 +1,37 @@
# Distributed GGUF runtime milestones
# Distributed GGUF Runtime milestones
## Gate A — measured runtime value
> **Specification status:** planning artifacts only. No distributed GGUF runtime is implemented. DGR-017 cleanup is complete; no runtime implementation story has completion credit. `prd.json` is authoritative.
- DGR-001 locks the safetensors-versus-GGUF performance/fit/quality contract.
- DGR-002 can proceed independently and defines the battle-proven backend-neutral wire protocol.
- DGR-003 builds exact recipe identity on DGR-002.
- Expensive native llama.cpp work remains gated by DGR-001.
## M0 — Truth and contracts
## Gate B — minimal native execution seam
- **Stories:** `DGR-017..DGR-020`
- **Outcome:** Reconciled legacy truth, canonical metadata, immutable gates, and a controlled whole-model baseline.
- DGR-004 creates the reproducible pinned fork boundary.
- DGR-005 implements dense-Llama range ownership.
- DGR-006 proves architecture-defined boundary parity.
## M1 — Protocol and native substrate
## Gate C — concurrent production worker
- **Stories:** `DGR-021..DGR-033`
- **Outcome:** Versioned gRPC protocol, exact identities/artifacts, pinned upstream, reproducible builds, ShardEngine, and fake worker.
- DGR-007 isolates concurrent Hot KV State.
- DGR-008 exposes the native worker over gRPC.
- DGR-009 integrates the worker without replacing Meshnet's control plane.
- DGR-010 passes local real-model two-process acceptance.
## M2 — Dense vertical proof
## Gate D — real consumer-hardware route
- **Stories:** `DGR-034..DGR-043`
- **Outcome:** Dense ranged execution, parity, local state, worker integration, and GGUF inputs to existing routing.
- DGR-011 passes two-physical-machine execution.
- DGR-012 adds continuous batching and bounded admission.
- DGR-013 hardens failure and cancellation.
## M3 — DeepSeek V4 Flash alpha
## Gate E — product release decision
- **Stories:** `DGR-044..DGR-054`
- **Outcome:** Pinned V4 adapter around upstream llama.cpp, real route certification, and pre-locked alpha decision with MTP off.
- DGR-014 compares distributed GGUF against the current distributed safetensors route under locked thresholds.
- DGR-015 adds Qwen3/Qwen3-MoE only after the dense runtime passes.
- DGR-016 prepares narrow upstream llama.cpp collaboration material.
## M4 — Performance and beta hardening
No later gate may be claimed from synthetic workers or documentation-only evidence.
- **Stories:** `DGR-055..DGR-067`
- **Outcome:** Batching, backpressure, recovery, scale certification, optimization, MTP, and hardware matrix.
## M5 — Release and maintenance
- **Stories:** `DGR-068..DGR-071`
- **Outcome:** Reproducible packages, upstream collaboration, beta decision, and sustainable recertification.
## Release semantics
Alpha is DGR-054 and requires correctness plus the immutable useful-speed contract; MTP remains off. Beta is DGR-070 and requires DGR-066 MTP evidence plus concurrency, recovery, long-context, 10+ scenario, compression/optimization where certified, hardware matrix, and packaging. Failed gates remain failed evidence; they are not relabeled as success.

File diff suppressed because it is too large Load Diff

View File

@@ -1,414 +1,37 @@
# Distributed GGUF Technical Challenge Register
> **Historical challenge register.** Route Session, binary activation, local Hot KV State, and transport performance work have advanced since this file was written. Current implementation gates live in [PRD.md](PRD.md), [implementation-strategy.md](implementation-strategy.md), [architecture.md](architecture.md), and [prd.json](prd.json). Preserve this file for detailed risk context; do not treat its “current constraint” section as live system state.
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.
# Distributed GGUF Runtime technical challenges
> **Specification status:** planning artifacts only. No distributed GGUF runtime is implemented. DGR-017 cleanup is complete; no runtime implementation story has completion credit. `prd.json` is authoritative.
## Key challenges and planned answers
1. **Truth/provenance:** old passes are unreliable. DGR-017 audits before preserving or cleaning anything.
2. **Baseline comparability:** lock lanes first (DGR-019), execute whole-model-only baseline next (DGR-020), and separate quant fit from runtime effects.
3. **Exact artifacts:** complete split manifests/hashes, resumable mounted-drive provisioning, no `/home` models, dynamic quant/topology (DGR-025..026).
4. **Fast-moving upstream:** exact manifest plus numbered patches in an ignored workspace; no vendoring/submodule/permanent fork (DGR-027..030, DGR-071).
5. **Stable project boundary:** gRPC/Protobuf and `ShardEngine` prevent upstream ABI leakage (DGR-021..033).
6. **V4 correctness:** llama.cpp owns mHC/MoE/attention/hash graphs and kernels; Meshnet adds ranged ownership and adapters, then validates whole-model parity (DGR-044..052).
7. **Boundary versus caches:** only mHC residual/positions/needed token IDs/schema expectations cross; KV and CSA/HCA/SWA/indexer/compressor state stay local/session-keyed (DGR-046, DGR-049).
8. **Recovery:** stale/missing local state causes cache miss and re-prefill/restart, never WAN migration (DGR-058..060).
9. **Scale without policy churn:** feed measured GGUF inputs into and certify existing backend-agnostic routing at 10+ candidates (DGR-043, DGR-061..062).
10. **Performance/concurrency:** bounded admission, continuous batching, fairness, long-context profiling, then evidence-selected optimization/compression (DGR-055..064).
11. **MTP:** define ownership/state first, keep off for alpha, implement/benchmark before beta (DGR-065..066).
12. **Hardware truth:** compile all five backend families but advertise only exact real-hardware-certified lanes (DGR-030, DGR-067).
## Locked scope
- Existing Meshnet Tracker routing, load balancing, billing, telemetry, relay, and provider semantics are backend-agnostic and are **not redesigned**. GGUF contributes exact compatibility, range/capacity, queue/load, seam-cost, health/reliability, and certification inputs only.
- The data plane is a standalone project-owned C++ Shard worker with gRPC/Protobuf and a project-owned `ShardEngine` boundary.
- llama.cpp is fetched at one exact commit into an ignored workspace from an in-repo manifest, then a numbered minimal patch stack is applied. There is no submodule, vendored tree, or permanent-fork dependency.
- llama.cpp owns DeepSeek V4 graphs, mHC, MoE, attention, hash routing, and kernels. Meshnet adds only range-ownership hooks, typed boundary/local-state adapters, worker integration, and parity/certification.
- Quantization and placement are dynamic recipe inputs. The 24 and 10+ stage layouts are certification scenarios, never product constants.
- Per-shard Hot KV and V4 CSA/HCA/SWA/indexer/compressor state remain local and keyed by route session/epoch. The WAN seam carries the typed mHC 4×4096 residual boundary, positions, token-ID sideband where required, and schema/cache expectations—not per-layer caches.
- Route changes use cache miss plus re-prefill/restart. There is no WAN KV or V4 auxiliary-cache migration.
- CPU/CUDA/ROCm/Vulkan/Metal compile lanes are planned; only exact real-hardware-certified backend/model/recipe lanes may be advertised.
- Alpha requires correctness and the pre-locked useful-speed gate. MTP is reserved and off for alpha; its ownership contract, implementation, and benchmark are required before beta.
## Target identities
- DeepSeek V4 official target SHA: `60d8d70770c6776ff598c94bb586a859a38244f1`.
- llama.cpp V4 support lineage began at PR 24162 / merge `8c146a8366304c871efc26057cc90370ccf58dad`; DGR-027 later pins one exact validated current commit.
- V4 scope: 43 main layers plus MTP; mHC 4×4096 boundary; 256 routed + 1 shared experts with six routed active; token IDs required for the first three hash-routed layers.
- Exact split-GGUF artifacts are provisioned to mounted-drive storage with a complete hashed manifest and resumable verification; no model artifact may be placed under `/home`.

View File

@@ -1,4 +1,4 @@
Status: ready-for-agent
Status: done (2026-07-14)
# 01 — Baseline and profiling harness
@@ -12,16 +12,15 @@ sizes and connection counts without requiring a real model or external host.
## Acceptance criteria
- [ ] The harness runs a fixed prompt and fixed generated-token count through a
- [x] The harness runs a fixed prompt and fixed generated-token count through a
two-node route in direct and relay modes.
- [ ] It reports p50/p95 per-token latency, per-hop latency, payload bytes,
- [x] It reports p50/p95 per-token latency, per-hop latency, payload bytes,
compression ratio, connection attempts, and queue wait.
- [ ] It distinguishes prefill from decode and cached from stateless mode.
- [ ] It emits machine-readable JSON suitable for CI artifacts and a concise
- [x] It distinguishes prefill from decode and cached from stateless mode.
- [x] It emits machine-readable JSON suitable for CI artifacts and a concise
human-readable summary.
- [ ] A test fixture can assert connection attempts and output token identity.
- [x] A test fixture can assert connection attempts and output token identity.
## Blocked by
None - can start immediately.
None - completed. Verified with `PYTHONPATH=packages/node pytest -q tests/test_route_session_benchmark.py` (7 passed).

View File

@@ -15,9 +15,10 @@
"Can assert connection count and output token identity"
],
"priority": 1,
"passes": false,
"passes": true,
"notes": "Source issue: .scratch/distributed-inference-performance/issues/01-baseline-profiling-harness.md",
"dependsOn": []
"dependsOn": [],
"completionNotes": "Completed by agent"
},
{
"id": "DIP-002",
@@ -31,9 +32,12 @@
"Tests cover binary, JSON, timeout, disconnect, cancellation, and cleanup"
],
"priority": 2,
"passes": false,
"passes": true,
"notes": "Source issue: .scratch/distributed-inference-performance/issues/02-relay-session-compatibility.md",
"dependsOn": ["DIP-001"]
"dependsOn": [
"DIP-001"
],
"completionNotes": "Completed by agent"
},
{
"id": "DIP-003",
@@ -47,9 +51,12 @@
"Benchmark shows healthy-session connection count independent of token count"
],
"priority": 3,
"passes": false,
"passes": true,
"notes": "Source issue: .scratch/distributed-inference-performance/issues/03-http-keepalive.md",
"dependsOn": ["DIP-001"]
"dependsOn": [
"DIP-001"
],
"completionNotes": "Completed by agent"
},
{
"id": "DIP-004",
@@ -63,9 +70,12 @@
"Tests verify cadence and cleanup"
],
"priority": 4,
"passes": false,
"passes": true,
"notes": "Source issue: .scratch/distributed-inference-performance/issues/04-seam-telemetry.md",
"dependsOn": ["DIP-001"]
"dependsOn": [
"DIP-001"
],
"completionNotes": "Completed by agent"
},
{
"id": "DIP-005",
@@ -79,9 +89,12 @@
"Tests cover compressible, incompressible, threshold, malformed, and legacy bodies"
],
"priority": 5,
"passes": false,
"passes": true,
"notes": "Source issue: .scratch/distributed-inference-performance/issues/05-adaptive-compression.md",
"dependsOn": ["DIP-001"]
"dependsOn": [
"DIP-001"
],
"completionNotes": "Completed by agent"
},
{
"id": "DIP-006",
@@ -95,9 +108,12 @@
"Wire and token-output regression tests pass"
],
"priority": 6,
"passes": false,
"passes": true,
"notes": "Source issue: .scratch/distributed-inference-performance/issues/06-activation-framing-copies.md",
"dependsOn": ["DIP-001"]
"dependsOn": [
"DIP-001"
],
"completionNotes": "Completed by agent"
},
{
"id": "DIP-007",
@@ -111,9 +127,13 @@
"Tests cover chunking, slow consumers, failure, and legacy peers"
],
"priority": 7,
"passes": false,
"passes": true,
"notes": "Source issue: .scratch/distributed-inference-performance/issues/07-prefill-backpressure.md",
"dependsOn": ["DIP-001", "DIP-004"]
"dependsOn": [
"DIP-001",
"DIP-004"
],
"completionNotes": "Completed by agent"
},
{
"id": "DIP-008",
@@ -127,9 +147,20 @@
"Gate verifies token identity, session stability, and resource cleanup"
],
"priority": 8,
"passes": false,
"passes": true,
"notes": "Source issue: .scratch/distributed-inference-performance/issues/08-end-to-end-performance-gate.md",
"dependsOn": ["DIP-002", "DIP-003", "DIP-004", "DIP-005", "DIP-006", "DIP-007"]
"dependsOn": [
"DIP-002",
"DIP-003",
"DIP-004",
"DIP-005",
"DIP-006",
"DIP-007"
],
"completionNotes": "Completed by agent"
}
]
}
],
"metadata": {
"updatedAt": "2026-07-12T02:35:28.752Z"
}
}

View File

@@ -35,11 +35,12 @@
"Full pytest passes or an exact unrelated blocker is recorded"
],
"priority": 2,
"passes": false,
"passes": true,
"notes": "Source issue: .scratch/node-capability-admission/issues/02-doctor-real-forward.md",
"dependsOn": [
"NCA-001"
]
],
"completionNotes": "Completed by agent"
},
{
"id": "NCA-003",
@@ -54,12 +55,13 @@
"Full pytest passes or an exact unrelated blocker is recorded"
],
"priority": 3,
"passes": false,
"passes": true,
"notes": "Source issue: .scratch/node-capability-admission/issues/03-fail-closed-startup-admission.md",
"dependsOn": [
"NCA-001",
"NCA-002"
]
],
"completionNotes": "Completed by agent"
},
{
"id": "NCA-004",
@@ -76,12 +78,13 @@
"Full pytest passes or an exact unrelated blocker is recorded"
],
"priority": 4,
"passes": false,
"passes": true,
"notes": "Source issue: .scratch/node-capability-admission/issues/04-tracker-validated-capability-routing.md",
"dependsOn": [
"NCA-001",
"NCA-003"
]
],
"completionNotes": "Completed by agent"
},
{
"id": "NCA-005",
@@ -96,15 +99,16 @@
"Full pytest passes or an exact unrelated blocker is recorded"
],
"priority": 5,
"passes": false,
"passes": true,
"notes": "Source issue: .scratch/node-capability-admission/issues/05-docs-hardware-lane-contract.md",
"dependsOn": [
"NCA-002",
"NCA-004"
]
],
"completionNotes": "Completed by agent"
}
],
"metadata": {
"updatedAt": "2026-07-11T19:16:52.768Z"
"updatedAt": "2026-07-12T01:54:03.030Z"
}
}

View File

@@ -16,12 +16,9 @@
.\.venv\Scripts\meshnet-node.exe start http://192.168.0.179:8081 --model-id Qwen/Qwen2.5-0.5B-Instruct --advertise-host 192.168.0.20
.\.venv\Scripts\meshnet-node.exe start --tracker http://ai.neuron.d-popov.com --model-id Qwen/Qwen2.5-0.5B-Instruct --advertise-host 192.168.0.20
.\.venv\Scripts\meshnet-node.exe start --tracker http://ai.neuron.d-popov.com --model Qwen/Qwen2.5-0.5B-Instruct --advertise-host 192.168.0.20
we .\.venv\Scripts\meshnet-node.exe start `
--tracker http://192.168.0.179:8081 `
--model Qwen/Qwen2.5-0.5B-Instruct `
--advertise-host 192.168.0.20
we .\.venv\Scripts\meshnet-node.exe start --tracker http://192.168.0.179:8081 --model Qwen/Qwen2.5-0.5B-Instruct
# trackers:
https://meshnet.2.d-popov.com
https://ai.neuron.d-popov.com

View File

@@ -1,9 +1,16 @@
# US-042 — GGUF/llama.cpp node backend
Status: planned
Priority: High (whole-model GGUF shortcut; distributed path in [ADR-0024](../adr/0024-distributed-gguf-runtime.md))
Priority: High (unlocks DeepSeek-V4-Flash on volunteer hardware — the pool's core value)
Stage: Draft design
## Goal
Run **DeepSeek-V4-Flash** as the first real large-model target on volunteer
hardware via GGUF/llama.cpp. This epic is no longer GLM-oriented: the initial
objective is to prove that DeepSeek-V4-Flash can load and serve correctly on
consumer/unified-memory nodes, then expand from there.
## Context
The node backend is transformers-only (`model_backend.py`
@@ -35,17 +42,7 @@ 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** (US-042), then **ADR-0024 benchmark gate** (DGR-001), then distributed native worker (DGR-002+). Direction B (llama.cpp RPC) is rejected per ADR-0024.
## Runtime sequencing
| Stage | Track | Delivers |
|---|---|---|
| **C — Whole-model GGUF** | US-042 (this issue) | Single-hop llama.cpp, billing, relay streaming |
| **0 — Benchmark gate** | ADR-0024 DGR-001 | Safetensors vs GGUF measured contract |
| **1 — Distributed GGUF** | ADR-0024 `.scratch/distributed-gguf-runtime/` | gRPC C++ worker, layer-range GGUF |
Phase C uses the existing tracker hop path (whole model, one node). ADR-0024 direction A (layer-range GGUF + activations) merges into the native worker track after the benchmark gate — not in parallel with phase C on the same backend without an integration plan.
Recommended sequencing: C first (small, real value), then A/B investigation.
## Also in scope

View File

@@ -0,0 +1,148 @@
# Colibrì implementation audit
Research date: 2026-07-15. Primary source: [JustVugg/colibri](https://github.com/JustVugg/colibri) at `main` (README and linked source files). The repository is a model-specific runtime, not a wrapper around llama.cpp.
## Answer in one paragraph
Colibrì runs inference in a project-owned, dependency-free C engine (`c/glm.c` for GLM-5.2 and `c/olmoe.c` for OLMoE). Python is used for the one-time FP8/safetensors-to-Colibrì-container conversion and for the standard-library OpenAI HTTP gateway; it is not in the runtime inference path. The engine keeps dense/shared weights resident, while routed MoE experts are stored as individually addressable quantized records on disk and loaded into a per-layer LRU working set. RAM and optional VRAM are hot tiers; disk is a cold immutable backing store. This is local memory/storage tiering on one machine—not distributed expert execution over a network.
## What performs inference
- The README explicitly describes a “single C file (`c/glm.c`, ~2,400 lines)” with no BLAS, Python, or GPU requirement; runtime is pure C and Python is conversion-only ([README](https://github.com/JustVugg/colibri#the-idea), [runtime/setup section](https://github.com/JustVugg/colibri#quick-start)).
- The C source declares the GLM MoE forward path, MLA attention, sigmoid router, shared expert, and “expert routed in streaming dal disco (per-expert)” ([`c/glm.c`](https://github.com/JustVugg/colibri/blob/main/c/glm.c)). It defines its own quantized tensor (`QT`) and expert-slot (`ESlot`) structures, rather than importing GGUF/llama.cpp data structures.
- Optional CUDA and Metal backends are native Colibrì backends. On Windows, CUDA is a separately built `coli_cuda.dll` loaded through `c/backend_loader.c`; the host falls back to CPU if it is absent ([README GPU section](https://github.com/JustVugg/colibri#windows-11-native-no-wsl), [`backend_loader.c`](https://github.com/JustVugg/colibri/blob/main/c/backend_loader.c), [`backend_cuda.cu`](https://github.com/JustVugg/colibri/blob/main/c/backend_cuda.cu)).
- `c/openai_server.py` is only an HTTP adapter. The README says inference remains in the same C engine and that one persistent process owns one mutable KV context ([API section](https://github.com/JustVugg/colibri#openai-compatible-api)).
## How experts are loaded on one laptop
The placement policy is a three-tier hierarchy:
1. Dense attention, embeddings, shared experts, and other always-used weights stay resident in RAM (roughly 9.9 GB int4 for the stated GLM-5.2 setup).
2. Routed experts are separate records (about 19 MB each at int4 in the README's GLM-5.2 example). A per-layer LRU cache holds the currently useful experts in RAM; an optional pinned hot store keeps frequently used experts from eviction. CUDA can make VRAM an additional hot tier.
3. Remaining experts stay on disk (about 370 GB in the stated int4 container). A token routes to top-k experts per MoE layer; cache misses issue bounded background reads, then the loaded records are multiplied before the layer completes.
The README quantifies the trade-off: 75 layers × 8 experts means approximately 11 GB of cold reads per token, and the reported cold rate is only 0.050.1 token/s on a ~1 GB/s disk ([expert layout](https://github.com/JustVugg/colibri#the-idea), [numbers/resource policy](https://github.com/JustVugg/colibri#honest-numbers), [resource policy](https://github.com/JustVugg/colibri#resource-policy)). `PILOT=1` predicts the next layer's routes (reported 71.6% top-8 recall) and prefetches them while the current layer computes ([README router-lookahead](https://github.com/JustVugg/colibri#resource-policy)). Prefill and MTP verification use “batch-union MoE”: each unique expert in a batch is read once and applied to all positions that selected it.
The learning cache persists expert-use counts in `.coli_usage`, pins hot experts at startup, and can periodically repin them using a session-local LFRU score. This is an adaptive placement policy, not a change to router semantics. The model directory is converted offline one source shard at a time; the original 756 GB FP8 checkpoint need not coexist on disk ([converter and warmup](https://github.com/JustVugg/colibri#quick-start), [cache policy](https://github.com/JustVugg/colibri#resource-policy)).
## Model format and scope
Colibrì does **not** consume GGUF. Its converter reads Hugging Face safetensors/config data and writes a Colibrì-specific quantized container/directory (the README calls it an “int4 container” and runs with `COLI_MODEL=/path/to/...`). The C loader and `QT`/`ESlot` types are custom to this repository ([converter](https://github.com/JustVugg/colibri/blob/main/c/tools/convert_fp8_to_int4.py), [`c/glm.c`](https://github.com/JustVugg/colibri/blob/main/c/glm.c)). Current fidelity is tied to `glm_moe_dsa` (GLM-5.2); OLMoE has a separate implementation. This should be treated as an architectural experiment and source of techniques, not as a drop-in GGUF backend.
## What is and is not distributed
There is no peer protocol, tensor RPC, layer hand-off, remote expert service, or multi-host scheduler in the repository. `coli serve` serializes requests through a local process (bounded FIFO queue; optional isolated KV slots), and the README explicitly says concurrent requests queue because the engine owns mutable KV state ([queue/KV section](https://github.com/JustVugg/colibri#openai-compatible-api)). The “distributed-looking” behavior is storage-tier streaming inside one address space: disk I/O overlaps compute, but every expert matmul and the KV state remain on the same laptop.
## Ideas worth carrying into Meshnet
1. **Expert-level placement, not only layer-level placement.** For MoE models, advertise and assign individual expert records (or expert groups) independently from dense/layer shards. A node can contribute capacity for hot experts without owning the whole model.
2. **Immutable cold backing + bounded hot cache.** Treat the model artifact as a content-addressed, immutable source; keep a bounded LRU/LFRU cache of resident experts. Placement changes then become cache promotion/eviction rather than model mutation.
3. **Router-aware prefetch.** Add an optional next-seam prefetch hint after layer L predicts likely expert IDs for layer L+1. Hints must be advisory and cancellable; correctness still waits for the router's actual top-k.
4. **Batch-union requests.** During prefill or verification, deduplicate expert IDs across tokens so one transfer serves many positions. This maps naturally to a Meshnet seam batch message.
5. **Persisted usage heat.** Track expert hit/miss/latency histograms and use them for placement recommendations. Keep this separate from billing/reputation and avoid treating historical heat as a correctness signal.
6. **Explicit cold-path telemetry.** Report disk/network service time separately from foreground-visible wait. Colibrì's profile distinguishes overlap; Meshnet should expose the same distinction per activation seam.
7. **Resource planning as a first-class contract.** `coli plan`/`doctor` produce a versioned placement/budget report before loading. Meshnet admission could use an equivalent plan: dense footprint, expert cache budget, KV reserve, bandwidth, and safe concurrency.
## Follow-up: distributed expert routing
### The transferable idea
For an MoE layer, the node that owns and executes that layer's router can select
the token or batch's top-*k* experts, dispatch the same layer input to the
providers that own those experts, then gather and weighted-sum the returned
expert outputs before continuing with the next layer. This is **expert
parallelism**. It is not a responsibility of the route's initial/head node:
every MoE layer has its own router and therefore makes its own selection.
```text
activation reaches MoE layer L
|
v
L's Shard computes attention + router scores
|
v
top-k expert IDs -> expert-provider groups
|
v
scatter inputs -> run expert(s) -> gather weighted outputs
|
v
complete layer L and continue the Inference Route
```
Colibrì proves the useful local analogue: experts are independently addressable
quantized records; its router selects them at execution time; a bounded
RAM/VRAM cache, pinning, and read-ahead decide whether a selected expert comes
from fast memory or its cold disk backing. It does **not** perform the
networked version: all expert execution and KV state remain local to one
process ([Colibrì README: expert layout](https://github.com/JustVugg/colibri#the-idea),
[Colibrì README: server/KV model](https://github.com/JustVugg/colibri#openai-compatible-api),
[`c/glm.c`](https://github.com/JustVugg/colibri/blob/main/c/glm.c)).
### Why this is not the first public-network primitive
Naively making every individual expert independently reachable over a WAN
would cause a scatter/gather at every MoE layer for every decode step. The
Colibrì GLM-5.2 example has 75 MoE layers and selects eight routed experts per
layer; that illustrates the potential fan-out, even though Colibrì satisfies
those selections locally ([Colibrì README: expert layout and cold-path
numbers](https://github.com/JustVugg/colibri#the-idea)). Network latency,
tail-provider delay, failure/retry behavior, and per-expert accounting would
become part of the autoregressive critical path.
This reinforces ADR-0024's current choice: public Inference Routes use
contiguous layer/pipeline Shards; tensor and expert parallelism are deferred to
trusted composite providers or managed clusters, where the network is
low-latency and one provider can own the collective's operational contract
([ADR-0024: distributed parallelism](../adr/0024-distributed-gguf-runtime.md)).
### Safe staged adoption
1. **Local tiered experts inside a contiguous MoE Shard.** Keep a Shard's
expert execution local, but apply Colibrì-style immutable cold storage,
bounded LRU/LFRU caches, hot-expert pinning, batch-union loading, and
router-aware prefetch.
2. **Expert routing within one trusted composite provider.** Let a managed
LAN/cluster expose a single Meshnet provider identity while it handles
expert scatter/gather internally. This is the earliest setting where the
technique should be benchmarked end-to-end.
3. **Public remote expert providers only behind a release gate.** If measured
performance warrants it, expose versioned remote *expert packs* rather than
unconstrained per-expert endpoints. The owning MoE-layer Shard must retain
control of selection and aggregation.
The public form would require all of the following before it can be routable:
- content-addressed artifact, quantization, architecture, and runtime-recipe
identity for every expert pack;
- stable ownership, replication, cache residency, and health reports;
- a versioned scatter/gather protocol carrying layer ID, expert IDs, route
session/epoch, token positions, inputs, weights, deadlines, and cancellation;
- batch-union deduplication by provider, bounded fan-out, backpressure, and
straggler/failure policy;
- separate telemetry for cache hit/miss, transfer bytes, overlap, remote
service time, tail latency, and aggregation time; and
- proof that the resulting output, KV isolation, and admission behavior match
the certified whole-model/contiguous-Shard execution.
The strategy is therefore to borrow Colibrì's **expert-as-movable-artifact and
memory-tiering** idea, while preserving Meshnet's Route Session ownership and
contiguous public layer Shards. Its local cache should be an optimization below
our existing activation seam, not a replacement for the control plane.
## Important limitations for our design
- Colibrì's cold path is local NVMe. Network expert fetches add latency, loss, authentication, retries, and Byzantine-data concerns that the project does not solve.
- One mutable KV context and one-at-a-time generation are deliberate constraints; Meshnet needs explicit Route Session/KV ownership and seam backpressure for concurrent users.
- Router lookahead is model-specific and only experimentally measured. It cannot be assumed for arbitrary MoE architectures.
- The custom container and hand-written kernels maximize control but increase maintenance and validation burden. Reusing llama.cpp/GGML remains attractive for a general GGUF lane; Colibrì's expert-cache and planning ideas can sit above that substrate.
## Source index
- Repository/README: <https://github.com/JustVugg/colibri>
- GLM engine and custom tensor/expert structures: <https://github.com/JustVugg/colibri/blob/main/c/glm.c>
- OLMoE engine: <https://github.com/JustVugg/colibri/blob/main/c/olmoe.c>
- FP8→Colibrì int4 converter: <https://github.com/JustVugg/colibri/blob/main/c/tools/convert_fp8_to_int4.py>
- Optional CUDA backend/loader: <https://github.com/JustVugg/colibri/tree/main/c>
- Local OpenAI gateway: <https://github.com/JustVugg/colibri/blob/main/c/openai_server.py>
- Placement planning/doctor implementation: <https://github.com/JustVugg/colibri/blob/main/c/resource_plan.py> and <https://github.com/JustVugg/colibri/blob/main/c/doctor.py>

View File

@@ -2,6 +2,7 @@
import json
import os
import shutil
import subprocess
import time
@@ -183,6 +184,17 @@ def with_forced_cpu(hw: dict) -> dict:
return forced
def _with_model_drive(profile: dict) -> dict:
"""Attach free space for the default model cache drive to tracker diagnostics."""
try:
cache_root = os.path.expanduser("~/.cache/meshnet/shards")
profile["model_drive_free_bytes"] = shutil.disk_usage(os.path.expanduser("~")).free
profile["model_drive_path"] = cache_root
except OSError:
pass
return profile
def detect_hardware() -> dict:
"""Detect GPU model and available VRAM. Returns hardware profile dict."""
ram_mb = _detect_ram_mb()
@@ -208,23 +220,23 @@ def detect_hardware() -> dict:
}
if torch_gpu is not None and torch_gpu.get("gcn_arch"):
profile["gcn_arch"] = torch_gpu["gcn_arch"]
return profile
return _with_model_drive(profile)
except ImportError:
pass
torch_inventory = _gpu_inventory_profile(torch_gpu, ram_mb)
if torch_inventory is not None:
return torch_inventory
return _with_model_drive(torch_inventory)
nvidia_gpu = _gpu_inventory_profile(_detect_nvidia_smi_gpu_memory(), ram_mb)
if nvidia_gpu is not None:
return nvidia_gpu
return _with_model_drive(nvidia_gpu)
windows_gpu = _gpu_inventory_profile(_detect_windows_gpu_memory(), ram_mb)
if windows_gpu is not None:
return windows_gpu
return _with_model_drive(windows_gpu)
return {
return _with_model_drive({
"device": "cpu",
"gpu_name": None,
"vram_mb": 0,
@@ -232,7 +244,7 @@ def detect_hardware() -> dict:
"shared_vram_mb": 0,
"ram_mb": ram_mb,
"cuda_available": False,
}
})
def benchmark_throughput_checked(device_str: str = "cpu") -> tuple[float, bool, str | None]:

View File

@@ -44,6 +44,7 @@ class SeamSample:
cache_mode: CacheMode
model_ms: float
encode_ms: float
activation_decode_ms: float
framing_ms: float
metadata_ms: float
copy_allocation_ms: float
@@ -52,6 +53,7 @@ class SeamSample:
decompression_ms: float
connection_setup_ms: float
queue_wait_ms: float
local_http_forwarding_ms: float
transport_ms: float
seam_latency_ms: float
payload_bytes: int
@@ -120,6 +122,10 @@ def _summary(samples: list[SeamSample]) -> dict[str, float | int]:
"compression_cpu_ms": round(
sum(sample.compression_ms + sample.decompression_ms for sample in samples), 4
),
"model_execution_ms": round(sum(sample.model_ms for sample in samples), 4),
"activation_encoding_ms": round(sum(sample.encode_ms for sample in samples), 4),
"activation_decoding_ms": round(sum(sample.activation_decode_ms for sample in samples), 4),
"local_http_forwarding_ms": round(sum(sample.local_http_forwarding_ms for sample in samples), 4),
"peak_buffered_bytes": max((sample.copy_allocation_bytes for sample in samples), default=0),
}
@@ -159,6 +165,7 @@ class _StubTransport:
queue_wait_ms = 0.0 if self.mode == "direct" else 0.18 + (0.05 if token_index is not None and token_index % 2 else 0.0)
model_ms = 1.6 if phase == "prefill" else 0.45
encode_ms = 0.16 if phase == "prefill" else 0.06
activation_decode_ms = 0.055 if phase == "prefill" else 0.02
# Keep framing/metadata/copy costs explicit rather than hiding them in
# serialization or transport time. The stub owns one binary frame and
# one response body per hop; no base64 body is modeled.
@@ -168,20 +175,26 @@ class _StubTransport:
copy_allocation_bytes = wire_bytes + payload_bytes
compression_ms = 0.09 if self.scenario.compression else 0.0
decompression_ms = 0.07 if self.scenario.compression else 0.0
# Both routes finish by forwarding the decoded activation to the local
# tail-node HTTP handler; relay adds its own queue before that hop.
local_http_forwarding_ms = 0.11 if self.mode == "direct" else 0.16
transport_ms = (0.32 if self.mode == "direct" else 0.61) + wire_bytes / 100_000
seam_latency_ms = round(
model_ms + encode_ms + framing_ms + metadata_ms + copy_allocation_ms
+ compression_ms + decompression_ms + connection_setup_ms + queue_wait_ms + transport_ms,
model_ms + encode_ms + activation_decode_ms + framing_ms + metadata_ms + copy_allocation_ms
+ compression_ms + decompression_ms + connection_setup_ms + queue_wait_ms + transport_ms
+ local_http_forwarding_ms,
4,
)
return SeamSample(
phase=phase, token_index=token_index, session_id=self.session_id,
activation_id=f"benchmark-activation-{self._activation_count}", seam="head->tail", mode=self.mode,
cache_mode=self.cache_mode, model_ms=model_ms, encode_ms=encode_ms,
activation_decode_ms=activation_decode_ms,
framing_ms=framing_ms, metadata_ms=metadata_ms,
copy_allocation_ms=copy_allocation_ms, copy_allocation_bytes=copy_allocation_bytes,
compression_ms=compression_ms, decompression_ms=decompression_ms,
connection_setup_ms=connection_setup_ms, queue_wait_ms=queue_wait_ms,
local_http_forwarding_ms=local_http_forwarding_ms,
transport_ms=round(transport_ms, 4), seam_latency_ms=seam_latency_ms,
payload_bytes=payload_bytes, wire_bytes=wire_bytes,
compression_ratio=round(payload_bytes / wire_bytes, 4), connection_attempted=connection_attempted,
@@ -329,9 +342,10 @@ def run_real_model_lan_benchmark(url: str, *, model: str, timeout: float = 120.0
sample = SeamSample(
phase="decode", token_index=0, session_id=session_id, activation_id="lan-activation-1",
seam="head->tail", mode="direct", cache_mode="cached", model_ms=0.0, encode_ms=0.0,
activation_decode_ms=0.0,
framing_ms=0.0, metadata_ms=0.0, copy_allocation_ms=0.0, copy_allocation_bytes=0,
compression_ms=0.0, decompression_ms=0.0, connection_setup_ms=elapsed_ms,
queue_wait_ms=0.0, transport_ms=elapsed_ms, seam_latency_ms=elapsed_ms,
queue_wait_ms=0.0, local_http_forwarding_ms=0.0, transport_ms=elapsed_ms, seam_latency_ms=elapsed_ms,
payload_bytes=len(body), wire_bytes=len(body) + len(response_body), compression_ratio=1.0,
connection_attempted=True,
)
@@ -354,6 +368,10 @@ def format_summary(report: dict) -> str:
f"{decode['tokens_per_sec']:.1f} tok/s; {decode['bytes_per_token']:.0f} B/tok; "
f"seam {seam['payload_bytes']}/{seam['wire_bytes']} B "
f"({seam['compression_ratio']:.2f}x); connections {run['connections']['attempts']}; "
f"model/encode/decode {decode['model_execution_ms']:.2f}/"
f"{decode['activation_encoding_ms']:.2f}/{decode['activation_decoding_ms']:.2f} ms; "
f"compression {decode['compression_cpu_ms']:.2f} ms; "
f"HTTP {decode['local_http_forwarding_ms']:.2f} ms; "
f"queue p95 {decode['p95_queue_wait_ms']:.2f} ms"
)
return "\n".join(lines)

View File

@@ -12,7 +12,7 @@ import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path
from typing import Any
from typing import Any, Callable
from .admission import (
AdmissionRequirement,
@@ -419,6 +419,7 @@ def _start_heartbeat(
interval: float = _HEARTBEAT_INTERVAL_IDLE,
node_ref: Any | None = None,
start_time: float | None = None,
refresh_capability: Callable[[dict], dict | None] | None = None,
) -> threading.Thread:
"""Daemon thread: sends heartbeats and re-registers automatically after tracker restarts.
@@ -430,6 +431,7 @@ def _start_heartbeat(
which is logged for now (hot-reload implemented in US-026).
"""
_start_time = start_time or time.monotonic()
completed_directives: list[dict] = []
def _current_requests_snapshot() -> list[dict]:
if node_ref is None:
@@ -454,6 +456,8 @@ def _start_heartbeat(
current_requests = _current_requests_snapshot()
if current_requests:
stats["current_requests"] = current_requests
if completed_directives:
stats["completed_directives"] = list(completed_directives)
return stats
def _sleep_interval() -> float:
@@ -461,9 +465,26 @@ def _start_heartbeat(
return _HEARTBEAT_INTERVAL_BUSY
return interval
def _refresh_proof(payload: dict) -> None:
"""Re-prove the current shard so a re-registration never presents an aged proof.
The tracker refuses proofs older than its freshness budget: re-sending the
startup-time report after an outage would re-register the node unroutable.
"""
if refresh_capability is None or "capability_report" not in payload:
return
try:
fresh = refresh_capability(payload)
except Exception as exc:
print(f" [node] WARNING: capability re-validation failed: {exc}", flush=True)
return
if fresh:
payload["capability_report"] = fresh
def _reregister() -> bool:
nonlocal node_id
try:
_refresh_proof(register_payload)
resp = _post_json(f"{tracker_url}/v1/nodes/register", register_payload)
node_id = resp.get("node_id", node_id)
if node_ref is not None:
@@ -485,6 +506,7 @@ def _start_heartbeat(
"managed_assignment": True,
}
try:
_refresh_proof(extra_payload)
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')}",
@@ -493,21 +515,26 @@ def _start_heartbeat(
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]) -> dict | None:
if not directives:
return
return None
if node_ref is None or not hasattr(node_ref, "apply_tracker_directives"):
print(f" [node] tracker directives received: {directives}", flush=True)
return
return None
try:
applied = node_ref.apply_tracker_directives(directives)
except Exception as exc:
print(f" [node] WARNING: failed to apply tracker directives: {exc}", flush=True)
return
return None
if applied:
completed_directives.append(dict(applied))
if applied.get("action") == "ADD_SHARD":
_register_additional_assignment(applied)
return
return applied
if applied.get("action") in {"DROP_SHARD", "DROP_ALL_SHARDS"}:
# A release has no replacement range. It is not a failed
# heartbeat and must not re-register the released assignment.
return applied
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["hf_repo"] = model_id
@@ -515,6 +542,7 @@ def _start_heartbeat(
register_payload["shard_end"] = applied["shard_end"]
register_payload["quantization"] = applied.get("quantization", register_payload.get("quantization"))
register_payload["tracker_mode"] = bool(applied.get("tracker_mode", False))
return applied
def _loop() -> None:
nonlocal node_id
@@ -542,7 +570,10 @@ def _start_heartbeat(
continue
try:
resp = _post_json(hb_url, _get_stats())
heartbeat = _get_stats()
resp = _post_json(hb_url, heartbeat)
if heartbeat.get("completed_directives"):
completed_directives.clear()
_apply_directives(resp.get("directives", []))
new_asgn = resp.get("new_assignment")
if new_asgn:
@@ -579,6 +610,7 @@ def _register_with_tracker(
reg_payload: dict,
node: Any,
start_time: float,
refresh_capability: Callable[[dict], dict | None] | None = None,
) -> str | None:
"""Register with the tracker, or start background retries when it is unreachable."""
try:
@@ -586,7 +618,14 @@ def _register_with_tracker(
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)
_start_heartbeat(
tracker_url,
tracker_node_id,
reg_payload,
node_ref=node,
start_time=start_time,
refresh_capability=refresh_capability,
)
return tracker_node_id
except Exception as exc:
setattr(node, "tracker_node_id", None)
@@ -598,6 +637,7 @@ def _register_with_tracker(
reg_payload,
node_ref=node,
start_time=start_time,
refresh_capability=refresh_capability,
)
return None
@@ -718,6 +758,54 @@ def _admit_capability(
return report
def _capability_refresher(
node: Any,
*,
manifest: RecipeManifest,
recipe: Recipe,
detected_device: str,
cache_dir: Path | None,
force_cpu: bool,
validator: CapabilityValidator | None = None,
) -> Callable[[dict], dict | None]:
"""A fresh proof for what the node serves *now*, run at re-registration time.
The startup proof ages past the tracker's freshness budget, and directives
can move the node to a shard the startup proof never covered — so every
re-registration re-proves against the currently loaded backend rather than
replaying the report captured at boot.
"""
def refresh(payload: dict) -> dict | None:
target_model = payload.get("hf_repo") or payload.get("model")
backend = None
accessor = getattr(node, "backend_for", None)
if callable(accessor) and target_model:
backend = accessor(str(target_model))
if backend is None:
backend = getattr(node, "backend", None)
if backend is None:
return None
context = CapabilityContext(
backend=backend,
selection=DoctorSelection(
model_id=str(getattr(backend, "model_id", target_model)),
shard_start=int(getattr(backend, "shard_start", 0) or 0),
shard_end=int(getattr(backend, "shard_end", 0) or 0),
quantization=str(getattr(backend, "quantization", None) or "auto"),
cache_dir=cache_dir,
force_cpu=force_cpu,
),
recipe=recipe,
manifest=manifest,
device=_capability_device(backend, detected_device),
)
report = (validator or probe_capability)(context)
setattr(node, "capability_report", report)
return report.to_dict()
return refresh
def run_startup(
tracker_url: str,
port: int = 0,
@@ -1026,6 +1114,15 @@ def run_startup(
}
tracker_node_id = _register_with_tracker(
tracker_url, reg_payload, node, _node_start_time,
refresh_capability=_capability_refresher(
node,
manifest=manifest,
recipe=recipe,
detected_device=device,
cache_dir=cache_dir,
force_cpu=force_cpu,
validator=capability_validator,
),
)
print(
@@ -1197,6 +1294,15 @@ def run_startup(
}
tracker_node_id = _register_with_tracker(
tracker_url, auto_reg_payload, node, _node_start_time,
refresh_capability=_capability_refresher(
node,
manifest=manifest,
recipe=recipe,
detected_device=device,
cache_dir=cache_dir,
force_cpu=force_cpu,
validator=capability_validator,
),
)
shard_label = _format_shard_label(
assigned_shard_start,
@@ -1389,6 +1495,15 @@ def run_startup(
}
tracker_node_id = _register_with_tracker(
tracker_url, reg_payload, node, _node_start_time,
refresh_capability=_capability_refresher(
node,
manifest=manifest,
recipe=recipe,
detected_device=device,
cache_dir=cache_dir,
force_cpu=force_cpu,
validator=capability_validator,
),
)
print(
f"\n{'=' * 32}\n"
@@ -1474,7 +1589,22 @@ def run_startup(
)
node_id = str(reg_resp["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)
_start_heartbeat(
tracker_url,
node_id,
reg_payload,
node_ref=node,
start_time=_node_start_time,
refresh_capability=_capability_refresher(
node,
manifest=manifest,
recipe=recipe,
detected_device=device,
cache_dir=shard_path,
force_cpu=force_cpu,
validator=capability_validator,
),
)
except Exception:
node.stop()
raise

View File

@@ -1543,8 +1543,52 @@ class TorchNodeServer:
def loaded_model_ids(self) -> list[str]:
return list(self._backends.keys())
def backend_for(self, model_id: str) -> TorchModelShard | None:
"""The loaded backend serving `model_id` — full repo id or short name."""
backend = self._backends.get(model_id)
if backend is not None:
return backend
short = model_id.split("/")[-1].lower()
for key, candidate in self._backends.items():
if key.split("/")[-1].lower() == short:
return candidate
return None
def apply_tracker_directives(self, directives: list[dict]) -> dict | None:
"""Apply tracker shard directives (LOAD_SHARD replace, ADD_SHARD load-more)."""
drop_all_directive = next(
(directive for directive in reversed(directives) if directive.get("action") == "DROP_ALL_SHARDS"),
None,
)
if drop_all_directive is not None:
self._backends.clear()
self._backend = None
self._tracker_mode = False
if self._server is not None:
self._server.backends = {}
self._server.backend = None
self._server.tracker_mode = False
return {"action": "DROP_ALL_SHARDS"}
drop_directive = next(
(directive for directive in reversed(directives) if directive.get("action") == "DROP_SHARD"),
None,
)
if drop_directive is not None:
model_id = str(drop_directive.get("model") or "")
removed = self._backends.pop(model_id, None)
if removed is None:
return None
if self._backends:
self._backend = next(iter(self._backends.values()))
self._tracker_mode = self._backend.shard_start == 0
else:
self._backend = None
self._tracker_mode = False
if self._server is not None:
self._server.backends = dict(self._backends)
self._server.backend = self._backend
self._server.tracker_mode = self._tracker_mode
return {"action": "DROP_SHARD", "model": model_id}
add_directive = next(
(directive for directive in reversed(directives) if directive.get("action") == "ADD_SHARD"),
None,
@@ -1574,6 +1618,8 @@ class TorchNodeServer:
flush=True,
)
try:
if replacing:
self._backends.clear()
new_backend = _load_backend(model_id, shard_start, shard_end, quantization, self._cache_dir)
except TypeError:
new_backend = _load_backend(model_id, shard_start, shard_end, quantization)

View File

@@ -22,8 +22,9 @@
border-bottom:1px solid var(--border); flex-shrink:0; }
header h1 { font-size:16px; margin:0; color:var(--accent); }
header .meta { color:var(--dim); font-size:12px; }
main { display:grid; grid-template-columns:repeat(auto-fit,minmax(340px,1fr));
main { display:grid; grid-template-columns:1fr;
gap:14px; padding:14px 20px; }
main > section { width:100%; min-width:0; }
body.chat-tab-active main {
flex:1; min-height:0; display:flex; flex-direction:column;
padding:0; gap:0; overflow:hidden;
@@ -43,12 +44,15 @@
.empty { color:var(--dim); font-style:italic; }
.pill { display:inline-block; padding:0 7px; border-radius:9px;
border:1px solid var(--border); font-size:11px; }
input, button { font:inherit; color:var(--fg); background:var(--bg);
input, button, select { font:inherit; color:var(--fg); background:var(--bg);
border:1px solid var(--border); border-radius:6px; padding:5px 8px; }
input { width:100%; margin-bottom:6px; }
button { cursor:pointer; color:var(--accent); }
button:hover { border-color:var(--accent); }
button.small { font-size:11px; padding:1px 7px; }
dialog { color:var(--fg); background:var(--panel); border:1px solid var(--border); border-radius:8px; min-width:min(420px,calc(100vw - 32px)); }
dialog::backdrop { background:rgba(0,0,0,.55); }
.placement-dialog-actions { display:flex; justify-content:flex-end; gap:8px; margin-top:12px; }
.form-row { display:flex; gap:8px; }
.form-row button { white-space:nowrap; }
.error-msg { color:var(--bad); font-size:12px; min-height:16px; }
@@ -71,6 +75,12 @@
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; }
/* Compact status cards fan out on desktop; tables remain readable at half width. */
@media (min-width:900px) {
main { grid-template-columns:repeat(4,minmax(0,1fr)); }
main > section { grid-column:span 1; }
.wide { grid-column:span 2; }
}
section[hidden] { display:none !important; }
section.chat-section {
padding:0; border:0; border-radius:0; background:var(--bg); min-height:0;
@@ -205,7 +215,7 @@
.chat-compose button:disabled { opacity:.45; cursor:not-allowed; }
.console {
background:var(--bg); border:1px solid var(--border); border-radius:6px;
min-height:160px; max-height:280px; overflow:auto; padding:7px 9px;
min-height:160px; max-height:520px; overflow-y:auto; overflow-x: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; }
@@ -288,6 +298,8 @@
<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"><h2>Tracker hive</h2><div id="hive" class="empty">loading…</div></section>
<section data-tab="admin" class="wide"><h2>Model placement</h2><div id="admin-model-placement-status" class="dim">Choose a model to load or release.</div><div id="admin-model-placement" class="empty">admin login required</div></section>
<section data-tab="admin" class="wide"><h2>Total node pool</h2><div id="admin-node-pool" 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>
@@ -315,6 +327,16 @@
<div id="testing-log" class="console empty">no test output yet</div>
</section>
</main>
<dialog id="model-placement-dialog">
<form method="dialog">
<div id="model-placement-dialog-title"></div>
<label for="model-placement-node">Node</label>
<select id="model-placement-node"></select>
<label id="model-placement-replace" style="display:none"><input type="checkbox" id="model-placement-replace-confirm"> Unload the currently loaded model before loading this one</label>
<div id="model-placement-replace-error" class="bad" style="display:none"></div>
<div class="placement-dialog-actions"><button value="cancel">Cancel</button><button type="button" id="model-placement-confirm">Confirm</button></div>
</form>
</dialog>
<script>
"use strict";
const $ = id => document.getElementById(id);
@@ -1074,6 +1096,7 @@ function renderBillingUsage(records) {
}
let consoleClearedAt = 0;
const CONSOLE_MAX_LINES = 1000;
function clearConsole() {
consoleClearedAt = Date.now() / 1000;
@@ -1087,7 +1110,7 @@ function renderConsole(data) {
$("console").innerHTML = '<div class="empty">no console events</div>';
return;
}
$("console").innerHTML = events.slice(-120).map(e => {
$("console").innerHTML = events.slice(-CONSOLE_MAX_LINES).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) : "";
@@ -1781,7 +1804,7 @@ async function requestSelectedModelLoad() {
if (!selectedChatModel) return;
const button = $("request-model-load");
if (button) button.disabled = true;
const result = await apiCall("/v1/models/load", "POST", { model: selectedChatModel });
const result = await apiCall("/v1/models/load", "POST", { model: selectedChatModel, force: isAdmin });
if (button) button.disabled = false;
if (!result.ok) {
alert(result.data.error || "model load request failed");
@@ -1791,6 +1814,136 @@ async function requestSelectedModelLoad() {
$("chat-status").textContent = `load queued on ${short(assignment.node_id || "node")} for layers ${assignment.shard_start}-${assignment.shard_end}`;
}
async function requestAdminModelLoad(model, nodeId, replacing) {
const result = await apiCall("/v1/models/load", "POST", { model, node_id: nodeId, force: replacing });
if (!result.ok) return showAdminModelPlacementStatus(result.data.error || "model load request failed", true);
const assignment = result.data.assignment || {};
showAdminModelPlacementStatus(`Load queued on ${short(assignment.node_id || "node")} for ${model}.`);
await refreshActiveTab(true);
}
async function releaseAdminModel(model, nodeId) {
const result = await apiCall("/v1/models/release", "POST", { model, node_id: nodeId });
if (!result.ok) return showAdminModelPlacementStatus(result.data.error || "model release request failed", true);
showAdminModelPlacementStatus(`Release queued for ${result.data.released || 0} node(s) serving ${model}.`);
await refreshActiveTab(true);
}
async function releaseAllNodeModels(nodeId) {
if (!confirm("Unload every model from this node?")) return;
const result = await apiCall("/v1/nodes/release-all", "POST", { node_id: nodeId });
if (!result.ok) return showAdminModelPlacementStatus(result.data.error || "node unload failed", true);
showAdminModelPlacementStatus(`Unload queued for ${short(nodeId)}.`);
await refreshActiveTab(true);
}
function showAdminModelPlacementStatus(message, isError) {
const status = $("admin-model-placement-status");
status.textContent = message;
status.className = isError ? "bad" : "ok";
}
function gib(bytes) { return bytes == null ? "not reported" : `${(Number(bytes) / 1073741824).toFixed(1)} GiB`; }
function renderAdminNodePool(map) {
const groups = {};
for (const node of (map && map.nodes) || []) {
const account = node.wallet_address || "unbound account";
(groups[account] = groups[account] || []).push(node);
}
let html = "";
for (const [account, nodes] of Object.entries(groups).sort(([a], [b]) => a.localeCompare(b))) {
html += `<div style="margin-top:10px"><b>${esc(short(account, 20))}</b> <span class="dim">${nodes.length} node(s)</span></div>`;
html += table(["node", "assignment", "state / slots", "model RAM", "RAM", "GPU / VRAM", "model drive", "action"], nodes.map(node => {
const hw = node.hardware_profile || {};
const cap = node.capacity || {};
// The network map keeps reported resource capacity under `capacity`.
node.ram_bytes = cap.ram_bytes ?? node.ram_bytes;
node.vram_bytes = cap.vram_bytes ?? node.vram_bytes;
const disk = hw.model_drive_free_bytes ?? hw.model_path_free_bytes ?? hw.disk_free_bytes;
const gpu = hw.gpu_name || (hw.cuda_available ? "CUDA GPU" : "CPU only");
const row = [nodeDisplayCell(node), esc(node.hf_repo || node.model || "unassigned"),
esc(`${node.stats?.status || "?"} · ${cap.loaded_slots ?? "?"}/${cap.max_loaded_shards ?? node.max_loaded_shards ?? "?"} slots`),
esc(gib(cap.loaded_model_bytes)),
esc(gib(node.ram_bytes || (hw.ram_mb && hw.ram_mb * 1048576))),
esc(`${gpu} · ${gib(node.vram_bytes || (hw.vram_mb && hw.vram_mb * 1048576))}`), esc(gib(disk))];
return row.concat([
node.shard_start == null ? '<span class="dim">empty</span>' :
`<button class="small" data-admin-node-release="${esc(node.node_id)}">unload all</button>`,
]);
}));
}
$("admin-node-pool").innerHTML = html || '<div class="empty">no nodes registered</div>';
}
$("admin-node-pool").addEventListener("click", event => {
const unload = event.target.closest("[data-admin-node-release]");
if (unload) void releaseAllNodeModels(unload.dataset.adminNodeRelease);
});
function renderAdminModelPlacement(models, map) {
const nodes = (map && map.nodes) || [];
const rows = ((models && models.data) || []).map(model => {
const aliases = new Set([model.id, model.hf_repo, ...(model.aliases || [])].filter(Boolean));
const serving = nodes.filter(node => aliases.has(node.model) || aliases.has(node.hf_repo)).length;
const downloaded = nodes.filter(node => aliases.has(node.model) || aliases.has(node.hf_repo) ||
(node.downloaded_models || []).some(item => aliases.has(item.model) || aliases.has(item.hf_repo))).length;
const loadable = model.id !== "stub-model";
const actions = `<button class="small" data-admin-model-load="${esc(model.id)}"${loadable ? "" : " disabled"}>load</button> ` +
`<button class="small" data-admin-model-release="${esc(model.id)}"${serving ? "" : " disabled"}>release</button>`;
return [esc(model.name || model.id), String(serving), String(downloaded), actions];
});
$("admin-model-placement").innerHTML = rows.length
? table(["model", "serving nodes", "downloaded on nodes", "admin action"], rows)
: '<div class="empty">no model presets configured</div>';
}
$("admin-model-placement").addEventListener("click", event => {
const load = event.target.closest("[data-admin-model-load]");
const release = event.target.closest("[data-admin-model-release]");
if (load) void chooseModelPlacementNode("load", load.dataset.adminModelLoad);
if (release) void chooseModelPlacementNode("release", release.dataset.adminModelRelease);
});
function chooseModelPlacementNode(action, model) {
const dialog = $("model-placement-dialog");
const select = $("model-placement-node");
const targetAlias = modelAliasKey(model);
const nodes = (lastNetworkMap?.nodes || []).filter(node => action === "load" ||
modelAliasKey(node.model) === targetAlias || modelAliasKey(node.hf_repo) === targetAlias);
if (!nodes.length) return showAdminModelPlacementStatus(`No node can ${action} ${model}.`, true);
$("model-placement-dialog-title").textContent = `${action === "load" ? "Load" : "Release"} ${model} on a node`;
select.innerHTML = nodes.map(node => `<option value="${esc(node.node_id)}">${esc(short(node.friendly_name || node.node_id, 20))}${esc(node.hf_repo || node.model || "unassigned")}</option>`).join("");
const replace = $("model-placement-replace");
const replaceConfirm = $("model-placement-replace-confirm");
const replaceError = $("model-placement-replace-error");
const confirmButton = $("model-placement-confirm");
const selectedNode = () => nodes.find(node => node.node_id === select.value);
const updateReplacementWarning = () => {
const node = selectedNode();
const occupied = action === "load" && node && node.shard_start != null && node.shard_end != null &&
modelAliasKey(node.hf_repo || node.model) !== targetAlias;
replace.style.display = occupied ? "" : "none";
replaceConfirm.checked = false;
replaceError.style.display = "none";
};
select.onchange = updateReplacementWarning;
updateReplacementWarning();
dialog.onclose = null;
confirmButton.onclick = () => {
const replacing = replace.style.display !== "none";
if (replacing && !replaceConfirm.checked) {
replaceError.textContent = "Tick the box to confirm that this will unload the current model.";
replaceError.style.display = "";
return;
}
dialog.close("confirm");
if (action === "load") void requestAdminModelLoad(model, select.value, replacing);
else void releaseAdminModel(model, select.value);
};
dialog.showModal();
}
function chatAuthToken() {
if (accountApiKeys.length) return accountApiKeys[0];
return null;
@@ -2427,14 +2580,19 @@ async function fetchAdminTab() {
fetchJson("/v1/console"),
fetchJson("/v1/billing/summary"),
fetchJson("/v1/registry/wallets"),
fetchJson("/v1/models"),
fetchJson("/v1/network/map"),
];
if (isAdmin) fetches.push(apiCall("/v1/admin/accounts"));
const results = await Promise.all(fetches);
const [raft, consoleData, summary, wallets, adminResp] = results;
const [raft, consoleData, summary, wallets, models, map, adminResp] = results;
if (map) lastNetworkMap = map;
renderIfChanged("hive", raft, renderHive);
renderIfChanged("console", consoleData, renderConsole);
renderIfChanged("billing-summary", summary, data => renderBilling(data));
renderIfChanged("fraud", { wallets, summary }, data => renderFraud(data.wallets, data.summary));
renderIfChanged("admin-model-placement", { models, map }, data => renderAdminModelPlacement(data.models, data.map));
renderIfChanged("admin-node-pool", map, renderAdminNodePool);
if (adminResp && adminResp.ok) {
renderIfChanged("admin", adminResp.data.accounts || [], accounts => {
const rows = accounts.map(a => {

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