Skip to content

perf(network): streaming hot-path optimizations + dead-code cleanup - #491

Merged
Gajesh2007 merged 4 commits into
masterfrom
refactor/network-comm-cleanup
Jul 2, 2026
Merged

Gajesh2007 merged 4 commits into
masterfrom
refactor/network-comm-cleanup

Conversation

@Gajesh2007

@Gajesh2007 Gajesh2007 commented Jul 1, 2026 •

Copy link
Copy Markdown
Member

Summary

Network/communication hot-path optimizations plus a dead-code and docs-drift cleanup pass, from a full-codebase audit (coordinator, provider-swift, console-ui, scripts, docs). One commit, behavior-preserving except where noted (chunk-overflow handling is a deliberate behavior fix).

+2,298 / −2,806 across 54 files.

Before / After

Behavior — per-token streaming relay & control traffic

flowchart LR
  subgraph Before
    A1[provider WS frame] --> B1["parse JSON x2<br/>(envelope + struct)"]
    B1 --> C1["X25519 scalar mult<br/>per chunk (~40-60us)"]
    C1 --> D1{ChunkCh full?}
    D1 -- no --> E1[SSE to consumer]
    D1 -- yes --> F1["silently DROP token<br/>stream corrupt, still billed"]
    G1[challenge / cancel] --> H1["single FIFO write queue<br/>waits behind ~21MiB vision frames<br/>-> attestation timeouts"]
  end
  subgraph After
    A2[provider WS frame] --> B2["parse JSON x1<br/>(type scan + struct)"]
    B2 --> C2["symmetric open (~2us)<br/>shared key precomputed once/request"]
    C2 --> D2{ChunkCh full?}
    D2 -- no --> E2[SSE to consumer]
    D2 -- yes --> F2["FAIL request: cancel provider,<br/>499 to consumer, no reputation hit"]
    G2[challenge / cancel] --> H2["priority control lane<br/>preempts data frames"]
  end
Loading

Code — coordinator relay & writer internals

flowchart LR
  subgraph Before
    a1["ProviderMessage.UnmarshalJSON<br/>envelope pass + full pass"] --> b1["decryptTextResponseChunk<br/>box.Open (fresh scalar mult)"]
    b1 --> c1["handleChunk: non-blocking send,<br/>default: log + drop"]
    d1["providerWriter.run<br/>one queue chan"] --> e1["writeFrame: goroutine + timer<br/>spawned PER FRAME"]
  end
  subgraph After
    a2["ProviderMessage.UnmarshalJSON<br/>scanTopLevelString fast path<br/>(type_scan.go, fallback-safe)"] --> b2["decryptTextResponseChunk<br/>chunkKeyCache -> DecryptWithSharedKey<br/>forget() on complete/error"]
    b2 --> c2["handleChunk: overflow -><br/>sendProviderCancel + handleInferenceError(499)"]
    d2["providerWriter.run<br/>control lane > data lane"] --> e2["writeFrame: atomic deadline,<br/>ONE watchWrites goroutine per conn"]
  end
Loading

Perf changes

Area Change Measured / expected impact
coordinator/internal/e2e, api/chunk_key_cache.go X25519 shared key precomputed once per request (bounded cache, keyed by SessionPrivKey, dropped on terminal) Chunk decrypt ~40-60µs → ~1-2µs, off the provider read loop; mirrors the provider-side DH precompute (#483)
coordinator/protocol/type_scan.go + messages.go Single-pass provider message decode; conservative top-level "type" scanner with full fallback −45% ns/op, −256 B/op, −6 allocs/op on BenchmarkUnmarshalProviderMessage
coordinator/registry/provider_writer.go Priority control lane (challenges via new WriteTextControl, cancels/load/status via EnqueueText) Control frames no longer queue behind multi-MiB sealed vision frames; transport congestion can't become attestation-timeout reputation events
coordinator/registry/provider_writer.go Per-frame timeout goroutine+timer → one watchdog per connection (atomic deadline, 250ms tick) Removes 1 goroutine + 1 timer per outbound frame
provider-swift ProtocolCodec/ChunkSender/CoordinatorClient Cached JSONEncoder; Data-only chunk encode path (no Data→String→Data round trip per token) Fewer per-token allocations on the decode-bound Mac; wire format byte-identical (golden tests pass)

Behavior fix

api/provider.go handleChunk: a full ChunkCh (256) previously dropped tokens silently — the consumer got a corrupted stream that was still billed. Now the request is failed fast: provider generation cancelled, 499 terminal to the consumer, classified as consumer-side (no provider reputation penalty). Covered by provider_chunk_overflow_test.go end-to-end.

Dead code / junk removed

  • Go: payments.Ledger write path (Deposit/PendingPayouts/SettlePayout — prod uses Stripe webhook → store.Credit and store.SettleProviderPayout), unused ReferralService.ledger field/param, RequestQueue.CleanStale, dead Server setters (SetConsoleURL/SetCORSOrigin/CoordinatorKey), duplicate sha256Hex in store/memory.go
  • Swift: Crypto/X25519ChaChaPoly.swift (prod crypto is Sodium NaCl box), 7× hand-rolled hex encoders → Util/Hex.swift, duplicated ws→http normalization → Util/WebSocketURLScheme.swift
  • UI: lib/localFirst.ts (zero importers), unused formatUsdSigned/usdToMicro, ~480 lines of mock geo fixtures moved out of the prod stats route into mock-geo.ts, vestigial IIFE in chat route
  • Scripts / e2e: calibrate-routing.sh (referenced retired vllm-mlx + moved paths), load-test.py, gptoss_soak.sh, mlx_lm_batch_bench.py, one-off e2e/pr311_compat_test.go. Kept: load_soak.py/cache_soak_monitor.sh (m5 stress runbook depends on them) and preposition-rollback-build.sh (live migration rollback prerequisite)
  • Docs drift: AGENTS.md (nonexistent build-bundle.sh/bundle-app.sh → release-swift.yml, stale "binary checked into tree" claim, runbook/dev-env paths, structure block), threat-model.yaml all stale coordinator/internal/* paths (YAML validated — feeds the automated review workflow), payments + kv-cache doc paths

Tests added

  • protocol/type_scan_test.go — 26-case scanner table cross-checked against encoding/json, full-corpus equivalence, adversarial no-panic
  • registry/provider_writer_test.go — control-lane priority ordering, per-lane queue-full, real stalled-socket watchdog timeout, all -race -count=2
  • internal/e2e/shared_key_test.go — precompute round-trip equivalence with Decrypt, exact provider→coordinator direction, tamper/truncation
  • api/chunk_key_cache_test.go — hit/recompute/forget/cap-reset/concurrent (-race)
  • api/provider_chunk_overflow_test.go — overflow → 499, channels closed, pending removed, cache forgotten, zero reputation impact

Verification

  • Coordinator: gofmt clean, go vet clean, full go test ./... green (incl. the 100s api suite)
  • Provider: swift build green against master's engine pin; Protocol/Crypto/CoordinatorClient/ChunkSender/Integration suites pass (96 tests)
  • Console UI: eslint 0 errors, npm run build green, npm test green except the 4 pre-existing provider-dashboard-* failures already on master

Deferred (follow-ups from the audit, not in this PR)

  • Unify the duplicated inference pipelines (handleGenericInference vs chat path) and the ~6× body re-marshal through map[string]any — touches files with in-flight v0.6.31 work
  • Heartbeat side-effects (drainQueuedRequestsForModels/TriggerModelSwaps) still run inline on the WS read loop
  • SecurityChecks.isHypervisorActive() stub silently reports hypervisor_active=false in attestation — needs its own fix/decision
  • God-file splits (store/postgres.go 4.8k, registry/registry.go 4.5k, api/consumer.go 3.9k, stats/page.tsx 3.2k)

View with Codesmith Autofix with Codesmith
Need help on this PR? Tag /codesmith with what you need. Autofix is disabled.

Coordinator relay path (per-token costs):
- Precompute the X25519 shared key once per request (chunk_key_cache) so
  chunk decryption is a symmetric open (~2us) instead of a fresh scalar
  multiplication (~40-60us) on the provider's single read goroutine.
- Single-pass provider message decode: lightweight top-level type scan
  replaces the envelope json.Unmarshal pass (-45% decode time, -6 allocs
  per frame; falls back to the full envelope decode on anything ambiguous).
- ChunkCh overflow now fails the request (cancel + 499, no reputation hit)
  instead of silently dropping tokens from a stream that is still billed.

Provider WebSocket writer:
- Priority control lane: attestation challenges and cancels preempt
  multi-MiB inference frames, so transport congestion can no longer turn
  into attestation-timeout reputation events or delayed cancels.
- Per-frame timeout goroutine+timer replaced by one watchdog per
  connection with an atomic write deadline.

Swift provider hot path:
- Cached JSONEncoder + Data-only chunk encode path (removes the
  Data->String->Data round trip per token). Wire format unchanged.
- Shared hex-encoding helper replaces 7 hand-rolled copies; shared
  ws->http URL normalization.

Dead code / junk removal:
- payments.Ledger write path (Deposit/PendingPayouts/SettlePayout),
  unused ReferralService.ledger, RequestQueue.CleanStale, dead Server
  setters, store sha256Hex dupe.
- X25519ChaChaPoly.swift (prod crypto is NaCl box), localFirst.ts,
  unused currency exports, mock geo fixtures out of the prod stats route.
- Stale scripts (calibrate-routing, load-test, gptoss_soak,
  mlx_lm_batch_bench), one-off e2e/pr311_compat_test.go.
- Docs drift: AGENTS.md (bundle scripts, runbook paths, binary claim),
  threat-model.yaml coordinator/internal/* paths, payments/kv-cache doc
  paths.

Verification: coordinator gofmt/vet clean, full go test green; provider
swift build + protocol/crypto/coordinator-client/chunk-sender suites
green; console-ui eslint/build green (4 pre-existing dashboard test
failures unrelated).
@vercel

vercel Bot commented Jul 1, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
d-inference Ready Ready Preview Jul 1, 2026 11:59pm
d-inference-console-ui-dev Ready Ready Preview Jul 1, 2026 11:59pm
d-inference-landing Ready Ready Preview Jul 1, 2026 11:59pm

Request Review

@ethenotethan ethenotethan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated Code Review — Layr-Labs/d-inference#

Verdict: COMMENT

Security — ⚠️ SKIPPED

Error: OpenRouter HTTP 402: {"error":{"message":"Insufficient credits. Add more using https://openrouter.ai/settings/credits","code":402}}

Performance — ⚠️ SKIPPED

Error: OpenRouter HTTP 402: {"error":{"message":"Insufficient credits. Add more using https://openrouter.ai/settings/credits","code":402}}

Type_diligence — ⚠️ SKIPPED

Error: OpenRouter HTTP 402: {"error":{"message":"Insufficient credits. Add more using https://openrouter.ai/settings/credits","code":402}}

Additive_complexity — ⚠️ SKIPPED

Error: OpenRouter HTTP 402: {"error":{"message":"Insufficient credits. Add more using https://openrouter.ai/settings/credits","code":402}}

✅ All four passes clean. No issues found.

🤖 Automated review by Centaur · DAR-186

@github-actions

github-actions Bot commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

This PR is a safe refactor and backpressure improvement with no security regressions; the two coordinator-side changes (challenge on control lane, chunk-key memoization) are neutral-to-positive against the threat model.


Trust boundaries touched

  • TB-002 — coordinator↔provider WebSocket (challenge delivery, chunk decryption, overflow handling)
  • TB-003 — provider operator vs process (binary hash output, SE identity hex, APNs token hex)
  • TB-008 — coordinator↔payments (referral service refactor)

Per-threat assessment

T-033 / T-034 / T-036 / T-037 — Challenge integrity (provider.go:822)
✅ provider.WriteText → provider.WriteTextControl routes challenges on a dedicated control lane, preventing a congested inference data lane from starving the attestation challenge. This strictly strengthens challenge liveness and makes the 30-second nonce timeout window more reliable. No change to nonce generation, SE signature verification, or the one-time-use nonce tracker.

T-008 — Plaintext chunk fall-through (provider.go:1498–1583)
✅ decryptTextResponseChunk is now a method on Server (no functional change to the rejection path), and the refactored overflow handler upgrades silent drop → sendProviderCancel + handleInferenceError with a 499 status. This is net-positive: a full ChunkCh no longer silently delivers a corrupted stream. The coordinator-side fail-closed defence (reject plaintext chunks, mark provider untrusted) is not touched.

The sendChunkWithGrace panic recovery is correct — it handles a ChunkCh closed by registry.Disconnect from a concurrent goroutine (provider.go:1548–1558). The 250 ms grace window is a bounded head-of-line stall on the provider's single read goroutine; acceptable given the stated trade-off.

T-006 — Registry flooding / WebSocket abuse
ℹ️ No change to pre-auth rate limiting or connection caps. Existing limitations (SEC-034) unchanged.

T-013 — Binary hash computation (BinaryHasher.swift)
✅ digest.hexString replaces the hand-rolled map { String(format:"%02x",$0) }.joined() in hashFile, sha256Hex, and hashFilesSorted. This is a pure refactor; the SHA-256 computation and byte ordering are identical. Attestation blob content is unchanged.

T-035 — SE identity hex (SecureEnclaveIdentity.swift)
✅ Same refactor pattern for publicKeyHex. No change to the raw representation or how the key is used in attestation signing.

T-034 / T-042 — APNs device token encoding (ProviderAppKitHost.swift)
✅ deviceToken.hexString replaces the inline map in didRegisterForRemoteNotificationsWithDeviceToken. The token value is identical; only the encoding call site changes. The code_challenge / APNs push payload path is not touched. T-042 mitigations (no alert-mode push, challenge encrypted in payload) are unaffected.

T-007 / T-012 / T-027 — Weight hash computation (AdaptivePrefillStore.swift, BatchScheduler+EngineFactory.swift)
ℹ️ SHA256.hash(...).hexString refactor in prefix-cache key derivation and model-key directory naming. No change to how hashes are advertised to the coordinator or enforced. SEC-007 (fail-open enforcement) remains open and is unaffected by this PR.

T-032 — Solana wallet / billing (billing.go, referral.go)
ℹ️ payments.Ledger is removed from ReferralService. The ledger was already not used in any ReferralService method visible in the diff; this is a dead-field removal. No change to mnemonic handling, payment execution, or the Solana signing path.

T-004 / T-024 — Admin key / server surface (server.go)
ℹ️ Two setter methods (SetConsoleURL, SetCORSOrigin) and one accessor (CoordinatorKey()) are removed. CoordinatorKey() was annotated "exposed for tests; production code should not need this." Removing it tightens the exported API surface slightly. No change to key comparison logic (SEC-009 still open).

T-040 — Host-header injection
ℹ️ SetConsoleURL removal: confirm at the call site in cmd/coordinator/main.go (not in diff) that consoleURL is still set from the hardcoded config rather than a request header. The PR does not appear to change URL generation logic, but the deleted setter should be confirmed unused or inlined.


New attack surface

Chunk-key cache (chunkKeys chunkKeyCache, server.go:336–340; provider.go:1600–1608, 1665, 2164)
The memoized X25519 shared key is held in a chunkKeyCache struct keyed by *SessionPrivKey pointer. Two questions worth confirming in chunk_key_cache.go (not in this diff):

  1. Eviction bound — the comment says "bounded by chunkKeyCacheMax." Confirm the bound is enforced and that a provider sending many concurrent small requests cannot grow the map unboundedly (potential memory DoS vector against the coordinator, loosely related to T-006).
  2. Key material in map — the raw [32]byte shared secret sits in a Go map. Confirm it is zeroed on forget() calls (provider.go:1667, 2166) rather than simply deleted, to reduce the window of residual key material in heap. This is a defence-in-depth concern; not a hard vulnerability given AMD SEV-SNP TEE memory encryption.

Neither concern is a blocking issue given the coordinator trust model, but chunk_key_cache.go should be reviewed for these two properties before merge.


Open findings resolved by this PR

None explicitly closed. The overflow abort path (provider.go:1521–1541) partially addresses the "silent drop = corrupted billed stream" operational concern but is not tied to a formal SEC-* finding.


🔐 Threat model: docs/threat-model.yaml · Updates on each push to this PR

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 73a2e30ad8

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread coordinator/protocol/type_scan.go Outdated
if !ok {
return "", false
}
return string(v), true

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Fall back on duplicate message type keys

For provider frames with duplicate top-level type fields, this scanner returns the first occurrence, while the encoding/json envelope path it replaces used the last occurrence (and the concrete struct unmarshal still keeps the last one). That means a malformed provider frame such as first inference_complete and later inference_response_chunk is dispatched by pm.Type to the wrong handler instead of preserving the previous parse semantics; please detect a second top-level type and fall back to the normal envelope decode.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 18dcaa4 — the scanner now walks all top-level keys and returns ok=false on a repeated type key or any case-variant (Type), deferring to the envelope decode, since encoding/json is last-match-wins and case-insensitive. The first-wins divergence is eliminated and the never-wrong invariant now holds unconditionally (the test escape hatch for it is gone). Benchmark still ~40% faster than the double-parse baseline (2.2µs vs 3.6–4.0µs).

@@ -1,103 +0,0 @@
// Local-first chat with coordinator fallback.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep the documented local-first helper available

Removing this module leaves the direct-mode guide pointing users at a non-existent import (docs/provider/direct-mode.md:79-86 still tells them to import chatCompletionWithFallback from @/lib/localFirst, and repo-wide rg localFirst now only finds those docs). Anyone following that documented local/coordinator fallback flow will get a module-not-found failure, so either keep a compatibility export here or update the guide to the replacement API.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 18dcaa4 — docs/provider/direct-mode.md no longer imports from the deleted module; it now documents the local-first fallback pattern inline and notes the chatCompletionWithFallback prototype is recoverable from git history. The helper itself stays deleted: it had zero importers in src/ (unwired prototype), and keeping a compatibility export for code nothing calls would recreate the dead code this PR removes.

…dering contract, hex golden tests

Addresses the two medium findings + cheap follow-ups from the multi-lens
review (approve-with-nits):

- api/provider.go: chunk-buffer overflow now grants a bounded 250ms grace
  window (sendChunkWithGrace) before failing the request, so a healthy
  consumer catching up after a TCP burst is not hard-killed at 256 chunks
  of lag; recover-guarded against a concurrent registry.Disconnect channel
  close (same idiom Disconnect itself uses). New test pins the grace-path
  delivery; overflow test's nil-deref Fatalf split.
- registry/provider_writer.go: documented the real ordering contract —
  FIFO within a lane only, non-preemptive priority, WriteText's
  synchronous-completion invariant (what keeps request->cancel ordering
  safe), accurate lane-user lists (load/prefetch/desired-models remain on
  the data lane; rerouting is a follow-up). New ordering test pins
  WriteText-then-EnqueueText delivery order. Shared checkAccept preamble.
- registry/queue.go: stale '(default 30s)' maxWait doc -> 120s.
- store/memory.go: header no longer claims keys are stored unhashed.
- provider-swift Util/Hex.swift: hex digit table hoisted to file scope
  (was rebuilt per byte); header no longer overclaims; NEW HexTests with
  golden vectors — hexString now backs attestation-critical hashes, so a
  silent change would alter every provider-reported hash fleet-wide.
- provider-swift ProtocolCodec.swift: shared-encoder comment now states
  the defensible safety claim (configured-once + Sendable) instead of the
  false 'no mutable state'.

Backward-compat verification (mixed-version fleet, both directions) came
back COMPATIBLE: wire bytes identical (opcode .text set in untouched
ChunkFrameWriter), decode fast path falls back to the exact old envelope
decode, precomputed-key decrypt equals box.Open, cancels cannot overtake
their own request (WriteText blocks to wire completion; every cancel site
verified), old providers no-op safely on early control frames.

@ethenotethan ethenotethan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated Code Review — Layr-Labs/d-inference#

Verdict: COMMENT

Security — ⚠️ SKIPPED

Error: OpenRouter HTTP 402: {"error":{"message":"Insufficient credits. Add more using https://openrouter.ai/settings/credits","code":402}}

Performance — ⚠️ SKIPPED

Error: OpenRouter HTTP 402: {"error":{"message":"Insufficient credits. Add more using https://openrouter.ai/settings/credits","code":402}}

Type_diligence — ⚠️ SKIPPED

Error: OpenRouter HTTP 402: {"error":{"message":"Insufficient credits. Add more using https://openrouter.ai/settings/credits","code":402}}

Additive_complexity — ⚠️ SKIPPED

Error: OpenRouter HTTP 402: {"error":{"message":"Insufficient credits. Add more using https://openrouter.ai/settings/credits","code":402}}

✅ All four passes clean. No issues found.

🤖 Automated review by Centaur · DAR-186

@Gajesh2007

Copy link
Copy Markdown
Member Author

Multi-lens review + backward-compat verification

Ran a 42-cell parallel review (security / logic / style per changed file, synthesized) plus a dedicated mixed-version-fleet compatibility audit.

Review verdict: approve-with-nits — no critical/high findings

The risky cores all verified clean: chunk-key cache design (pointer-keying safe against GC address reuse, peerPub cross-check prevents stale-key reuse), writer lane ordering (cancel provably cannot overtake its own request), scanner fallback safety (bounds-checked, no-panic across adversarial corpus, acceptance set unchanged), and overflow-499 billing/reputation semantics (refund consistent, no breaker/reputation impact).

Addressed in 318e6c7 (both mediums + cheap nits)

Finding Fix
M1 — instantaneous full-buffer check could kill healthy-but-bursty consumers sendChunkWithGrace: bounded 250ms wait for one slot before aborting; recover-guarded vs concurrent Disconnect close; grace-path delivery pinned by a new test
M2 — undocumented cross-lane ordering contract Ordering paragraph on the writer (per-lane FIFO only, non-preemptive priority, WriteText synchronous-completion invariant); accurate lane-user lists; new WriteText-then-EnqueueText ordering test
Hex helper backs attestation-critical hashes with no test HexTests.swift golden vectors (all 256 byte values, SHA-256 pin, lowercase pin); digit table hoisted to file scope
Stale docs queue.go maxWait 30s→120s, memory.go hashing claim, encoder thread-safety rationale, Hex header overclaim, overflow-test nil-deref Fatalf

Backward compatibility: COMPATIBLE, both directions

  • New coordinator ↔ old providers: decode fast path falls back to the exact old envelope decode; precomputed-key decrypt is mathematically box.Open behind an unchanged guard chain; old providers no-op safely on early control frames (InferenceCancellationRegistry.cancel returns false for unknown ids).
  • New providers ↔ current prod coordinator: wire bytes are byte-identical — the Data→String→Data round trip removed was lossless, encoder options unchanged, and the WS .text opcode is set in ChunkFrameWriter, which this PR does not touch. Go read loop discards frame type anyway (provider.go:150).
  • Version gates untouched (LatestProviderVersion still 0.6.30).
  • Only client-visible delta (intentional): a consumer ≥256 chunks behind for >250ms now gets a well-formed in-band SSE error event + refund instead of a silently corrupted, fully billed stream — the same mid-stream error shape clients already receive for provider errors today.

Follow-ups (tracked, not blocking)

  1. Centralize chunkKeys.forget() across ALL terminal paths (speculative-race losers, Disconnect, grace expiry, retry reassignment) + zero key bytes on eviction — highest-agreement finding
  2. Watchdog↔writeFrame deadline CAS handoff; unlatch writeTimedOut per frame
  3. Classify overflow-499 as consumer-side in the relay's ErrorCh route-outcome path; shared constants for the 499/"request cancelled" literals
  4. Scanner: bail on duplicate "type" keys + add a fuzz target for the never-wrong invariant
  5. Reroute SendLoadModel/SendPrefetchModel/SendDesiredModels to the control lane
  6. Delete dbkvHexString in favor of hexString; migrate remaining peripheral hex copies
  7. mock-geo.ts pre-existing MOCK_MODELS[2] out-of-bounds (moved verbatim)

…ct-mode doc

- protocol/type_scan.go: scanTopLevelString now scans ALL top-level keys
  and bails to the envelope decode on a repeated 'type' key or any
  case-variant ('Type') — encoding/json is last-match-wins and
  case-insensitive, so the first-wins fast path could dispatch a
  malformed frame to the wrong handler. Divergence eliminated; the
  never-wrong invariant now holds unconditionally (skipReference escape
  hatch removed from the tests). Benchmark still ~40% faster than the
  double-parse baseline (2.2us vs 3.6-4.0us, 17 vs 23 allocs).
- docs/provider/direct-mode.md: no longer points at the deleted
  console-ui/src/lib/localFirst.ts helper; documents the local-first
  fallback pattern inline and notes the prototype lives in git history.

@ethenotethan ethenotethan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated Code Review — Layr-Labs/d-inference#

Verdict: COMMENT

Security — ⚠️ SKIPPED

Error: OpenRouter HTTP 402: {"error":{"message":"Insufficient credits. Add more using https://openrouter.ai/settings/credits","code":402}}

Performance — ⚠️ SKIPPED

Error: OpenRouter HTTP 402: {"error":{"message":"Insufficient credits. Add more using https://openrouter.ai/settings/credits","code":402}}

Type_diligence — ⚠️ SKIPPED

Error: OpenRouter HTTP 402: {"error":{"message":"Insufficient credits. Add more using https://openrouter.ai/settings/credits","code":402}}

Additive_complexity — ⚠️ SKIPPED

Error: OpenRouter HTTP 402: {"error":{"message":"Insufficient credits. Add more using https://openrouter.ai/settings/credits","code":402}}

✅ All four passes clean. No issues found.

🤖 Automated review by Centaur · DAR-186

@blacksmith-sh

blacksmith-sh Bot commented Jul 1, 2026

Copy link
Copy Markdown
Contributor

Found 1 test failure on Blacksmith runners:

Failure

Test View Logs
github.com/eigeninference/d-inference/e2e/TestIntegration_ConcurrentRequests View Logs

Fix with Codesmith
Need help on this PR? Tag /codesmith with what you need.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 18dcaa49f9

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread docs/provider/direct-mode.md Outdated
);
// `via` is "local" or "coordinator"; stream `response` as usual.
// proxy route, or a coordinator /v1/chat/completions with X-Darkbloom-Route: self
return { via: "coordinator", response: await postChat("/api/chat", body, coordinatorApiKey) };

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve self-route in the fallback example

The replacement local-first example falls back to /api/chat with only an API key, but that proxy only self-routes when the caller supplies X-Darkbloom-Route: self; as written, users following the doc will fall back to the public paid fleet despite this section promising the coordinator path is free. Pass the self-route header in the sample (or make postChat explicitly set it) so the documented behavior matches the text.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in ca47741 — the fallback in the example now sets X-Darkbloom-Route: self with a comment warning that omitting it routes to the public paid fleet.

Without X-Darkbloom-Route: self the coordinator fallback would hit the
public paid fleet, contradicting the section's 'both paths are free'
promise.

@ethenotethan ethenotethan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated Code Review — Layr-Labs/d-inference#

Verdict: COMMENT

Security — ⚠️ SKIPPED

Error: OpenRouter HTTP 402: {"error":{"message":"Insufficient credits. Add more using https://openrouter.ai/settings/credits","code":402}}

Performance — ⚠️ SKIPPED

Error: OpenRouter HTTP 402: {"error":{"message":"Insufficient credits. Add more using https://openrouter.ai/settings/credits","code":402}}

Type_diligence — ⚠️ SKIPPED

Error: OpenRouter HTTP 402: {"error":{"message":"Insufficient credits. Add more using https://openrouter.ai/settings/credits","code":402}}

Additive_complexity — ⚠️ SKIPPED

Error: OpenRouter HTTP 402: {"error":{"message":"Insufficient credits. Add more using https://openrouter.ai/settings/credits","code":402}}

✅ All four passes clean. No issues found.

🤖 Automated review by Centaur · DAR-186

@Gajesh2007
Gajesh2007 merged commit f19c4e4 into master Jul 2, 2026
19 of 20 checks passed
@Gajesh2007
Gajesh2007 deleted the refactor/network-comm-cleanup branch July 2, 2026 00:19

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ca47741062

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

// X-Darkbloom-Route: self header the request goes to the public paid fleet.
return {
via: "coordinator",
response: await postChat("/api/chat", body, coordinatorApiKey, {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Pass the coordinator API key into the fallback sample

In this documented local-first fallback path, the sample now calls postChat(..., coordinatorApiKey, ...) even though coordinatorApiKey is not in scope or accepted by chatCompletionWithFallback. Users copying this replacement for the removed helper will hit a ReferenceError/TypeScript error before reaching the self-route fallback; add the key to the function options/parameters or show where it comes from.

Useful? React with 👍 / 👎.

async function chatCompletionWithFallback(body: object, local: { baseURL: string; apiKey?: string } | null) {
if (local) {
try {
return { via: "local", response: await postChat(`${local.baseURL}/v1/chat/completions`, body, local.apiKey) };

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Avoid duplicating /v1 in the local URL

When the local value comes from discoverLocalEndpoint above, baseURL is info.base_url, and the provider writes that discovery value with the /v1 suffix (provider-swift/Sources/ProviderCore/Server/LocalEndpoint.swift:90; the same doc also shows OPENAI_BASE_URL=.../v1). Appending /v1/chat/completions here therefore produces /v1/v1/chat/completions, so users following the new fallback sample cannot reach the local server; append only /chat/completions to the discovered base URL.

Useful? React with 👍 / 👎.

Gajesh2007 added a commit that referenced this pull request Jul 5, 2026
Master moved (test-suite refactor #518, streaming perf #491, Harmony tag
fix #422) and the PR went CONFLICTING, which also stopped pull_request CI
from triggering. Single conflict: store_test.go — resolved by taking
master's refactored file and relocating this branch's
TestMemoryCreateStripeWithdrawalWithDebit into the branch's focused
stripe_withdrawals_memory_test.go. Verified post-merge: coordinator full
suite green, UI eslint 0 errors, vitest 454/454 (master's refactor fixed
the 4 pre-existing provider-dashboard failures), production build passes.
Gajesh2007 added a commit that referenced this pull request Oct 27, 2026
…current evidence (#1633)

* fix(provider): judge coordinator traffic and re-registration only on current evidence

#1607 (unreleased) treated the latest trust_status as current forever. The
production coordinator computes the registration status before it records
the connection's first verified challenge, so it carries authorization path
"none" (app_attest_qualification_required), and it sends no status when
legacy verification authorizes the connection right after: challenge
success sends one only on transient-deroute recovery, and App Attest
statuses follow lease changes. Every legacy (MDM-cohort) Mac would have
read "Traffic: NOT receiving coordinator work" (macOS 26 Macs: "upgrade to
macOS 27"), and an idle one would have re-registered after 15-30 min, then
30 min, 1 h, 2 h and every 4 h, with a backoff that never reset.

ServingReadiness is now the one decision tree for both the Traffic verdict
and re-registration (UnauthorizedConnectionRecovery's duplicate
connectionLacksAuthorization is removed; the policy keeps the timing):

- A refusal (no App Attest lease, current or expired, and no legacy path)
  blocks only while current: past statusGraceSeconds (90 s) after
  connecting and at most refusalMaxAge (60 s) old. The coordinator renews a
  status it maintains every 5 s (App Attest leases; platform #491 adds
  refused connections), so 60 s tolerates a dozen lost renewals, and since
  60 < 90 the registration status alone never blocks. An older refusal is
  the new `unconfirmed` verdict: its age and reason, no fix, no macOS 27.
- Explicit evidence still blocks at any age: untrusted/offline (the
  coordinator sends a recovery status), an expired App Attest lease (it
  names its own expiry), and no status 90 s after connecting (the
  coordinator always sends one at registration; it is not a stale verdict).
- A request the coordinator routed after its latest status
  (coordinator_connection.last_request_at, noted by the connection reader)
  reads as eligible and resets the backoff; it does not outweigh untrusted
  or an expired lease.
- Leaving the refused state logs "Coordinator authorizes this connection
  for work" only on positive evidence; a refusal that ages out logs
  "Coordinator refusal of this connection is no longer current; routing is
  unconfirmed".

handleTrustStatus takes an injectable receivedAt for tests. status and
doctor render `unconfirmed` (doctor: info, no fix).

Tests: a registration refusal with no later status never re-registers over
a simulated day and reads pending, then unconfirmed without macOS 27
advice; a refusal repeated every 5 s still re-registers at the threshold
when idle; an expired lease from a 2-minute-old status is still judged; a
routed request outweighs an earlier refusal and a later refusal counts
again; an aged-out refusal logs the unconfirmed line, not the routing one.
The #1607 tests are kept and now deliver statuses as a refreshing
coordinator does; judgesOnlyCoordinatorVerdictsItCanRead keeps its cases,
checked through the shared verdict. With master's rule restored in the
new code (refusals never age, no refusal grace) the legacy-scenario tests
fail.

Docs: cli-reference Traffic line, troubleshooting rows; the unreleased
coordinator-traffic-verdict fragment is amended in place.

* refactor(provider): state the request-ordering invariant; stop calling unconfirmed "not an exclusion"

Refactor pass on the current-evidence traffic verdict. No behavior change.

- ProviderLoop+Serve: say why noteCoordinatorRequest runs in the
  connection-control reader. ServingReadiness compares lastRequestAt with
  trust.receivedAt; noted from the work reader instead, a request parked
  behind a model load could be stamped after a refusal that arrived later.
- ServingReadiness: the type doc said "Diagnostics only", but the blocked
  verdict now also triggers re-registration
  (ProviderLoop.superviseServingAuthorization).
- troubleshooting: `unconfirmed` also covers an App Attest refusal the
  current coordinator does not repeat (for example a locked keychain), so
  "this is not an exclusion" and "needs no action" overclaimed. The row now
  says it does not show an exclusion and that its reason may no longer apply.
Gajesh2007 added a commit that referenced this pull request Oct 27, 2026
…nd platform #491/#541

The re-registration note now states which evidence counts (#1633); the
delta-checkpoint off switch is forwarded to the launchd job (#1630); the
coordinator to deploy before the tag must include #516, #491 and #541;
#1631 joins the non-provider entries.
Gajesh2007 added a commit that referenced this pull request Oct 27, 2026
- A prompt_anchor_mismatch receipt quarantines the provider's cache
  capability for the whole model (coordinator CacheQuarantineCommit.Apply;
  ProofFenceBase 60 s, doubling to ProofFenceMax 10 min), not only the
  mismatched requests' affinity. Say so in the changelog note and runbook
  step 1, and cite the platform code in the evidence table.
- #1599 shipped in v0.10.2 (99e1059 is an ancestor of f9d1af3), not
  first in the v0.10.3 hotfix.
- Drop the runbook's "platform change that pushes trust_status when legacy
  authorization starts is in progress": that change is
  darkbloom-platform#541, merged as 6beb8514, which step 1 already requires.
- Step 1: deploy shortly before the tag, matching the changelog's "close to
  this rollout" for #516, and limit #491's 5 s refresh to App Attest
  serving (startUnauthorizedStatusRefresh returns unless ServingEnabled).
- Step 3: name LatestProviderVersion instead of the dangling "That fallback
  constant", and scope "only ProviderCore.swift should change" to the
  snapshotted inputs.
- Evidence: production 2acffb5c also lacks #491 and #541; add rows for the
  #491/#541 status behavior and the quarantine.
@Gajesh2007 Gajesh2007 mentioned this pull request Oct 27, 2026
7 of 9 tasks
Gajesh2007 added a commit that referenced this pull request Oct 27, 2026
* chore(release): prepare provider 0.10.4

Set ProviderCore.version to 0.10.4 and mark v0.10.3 as published on
2026-10-26 (tag target 3ddd11c).

Open the v0.10.4 candidate entry with its upgrade and rollout notes: deploy
darkbloom-platform#516 close to the rollout (Qwen JSON prompts render without
thinking; mixed versions fail cache receipts with prompt_anchor_mismatch but
still serve), the client-visible Qwen JSON changes (no default reasoning, a
grammar-constrained answer cut short is a 422 after streaming, no MTP beside a
constrained row), forced tool_choice on four more models without a version
floor, delta checkpoints across upgrade and rollback, the unauthorized
re-registration cadence, the status served-line format, the add-on hold
(darkbloom-platform#514 already in production), unchanged MLX pins, and the
entries that build no provider artifact.

Update the release runbook: the 0.10.4 scope, the pin and metallib checks
before tagging, the rollout order and post-tag platform snapshot, the 0.10.2
enablement steps that still apply, platform evidence inspected on 2026-10-27,
and the published history.

The pending changelog fragments are rendered in the next commit.

* chore(release): render the pending changelog fragments into provider 0.10.4

Insert the output of

  python3 scripts/changelog.py render --version 0.10.4 --date 2026-10-27 \
    base-reward-zero-reason.md ci-darkbloom-runner-routing.md \
    coordinator-reconnect-stall.md coordinator-traffic-verdict.md \
    delta-complete-checkpoints.md desktop-release-sign-dmg.md \
    desktop-update-feed.md forced-tool-choice-admission.md \
    json-response-format-enforcement.md landing-agent-documents.md \
    provider-addon-hold-hardening.md provider-addon-hold.md \
    status-served-session-counts.md switch-model-cache-directory.md

verbatim, without its heading line, below the v0.10.4 upgrade and rollout
notes, and remove exactly those 14 fragments. The render ran against an
export of origin/master aa2887f, whose changelog.d matches this branch,
because the renderer refuses a version that CHANGELOG.md already names.

This commit is mechanical so the final roll-up can revert it, merge master
and render again once the in-flight 0.10.4 changes have landed.

* Revert "chore(release): render the pending changelog fragments into provider 0.10.4"

This reverts commit f673fff.

* chore(release): update 0.10.4 rollout notes for #1630, #1631, #1633 and platform #491/#541

The re-registration note now states which evidence counts (#1633); the
delta-checkpoint off switch is forwarded to the launchd job (#1630); the
coordinator to deploy before the tag must include #516, #491 and #541;
#1631 joins the non-provider entries.

* chore(release): correct the 0.10.4 rollout notes from the review pass

- A prompt_anchor_mismatch receipt quarantines the provider's cache
  capability for the whole model (coordinator CacheQuarantineCommit.Apply;
  ProofFenceBase 60 s, doubling to ProofFenceMax 10 min), not only the
  mismatched requests' affinity. Say so in the changelog note and runbook
  step 1, and cite the platform code in the evidence table.
- #1599 shipped in v0.10.2 (99e1059 is an ancestor of f9d1af3), not
  first in the v0.10.3 hotfix.
- Drop the runbook's "platform change that pushes trust_status when legacy
  authorization starts is in progress": that change is
  darkbloom-platform#541, merged as 6beb8514, which step 1 already requires.
- Step 1: deploy shortly before the tag, matching the changelog's "close to
  this rollout" for #516, and limit #491's 5 s refresh to App Attest
  serving (startUnauthorizedStatusRefresh returns unless ServingEnabled).
- Step 3: name LatestProviderVersion instead of the dangling "That fallback
  constant", and scope "only ProviderCore.swift should change" to the
  snapshotted inputs.
- Evidence: production 2acffb5c also lacks #491 and #541; add rows for the
  #491/#541 status behavior and the quarantine.

* changelog: delta complete checkpoints apply to Qwen native recurrent layouts, not only Qwen 3.8

Eligibility follows the checkpoint layout (native-paged/contiguous-full-recurrent-v1),
which Qwen 3.5/3.6 MTP builds also produce; the fragment is rendered verbatim into 0.10.4.

* chore(release): render the pending changelog fragments into provider 0.10.4

Verbatim scripts/changelog.py render output for the 15 fragments pending on
master (rendered from a master export, since CHANGELOG.md already names
0.10.4), inserted below the rollout notes; exactly those fragments deleted.
#1427 is not in 0.10.4 and its fragments stay with it.

This branch had an error being deployed

1 failed and 3 active deployments
Preview – d-inference-console-ui-dev — ca477410 Deployed Jul 1, 2026 by vercel[bot]
Preview – d-inference — ca477410 Deployed Jul 1, 2026 by vercel[bot]
Preview – d-inference-landing — ca477410 Deployed Jul 1, 2026 by vercel[bot]
benchmarks — ca477410 Deployed Jul 1, 2026 by Gajesh2007 via E2E Benchmarks #1501
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants