Skip to content

security: pin coordinator URL in console proxies + installer sync + billing mock-mode guard - #316

Closed
anupsv wants to merge 4 commits into
masterfrom
security/console-ssrf-installer-mockmode
Closed

anupsv wants to merge 4 commits into
masterfrom
security/console-ssrf-installer-mockmode

Conversation

@anupsv

@anupsv anupsv commented Jun 11, 2026 •

Copy link
Copy Markdown
Contributor

Frontend + ops security hardening, split out from a larger working tree (PR 1 of 2).

SEC-001 / SEC-002 — SSRF + credential forwarding

The six Next proxy routes (stripe checkout/status/onboard/withdrawals, withdraw/stripe, telemetry) and the provider Earnings page no longer honor the client-supplied x-coordinator-url header / localStorage coordinator URL. They pin to the build-time NEXT_PUBLIC_COORDINATOR_URL, so Privy session cookies / API bearer tokens can no longer be forwarded to an attacker-supplied origin.

Privy production guard

A production build missing or carrying a "placeholder" NEXT_PUBLIC_PRIVY_APP_ID now renders a config-error screen instead of silently serving mock-authenticated UI.

install.sh drift

coordinator/api/install.sh (served to providers via //go:embed) is synced with scripts/install.sh, and TestInstallScriptNoDrift now fails if they diverge.

DAR-59 — billing MockMode boot guard

The coordinator refuses to boot when billing mock mode is enabled alongside real payment credentials (mnemonic / Stripe key) — a silent payment-bypass becomes a loud startup failure.

Tests

  • vitest: coordinator-url-pinning, earnings-url-pinning, privy-client-provider (250/250 suite green, eslint clean)
  • Go: TestInstallScriptNoDrift, MockMode boot-guard table test
  • All regression tests revert-verified (fail without the fix).

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

…illing mock-mode guard

- SEC-001/002: the six Next proxy routes (stripe checkout/status/onboard/
  withdrawals, withdraw/stripe, telemetry) and the provider Earnings page no
  longer honor the client-supplied x-coordinator-url header / localStorage URL;
  they pin to the build-time NEXT_PUBLIC_COORDINATOR_URL, so Privy/API bearer
  tokens can't be forwarded to an attacker-supplied origin (SSRF + credential
  exfiltration).
- Privy: a production build missing/with a 'placeholder' NEXT_PUBLIC_PRIVY_APP_ID
  now renders a config-error screen instead of silently serving mock-authenticated UI.
- install.sh: sync the coordinator-served copy (coordinator/api/install.sh) with
  scripts/install.sh and add a drift regression test so they can't diverge silently.
- DAR-59: refuse to boot when billing mock mode is enabled alongside real payment
  credentials (mnemonic / Stripe key).

Tests: vitest URL-pinning + Privy guard, install-drift test, MockMode boot guard.
All revert-verified (fail without the fix).
@vercel

vercel Bot commented Jun 11, 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 Jun 11, 2026 9:02pm
d-inference-console-ui-dev Ready Ready Preview Jun 11, 2026 9:02pm
d-inference-landing Ready Ready Preview Jun 11, 2026 9:02pm

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: REQUEST_CHANGES

Security — 7 finding(s) (7 blocking)

  • 🔴 [CRITICAL] console-ui/src/app/api/payments/stripe/checkout/route.ts:10 — SSRF vulnerability fixed by pinning coordinator URL
    • Suggestion: The fix correctly removes client-controlled coordinator URL to prevent SSRF and credential forwarding
  • 🔴 [CRITICAL] console-ui/src/app/api/payments/stripe/onboard/route.ts:10 — SSRF vulnerability fixed by pinning coordinator URL
    • Suggestion: The fix correctly removes client-controlled coordinator URL to prevent SSRF and credential forwarding
  • 🔴 [CRITICAL] console-ui/src/app/api/payments/stripe/status/route.ts:9 — SSRF vulnerability fixed by pinning coordinator URL
    • Suggestion: The fix correctly removes client-controlled coordinator URL to prevent SSRF and credential forwarding
  • 🔴 [CRITICAL] console-ui/src/app/api/payments/stripe/withdrawals/route.ts:9 — SSRF vulnerability fixed by pinning coordinator URL
    • Suggestion: The fix correctly removes client-controlled coordinator URL to prevent SSRF and credential forwarding
  • 🔴 [CRITICAL] console-ui/src/app/api/payments/withdraw/stripe/route.ts:10 — SSRF vulnerability fixed by pinning coordinator URL
    • Suggestion: The fix correctly removes client-controlled coordinator URL to prevent SSRF and credential forwarding
  • 🔴 [CRITICAL] console-ui/src/app/api/telemetry/route.ts:14 — SSRF vulnerability fixed by pinning coordinator URL
    • Suggestion: The fix correctly removes client-controlled coordinator URL to prevent SSRF and credential forwarding
  • 🟡 [MEDIUM] console-ui/src/app/providers/earnings/EarningsContent.tsx:124-125 — Session poisoning vulnerability fixed by pinning coordinator URL
    • Suggestion: The fix correctly removes localStorage-controlled coordinator URL to prevent bearer token forwarding to attacker origins

Performance — ✅ No issues found

Type_diligence — ✅ No issues found

Additive_complexity — 5 finding(s) (1 blocking)

  • 🔵 [INFO] console-ui/__tests__/coordinator-url-pinning.test.ts:1-127 — Test file creates complex mock infrastructure for simple security fix verification
    • Suggestion: Consider simpler unit tests that directly test the route handlers without full NextRequest mocking - the security fix is just removing header reading
  • 🔵 [INFO] console-ui/__tests__/earnings-url-pinning.test.tsx:1-90 — Heavy mocking setup for testing a simple localStorage ignore change
    • Suggestion: Test could be simplified to just verify the fetch URL without full component rendering and extensive mocking
  • 🔵 [INFO] console-ui/__tests__/privy-client-provider.test.tsx:1-94 — Complex module reset/import dance for testing environment variable behavior
    • Suggestion: Consider extracting the environment check logic to a pure function that can be tested directly without module reloading
  • 🟡 [MEDIUM] coordinator/api/install_sh_test.go:115-163 — Complex file path resolution and normalization logic for simple drift detection
    • Suggestion: Use a simpler approach like embedding both files as constants or using relative paths from a known project root
  • 🔵 [INFO] coordinator/billing/config_test.go:1-104 — Repetitive environment variable setup pattern across test cases
    • Suggestion: Extract a helper function for setting up test environments to reduce the repeated env clearing and setting logic

12 finding(s) total, 8 blocking. Verdict: REQUEST_CHANGES.

🤖 Automated review by Centaur · DAR-186


export async function POST(req: NextRequest) {
const coordUrl = req.headers.get("x-coordinator-url") || DEFAULT_COORD;
const coordUrl = DEFAULT_COORD;

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.

🔴 [CRITICAL] 🔒 SSRF vulnerability fixed by pinning coordinator URL

💡 Suggestion: The fix correctly removes client-controlled coordinator URL to prevent SSRF and credential forwarding

📊 Score: 4×4 = 16 · Category: auth-bypass


export async function POST(req: NextRequest) {
const coordUrl = req.headers.get("x-coordinator-url") || DEFAULT_COORD;
const coordUrl = DEFAULT_COORD;

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.

🔴 [CRITICAL] 🔒 SSRF vulnerability fixed by pinning coordinator URL

💡 Suggestion: The fix correctly removes client-controlled coordinator URL to prevent SSRF and credential forwarding

📊 Score: 4×4 = 16 · Category: auth-bypass


export async function GET(req: NextRequest) {
const coordUrl = req.headers.get("x-coordinator-url") || DEFAULT_COORD;
const coordUrl = DEFAULT_COORD;

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.

🔴 [CRITICAL] 🔒 SSRF vulnerability fixed by pinning coordinator URL

💡 Suggestion: The fix correctly removes client-controlled coordinator URL to prevent SSRF and credential forwarding

📊 Score: 4×4 = 16 · Category: auth-bypass


export async function GET(req: NextRequest) {
const coordUrl = req.headers.get("x-coordinator-url") || DEFAULT_COORD;
const coordUrl = DEFAULT_COORD;

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.

🔴 [CRITICAL] 🔒 SSRF vulnerability fixed by pinning coordinator URL

💡 Suggestion: The fix correctly removes client-controlled coordinator URL to prevent SSRF and credential forwarding

📊 Score: 4×4 = 16 · Category: auth-bypass


export async function POST(req: NextRequest) {
const coordUrl = req.headers.get("x-coordinator-url") || DEFAULT_COORD;
const coordUrl = DEFAULT_COORD;

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.

🔴 [CRITICAL] 🔒 SSRF vulnerability fixed by pinning coordinator URL

💡 Suggestion: The fix correctly removes client-controlled coordinator URL to prevent SSRF and credential forwarding

📊 Score: 4×4 = 16 · Category: auth-bypass

Comment on lines +1 to +127
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { NextRequest } from "next/server";

// SEC-001 regression: server proxy routes must resolve the coordinator URL
// from the build-time constant only. A client-supplied `x-coordinator-url`
// header must never choose the upstream origin — it turns the Next server
// into an SSRF proxy and forwards Privy session tokens to that origin.
//
// Each case sends an attacker-controlled header (plus a privy-token cookie
// for the routes that forward it) and asserts the upstream fetch went to the
// pinned coordinator.

const DEFAULT_COORD = "https://api.darkbloom.dev";
const ATTACKER = "https://attacker.example.com";

let upstreamFetch: ReturnType<typeof vi.fn>;

beforeEach(() => {
upstreamFetch = vi.fn().mockResolvedValue(
new Response(JSON.stringify({}), {
status: 200,
headers: { "Content-Type": "application/json" },
})
);
vi.stubGlobal("fetch", upstreamFetch);
});

afterEach(() => {
vi.restoreAllMocks();
vi.resetModules();
});

function makeRequest(
url: string,
init?: { method?: string; body?: string }
): NextRequest {
return new NextRequest(new URL(url, "http://localhost:3000"), {
method: init?.method ?? "GET",
headers: {
"x-coordinator-url": ATTACKER,
cookie: "privy-token=privy-tok-123",
...(init?.body ? { "content-type": "application/json" } : {}),
},
...(init?.body ? { body: init.body } : {}),
});
}

interface RouteCase {
name: string;
importPath: () => Promise<{
POST?: (req: NextRequest) => Promise<Response>;
GET?: (req: NextRequest) => Promise<Response>;
}>;
method: "GET" | "POST";
requestPath: string;
upstreamPath: string;
body?: string;
}

const CASES: RouteCase[] = [
{
name: "POST /api/payments/stripe/checkout",
importPath: () => import("@/app/api/payments/stripe/checkout/route"),
method: "POST",
requestPath: "/api/payments/stripe/checkout",
upstreamPath: "/v1/billing/stripe/create-session",
body: JSON.stringify({ amount_usd: 10 }),
},
{
name: "GET /api/payments/stripe/status",
importPath: () => import("@/app/api/payments/stripe/status/route"),
method: "GET",
requestPath: "/api/payments/stripe/status",
upstreamPath: "/v1/billing/stripe/status",
},
{
name: "POST /api/payments/stripe/onboard",
importPath: () => import("@/app/api/payments/stripe/onboard/route"),
method: "POST",
requestPath: "/api/payments/stripe/onboard",
upstreamPath: "/v1/billing/stripe/onboard",
body: JSON.stringify({ country: "US" }),
},
{
name: "GET /api/payments/stripe/withdrawals",
importPath: () => import("@/app/api/payments/stripe/withdrawals/route"),
method: "GET",
requestPath: "/api/payments/stripe/withdrawals",
upstreamPath: "/v1/billing/stripe/withdrawals",
},
{
name: "POST /api/payments/withdraw/stripe",
importPath: () => import("@/app/api/payments/withdraw/stripe/route"),
method: "POST",
requestPath: "/api/payments/withdraw/stripe",
upstreamPath: "/v1/billing/withdraw/stripe",
body: JSON.stringify({ amount_usd: 5, method: "standard" }),
},
{
name: "POST /api/telemetry",
importPath: () => import("@/app/api/telemetry/route"),
method: "POST",
requestPath: "/api/telemetry",
upstreamPath: "/v1/telemetry/events",
body: JSON.stringify({ events: [] }),
},
];

describe("coordinator URL pinning (SEC-001)", () => {
for (const c of CASES) {
it(`${c.name} ignores x-coordinator-url`, async () => {
const mod = await c.importPath();
const handler = c.method === "GET" ? mod.GET! : mod.POST!;
const res = await handler(
makeRequest(c.requestPath, { method: c.method, body: c.body })
);

expect(res.status).toBe(200);
expect(upstreamFetch).toHaveBeenCalledTimes(1);
const upstreamUrl = String(upstreamFetch.mock.calls[0][0]);
expect(upstreamUrl.startsWith(`${DEFAULT_COORD}${c.upstreamPath}`)).toBe(
true
);
expect(upstreamUrl).not.toContain("attacker.example.com");
});
}
});

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.

🔵 [INFO] 🧩 Test file creates complex mock infrastructure for simple security fix verification

💡 Suggestion: Consider simpler unit tests that directly test the route handlers without full NextRequest mocking - the security fix is just removing header reading

📊 Score: 2×2 = 4 · Category: over-abstraction

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Keeping as-is. This is a table-driven test over all 6 pinned routes — collapsing the NextRequest setup would mean testing fewer routes or not invoking the real handlers. This repo's testing guide calls for exercising the real request path (not an extracted helper), which is what catches a route re-introducing header trust. The setup is already one makeRequest helper + a CASES table, and the per-route assertion is ~5 lines; the only "infrastructure" is a stubbed global fetch to capture the upstream URL — the minimum needed to assert where the request went.

Comment on lines +1 to +90
import { render, waitFor } from "@testing-library/react";
import { beforeEach, afterEach, describe, expect, it, vi } from "vitest";

// SEC-002 regression: the Earnings page sends a bearer token with its
// account-earnings fetch. That fetch must go to the build-time coordinator
// URL — a localStorage-poisoned `darkbloom_coordinator_url` must never
// receive the token.

vi.mock("@/hooks/useAuth", () => ({
useAuth: () => ({
ready: true,
authenticated: true,
login: vi.fn(),
getAccessToken: vi.fn().mockResolvedValue("privy-access-token"),
}),
}));

vi.mock("@/hooks/useToast", () => ({
useToastStore: (selector: (s: { addToast: () => void }) => unknown) =>
selector({ addToast: vi.fn() }),
}));

vi.mock("@/lib/google-analytics", () => ({
trackEvent: vi.fn(),
}));

vi.mock("@/lib/api", () => ({
fetchStripeStatus: vi.fn().mockResolvedValue({
connected: false,
payouts_enabled: false,
requirements_due: [],
}),
startStripeOnboarding: vi.fn(),
withdrawStripe: vi.fn(),
fetchStripeWithdrawals: vi.fn().mockResolvedValue([]),
computeStripeFeeUsd: vi.fn().mockReturnValue(0),
}));

let fetchMock: ReturnType<typeof vi.fn>;

beforeEach(() => {
fetchMock = vi.fn().mockResolvedValue({
ok: true,
status: 200,
json: () =>
Promise.resolve({
account_id: "acct",
earnings: [],
total_micro_usd: 0,
total_usd: "0.00",
count: 0,
recent_count: 0,
history_limit: 100,
available_balance_micro_usd: 0,
available_balance_usd: "0.00",
withdrawable_balance_micro_usd: 0,
withdrawable_balance_usd: "0.00",
}),
});
vi.stubGlobal("fetch", fetchMock);
localStorage.clear();
});

afterEach(() => {
vi.restoreAllMocks();
});

describe("EarningsContent coordinator URL pinning (SEC-002)", () => {
it("ignores a poisoned localStorage coordinator URL", async () => {
localStorage.setItem(
"darkbloom_coordinator_url",
"https://attacker.example.com"
);

const { default: EarningsContent } = await import(
"@/app/providers/earnings/EarningsContent"
);
render(<EarningsContent />);

await waitFor(() => expect(fetchMock).toHaveBeenCalled());

const earningsCall = fetchMock.mock.calls.find((c) =>
String(c[0]).includes("/v1/provider/account-earnings")
);
expect(earningsCall).toBeDefined();
const url = String(earningsCall![0]);
expect(url.startsWith("https://api.darkbloom.dev/")).toBe(true);
expect(url).not.toContain("attacker.example.com");
});
});

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.

🔵 [INFO] 🧩 Heavy mocking setup for testing a simple localStorage ignore change

💡 Suggestion: Test could be simplified to just verify the fetch URL without full component rendering and extensive mocking

📊 Score: 2×2 = 4 · Category: over-abstraction

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Keeping as-is. The regression is specifically that the component must ignore a localStorage-poisoned coordinator URL when it builds its authenticated fetch, so rendering the real component is the test. "Verify the fetch URL without rendering" would require extracting the URL logic out of the component — which is exactly the code path under test. The vi.mocks are the minimum needed to mount EarningsContent (auth, toast, analytics, api); dropping them lets the component hit real deps and crash.

Comment on lines +1 to +94
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { render, screen } from "@testing-library/react";

// ---------------------------------------------------------------------------
// PrivyClientProvider — production misconfiguration guard
//
// IS_PRIVY_CONFIGURED is evaluated at module scope, so we use
// vi.resetModules() + dynamic import to get a fresh evaluation of the
// NEXT_PUBLIC_PRIVY_APP_ID env var. The production check itself (isProductionEnv)
// reads process.env.NODE_ENV at render time, so vi.stubEnv works for it even
// without a module reload.
// ---------------------------------------------------------------------------

beforeEach(() => {
vi.resetModules();
});

afterEach(() => {
vi.unstubAllEnvs();
});

// ---------------------------------------------------------------------------
// Case A: production build + missing/placeholder app ID → config-error screen
// ---------------------------------------------------------------------------

const CONFIG_ERROR_PATTERN = /Authentication is not configured/i;

async function renderProviderProd(appId: string) {
vi.stubEnv("NEXT_PUBLIC_PRIVY_APP_ID", appId);
vi.stubEnv("NODE_ENV", "production");
const { PrivyClientProvider } = await import(
"@/components/providers/PrivyClientProvider"
);
render(
<PrivyClientProvider>
<span data-testid="child-probe">should not appear</span>
</PrivyClientProvider>
);
}

describe("PrivyClientProvider — production with unconfigured app ID", () => {
it("shows config-error UI and does NOT render children when NODE_ENV=production and app ID is absent", async () => {
// Ensure NEXT_PUBLIC_PRIVY_APP_ID is absent (force module re-evaluation).
await renderProviderProd("");

// Config-error message must be visible.
expect(screen.getByText(CONFIG_ERROR_PATTERN)).toBeInTheDocument();
expect(
screen.getByText(/NEXT_PUBLIC_PRIVY_APP_ID/i)
).toBeInTheDocument();
expect(screen.getByText(/misconfigured/i)).toBeInTheDocument();

// Children must NOT be rendered.
expect(screen.queryByTestId("child-probe")).not.toBeInTheDocument();
});

it("shows config-error UI when app ID is the literal 'placeholder' string in production", async () => {
await renderProviderProd("placeholder");

expect(screen.getByText(CONFIG_ERROR_PATTERN)).toBeInTheDocument();
expect(screen.queryByTestId("child-probe")).not.toBeInTheDocument();
});
});

// ---------------------------------------------------------------------------
// Case B: non-production (test/dev) + missing app ID → mock fallback renders children
// ---------------------------------------------------------------------------

describe("PrivyClientProvider — non-production with unconfigured app ID", () => {
it("renders children via mock-auth fallback when NODE_ENV is not production", async () => {
// Default vitest NODE_ENV is "test"; NEXT_PUBLIC_PRIVY_APP_ID unset.
vi.stubEnv("NEXT_PUBLIC_PRIVY_APP_ID", "");
// Do NOT stub NODE_ENV — vitest default is "test", which is non-production.

const { PrivyClientProvider } = await import(
"@/components/providers/PrivyClientProvider"
);

render(
<PrivyClientProvider>
<span data-testid="child-probe">hello</span>
</PrivyClientProvider>
);

// Children must render.
expect(screen.getByTestId("child-probe")).toBeInTheDocument();
expect(screen.getByText("hello")).toBeInTheDocument();

// Config-error message must NOT be present.
expect(
screen.queryByText(/Authentication is not configured/i)
).not.toBeInTheDocument();
});
});

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.

🔵 [INFO] 🧩 Complex module reset/import dance for testing environment variable behavior

💡 Suggestion: Consider extracting the environment check logic to a pure function that can be tested directly without module reloading

📊 Score: 2×2 = 4 · Category: over-abstraction

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Keeping as-is. IS_PRIVY_CONFIGURED is evaluated at module scope, so resetModules() + dynamic import is the correct way to re-read the env per case. Extracting a pure isPrivyConfigured() predicate would let me unit-test the predicate directly, but the valuable assertions here are the render behaviors (prod + missing ID → config-error screen and children NOT rendered; non-prod → children render via mock fallback) — which still need the module re-eval. So the extraction would add a predicate test on top of these, not remove the module dance: net more code, same complexity.

Comment on lines +115 to +163
// TestInstallScriptNoDrift asserts that coordinator/api/install.sh and
// scripts/install.sh are byte-for-byte identical after normalizing the single
// intentional difference: the COORD_URL default line. In coordinator/api/install.sh
// that line carries __DARKBLOOM_COORD_URL__ (substituted at serve time); in
// scripts/install.sh it carries https://api.darkbloom.dev (direct-fetch default).
// If someone edits one copy without the other this test fails.
func TestInstallScriptNoDrift(t *testing.T) {
// Locate scripts/install.sh relative to this source file. runtime.Caller
// gives us the absolute path of the test file; walk up two directories to
// the repo root, then descend into scripts/.
_, thisFile, _, ok := runtime.Caller(0)
if !ok {
t.Fatal("runtime.Caller(0) failed — cannot locate test source file")
}
// thisFile: .../coordinator/api/install_sh_test.go
// repoRoot: .../
repoRoot := filepath.Join(filepath.Dir(thisFile), "..", "..")
scriptsSrc := filepath.Join(repoRoot, "scripts", "install.sh")

scriptsSrcBytes, err := os.ReadFile(scriptsSrc)
if err != nil {
if os.IsNotExist(err) {
t.Skipf("scripts/install.sh not found at %s (vendored layout?); skipping drift check", scriptsSrc)
}
t.Fatalf("read scripts/install.sh: %v", err)
}

// installScript is the embedded coordinator/api/install.sh (package-level var).
embedded := string(installScript)
scriptsRef := string(scriptsSrcBytes)

// normalizeCoordURL replaces both the placeholder and the prod-URL default
// with a fixed token so the one intentional difference is invisible to the
// equality check.
normalizeCoordURL := func(s string) string {
s = strings.ReplaceAll(s, `COORD_URL="${COORD_URL:-__DARKBLOOM_COORD_URL__}"`, `COORD_URL="__NORMALIZED__"`)
s = strings.ReplaceAll(s, `COORD_URL="${COORD_URL:-https://api.darkbloom.dev}"`, `COORD_URL="__NORMALIZED__"`)
return s
}

embeddedNorm := normalizeCoordURL(embedded)
scriptsNorm := normalizeCoordURL(scriptsRef)

if embeddedNorm != scriptsNorm {
t.Errorf("coordinator/api/install.sh has drifted from scripts/install.sh\n" +
"Run: diff scripts/install.sh coordinator/api/install.sh\n" +
"The only intentional difference is the COORD_URL default line.\n" +
"Sync both copies before committing.")
}

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.

🟡 [MEDIUM] 🧩 Complex file path resolution and normalization logic for simple drift detection

💡 Suggestion: Use a simpler approach like embedding both files as constants or using relative paths from a known project root

📊 Score: 3×3 = 9 · Category: over-configuration

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Keeping as-is — both suggested alternatives are infeasible here:

  • Embed both as constants: go:embed patterns cannot contain .. and are resolved relative to the package directory, so the api package physically cannot embed ../../scripts/install.sh. Detecting drift between the embedded copy and that sibling script is the entire purpose of the test.
  • Relative path from project root: go test runs with the working directory set to the package dir (coordinator/api/), not the repo root, so a relative scripts/install.sh would resolve to coordinator/api/scripts/install.sh and fail. runtime.Caller(0) + ../.. is the standard CWD-independent way to locate a sibling file from a test, and it already t.Skips gracefully on vendored layouts where the script is absent.

The normalization is two ReplaceAlls for the single intentional difference (the COORD_URL default line) — that asymmetry is inherent to what the test asserts.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Followed up in fd3205e: collapsed the two hardcoded ReplaceAlls into a single regex that normalizes whatever the COORD_URL default is — simpler, and more robust (it won't silently stop normalizing if the prod default URL ever changes). The path resolution stays on runtime.Caller for the reason above; drift detection was revert-verified (still fires on injected drift).

Comment on lines +1 to +104
package billing

import (
"strings"
"testing"

"github.com/eigeninference/d-inference/coordinator/env"
)

// TestCheckMockModeTripwire exercises the DAR-59 fail-closed guard in
// Config.Check via ReadConfig so that the real env-var→Config path is covered
// (not a hand-built Config struct that could drift from ReadConfig).
//
// Table layout:
//
// (a) mock + no real creds → loads fine
// (b) mock + mnemonic set → error
// (c) mock + stripe key set → error
// (d) no mock + real creds → loads fine (production baseline)
func TestCheckMockModeTripwire(t *testing.T) {
prefix := env.EnvPrefix // "EIGENINFERENCE"

cases := []struct {
name string
envs map[string]string
wantErr bool
errFrag string // substring that must appear in the error message
}{
{
name: "(a) mock only — no real creds — OK",
envs: map[string]string{
prefix + "_BILLING_MOCK": "true",
},
wantErr: false,
},
{
name: "(b) mock + Solana mnemonic — must error",
envs: map[string]string{
prefix + "_BILLING_MOCK": "true",
prefix + "_SOLANA_MNEMONIC": "word1 word2 word3 word4 word5 word6 word7 word8 word9 word10 word11 word12",
},
wantErr: true,
errFrag: "DAR-59",
},
{
name: "(b2) mock + bare MNEMONIC env — must error",
envs: map[string]string{
prefix + "_BILLING_MOCK": "true",
"MNEMONIC": "word1 word2 word3 word4 word5 word6 word7 word8 word9 word10 word11 word12",
},
wantErr: true,
errFrag: "DAR-59",
},
{
name: "(c) mock + Stripe secret key — must error",
envs: map[string]string{
prefix + "_BILLING_MOCK": "true",
prefix + "_STRIPE_SECRET_KEY": "sk_live_fakekeyfortest",
},
wantErr: true,
errFrag: "DAR-59",
},
{
name: "(d) no mock + real creds — production baseline — OK",
envs: map[string]string{
prefix + "_SOLANA_MNEMONIC": "word1 word2 word3 word4 word5 word6 word7 word8 word9 word10 word11 word12",
prefix + "_STRIPE_SECRET_KEY": "sk_live_fakekeyfortest",
},
wantErr: false,
},
}

for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
// Isolate env state: clear all billing-related vars, then set the
// ones for this case. t.Setenv restores on cleanup automatically.
for _, key := range []string{
prefix + "_BILLING_MOCK",
prefix + "_SOLANA_MNEMONIC",
prefix + "_MNEMONIC",
"MNEMONIC",
prefix + "_STRIPE_SECRET_KEY",
} {
t.Setenv(key, "")
}
for k, v := range tc.envs {
t.Setenv(k, v)
}

cfg := ReadConfig()
err := cfg.Check()

if tc.wantErr && err == nil {
t.Fatalf("expected an error but Check() returned nil")
}
if !tc.wantErr && err != nil {
t.Fatalf("expected no error but Check() returned: %v", err)
}
if tc.wantErr && tc.errFrag != "" && !strings.Contains(err.Error(), tc.errFrag) {
t.Fatalf("error message %q does not contain expected fragment %q", err.Error(), tc.errFrag)
}
})
}
}

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.

🔵 [INFO] 🧩 Repetitive environment variable setup pattern across test cases

💡 Suggestion: Extract a helper function for setting up test environments to reduce the repeated env clearing and setting logic

📊 Score: 2×2 = 4 · Category: duplicate logic

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in fd3205e — extracted a setBillingEnv(t, prefix, envs) helper that clears the billing vars then applies the case's vars, replacing the inlined loop in the table runner.

@github-actions

github-actions Bot commented Jun 11, 2026 •

Copy link
Copy Markdown
Contributor

This PR closes the two highest-impact open security findings in the console-UI surface (SEC-001/SEC-002 and SEC-026) with minimal, well-targeted changes.


Trust boundaries touched

  • TB-004 — Browser → Coordinator (BFF routes, auth provider)

Threat assessment

T-017 — SSRF via client-controlled coordinator URL (SEC-001, SEC-002)

✅ Fixes the mitigation

All six BFF routes that previously accepted x-coordinator-url from the request header now ignore it entirely and use the build-time constant DEFAULT_COORD:

File Line (old)
payments/stripe/checkout/route.ts req.headers.get("x-coordinator-url")
payments/stripe/onboard/route.ts same
payments/stripe/status/route.ts same
payments/stripe/withdrawals/route.ts same
payments/withdraw/stripe/route.ts same
telemetry/route.ts same

The SSRF primitive (attacker-supplied URL causing the Next.js server to forward auth tokens to an arbitrary origin) is eliminated for all six routes. No server-side allowlist was needed because the fix is simpler: the URL is no longer a variable.

One residual to verify: DEFAULT_COORD falls back to the hardcoded string "https://api.darkbloom.dev" when NEXT_PUBLIC_COORDINATOR_URL is unset. That hardcoded fallback is api.darkbloom.dev, which is the dev environment. Confirm the production deployment always sets NEXT_PUBLIC_COORDINATOR_URL; otherwise, prod BFF calls silently hit the dev coordinator and auth tokens are forwarded there. This is an ops misconfiguration risk, not a new attack vector introduced by the PR, but worth a deploy-checklist note.

T-020 — Mock auth active in production due to missing Privy config (SEC-026)

✅ Fixes the mitigation

PrivyClientProvider.tsx now checks isProductionEnv() (NODE_ENV === "production") before allowing the MOCK_AUTH fallback. In production with a missing or placeholder NEXT_PUBLIC_PRIVY_APP_ID, the component renders a hard error page instead of granting a mock-authenticated state (PrivyClientProvider.tsx, new block at ~line 102–115).

Two notes:

  1. NODE_ENV is reliable here because Next.js sets it at build time for server components/BFF routes; this is sound for SSR. For client-side components the same env var is inlined at build time, so the guard is consistent.
  2. MOCK_AUTH on non-production is intentional and unchanged — that path is correctly preserved for local dev. The guard doesn't accidentally break the dev workflow.

New attack surface introduced

None. The changes are strictly subtractive (removing a variable input) and additive only in the error-page path, which has no coordinator interaction.


Open findings resolved by this PR

  • ✅ SEC-001 — SSRF via x-coordinator-url in payment routes
  • ✅ SEC-002 — SSRF via x-coordinator-url in telemetry route
  • ✅ SEC-026 — Mock auth reachable in production

Minor follow-ups (not blockers)

  1. DEFAULT_COORD hardcoded fallback ("https://api.darkbloom.dev") — Add a startup assertion or a Next.js build check that NEXT_PUBLIC_COORDINATOR_URL is non-empty in production, so a misconfigured deploy fails loudly rather than silently routing to dev.
  2. Test coverage — console-ui/__tests__/coordinator-url-pinning.test.ts is listed in the PR but not shown in the diff; confirm the tests assert that passing x-coordinator-url in the header is ignored (not just that the default is used), to prevent a future regression that re-introduces the header read.

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

@anupsv

anupsv commented Jun 11, 2026

Copy link
Copy Markdown
Contributor Author

Triaged the automated review — no code changes warranted. Disposition by finding:

Security (7 findings, marked CRITICAL/MEDIUM "blocking"): these are confirmations that the fix is correct, not defects — each body reads "SSRF/session-poisoning vulnerability fixed by pinning coordinator URL." They are tallied as blocking because the severity reflects the pre-fix vulnerability that this PR removes. No action.

Additive complexity (5 findings):

  • install_sh_test.go (MEDIUM) — replied inline. The two suggested simplifications are infeasible: go:embed cannot reference ../../scripts/install.sh (no .. in embed patterns, resolved relative to the package dir), and a CWD-relative path breaks because go test runs from the package directory, not the repo root. runtime.Caller(0) is the correct CWD-independent idiom and the drift check is the whole point of the test.
  • 3 console-ui tests + config_test.go (INFO) — keeping as-is. These exercise the real route-handler / component / module-scope behavior that the security fix changes (an attacker header being ignored, a localStorage-poisoned URL not receiving the bearer token, the prod misconfig guard firing). That matches this repo's testing guidance to test the real path rather than a calling-the-handler-directly shortcut. The suggested simplifications would require extracting logic out of prod code and would test less — a pure-function unit test can't catch a route re-introducing header trust. config_test.go is already a tight table-driven test; the env-clear is a single loop in the table runner, not duplicated across cases.

The security fixes themselves were independently confirmed correct by the reviewer. The only non-confirmation finding (the install.sh drift test) rests on infeasible suggestions, so the REQUEST_CHANGES can be dismissed.

…ze install.sh drift check

Centaur review on #316 (additive-complexity):
- config_test.go: extract the per-case env clear+set into a setBillingEnv(t, ...)
  helper instead of inlining the loop in the table runner.
- install_sh_test.go: collapse the two hardcoded COORD_URL ReplaceAll calls into a
  single regex that normalizes whatever the default is — simpler, and it won't
  silently stop normalizing if the prod default URL ever changes.

Behavior-preserving: tripwire test still green; drift test still fires on injected
drift (revert-verified) and the runtime.Caller path resolution is unchanged (the
correct CWD-independent idiom — go:embed can't reach ../../scripts).

@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: REQUEST_CHANGES

Security — 1 finding(s)

  • 🔵 [INFO] coordinator/billing/config.go:71-96 — MockMode tripwire relies on string comparison for mnemonic validation
    • Suggestion: Add validation that mnemonic is a valid BIP39 phrase format, not just non-empty string

Performance — 1 finding(s) (1 blocking)

  • 🟡 [MEDIUM] console-ui/src/app/providers/earnings/EarningsContent.tsx:124-125 — Repeated environment variable access in fetchEarnings callback
    • Suggestion: Move process.env.NEXT_PUBLIC_COORDINATOR_URL || "https://api.darkbloom.dev" to a module-level constant to avoid repeated property access on every fetch

Type_diligence — ✅ No issues found

Additive_complexity — 4 finding(s)

  • 🔵 [INFO] console-ui/__tests__/coordinator-url-pinning.test.ts:1-127 — Test file creates complex abstraction for simple security fix verification
    • Suggestion: Consider simplifying to individual test functions rather than a parameterized table-driven approach for better readability
  • 🔵 [INFO] console-ui/__tests__/earnings-url-pinning.test.tsx:1-90 — Extensive mocking setup for testing a single line change
    • Suggestion: Consider a more focused test that directly verifies the coordinator URL is pinned without complex mock infrastructure
  • 🔵 [INFO] console-ui/__tests__/privy-client-provider.test.tsx:1-94 — Complex module reset pattern for testing environment variable behavior
    • Suggestion: Consider using a simpler approach or extracting the environment check to a pure function that can be tested directly
  • 🔵 [INFO] coordinator/billing/config_test.go:95-110 — setBillingEnv helper manually lists environment variables that could be derived
    • Suggestion: Consider using reflection or a constant slice to avoid maintaining the env var list in two places

6 finding(s) total, 1 blocking. Verdict: REQUEST_CHANGES.

🤖 Automated review by Centaur · DAR-186

Comment on lines +71 to 96
// Check validates billing configuration invariants.
//
// Fail-closed tripwire (DAR-59): MockMode must never coexist with real payment
// credentials. A production deployment that accidentally sets
// EIGENINFERENCE_BILLING_MOCK=true would silently skip on-chain Solana
// verification and Stripe payment checks. By refusing to boot in that state we
// convert a silent exploit path into a loud startup failure.
//
// Dev/test environments that legitimately use MockMode have no real credentials,
// so this check is a no-op for them.
func (c Config) Check() error {
if c.MockMode && c.EncryptionMnemonic != "" {
return fmt.Errorf(
"billing mock mode is enabled but real payment credentials (Solana mnemonic) are configured — refusing to start (DAR-59); "+
"unset MNEMONIC / %s_MNEMONIC / %s_SOLANA_MNEMONIC or disable %s_BILLING_MOCK",
env.EnvPrefix, env.EnvPrefix, env.EnvPrefix,
)
}
if c.MockMode && c.StripeSecretKey != "" {
return fmt.Errorf("billing mock mode is enabled but a real Stripe secret key is configured — these are mutually exclusive; unset %s_STRIPE_SECRET_KEY or disable %s_BILLING_MOCK", env.EnvPrefix, env.EnvPrefix)
return fmt.Errorf(
"billing mock mode is enabled but real payment credentials (Stripe secret key) are configured — refusing to start (DAR-59); "+
"unset %s_STRIPE_SECRET_KEY or disable %s_BILLING_MOCK",
env.EnvPrefix, env.EnvPrefix,
)
}
return nil

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.

🔵 [INFO] 🔒 MockMode tripwire relies on string comparison for mnemonic validation

💡 Suggestion: Add validation that mnemonic is a valid BIP39 phrase format, not just non-empty string

📊 Score: 3×2 = 6 · Category: missing-input-validation

Comment thread coordinator/billing/config_test.go Resolved
…sages

Same cleanup as the H2/H3 PR: internal tracker IDs (SEC-001/SEC-002/DAR-59) mean
nothing to a reader of the public repo — and DAR-59 was even in operator-facing
boot error messages an operator can't look up. Removed them:
- config.go: drop "(DAR-59)" from both mock-mode boot error messages and from the
  field/Check comments; the messages stay fully actionable on their own.
- config_test.go: assert on "refusing to start" instead of the DAR-59 tag.
- console url-pinning tests: drop "SEC-001"/"SEC-002" from the header comments and
  describe() labels.

Behavior-preserving (error text minus the tag); tripwire test green.
@anupsv

anupsv commented Jun 11, 2026

Copy link
Copy Markdown
Contributor Author

Pushed 9be1b9c: dropped the non-referenceable internal IDs (SEC-001/SEC-002/DAR-59) from comments — and, notably, from the operator-facing mock-mode boot error messages in config.go (an operator hitting "refusing to start" can't look up a DAR-59 anyway). The error text stays fully actionable without the tag; config_test.go now asserts on "refusing to start". Mirrors the same cleanup on #319.

@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: REQUEST_CHANGES

Security — 7 finding(s) (7 blocking)

  • 🔴 [CRITICAL] console-ui/src/app/api/payments/stripe/checkout/route.ts:10 — SSRF vulnerability fixed by pinning coordinator URL
    • Suggestion: Good fix - removing client-controlled coordinator URL prevents SSRF and credential forwarding
  • 🔴 [CRITICAL] console-ui/src/app/api/payments/stripe/onboard/route.ts:10 — SSRF vulnerability fixed by pinning coordinator URL
    • Suggestion: Good fix - removing client-controlled coordinator URL prevents SSRF and credential forwarding
  • 🔴 [CRITICAL] console-ui/src/app/api/payments/stripe/status/route.ts:9 — SSRF vulnerability fixed by pinning coordinator URL
    • Suggestion: Good fix - removing client-controlled coordinator URL prevents SSRF and credential forwarding
  • 🔴 [CRITICAL] console-ui/src/app/api/payments/stripe/withdrawals/route.ts:9 — SSRF vulnerability fixed by pinning coordinator URL
    • Suggestion: Good fix - removing client-controlled coordinator URL prevents SSRF and credential forwarding
  • 🔴 [CRITICAL] console-ui/src/app/api/payments/withdraw/stripe/route.ts:10 — SSRF vulnerability fixed by pinning coordinator URL
    • Suggestion: Good fix - removing client-controlled coordinator URL prevents SSRF and credential forwarding
  • 🔴 [CRITICAL] console-ui/src/app/api/telemetry/route.ts:14 — SSRF vulnerability fixed by pinning coordinator URL
    • Suggestion: Good fix - removing client-controlled coordinator URL prevents SSRF and credential forwarding
  • 🔴 [CRITICAL] console-ui/src/app/providers/earnings/EarningsContent.tsx:122-125 — Session poisoning vulnerability fixed by pinning coordinator URL
    • Suggestion: Good fix - removing localStorage-controlled coordinator URL prevents bearer token forwarding to attacker origins

Performance — 1 finding(s) (1 blocking)

  • 🟡 [MEDIUM] console-ui/src/app/providers/earnings/EarningsContent.tsx:124-125 — Repeated environment variable access in hot path
    • Suggestion: Move process.env.NEXT_PUBLIC_COORDINATOR_URL to module-level constant to avoid repeated property access on every fetch

Type_diligence — ✅ No issues found

Additive_complexity — 5 finding(s)

  • 🔵 [INFO] console-ui/__tests__/coordinator-url-pinning.test.ts:57-105 — Test cases array contains repetitive route configuration patterns
    • Suggestion: Extract common test case generation logic into a helper function or use parameterized test patterns to reduce duplication
  • 🔵 [INFO] console-ui/__tests__/earnings-url-pinning.test.tsx:27-36 — Extensive mocking setup for a simple URL pinning test
    • Suggestion: Consider testing the URL pinning logic in isolation rather than mocking the entire API layer
  • 🔵 [INFO] console-ui/__tests__/privy-client-provider.test.tsx:28-38 — Repeated renderProviderProd function pattern could be simplified
    • Suggestion: Extract the common provider rendering logic into a reusable test helper
  • 🔵 [INFO] coordinator/billing/config_test.go:26-70 — Test cases table has repetitive environment variable setup patterns
    • Suggestion: Consider using a test helper that generates common environment configurations to reduce duplication
  • 🔵 [INFO] coordinator/billing/config_test.go:96-110 — setBillingEnv clears hardcoded list of environment variables
    • Suggestion: Consider using a more dynamic approach to clear environment variables or document why this specific list is needed

13 finding(s) total, 8 blocking. Verdict: REQUEST_CHANGES.

🤖 Automated review by Centaur · DAR-186


export async function POST(req: NextRequest) {
const coordUrl = req.headers.get("x-coordinator-url") || DEFAULT_COORD;
const coordUrl = DEFAULT_COORD;

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.

🔴 [CRITICAL] 🔒 SSRF vulnerability fixed by pinning coordinator URL

💡 Suggestion: Good fix - removing client-controlled coordinator URL prevents SSRF and credential forwarding

📊 Score: 4×4 = 16 · Category: auth-bypass


export async function POST(req: NextRequest) {
const coordUrl = req.headers.get("x-coordinator-url") || DEFAULT_COORD;
const coordUrl = DEFAULT_COORD;

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.

🔴 [CRITICAL] 🔒 SSRF vulnerability fixed by pinning coordinator URL

💡 Suggestion: Good fix - removing client-controlled coordinator URL prevents SSRF and credential forwarding

📊 Score: 4×4 = 16 · Category: auth-bypass


export async function GET(req: NextRequest) {
const coordUrl = req.headers.get("x-coordinator-url") || DEFAULT_COORD;
const coordUrl = DEFAULT_COORD;

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.

🔴 [CRITICAL] 🔒 SSRF vulnerability fixed by pinning coordinator URL

💡 Suggestion: Good fix - removing client-controlled coordinator URL prevents SSRF and credential forwarding

📊 Score: 4×4 = 16 · Category: auth-bypass


export async function GET(req: NextRequest) {
const coordUrl = req.headers.get("x-coordinator-url") || DEFAULT_COORD;
const coordUrl = DEFAULT_COORD;

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.

🔴 [CRITICAL] 🔒 SSRF vulnerability fixed by pinning coordinator URL

💡 Suggestion: Good fix - removing client-controlled coordinator URL prevents SSRF and credential forwarding

📊 Score: 4×4 = 16 · Category: auth-bypass


export async function POST(req: NextRequest) {
const coordUrl = req.headers.get("x-coordinator-url") || DEFAULT_COORD;
const coordUrl = DEFAULT_COORD;

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.

🔴 [CRITICAL] 🔒 SSRF vulnerability fixed by pinning coordinator URL

💡 Suggestion: Good fix - removing client-controlled coordinator URL prevents SSRF and credential forwarding

📊 Score: 4×4 = 16 · Category: auth-bypass

Comment on lines +57 to +105
body?: string;
}

const CASES: RouteCase[] = [
{
name: "POST /api/payments/stripe/checkout",
importPath: () => import("@/app/api/payments/stripe/checkout/route"),
method: "POST",
requestPath: "/api/payments/stripe/checkout",
upstreamPath: "/v1/billing/stripe/create-session",
body: JSON.stringify({ amount_usd: 10 }),
},
{
name: "GET /api/payments/stripe/status",
importPath: () => import("@/app/api/payments/stripe/status/route"),
method: "GET",
requestPath: "/api/payments/stripe/status",
upstreamPath: "/v1/billing/stripe/status",
},
{
name: "POST /api/payments/stripe/onboard",
importPath: () => import("@/app/api/payments/stripe/onboard/route"),
method: "POST",
requestPath: "/api/payments/stripe/onboard",
upstreamPath: "/v1/billing/stripe/onboard",
body: JSON.stringify({ country: "US" }),
},
{
name: "GET /api/payments/stripe/withdrawals",
importPath: () => import("@/app/api/payments/stripe/withdrawals/route"),
method: "GET",
requestPath: "/api/payments/stripe/withdrawals",
upstreamPath: "/v1/billing/stripe/withdrawals",
},
{
name: "POST /api/payments/withdraw/stripe",
importPath: () => import("@/app/api/payments/withdraw/stripe/route"),
method: "POST",
requestPath: "/api/payments/withdraw/stripe",
upstreamPath: "/v1/billing/withdraw/stripe",
body: JSON.stringify({ amount_usd: 5, method: "standard" }),
},
{
name: "POST /api/telemetry",
importPath: () => import("@/app/api/telemetry/route"),
method: "POST",
requestPath: "/api/telemetry",
upstreamPath: "/v1/telemetry/events",
body: JSON.stringify({ events: [] }),

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.

🔵 [INFO] 🧩 Test cases array contains repetitive route configuration patterns

💡 Suggestion: Extract common test case generation logic into a helper function or use parameterized test patterns to reduce duplication

📊 Score: 2×3 = 6 · Category: duplicate logic

Comment on lines +27 to +36
vi.mock("@/lib/api", () => ({
fetchStripeStatus: vi.fn().mockResolvedValue({
connected: false,
payouts_enabled: false,
requirements_due: [],
}),
startStripeOnboarding: vi.fn(),
withdrawStripe: vi.fn(),
fetchStripeWithdrawals: vi.fn().mockResolvedValue([]),
computeStripeFeeUsd: vi.fn().mockReturnValue(0),

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.

🔵 [INFO] 🧩 Extensive mocking setup for a simple URL pinning test

💡 Suggestion: Consider testing the URL pinning logic in isolation rather than mocking the entire API layer

📊 Score: 2×2 = 4 · Category: over-mocking

Comment on lines +28 to +38
async function renderProviderProd(appId: string) {
vi.stubEnv("NEXT_PUBLIC_PRIVY_APP_ID", appId);
vi.stubEnv("NODE_ENV", "production");
const { PrivyClientProvider } = await import(
"@/components/providers/PrivyClientProvider"
);
render(
<PrivyClientProvider>
<span data-testid="child-probe">should not appear</span>
</PrivyClientProvider>
);

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.

🔵 [INFO] 🧩 Repeated renderProviderProd function pattern could be simplified

💡 Suggestion: Extract the common provider rendering logic into a reusable test helper

📊 Score: 2×2 = 4 · Category: duplicate logic

Comment on lines +26 to +70
wantErr bool
errFrag string // substring that must appear in the error message
}{
{
name: "(a) mock only — no real creds — OK",
envs: map[string]string{
prefix + "_BILLING_MOCK": "true",
},
wantErr: false,
},
{
name: "(b) mock + Solana mnemonic — must error",
envs: map[string]string{
prefix + "_BILLING_MOCK": "true",
prefix + "_SOLANA_MNEMONIC": "word1 word2 word3 word4 word5 word6 word7 word8 word9 word10 word11 word12",
},
wantErr: true,
errFrag: "refusing to start",
},
{
name: "(b2) mock + bare MNEMONIC env — must error",
envs: map[string]string{
prefix + "_BILLING_MOCK": "true",
"MNEMONIC": "word1 word2 word3 word4 word5 word6 word7 word8 word9 word10 word11 word12",
},
wantErr: true,
errFrag: "refusing to start",
},
{
name: "(c) mock + Stripe secret key — must error",
envs: map[string]string{
prefix + "_BILLING_MOCK": "true",
prefix + "_STRIPE_SECRET_KEY": "sk_live_fakekeyfortest",
},
wantErr: true,
errFrag: "refusing to start",
},
{
name: "(d) no mock + real creds — production baseline — OK",
envs: map[string]string{
prefix + "_SOLANA_MNEMONIC": "word1 word2 word3 word4 word5 word6 word7 word8 word9 word10 word11 word12",
prefix + "_STRIPE_SECRET_KEY": "sk_live_fakekeyfortest",
},
wantErr: false,
},

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.

🔵 [INFO] 🧩 Test cases table has repetitive environment variable setup patterns

💡 Suggestion: Consider using a test helper that generates common environment configurations to reduce duplication

📊 Score: 2×2 = 4 · Category: duplicate logic

Comment on lines +96 to +110
func setBillingEnv(t *testing.T, prefix string, envs map[string]string) {
t.Helper()
for _, key := range []string{
prefix + "_BILLING_MOCK",
prefix + "_SOLANA_MNEMONIC",
prefix + "_MNEMONIC",
"MNEMONIC",
prefix + "_STRIPE_SECRET_KEY",
} {
t.Setenv(key, "")
}
for k, v := range envs {
t.Setenv(k, v)
}
}

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.

🔵 [INFO] 🧩 setBillingEnv clears hardcoded list of environment variables

💡 Suggestion: Consider using a more dynamic approach to clear environment variables or document why this specific list is needed

📊 Score: 1×2 = 2 · Category: over-configuration

@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: REQUEST_CHANGES

Security — 7 finding(s) (7 blocking)

  • 🔴 [CRITICAL] console-ui/src/app/api/payments/stripe/checkout/route.ts:10 — SSRF vulnerability fixed by pinning coordinator URL
    • Suggestion: Good fix - removing client-controlled coordinator URL prevents SSRF and credential forwarding
  • 🔴 [CRITICAL] console-ui/src/app/api/payments/stripe/onboard/route.ts:10 — SSRF vulnerability fixed by pinning coordinator URL
    • Suggestion: Good fix - removing client-controlled coordinator URL prevents SSRF and credential forwarding
  • 🔴 [CRITICAL] console-ui/src/app/api/payments/stripe/status/route.ts:9 — SSRF vulnerability fixed by pinning coordinator URL
    • Suggestion: Good fix - removing client-controlled coordinator URL prevents SSRF and credential forwarding
  • 🔴 [CRITICAL] console-ui/src/app/api/payments/stripe/withdrawals/route.ts:9 — SSRF vulnerability fixed by pinning coordinator URL
    • Suggestion: Good fix - removing client-controlled coordinator URL prevents SSRF and credential forwarding
  • 🔴 [CRITICAL] console-ui/src/app/api/payments/withdraw/stripe/route.ts:10 — SSRF vulnerability fixed by pinning coordinator URL
    • Suggestion: Good fix - removing client-controlled coordinator URL prevents SSRF and credential forwarding
  • 🔴 [CRITICAL] console-ui/src/app/api/telemetry/route.ts:14 — SSRF vulnerability fixed by pinning coordinator URL
    • Suggestion: Good fix - removing client-controlled coordinator URL prevents SSRF and credential forwarding
  • 🟡 [MEDIUM] console-ui/src/app/providers/earnings/EarningsContent.tsx:122-125 — Session poisoning vulnerability fixed by pinning coordinator URL
    • Suggestion: Good fix - removing localStorage-controlled coordinator URL prevents bearer token forwarding to attacker origins

Performance — 1 finding(s) (1 blocking)

  • 🟡 [MEDIUM] console-ui/src/app/providers/earnings/EarningsContent.tsx:124-125 — Repeated environment variable access in fetchEarnings callback
    • Suggestion: Move process.env.NEXT_PUBLIC_COORDINATOR_URL || "https://api.darkbloom.dev" to a module-level constant to avoid repeated property access on every fetch

Type_diligence — ✅ No issues found

Additive_complexity — 4 finding(s)

  • 🔵 [INFO] console-ui/__tests__/coordinator-url-pinning.test.ts:58-105 — Test cases array contains repetitive route configuration patterns
    • Suggestion: Extract common test case generation logic into a helper function or use parameterized test patterns to reduce duplication
  • 🔵 [INFO] console-ui/__tests__/earnings-url-pinning.test.tsx:15-36 — Extensive vi.mock setup for components not directly under test
    • Suggestion: Consider testing the URL pinning behavior more directly without mocking the entire dependency tree
  • 🔵 [INFO] console-ui/__tests__/privy-client-provider.test.tsx:28-39 — Repeated pattern of stubbing env vars and dynamic imports across test cases
    • Suggestion: Extract the env setup and component import logic into a shared test helper function
  • 🔵 [INFO] coordinator/billing/config_test.go:95-110 — Test helper clears many environment variables that may not all be relevant
    • Suggestion: Only clear the specific environment variables that are actually used in the test cases to reduce unnecessary setup complexity

12 finding(s) total, 8 blocking. Verdict: REQUEST_CHANGES.

🤖 Automated review by Centaur · DAR-186


export async function POST(req: NextRequest) {
const coordUrl = req.headers.get("x-coordinator-url") || DEFAULT_COORD;
const coordUrl = DEFAULT_COORD;

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.

🔴 [CRITICAL] 🔒 SSRF vulnerability fixed by pinning coordinator URL

💡 Suggestion: Good fix - removing client-controlled coordinator URL prevents SSRF and credential forwarding

📊 Score: 4×4 = 16 · Category: auth-bypass


export async function POST(req: NextRequest) {
const coordUrl = req.headers.get("x-coordinator-url") || DEFAULT_COORD;
const coordUrl = DEFAULT_COORD;

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.

🔴 [CRITICAL] 🔒 SSRF vulnerability fixed by pinning coordinator URL

💡 Suggestion: Good fix - removing client-controlled coordinator URL prevents SSRF and credential forwarding

📊 Score: 4×4 = 16 · Category: auth-bypass


export async function GET(req: NextRequest) {
const coordUrl = req.headers.get("x-coordinator-url") || DEFAULT_COORD;
const coordUrl = DEFAULT_COORD;

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.

🔴 [CRITICAL] 🔒 SSRF vulnerability fixed by pinning coordinator URL

💡 Suggestion: Good fix - removing client-controlled coordinator URL prevents SSRF and credential forwarding

📊 Score: 4×4 = 16 · Category: auth-bypass


export async function GET(req: NextRequest) {
const coordUrl = req.headers.get("x-coordinator-url") || DEFAULT_COORD;
const coordUrl = DEFAULT_COORD;

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.

🔴 [CRITICAL] 🔒 SSRF vulnerability fixed by pinning coordinator URL

💡 Suggestion: Good fix - removing client-controlled coordinator URL prevents SSRF and credential forwarding

📊 Score: 4×4 = 16 · Category: auth-bypass


export async function POST(req: NextRequest) {
const coordUrl = req.headers.get("x-coordinator-url") || DEFAULT_COORD;
const coordUrl = DEFAULT_COORD;

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.

🔴 [CRITICAL] 🔒 SSRF vulnerability fixed by pinning coordinator URL

💡 Suggestion: Good fix - removing client-controlled coordinator URL prevents SSRF and credential forwarding

📊 Score: 4×4 = 16 · Category: auth-bypass

Comment on lines 124 to +125
const coordinatorUrl =
localStorage.getItem("darkbloom_coordinator_url") ||
process.env.NEXT_PUBLIC_COORDINATOR_URL ||
"https://api.darkbloom.dev";
process.env.NEXT_PUBLIC_COORDINATOR_URL || "https://api.darkbloom.dev";

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.

🟡 [MEDIUM] ⚡ Repeated environment variable access in fetchEarnings callback

💡 Suggestion: Move process.env.NEXT_PUBLIC_COORDINATOR_URL || "https://api.darkbloom.dev" to a module-level constant to avoid repeated property access on every fetch

📊 Score: 2×4 = 8 · Category: repeated work

Comment on lines +58 to +105
}

const CASES: RouteCase[] = [
{
name: "POST /api/payments/stripe/checkout",
importPath: () => import("@/app/api/payments/stripe/checkout/route"),
method: "POST",
requestPath: "/api/payments/stripe/checkout",
upstreamPath: "/v1/billing/stripe/create-session",
body: JSON.stringify({ amount_usd: 10 }),
},
{
name: "GET /api/payments/stripe/status",
importPath: () => import("@/app/api/payments/stripe/status/route"),
method: "GET",
requestPath: "/api/payments/stripe/status",
upstreamPath: "/v1/billing/stripe/status",
},
{
name: "POST /api/payments/stripe/onboard",
importPath: () => import("@/app/api/payments/stripe/onboard/route"),
method: "POST",
requestPath: "/api/payments/stripe/onboard",
upstreamPath: "/v1/billing/stripe/onboard",
body: JSON.stringify({ country: "US" }),
},
{
name: "GET /api/payments/stripe/withdrawals",
importPath: () => import("@/app/api/payments/stripe/withdrawals/route"),
method: "GET",
requestPath: "/api/payments/stripe/withdrawals",
upstreamPath: "/v1/billing/stripe/withdrawals",
},
{
name: "POST /api/payments/withdraw/stripe",
importPath: () => import("@/app/api/payments/withdraw/stripe/route"),
method: "POST",
requestPath: "/api/payments/withdraw/stripe",
upstreamPath: "/v1/billing/withdraw/stripe",
body: JSON.stringify({ amount_usd: 5, method: "standard" }),
},
{
name: "POST /api/telemetry",
importPath: () => import("@/app/api/telemetry/route"),
method: "POST",
requestPath: "/api/telemetry",
upstreamPath: "/v1/telemetry/events",
body: JSON.stringify({ events: [] }),

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.

🔵 [INFO] 🧩 Test cases array contains repetitive route configuration patterns

💡 Suggestion: Extract common test case generation logic into a helper function or use parameterized test patterns to reduce duplication

📊 Score: 2×3 = 6 · Category: duplicate logic

Comment on lines +15 to +36
}),
}));

vi.mock("@/hooks/useToast", () => ({
useToastStore: (selector: (s: { addToast: () => void }) => unknown) =>
selector({ addToast: vi.fn() }),
}));

vi.mock("@/lib/google-analytics", () => ({
trackEvent: vi.fn(),
}));

vi.mock("@/lib/api", () => ({
fetchStripeStatus: vi.fn().mockResolvedValue({
connected: false,
payouts_enabled: false,
requirements_due: [],
}),
startStripeOnboarding: vi.fn(),
withdrawStripe: vi.fn(),
fetchStripeWithdrawals: vi.fn().mockResolvedValue([]),
computeStripeFeeUsd: vi.fn().mockReturnValue(0),

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.

🔵 [INFO] 🧩 Extensive vi.mock setup for components not directly under test

💡 Suggestion: Consider testing the URL pinning behavior more directly without mocking the entire dependency tree

📊 Score: 2×2 = 4 · Category: over-mocking

Comment on lines +28 to +39
async function renderProviderProd(appId: string) {
vi.stubEnv("NEXT_PUBLIC_PRIVY_APP_ID", appId);
vi.stubEnv("NODE_ENV", "production");
const { PrivyClientProvider } = await import(
"@/components/providers/PrivyClientProvider"
);
render(
<PrivyClientProvider>
<span data-testid="child-probe">should not appear</span>
</PrivyClientProvider>
);
}

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.

🔵 [INFO] 🧩 Repeated pattern of stubbing env vars and dynamic imports across test cases

💡 Suggestion: Extract the env setup and component import logic into a shared test helper function

📊 Score: 2×2 = 4 · Category: duplicate logic

Comment on lines +95 to +110
// t.Setenv restores all of them on test cleanup.
func setBillingEnv(t *testing.T, prefix string, envs map[string]string) {
t.Helper()
for _, key := range []string{
prefix + "_BILLING_MOCK",
prefix + "_SOLANA_MNEMONIC",
prefix + "_MNEMONIC",
"MNEMONIC",
prefix + "_STRIPE_SECRET_KEY",
} {
t.Setenv(key, "")
}
for k, v := range envs {
t.Setenv(k, v)
}
}

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.

🔵 [INFO] 🧩 Test helper clears many environment variables that may not all be relevant

💡 Suggestion: Only clear the specific environment variables that are actually used in the test cases to reduce unnecessary setup complexity

📊 Score: 2×2 = 4 · Category: over-configuration

jonathan308 added a commit that referenced this pull request Oct 21, 2026
libs/mlx-swift e03513c6 (mlx 4a355746, mlx-c 0a97d9ab) reverts the
one-page minimum on sub-page footprint quotations, so admission charges
for models other than GLM are unchanged from the current release.
libs/mlx-swift-lm 0d43713e (#314) merges main (#316: checkpoint imports
staged from host zeros), carries the matching pin and fixes CI.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Gajesh2007 added a commit that referenced this pull request Oct 21, 2026
… (#1519)

* Stage SSD checkpoint restores without waiting on another prefill

Bumps libs/mlx-swift-lm to stage provider checkpoint imports with
host-materialized destinations, so a restore no longer waits for MLX-Swift's
process-wide evalLock while the engine evaluates another request's prefill
chunk (#867).

Adds ModelCheckpointRestoreContentionLiveTests, an opt-in real-model
regression that serves the same fork restored and cold, idle, during another
tenant's prefill and after another tenant's donor, and requires the restore to
reach its demanded boundary and never to produce its first token later than
cold prefill.

Measured on M5 Max 128 GB, Qwen 3.8 27B, 16,667-token fork, 12,288 restored
tokens (0.96 GB): contended staging 2.6-3.8 s -> 0.31-0.37 s; contended
restore TTFT 27.0-27.5 s -> 26.1-27.1 s, within run-to-run variance (cold
40.4-42.3 s); idle unchanged (6.6 s vs 20.6 s cold). Restored outputs match cold in ModelCheckpointStorageLiveTests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Assert contended restore staging and keep partial contention reports

The contention regression now fails when a contended restore stages more
than 1 s slower than its pair's idle restore; the TTFT bound alone still
passed on the build that waited on evalLock (2.6-3.8 s stage vs 0.3 s idle).
The report is rewritten atomically after each condition and records the
failure, including a teardown error that was previously discarded.

Bumps libs/mlx-swift-lm to charge the largest host-zero source as import
staging scratch, and documents the staged-import exception in the
prefix-cache architecture.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CDrGQJwa1LC3j4TE6Dvgmo

* Pin mlx-swift-lm to the merged checkpoint-import change (#316)

Layr-Labs/mlx-swift-lm#316 was squash-merged as c17693f5, whose tree is identical
to the reviewed PR head 86c7899e and whose only parent is the previous pin
14661d9b.

* Record contention-report failures and identity; document host-zero scratch

Addresses the second round of review on the restore contention test:
- require native live and checkpoint precision, since a lossy checkpoint can
  legitimately restore slower than recompute;
- record the session's runtime identity (makeReport) in the report;
- record contract violations and teardown-only failures in the saved report,
  not just as test issues;
- describe the provider-staged host-zero buffer and its scratch charge in
  hardware-support.md and advance the inference.md freshness stamp.

* Cite staged-import code by full path and create the report directory

- Cite the provider-staged host-zero contract by full libs/mlx-swift-lm paths
  and symbols in ssd-kv-cache.md, prefix-cache.md, inference.md and
  hardware-support.md.
- Create the contention report's parent directory before the first write, as
  ModelPrefixBenchmarkReport.save does.

* Isolate contention conditions and prove foreign-prefill overlap

- Give each condition its own donor and cache scope, so a deeper checkpoint a
  measured fork donates can never serve a later condition; record a violation
  if a restore's depth differs from its pair's idle restore.
- Record whether the foreign prefill was still running when a contended
  stage finished, and fail the run when it was not.
- Require DARKBLOOM_PREFIX_EXCLUSIVE_GPU=1 like the sibling timing benchmarks,
  and document it in the invocation.

* Refuse native-bound MiMo specs in the contention test

MiMo loads through the native engine, whose native-bound imports keep device
allocation and the eval lock, so the staging gate does not apply to it. The
test guide now states that the report is rewritten after each measured run.

* Pin the latest mlx-swift-lm, mlx-swift and mlx

- libs/mlx-swift-lm: c17693f5 -> 19634dd8 (Nemotron 3.5 Super native VL/MTP/video, GLM-5.3-Flash native)
- libs/mlx-swift: 6923a80f -> 67dc7528 (Metal kernel math modes, thread-scoped command-buffer limits, GLM-5.3-Flash native stack)
- libs/mlx: cb77239b -> ad4745a2 (matches mlx-swift's nested Cmlx/mlx)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Gajesh Naik <26431906+Gajesh2007@users.noreply.github.com>
Gajesh2007 added a commit that referenced this pull request Oct 21, 2026
…TP, batching, images and qualification runner (#1510)

* feat: stage admitted Nemotron Super local image binding and qualification fixtures

* docs: record Nemotron fixture validation and pending calibration gates

* chore(libs): pin mlx-swift-lm #312 at 1ce44e9a and record final-head fixture runs

The SDK draft gained two commits that fix its Lint and fork.yaml gates
(swift-format output and a fork.yaml section for the Nemotron Super
components). Neither changes behavior.

At SDK 1ce44e9a and these provider sources, the shipped fixture
harnesses build and pass on the GPU: SDK 111 Swift Testing tests in 32
suites plus 2 XCTest tests; provider 25 Swift Testing tests in 6 suites
plus 12 XCTest tests, including the corrected
imageHTTPResetRetainsChargeUntilTerminalRetires test that was pending a
rerun. These are synthetic fixtures, not a full-checkpoint run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(nemotron-super): golden prompt corpus from the reference template and tokenizer

prompt_golden.py renders the pinned chat_template.jinja as Transformers'
apply_chat_template does, expands image placeholders per
processing_nemotron_h_omni.py and tokenizes with the pinned tokenizer.json
through the tokenizers library (pinned jinja2/markupsafe/tokenizers, isolated
interpreter). The committed corpus holds 30 request bodies, rendered prompts
and token IDs; the tokenizer itself is not committed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(nemotron-super): render prompts exactly like the reference template

The Super prompt contract now reproduces the reference apply_chat_template
bytes: request-order tool schemas and tool-call arguments (strict ordered JSON
parser into Jinja values), Python str/strip/json.dumps filters bound only for
the pinned template, swift-jinja comment normalization, and the processor's
<img>/<image>*n/</img> placeholder expansion. NemotronSuperRequestPlan resolves
controls (template defaults; force_nonempty_content added), the shared
tool-choice policy and the response-format instruction once, and refuses output
controls the owner cannot honor.

Golden tests check rendered text and image grids against the corpus always, and
token IDs through swift-transformers when NEMOTRON_SUPER_REFERENCE_DIR names
the pinned tokenizer (all 30 cases match).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(nemotron-super): ultra_v3 reasoning channel with validated tool and JSON output

NemotronSuperReasoningChannel follows vLLM ultra_v3 over deepseek_r1: streamed
output drops <think> deltas inside reasoning and ends it at the first
</think>; a complete response discards text before <think>, strips the
template-owned newline, and honors force_nonempty_content; thinking off makes
all output content. NemotronSuperLocalOutput streams reasoning and plain
content, routes only content through the native Nemotron frame parser, and
withholds tool calls, forced-tool output and JSON content until the shared
ToolConstraintValidation and OpenAIResponseFormatSupport checks pass. Content
is split at each '<' so the shared parser cannot drop text that precedes an
open frame; mid-stream parse failures are refused before exposure. Output
stays bounded. runValidatedText uses the same plan and complete-mode split.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(qualification): add a loopback Nemotron Super runner to the harness

NemotronSuperRunner is an executable target of the qualification harness
template only; the shipping provider manifest has no such product. It
loads the pinned checkpoint through NemotronSuperLocalLoad (or mirrors
that transaction on the tiny synthetic fixture), serves the real local
HTTP stack with the opt-in Super image hook on 127.0.0.1 with isolated
home/state and a per-run token, and drains and retires the owner on
SIGINT/SIGTERM. A loopback diagnostics listener reports process
footprint (kernel interval maxima), MLX active/cache/peak and the
LOAD/media/KV charges held, and holds a test ballast for near-limit
probes. --preflight checks checkpoint identity without reading shards.

Per-reservation bytes and the loaded owner are read by reflection in one
file until internal accessors exist.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(nemotron-super): serve text, reasoning, tools and JSON through the local hook

The opt-in owner hook now handles every chat request for the Super model ID.
Text renders with the owner's own tokenizer and pinned template before headers
and runs on the owner's bridge through a hook-owned NemotronSuperLocalBinding
(drain() joins it; the owner refuses after close or a retained fault). Images
keep the owner's runEncoded path. Both relay native chunks through the request
plan's output parser, so reasoning_content and content stream as SSE deltas or
JSON fields, tool_calls leave only after validation, and response_format
content is withheld and normalized. enable_thinking true or absent now uses
the template default; contradictory controls stay 400, schema/forced-tool
violations 422.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(qualification): benchmark and calibrate memory through the Super runner

bench_super.py (stdlib, python3 -I) measures cold load from runner
events, first/cold/warm TTFT, prefill, steady decode and end-to-end
output rates for text contexts and inline PNG images, and latency
percentiles under concurrency, with greedy fixed-seed requests and a
receipt holding hardware/OS, git heads plus diff hashes, model
identity, settings and raw samples. An arm label, --extra-body and
runner --engine-env entries support plain/speculative A/B; compare
refuses receipts with different workloads.

memory_calibration.py compares measured footprint and MLX peaks with
the LOAD and per-request reservations, probes near-limit admission
with a ledger ballast, cancels at each observed phase, runs concurrent
requests, and checks SIGTERM drain plus restart. Procedures live in
super-runner.md and memory_calibration.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(nemotron-super): document reference prompt parity and hook output controls

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(nemotron-super): opt-in text speculation for the local owner

DARKBLOOM_NEMOTRON_SUPER_MTP=1 (default off) makes the unpublished Super
load transaction add the embedded head's payload and loader construction
allowance to its single LOAD claim, load the head in its own fenced epoch and
serve NemotronSuperMTPTextTarget with the SDK assistant: greedy, one request,
fixed depth (DARKBLOOM_NEMOTRON_SUPER_MTP_DEPTH 1 to 3) and serial target
verification. The engine admits the assistant's bounded per-request charge
before allocation. A speculating owner refuses every media entry.

The shared production model dispatch does not yet recognize the MTP target,
so NemotronSuperLocalMTP assembles the contiguous build itself, resolving the
calibrated scheduler policy on the ordinary adapter over the same composite.

Synthetic provider tests serve identical text through the real bridge with
and without speculation at depths one and three, refuse media, and retire
every LOAD/KV charge.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(nemotron-super): document opt-in local text speculation

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(nemotron-super): clarify output and channel names after review

Behavior-preserving refactor pass: no shadowed marker binding, no keyword-named
local, one computed reasoning value, a one-line route flag, and comments on why
the relay maps parser errors route-independently and why the filter rebinding
is exact only for the hash-pinned template.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(nemotron-super): owner owns and drains its text binding

Owner.localTextBinding mints one NemotronSuperLocalBinding on the owner's own
bridge and tokenizer; its acquisition refuses once the owner closes or retains
a fault, without consulting the image binding (which a speculating owner
refuses). closeAfterDrain now drains it before the image binding and bridge,
so hosts no longer drain text separately. A synthetic test closes the owner
while a request may still stream and checks drain, refusal and full refund.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(nemotron-qualification): list the SDK ModelOpt graph parity suites

The isolated SDK harness template compiles the new graph/eager parity,
trunk integration and opt-in real-dimension benchmark tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(qualification): harden runner retirement, reserves and sampling

From the independent refactor review:
- Synthetic load retains construction scope and owners for the process
  lifetime on a retained fault or failed retirement, creates residency
  inside the failure path, and keeps the scope alive while serving.
- Checkpoint load retires the owner if the image hook cannot be built.
- --kv-bytes-per-token may only raise the configured rate, --cap-fraction
  may only lower the default cap, and an inherited
  DARKBLOOM_MEM_CAP_FRACTION is removed and the cap recorded.
- Exit 4 reports a clean retirement after a listener failure or a timed
  out drain; only a second signal force-exits (via _exit); a shutdown
  during load serves nothing; every listener exit settles its bind waiter.
- The sampler reads charge rows before the other counters, drops stale
  or pre-reset samples, records request charges held at the same time,
  and reports ledger charge outside the rows as unattributed.
- Preflight writes runner-preflight.json instead of a ready file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(qualification): correct calibration evidence and receipt handling

From the independent refactor review:
- Reservation-versus-peak and near-limit use the request charges held
  at the same time, not a sum of per-kind maxima.
- Decode-phase aborts are recorded; near-limit reports not_exercised
  when the ballast is refused or the reference is within the margin.
- Settling waits for request charges and HTTP/bridge work, and reports
  engine-owner-only ledger movement as review instead of a leak.
- Receipts are written before stopping a launched runner; a restarted
  runner is always stopped; compare also requires the same model
  identity and runner build configuration.
- Workload parsing and provenance move into the shared client; docs
  list every runner option, exit code and diagnostics field.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(qualification): cover the Super runner client without a runner

A local SSE server checks TTFT, prefill, decode and end-to-end rate
math against usage and delta times, that an abort from the first-delta
callback is recorded, loopback-only endpoints, workload parsing,
percentile interpolation and the RGB8 PNG generator.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(vision): decode PNG and JPEG with the reference RGB8 semantics for Nemotron Super

Replace the narrow RGB8 PNG subset with content-sniffed PNG and JPEG
ingress that reproduces transformers load_image (Pillow exif_transpose,
then convert("RGB")):

- PNG is decoded in-process: every colour type and bit depth, Adam7,
  all filters and split IDAT, with Pillow's rawmode conversions (16-bit
  high byte, I;16 gray clipping, palette expansion, alpha dropped, tRNS
  and colour-management chunks ignored). zlib verifies the stream and
  its Adler-32; the stream must end exactly at the last IDAT byte.
- EXIF IFD0 and XMP tiff:Orientation follow Pillow's lookup order and
  truncation rules; APNG frame 0 is the IDAT image.
- JPEG frames (8-bit Huffman baseline/extended/progressive) are checked
  from their markers, then decoded by ImageIO and read without drawing.
  Only colour interpretations on which libjpeg-turbo and ImageIO agree
  are admitted; CMYK is read Adobe-inverted as Pillow does.
- Declared geometry, pixel count and encoded size are bounded before any
  raster buffer exists; rows are written at their oriented position.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(vision): golden parity and fail-closed coverage for Nemotron Super images

- 80 synthetic fixtures (50 PNG, 30 JPEG; 352 KB) with Pillow 12.2.0
  RGB8 references and CPU PyTorch 2.12.0 processor tensors, generated
  reproducibly by scripts/nemotron-qualification/image-goldens.
- PNG must match Pillow byte for byte (oriented and unoriented) and the
  final normalized tensors bitwise; JPEG must stay within per-chroma
  ImageIO bounds derived from measurement.
- Refusal, limit, signature-sniffing, cancellation and mutation tests,
  plus live loopback HTTP requests through the tiny synthetic owner.
- Register the new test files in the shipped provider harness template.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(nemotron-qualification): list the SDK ModelOpt graph suites in the harness

The integrated SDK carries the fastpath track's graph parity, benchmark
and graph execution tests. List them in the SDK harness template with the
MTP track's suites so the integration harness compiles every Super test
file. Same four entries as claude/super-fastpath 5a5e078.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(vision): reserve the Nemotron Super tower working memory per image request

The runner track measured a 2048x1536 image request growing MLX peak by
683 MB against a 474 MB media+KV reservation; only the global activation
reserve covered the RADIO tower and projector. Add the pinned
composition's derived activation bound for the largest image (images
are evaluated one at a time) to both encodedPlan and preparationQuote.
Existing charges and the global activation reserve are unchanged;
grids the SDK would refuse are rejected as capacity.

At the largest admitted grid (13312 patches) the fixture request over
live HTTP grew MLX peak by 794 MB against a media reservation of
2,556 MB (461 MB before this change). The exact-quote binding test now
includes the 85,232,640-byte bound for its 2x2-patch input. The SDK
harness template lists the new SDK source and test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs: Nemotron Super image format reference and ingress measurements

- Reference page: reference pipeline, PNG/JPEG conversion tables, JPEG
  error bounds, refused inputs, limits and admission (including the
  tower working-memory charge and the largest grid).
- Dated report: parity, JPEG error, CPU time, decoder peak footprint and
  tower working memory measured on 2026-10-15.
- Inference architecture, direct mode, test guide and qualification
  README updated; the existing Nemotron Super changelog fragment is
  updated in place.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(nemotron-super): frame owner image prompts like the reference processor

The owner's image prompt expanded each <image> slot to N placeholder
tokens without the processor's <img> (19) and </img> (20) markers, so it
did not match processing_nemotron_h_omni.py or the golden corpus.
NemotronSuperPromptContract.imagePrompt renders the pinned template and
expands every slot through expandImagePlaceholders; the owner uses it and
keeps its existing statuses (context overflow stays capacity, a slot
count mismatch stays invalid input). Overflow now has its own
contextExceeded failure.

The real-tokenizer golden test checks imagePrompt against every image
case's expanded token runs; an owner test checks the framing, context
bound and count refusal with the synthetic tokenizer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(nemotron-super): build the speculative owner through the shared factory

The MTP track mirrored the contiguous branch of prepareProductionBackend
in NemotronSuperLocalMTP.makeProductionBuild because the shared factory
did not recognise NemotronSuperMTPTextTarget. Recognise it instead:
ProductionModelAdapter takes its layer kinds, capabilities and caches,
and one calibratedPrefillTokenLimit(model:) lookup (NemotronHModel, the
Super adapter, the Super text target) feeds both the scheduler clamp and
the one-token workspace check. Other models match no new case, so their
behaviour is unchanged.

The builder now calls EngineV2Factory.makeProductionBuild for both owners,
passing the assistant and its serial-verification config for the
speculative one, and the mirrored assembly is removed. A test checks that
the target resolves to the adapter's layer kinds plus MTP and that both
schedulers keep the calibrated prefill bound.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(nemotron-super): hook text binding, busy 429 and text-only speculation

The local HTTP hook built its own text binding whose acquisition asked
the owner for its image binding, and its initializer requested that image
binding unconditionally. An owner with text speculation installed refuses
media with mediaWithSpeculation, so the hook could not be built for it.
The hook now takes the owner's localTextBinding and asks for the image
binding only when the owner does not speculate; while it does, an image
request is refused with mediaUnsupportedByModel (400) before any work.

The owner's bridge serves one request. A concurrent text request reached
the bridge and was refused with 503 (whole-Mac service allowance), and a
concurrent image request got the image binding's 429. The hook now admits
one request at a time across both routes and refuses another with the
existing local busy convention, queueFull (429, OpenAI error envelope),
before any response starts and before any media or KV reservation. The
permit returns after the admitted work returns, which follows native
retirement.

Live loopback tests hold a real request before its native terminal and
check 429 for text and image, streaming and not, with no new reservation,
then success after retirement; and a speculating owner's hook serves text
and answers image requests with 400. The reset test's socket, latch and
polling helpers are shared within the test target for this.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(qualification): read runner charges and hook through accessors

The runner read three private fields by reflection: the budget's
reservation table, and the load transaction's owner and residency. Add
read-only accessors instead: GlobalKVCacheBudget.reservationBytesSnapshot()
(request reservation ID to charged bytes), NemotronSuperLocalLoad
.localImageHTTP(templateBytes:) (the hook over the transaction's own
owner, text-only while it speculates) and residencySnapshot. The runner
uses them, so charge rows always carry bytes and the hook is always
installed; RunnerReflectedState.swift (renamed in 71c653a) becomes
RunnerChargeRows.swift without any Mirror read. super-runner.md describes
the accessors, the 429 busy status and the speculation behaviour, and no
longer says the image hook requires thinking off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(nemotron-super): admit the calibrated prefill workspace with each request

The fastpath SDK runs prefill chunks of up to 2,048 tokens inside an
explicit ModelOpt array workspace of up to 2 GiB and leaves its admission
to the owner. The Super builder did not charge it anywhere. It now adds
modelOptGraphPrefillWorkspaceBytes(tokens:) at the calibrated prefill
limit to the build's fixed request bytes, so every bridge request
reservation carries it on the shared budget from admission until the
request retires; prefill, decode and verify chunks never exceed that
limit. The eager reference (nil workspace) keeps its own bounded tiles.

Because the bridge carves fixed request bytes from the KV grant, the
builder now refuses a grant that cannot serve one request
(requireServiceableOrdinaryGrant), shutting the bridge down first,
instead of returning an owner that refuses every request.

Tests check that the bridge's fixed bytes are the engine's plus the
workspace, that a live request's single reservation equals the bridge's
quote (which includes the workspace) and is released at retirement, and
that a minimum-KV grant fails the build.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(nemotron-super): describe the integrated hook, framing and workspace

Inference architecture and direct-mode docs describe the hook's owner
text binding, the one-request 429, the text-only speculating hook, the
reference image framing, the shared-factory MTP target and the per-request
prefill workspace charge. The changelog fragment is updated in place.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore(libs): pin mlx-swift-lm at the Super integration head d8303e75

The SDK integration branch claude/super-integration merges
claude/super-mtp-fastpath (2442305c) and claude/super-fastpath (916881fe,
f495d987) onto codex/nemotron-super-vl-intake (71752118) and switches the
MTP calibration checks to graphCalibrationValid.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(nemotron-super): exact rectangular verification for local speculation

Under the existing DARKBLOOM_NEMOTRON_SUPER_MTP=1 opt-in (still default off),
the local owner now verifies each round in one exact captured target window
through the SDK NemotronSuperMTPCaptureTarget. The new
DARKBLOOM_NEMOTRON_SUPER_MTP_VERIFICATION selects rectangular (default) or
serial; any other value fails the opt-in load. Media stays refused.

The owner test runs depths 1 and 3 in both modes against the ordinary owner
(token-exact, retirement, reservations returned). The qualification SDK
template lists the new SDK test files. Docs and the changelog fragment
describe the setting.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(nemotron-super): apply the integration refactor review

Required refactor pass over the integration wiring (dedicated review
subagent, then parent follow-ups):
- One-request admission moves from a per-hook gate to the owner
  (admitLocalRequest/finishLocalRequest), so every hook over one owner
  shares it; the hook keeps the owner it was built from.
- A builder that throws retirementIncomplete after refusing an
  unserviceable grant leaves the load transaction in retainedFault with
  its LOAD charge, instead of closing the installation behind a bridge
  that may still use it.
- The hook's drain() comment states what closeAfterDrain drains.
- The factory test checks that the text target's capabilities equal the
  adapter's with MTP added, and no longer shadows its model variable.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(vision): match Pillow's PNG compressed-chunk limits and cap JPEG scans

Pillow refuses any zTXt, compressed iTXt or iCCP chunk that inflates past
MAX_TEXT_CHUNK (1 MiB) and text totalling more than MAX_TEXT_MEMORY
(64 MiB, decoded characters); the parser only inflated XMP, so it admitted
PNGs the reference refuses. NemotronSuperPNGText now applies both limits
to every compressed chunk, with Python decompressobj(limit) semantics
(exactly 1 MiB is accepted; corrupt, truncated, malformed and non-UTF-8
non-XMP chunks are ignored as in Pillow). XMP stays strict. A second iCCP
is refused as spec-based hardening that bounds inflate work.

A progressive JPEG could carry ~1e5 scans in 25 MiB and keep ImageIO busy
without cancellation; more than 500 scans is now refused (hardening
beyond the reference). The container also switches to a ChunkType enum
and handles unknown chunks before an exhaustive switch.

Tests mirror verdicts checked with Pillow 12.2.0 on identical constructions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(vision): apply the Nemotron Super image refactor review

Behavior-preserving: a Parsed struct and rasterize() in the decode
facade with an accurate workspace-quote comment, a hoisted `packed`
flag and `bytesPerPixel` naming in the PNG raster, a private static
TIFF unit-size table, a single overflow-checked sum in the image
binding with updated comments, and two generator script nits.
Regenerated fixtures are byte-identical.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(nemotron-super): cover the capture target in the shared-factory test

The rectangular capture target resolves through the same factory case and
calibrated prefill lookup as the serial text target; check both, and the
scheduler bound for all three served models.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore(libs): pin mlx-swift-lm at the Super integration head 253d9fbe

Adds the MTP track's exact rectangular verification (d64cd63b) and the
images track's bitwise resize and tower working-memory bound (dc8d7cd6),
which the merged provider image binding and golden tests require.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(nemotron-super): admit the JPEG data-URI label for inline images

parseEncodedBody accepted only data:image/png;base64, so JPEG reached
the decoder only under the PNG label. Admit the labels of both formats
NemotronSuperImageDecode decodes (admittedDataURIPrefixes: png, jpeg).
Content sniffing stays authoritative, as in the reference loader, so
either label carries either format; any other label (for example gif or
the unregistered jpg) is still refused before decoding.

The live format test now sends every accepted fixture under both labels
(each format also under the other's label) and checks that rejected
content stays 400 under both, and that gif and jpg labels are refused
even for content that would decode. Image docs and the changelog name
the admitted labels.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(qualification): record runner speculation and refuse it without a head

Plain versus speculative A/B runs on the full checkpoint pass the MTP
switches through --engine-env, which the load transaction already reads.
Record the resolved setting (depth, verification) as `speculation` in the
ready file identity, null for the plain arm, so receipts show which arm
ran. --synthetic has no embedded MTP head and used to serve plain
silently; it now refuses the opt-in. super-runner.md documents the
switches.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(nemotron-super): apply the second integration refactor review

Second required refactor pass, over the round-2 merges and wiring
(dedicated review subagent, then parent follow-ups):
- admittedDataURIPrefixes is private to the binding; runEncoded's comment
  names it instead of repeating the labels.
- The format test shares one admitted-label list and states each
  request's label explicitly.
- The runner's speculation identity switches exhaustively over the
  verification modes, and the checkpoint loader resolves the setting
  before any shard read instead of after the owner is live.
- The factory test holds the capture target to the same full capability
  check as the serial target.
- Merged changelog and inference paragraphs are rewrapped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(nemotron-super): expect the admitted JPEG label in the encoded-body test

386334d admitted data:image/jpeg;base64, but left the images track's
encoded-body test expecting that label to be refused. The test now
refuses the gif and unregistered jpg labels and non-base64 URIs of both
admitted labels, and checks that a JPEG-labelled body parses and its
content is then judged by the decoder.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(nemotron-super): batched plain owner and a specific grant refusal

Concurrency: DARKBLOOM_NEMOTRON_SUPER_MAX_CONCURRENT (runtime policy
environment, 1...64, default 1) sets how many requests the plain owner
serves. Above one the builder serves NemotronSuperRecurrentAdapter with
maximumDecodeRows N and row-exact products, and builds the bridge and
engine with maxConcurrentRequests N; the hook's owner admission counts up
to N and refuses the next with 429 before headers. Speculation keeps one
request: N above one with DARKBLOOM_NEMOTRON_SUPER_MTP=1, or a malformed
value, fails the load with invalidConcurrency.

Per-request charge: the bridge reservation already carried the engine's
recurrent generations (3 x 170,229,760 B for the pinned configuration);
requestWorkspaceBytes adds one NemotronSuperDecodeCharge decode row to
the prefill workspace, so every request is charged its row. This is a
provider-side supplement to the build's fixed request bytes; EngineV2's
replacement of caller fixed bytes for recurrent models is not on this
path (no caller sets them), so the SDK engine is unchanged.

Grant refusal: instead of the generic unsupportedSizing, a grant that
cannot serve every configured request throws UnserviceableGrant with the
grant, the smallest serviceable grant for N requests
(superMinimumGrantBytes) and the fixed bytes per request.

Tests: concurrency parsing; the refusal's numbers for one and two
requests and that the reported minimum serves; the speculative refusal
reports the assistant charge; a batched owner's charge composition
matches NemotronSuperDecodeCharge; live HTTP holds two batched requests
and refuses a third with 429.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(qualification): report the runner's KV grant and size it for MTP and N

The MTP arm failed to load with the generic unsupportedSizing at the
default 4 GiB grant. The runner now:
- reports `kv_grant` (grant, minimum serviceable grant, fixed request
  bytes, serving concurrency) in the ready file identity;
- on UnserviceableGrant, logs `kv_grant_refused` with the numbers and a
  suggested --kv-capacity-gib in `load.failed` and prints it on stderr;
- defaults --kv-capacity-gib to 12 GiB when --engine-env enables
  speculation and to 1 + 3 x N GiB when it sets
  DARKBLOOM_NEMOTRON_SUPER_MAX_CONCURRENT=N > 1 (unmeasured defaults; an
  explicit value always wins).
super-runner.md documents the defaults, the report and the concurrency
switch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(nemotron-qualification): list the batching suites in the SDK harness

The integrated SDK carries the batching track's batched decode, engine,
charge and residency suites, its fixture and its opt-in benchmark. List
the seven files in the SDK harness template next to the fastpath graph
suites, as in that track's harness manifest.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore(libs): pin mlx-swift-lm at the Super integration head 8f096476

Adds the batching track's row-exact batched text decode and
NemotronSuperDecodeCharge (a53e8cb4), which the batched plain owner uses.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(nemotron-super): apply the third integration refactor review

Third required refactor pass, over the batched owner and grant report
(dedicated review subagent, then parent follow-ups):
- superGrantRefusal decides and reports the refusal in one isolated read,
  so the reported minimum matches the decision; the builder uses one
  adapter initializer for every width.
- The bridge gets the configured width as its unqualified width. Without
  it N above eight fell back to the posture-gated M5 default: the load
  could be refused, and requests above eight got the bridge's 503 while
  the hook admitted N. A test builds a twelve-request owner.
- The runner's ready-file minimum covers the configured requests, both
  grant objects carry `requests`, the suggested GiB is null instead of an
  overflow for an unprovable minimum, and its default-grant parsing reuses
  the builder's concurrency parser (an out-of-range value no longer sizes
  a huge LOAD claim before failing).
- Test helpers: the held-terminal failsafe is cancelled on release; the
  upper concurrency bound is checked; a comment matches what the HTTP
  test checks. Hook and runner docs describe the counted admission.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(nemotron-super): run the batched owner tests on the latent-MoE fixture

Row-exact batched decode resolves superMTPCapturePlan, which accepts only
latent MoE blocks; the plain installed fixture has none, so a batched
owner on it fails with SuperMTPCaptureError.layout (the pinned checkpoint
is latent MoE). The batched owner and live HTTP tests now stage the MTP
fixture's target without its head. The HTTP test re-arms the bridge's
one-shot terminal seam from each held pump so both batched requests are
held while the third is refused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(nemotron-super): hold batched terminals with a persistent gate

batchedOwnerAdmitsItsRequestsAndRefusesTheNextWith429 failed in 2 of 4
runs waiting for both requests to be held. Its terminal gate was the
bridge's one-shot seam, re-armed from inside the first held request;
with batching both 2-token requests can finish in the same decode step,
so the second terminal could pass before the re-arm ran. Add a
DEBUG-only persistent terminal gate beside the one-shot seam (existing
tests keep the one-shot behaviour) and use it here. 10 of 10 runs pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(nemotron-super): record full-checkpoint and endpoint qualification results

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(nemotron-super): speculative owner serves several requests

`DARKBLOOM_NEMOTRON_SUPER_MAX_CONCURRENT` was refused with speculation.
With rectangular verification the owner now serves up to eight requests:
the capture target and assistant are built for that many rows, the
engine's speculative batch matches, and every request carries the
assistant's bounded charge in the grant. Serial verification still serves
one request; a value above eight fails the load.

Synthetic tests: concurrent speculative requests (depth 1-3, three and
four rows) return the same text as the plain owner serving each alone,
the grant must hold every request's charge, and the harness templates
list the new SDK and provider suites.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(nemotron-qualification): list the Super fused SSD tests

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(nemotron-super): fixed prefill chunks and one owner-wide prefill lane

Every request reserved the prefill workspace of the largest chunk for its
whole life, so N concurrent requests charged N prefill allowances, and a
burst of short prompts ran as several prefill forwards in one step.

- `NemotronSuperLocalPrefill.Policy`: prompts run in chunks of
  `DARKBLOOM_NEMOTRON_SUPER_PREFILL_CHUNK` tokens (default 2048, at most
  the calibrated limit), one prompt row per step, a step budget holding a
  whole chunk plus every decode or verify row (so no chunk is shortened
  and outputs match solo serving), and optionally
  `DARKBLOOM_NEMOTRON_SUPER_DECODE_STEPS_BETWEEN_CHUNKS` decode-only steps
  between chunks. Applied through a new optional `schedulerPolicy` on the
  production factory (nil keeps every other model's policy).
- The prefill activation is one lane per owner, reserved in the shared
  budget after the grant check and before the bridge admits a request,
  released only after native retirement. The pinned load transaction
  charges the SDK's measured whole-chunk bound
  (`prefillActivationBoundBytes`, 12 GiB at 2048 tokens); fixtures charge
  their ModelOpt workspace quote. A lane that does not fit fails the load.
- Requests now reserve recurrent state, any speculation charge, one decode
  row and KV. The runner reports the lane as `prefill_lane` and counts it
  in the request charges memory calibration compares with.

Tests: policy parsing and scheduler fields; a burst through plain batched
and speculative owners with 4-token chunks (with and without decode
steps between chunks) equals solo serving; one lane per owner, released
at retirement; a lane that does not fit refuses the load.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(nemotron-qualification): list the Super decode pipeline and serving timing suites

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(nemotron-super): opt-in adaptive speculation depth

`DARKBLOOM_NEMOTRON_SUPER_MTP_DEPTH=auto` (rectangular verification only)
leaves the depth unfixed, so the engine's marginal policy picks 0-3 per
step from each request's measured acceptance and the round cost at the
current batch size. Synthetic real-dimension timings show the captured
window's cost growing with the batch, so a fixed depth three can lose its
margin at four or more concurrent requests; the coordinator can A/B this
arm. Every emitted token is still target-verified. The runner's
`speculation` identity records `adaptive`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(nemotron-super): apply the serving refactor review

- The prefill lane charges the SDK's full-model bound whenever the
  installation is the pinned checkpoint (`isPinnedCheckpoint`), so no
  caller can forget it; the builder parameter is gone.
- Serial speculation with several requests is refused before native
  setup (`NemotronSuperLocalMTP.validate`).
- The lane's reservation ID has a distinct suffix and one predicate
  (`isLaneReservationID`) used by the runner's charge rows and the tests.
- The lane-refusal test fills the budget with ballast instead of relying
  on the full-model bound.
- docs/architecture/inference.md, the runner doc and the changelog
  fragment describe the concurrency limits, the prompt policy, the lane
  and adaptive depth; the stale per-request prefill workspace sentence is
  rewritten.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(nemotron-super): explicit closure types in prompt fixtures

Untyped integer arithmetic in map closures can exceed the Xcode 26.0.1
type checker's time limit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(nemotron-super): observe the lane and request charge while in flight

The charge test read the budget at the first event callback, which can
run after a two-token request already retired. It now generates twelve
tokens, records every callback's snapshot, and checks that the lane is
always present and that one snapshot holds exactly the request charge
and the lane.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore(libs): pin mlx-swift-lm #312 at 637b1c82 and record ship-check results

The serving branch was built and tested against the serving SDK but its
gitlink still pointed at 8f096476. Pin the SDK head that contains the
serving, fastpath and type-check fixes, and record the full-checkpoint
endpoint ship check: MTP depth 3 byte-identical to plain on 6/6 prompts;
plain 62.5 and MTP depth 3 76.4 tok/s aggregate at 8 clients.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(nemotron-super): opt-in exact text prefix reuse for the plain owner

`DARKBLOOM_PREFIX_CACHE_MEMORY=1` gives the non-speculating local owner the
SDK's resident recurrent checkpoint bank on the contiguous backend
(`NemotronSuperLocalPrefixCache`, sized by `PrefixCachePolicy.hybridConfig`
from the KV grant). The adapter is built with `exactPrefixCheckpoints`, so
checkpoints sit only on the fixed prefill chunk grid where a restore
continues a cold prefill bit for bit. The backend carves the bank from the
grant before the grant check, and the whole bank budget is reserved in the
shared budget from before the first request until native retirement, like
the prefill lane; a bank that does not fit fails the load after the engine
retired and a retained native fault keeps it charged. Text requests are
submitted with prefix caching on; image requests stay cold and never
publish; the speculating owner has no bank. The minimum serviceable grant
now includes the bank.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(nemotron-qualification): Super text prefix reuse and its charges

Provider fixture tests: the bank is an explicit opt-in of the plain owner
only; a restored request streams the same text as a second owner serving
it cold, which never sees the first owner's entries; lane and bank stay
reserved from build to retirement and nothing stays charged after close;
a bank that does not fit fails the load and refunds the lane; a retained
native fault keeps the bank charged. The harness templates list the new
SDK and provider suites plus the generic hybrid prefix regression tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(nemotron-qualification): runner prefix bank diagnostics

The runner enables the bank with `--engine-env DARKBLOOM_PREFIX_CACHE_MEMORY=1`
(optionally `DARKBLOOM_CBV2_HYBRID_PREFIX_BYTES`). Its reservation is the
`prefix_bank` charge kind, and `context.prefix_cache` in the status and
memory routes reports adoptions, tokens saved, lookups, entries,
evictions and bytes, so cold and warm TTFT can be told apart; the HTTP
usage's cached tokens stay 0 on this route. `bench_super.py` records the
counters after every sample. The runner guide says how to size the bank
for alternating cold/warm runs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(nemotron-super): apply the prefix reuse refactor review

Read the bank size only when a bank is configured and pass it as one
optional pair; name the fixture chunk in the provider tests; restore the
speculative-grant sentence to its paragraph in the runner guide. No
behaviour change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore(libs): pin mlx-swift-lm at the Super prefix reuse head 2e97dae4

The plain Super owner's exact text prefix reuse needs the SDK's
chunk-aligned recurrent checkpoints and the adapter's
exactPrefixCheckpoints opt-in.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(ssd): return a cold staging result only after its host IO refund

`SSDCheckpointStageReservation.release()` refunds the shared budget and the
store's `stagedBytesInUse` on its own task. A non-retryable cold result
(for example an AR allocation refusal) released its attempt's 20 MiB host
IO lease in a `defer` and returned at once, so the refund could still be
pending when the caller read the store or the ledger. The retry path
already awaited `waitForRefund()`. A cold result now also awaits the
refund before returning; the registration is kept until then, as on the
retry path. This is the race behind the intermittent
`SSDShorterCheckpointRestoreTests` "AR allocation refusal stays cold"
failure under parallel load (stagedBytesInUse still 20971520).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore(nemotron): pin validated SDK parent refresh

* Pin the exact Super SSD correction in the intake stack

* Pin mlx-swift-lm to the merged Nemotron Super base (Layr-Labs/mlx-swift-lm#312)

libs/mlx-swift-lm moves from the PR head cda62e9f to the squash-merged main commit 025d65a4, which carries #312 plus main's c17693f5 (#316).

* docs(nemotron-super): restore this branch's hardware-support and prefix-cache text

The master merge (c221da6) resolved these two files' Last updated conflict by taking master's whole file, dropping this branch's Super paragraphs. Three-way merge of both sides; only the stamp takes master's 2026-10-21.

* test(nemotron-super): assert the prefill bound of the pinned mlx-swift-lm

The master merge moved this branch's mlx-swift-lm pin to 19634dd8, whose
NemotronHModel.prefillActivationBoundBytes is (1 << 30) + tokens * (15 << 18)
(re-measured whole-chunk bound); the child branches already assert it.

---------

Co-authored-by: Jonathan Spangler <5055076+jonathan308@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Gajesh Naik <26431906+Gajesh2007@users.noreply.github.com>
Gajesh2007 pushed a commit that referenced this pull request Oct 22, 2026
…1516)

* GLM-5.3-Flash provider: NVFP4 artifact, serving defaults (MTP/paged/prefix on), images, standing wired residency

* GLM-5.3-Flash provider: rectangular adaptive MTP by default (DARKBLOOM_GLM_RECTANGULAR_VERIFY=0 rolls back)

* GLM-5.3-Flash provider: coordinator mode (glm-5.3-flash, 262K context, glm5_next_v1 gate), 2048-token steps, per-token admission rate, NVFP4 model id, refactor review

* Pin mlx-swift-lm to the GLM-5.3-Flash native PR (Layr-Labs/mlx-swift-lm#314)

* Pin mlx-swift-lm to the GLM-5.3-Flash native PR head (Layr-Labs/mlx-swift-lm#314)

* Pin GLM MTP on by default for the local and coordinator identities

* Expect the GLM refusal evidence that chat template controls now carry

* Pin mlx-swift-lm to the GLM-5.3-Flash native PR head (Layr-Labs/mlx-swift-lm#314)

* GLM-5.3-Flash review fixes: reserve step setup, drain consumers on retirement, revision rollback, MTP-gated capability, 32 MiB config bound, provider-loop tests

* Pin mlx-swift-lm to the GLM5-Next review-fix head dba98a56

* Refactor pass and cancellation fix: a cancelled GLM unload still completes retirement; one named index bound

* Pin mlx-swift-lm to the GLM5-Next refactor-pass head b309cc2c

* Preserve GLM residency ownership and surface malformed tool output

* Honor selected test volume in SSD write fixtures

Route prefix-cache and bridge write fixtures through the existing validated parent selector and propagate setup errors. Preserve production cache policy, assertions, cleanup, runtime sources and dependency pins; document test-only volume selection.

Private integration coverage uses different pins. Exact-head public CI remains required.

* fix: preserve MiMo tool-schema ingress parity

* Fix local response compatibility and update GLM runtime dependencies

* Pin the single-Mac native stack (no cluster dependency)

libs/mlx-swift -> cf921c05 (Layr-Labs/mlx-swift work/glm53-flash-release, which pins
mlx 2bba342d and mlx-c 2f1bcab9) and libs/mlx-swift-lm -> 3ab6dd68
(Layr-Labs/mlx-swift-lm work/glm53-flash-release, the same SDK repinned to that stack).

The previous pins (mlx-swift bfaa8a90, mlx 3a179119, mlx-c 46bce47e) existed only on
the two-Mac darkbloom/sealed-all-sum branches, so this PR could not merge before the
cluster PRs. The new stack is that one minus the JACCL bootstrap bridge, sealed
all-sum and collective startup waits; the Metal kernel sources and generated JIT
copies are identical, and the provider uses none of the removed C entry points.

* Carry the OpenAI error code in local error responses

d62bf6b made the local Responses route answer an unknown
previous_response_id with code "previous_response_not_found", but
CORSResponder.openAIErrorResponse took no code, so the provider did not
compile ("extra argument 'code' in call"). The helper now takes an
optional code and the envelope encodes it only when present, so every
existing error body is byte-for-byte unchanged.

* Hash model weights with uncached reads

WeightHasher now reads each file through a descriptor with F_NOCACHE and
a page-aligned 1 MiB buffer before trying the existing cached readers, so
the pre- and post-load integrity hashes no longer pull a second copy of
the weights through the unified buffer cache. On a 256 GB M5 Ultra the
cached hashes of GLM-5.3-Flash's 181.7 GB filled the file cache to 195 GB
while the loader allocated the weights, and the kernel compressed about
150 GB of the just-loaded weights (memory pressure warning, a 17.5 s
first request while they decompressed). With uncached reads the file
cache stays at 25 GB, compression at 2.8 GB and pressure normal through
the load; each hash takes 25 s. Digests and every fallback are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Report why the SSD prefix store is off; DEBUG-only cache key file

SSDHybridCheckpointStoreFactory swallowed every construction failure, so a
GLM load without its persistent cache key (an ad hoc signed app cannot
reach the keychain-wrapped key) served with no prefix cache and only
prefix_cache_status{state="error",reason="cache_init_failed"} as a trace;
every response reported cached_tokens = 0. build(...) now returns a typed
ConstructionFailure, make(...) wraps it, each refusal logs one public line
naming the model and the reason, and /metrics adds detail="<reason>"
behind the error status. The heartbeat reason is unchanged (the platform
accepts a closed set).

Qualification on ad hoc builds: under #if DEBUG only,
DARKBLOOM_DEBUG_CACHE_KEY_FILE names a 32-byte, 0600, single-link regular
file owned by the user, used as the persistent cache key so the SSD tier
can be tested across restarts. Release builds do not contain the path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Serve GLM-5.3-Flash video input

GLM-5.3-Flash is a video model (its shipped template renders video_url
parts, its processor samples 2 FPS in temporal pairs), but the provider
refused every GLM video with 400. Video parts with an inline
data:video/mp4 or data:video/quicktime URL (the coordinator inlines https
media before forwarding) now reach the GLM processor; video rows decode
target-only and never reuse cached prefixes, like images. The media
reservation adds each video's token ceiling and, once, the processor's
decoded-frame cap (videos decode one at a time).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Accept OpenRouter's GLM reasoning controls

OpenRouter sends its unified reasoning object to GLM-5.3-Flash
(reasoning.enabled: true, effort, max_tokens) and the GLM prompt policy
refused every reasoning key except effort, so OpenRouter's reasoning,
reasoning-content-return, reasoning-effort and image templates errored
with 400. reasoning.enabled: true, reasoning.exclude: false,
include_reasoning: true, enable_thinking: true and chat_template_kwargs
enable_thinking/thinking: true are now accepted as no-ops (GLM always
reasons; the rendered prompt is byte-identical), and reasoning.max_tokens
maps to an effort when no effort is given (<= 1024 low, <= 8192 high,
else max). Thinking-off and exclude: true still refuse with 400, now with
a fixed message and code unsupported_value on the local endpoint.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Pin the SDK with GLM-5.3-Flash's single-Mac speedups

mlx-swift-lm 3ab6dd68 -> e4eed647 (#314): 16 bitwise GLM kernel speedups
ported from the cluster SDK, a fix that keeps the shared-experts-in-launch
speedup to prefill steps where it is bitwise (65 rows and more), the MTP
history work charged per chunk (4.89 GB fixed per MTP request instead of
11.31 GB) and video decoding that keeps only the 2 FPS sample. On one M5
Ultra the provider endpoint's greedy output is byte-identical to the
previous pin (14/14 cases, deterministic serial-target mode) and the SDK
real-model MTP test matches in 30/30 token sequences across fixed depths;
prefill is 12-13 % and decode 16-18 % faster. Docs and changelog record
the single-Mac serving changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Document the omitted max_tokens default for GLM accurately

A GLM request that omits max_tokens gets the smaller of the model default
output budget (4,096 for the pinned artifact) and half the context bound
(GLM5NextCoordinatorServing.boundedSizing), not half the bound: measured
4,096 completion tokens at the 65,536-token local selection.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Refuse GLM capacity before the stream starts

The GLM slot gate yielded its token_budget_exhausted refusal inside an
already returned stream, so the local endpoint committed a 200 SSE response
and rendered the refusal as "Response generation failed"/server_error. In
an 8-request flood of ~60K-token reservations on one M5 Ultra, 5 refusals
arrived that way. EngineV2Bridge.submitTokenized now throws
MultiModelBatchSchedulerEngineError.tokenBudgetExhausted for the GLM slot
refusals, as it already does for advertisedContextExceeded, so the local
endpoint returns 503 "Provider capacity is temporarily unavailable." before
headers (streaming or not) and the coordinator gets the typed retriable
capacity refusal. The non-throwing overload keeps its in-band error, and the
GLM media path no longer relabels the refusal as a construction failure.
Measured after the change: the same flood gives 5 clean 503s and serves the
3 requests that fit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Pin the SDK with the step-scratch deferral

mlx-swift-lm e4eed647 -> 48f1e000 (#314): a step whose scratch
reservation is refused is deferred (rows rolled back exactly, newcomers
requeued, admissions held until a running request leaves) instead of
failing every row of the step. With the SSD prefix store on, three
~60K-token GLM requests no longer all fail when the second finishes
prefill. No change on the success path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Refuse a full Mac before the stream starts

When the serving concurrency is full, acquireServiceAllowance refuses the
request so routing moves on, but submitTokenized yielded that refusal inside
an already returned stream: local streaming clients got a 200 and an
immediate "Response generation failed"/server_error frame (non-streaming
clients already got 503). A 40-minute mixed soak on one M5 Ultra recorded
406 such frames in bursts at concurrency 4 (workers retrying at once); no
admitted request failed. The refusal is now thrown as
MultiModelBatchSchedulerEngineError.tokenBudgetExhausted before any stream
exists, so streaming and non-streaming requests both get 503 "Provider
capacity is temporarily unavailable." locally and the coordinator keeps its
typed retriable capacity refusal; the non-throwing overload keeps the same
in-band message. Measured: probes at concurrency 4+1 now return 503 for
stream and non-stream alike.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Record the GLM-5.3-Flash single-Mac qualification

Adds docs/reports/2026-10-21-glm53-flash-single-mac-qualification.md: the
artifact, executable and metallib identities, the serving policy, every
check with its evidence (bitwise port gate, perplexity, endpoint, OpenRouter
templates, prefix cache incl. restart, images, video, long context,
admission, soak), the final performance table on one M5 Ultra 256 GB and the
known limits.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Pin the single-Mac native stack with production allocation footprints

libs/mlx-swift e03513c6 (mlx 4a355746, mlx-c 0a97d9ab) reverts the
one-page minimum on sub-page footprint quotations, so admission charges
for models other than GLM are unchanged from the current release.
libs/mlx-swift-lm 0d43713e (#314) merges main (#316: checkpoint imports
staged from host zeros), carries the matching pin and fixes CI.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Pin the single-Mac stack's fork.yaml fix

libs/mlx-swift 205ee3d8 (mlx 6ee3062c, mlx-c bd03297a) and
libs/mlx-swift-lm 322a231f. Only the core's fork.yaml and the pins
changed since 3de98eb; the compiled sources are identical.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Record the GLM recheck on the production footprint policy

Adds the recheck of the final executable (darkbloom 94a83e27, #1516
15d7a83) after the core reverted the one-page footprint minimum and the
SDK merged main: tokens, admission flood, performance, prefix cache, SSD
restart, 125K context and a 20-minute soak all pass. GLM's serving MTP
charge is 4.05 GB per request.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Pin mlx-swift-lm 97b2ca6d (#314 test-suite fix)

Only tests changed since 322a231f: two GLM suites that create MLX arrays
move from the no-GPU unit tests to the kernel tests. The library sources
the final executable compiled are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Let Responses echo the declared tool in the disabled-thought test

Responses objects echo the request's tools and tool_choice (mlx-swift-lm
37eaf5d6, the OpenAI shape), so the streamed response.created event
contains the declared tool name. The test still refuses the leaked call
itself: the thought marker, the call's argument, any function_call item
or arguments, and the tool name anywhere in Chat Completions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Pin the single-Mac stack merged with the Nemotron Super chain

libs/mlx-swift c2cbef34 (core ad596687, C fa6565d4) and libs/mlx-swift-lm
a630039b (#314), which merge main of each repository: thread-scoped
command-buffer limits (mlx#36, mlx-swift#57), custom-kernel math modes
and the Nemotron 3.5 Super SDK stack. GLM's chain keeps the production
footprint policy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Pin mlx-swift-lm 152cd5c0 (#314 formatting)

Layout only since a630039b.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Pin mlx-swift-lm 77a0d1d9 (#314 test tolerance on non-M5 GPUs)

Tests and layout only since a630039b.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Record the final GLM recheck after merging main

Final executable d9780e86 (SDK merged with the Nemotron 3.5 Super stack):
tokens identical to the previous final build, endpoint, OpenRouter
templates, images, video, prefix cache, SSD restart, 64K/125K context,
admission flood, a 20-minute soak and a same-state performance A/B.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* GLM-5.3-Flash: serve thinking-off with a closed think block

Thinking-off (reasoning.enabled false, enable_thinking false,
chat_template_kwargs enable_thinking/thinking false, effort none/off) adds
enable_thinking false to the render context. The pinned template has no
thinking switch and always ends with an open <think>, so
GLM5NextThinkingTokenizer, wrapping the GLM tokenizer once at load for text,
media and token counting, appends </think>: the empty block the template
writes for an assistant turn without reasoning. ReasoningPromptProbe starts
the reply in content mode. The platform sidecar appends the same text.

Thinking-off beside a thinking-on switch, effort level or budget is a 400.
Hidden reasoning (reasoning.exclude true, include_reasoning false) stays a
400, renamed reasoningExclusionUnsupported. Other families are unchanged.
Docs, changelog and the qualification record's limits (catalog now lists the
full 262,144 context) are updated.

* Pin mlx-swift-lm 13fba500: GLM speedups reach paged serving

#314 deprecates the contiguous GLM forward; the paged CBv2 target is the
only serving path. Four speedups that reached only the contiguous forward
now reach it: the shared all-true validity and one-launch embedding for
decode and verification steps, .serving's native NAX prefill projections,
one-launch DSA payload staging, and split-K DSA decode attention for paged
decode and MTP verification. The first three are bit-identical (the
perplexity panel's 15,901 positions match exactly at 2,048-token chunks);
the fourth gives paged decode the contiguous path's qualified arithmetic,
so output differs from the previous pin only past 2,048 tokens of history.

Native pins and the metallib (156f2624) are unchanged. Docs: the
qualification record's new paged-attention section (token check, same-state
A/B), the changelog fragment, the inference architecture page and the CLI
reference's .serving description.

* Qualification record: paged-attention perplexity and re-qualification

8-token-step perplexity of the split-K decode attention (+0.0049 %), and the endpoint, template, needle, image, video and SDK GPU-suite re-qualification of 344b39e3.

* Pin mlx-swift-lm 46e4d0ba (#314 head: 13fba500 plus swift-format layout)

* Pin mlx-swift-lm ffb71842: paged speedups, bit-exact

#314 keeps paged decode attention bit-exact: the split-K paged path is
left off (perplexity +0.0049 %, top-1 97.6 % at decode-sized steps, below
the lossless bar). Three speedups reach paged serving bit-identically:
shared validity and one-launch embedding, native NAX prefill projections,
one-launch DSA payload staging.

darkbloom 6b95747e (metallib 156f2624 unchanged) is bit-identical to the
qualified d9780e86: SDK real-model MTP tokens 30/30 with identical MTP
counts, endpoint serial-target 14/14. The record, changelog, inference
architecture page and CLI reference now describe that state.

* Pin the merged mlx-swift and mlx-swift-lm main

mlx-swift main 67dc7528 (#58; mlx main ad4745a2, mlx-c main 5e9be4da) has
exactly the tree of the qualified d80124e. mlx-swift-lm main 19634dd8 (#314)
is the qualified ffb71842 plus #318, which changes only Nemotron Super and
ModelOpt files that no GLM path reaches. The record and changelog name the
merged pins.

* Record and changelog: name the latest mlx-swift-lm pin 0351444e

main after #314 (19634dd8), #325 and #323; the later two only pin mlx-swift main and add Nemotron Super/ModelOpt code that no GLM path reaches.

---------

Co-authored-by: jonathan308 <5055076+jonathan308@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Gajesh2007 added a commit that referenced this pull request Oct 22, 2026
#1539)

* fix(gptoss): pin the SDK that keeps GPT-OSS activations and KV in bf16

Pin libs/mlx-swift-lm to the GPT-OSS bf16 activation fix (741d2d0c, on
top of mlx-swift-lm c17693f5, #316). The SDK's expert SwiGLU clamp used
float32 `MLXArray` bounds, which promoted every layer after layer 0 of a
bf16 gpt-oss-20b checkpoint to float32 activations and K/V. Scalar
bounds keep the checkpoint dtype.

Provider sizing already reads the observed native K/V types, so the
gpt-oss-20b native full-attention rate falls from 49,152 to 24,576 bytes
per token in admission, paged storage and the heartbeat without a logic
change. The `fullRowsUseFP32` fallback stays: production slots always
supply observed types, and the fallback over-reserves rather than
under-reserves. Its comments and the EngineV2KVSizing header now say so.

Complete-checkpoint identity binds per-layer dtypes, so float32-era
GPT-OSS SSD checkpoints land in another namespace and are never
restored; matching prompts prefill cold until new checkpoints exist.

Docs: the prefix-cache checkpoint sizes, the inference `gpt_oss` row,
the provenance of the gpt-oss-20b activation floor and the
constant-cast cache row. The fleet geometry fixture's GPT-OSS row is
bf16 on every layer. Adds changelog.d/gptoss-bf16-activations.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(gptoss): correct the remaining float32 GPT-OSS sizing notes

Pin libs/mlx-swift-lm to 4aaf012c, one test-and-comment commit on top
of 741d2d0c on the SDK pin branch. The SDK's catalog window reservation
test now prices gpt-oss-20b with bf16 K/V (4,462,452 bytes reserved per
checkpoint instead of the float32 7.6 MB), and the staged-window budget
comment quotes that ~4.5 MB reserved figure rather than the 3.15 MB
logical window. SDK library behavior is unchanged.

The `EngineV2Bridge.kvBytesPerToken` comment still said contiguous
GPT-OSS adds an fp32 owning-full-row delta and that paged slots stay
fp16. Ordinary CBv2 slots price the observed native per-layer K/V types
through `EngineV2SlotFactory.slotKVBytesPerToken`; the comment now says
so.

The changelog fragment says "every layer after the first" instead of
the gpt-oss-20b-specific "layers 1-23", and that admission, paged
storage and checkpoint identity use the observed native K/V types
instead of sizing from them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Pin libs/mlx-swift-lm to the SDK change on master's SDK commit

The paired SDK PR branch (ttft/gptoss-bf16-activations) was published on SDK main 0351444e, which
also carries mlx-swift-lm #323 and #325 that d-inference master does not pin
yet. Pin ttft/gptoss-bf16-activations-pin (c4947f7a) instead: the same commits cherry-picked onto
0351444e, the SDK commit master pins, so this PR adds only this change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Revert "Pin libs/mlx-swift-lm to the SDK change on master's SDK commit"

d-inference master now pins SDK main 0351444e (#1531), the base the paired SDK
PR branch (ttft/gptoss-bf16-activations) was published on, so the PR head is already the right pin and
the cherry-picked ttft/gptoss-bf16-activations-pin copy is redundant.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Re-pin libs/mlx-swift-lm to the merged SDK change (#326)

Layr-Labs/mlx-swift-lm#326 squash-merged as f2eb29b8 ("fix(gptoss): keep bf16 activations through the expert SwiGLU clamp (#326)").
Move the gitlink from the PR branch head 4aaf012c to that commit on SDK main.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(provider): cite the gpt-oss-20b activation-floor measurement

The floor's float32-activation basis was asserted without evidence.
Cite the 2026-07-10 sweep report that sized it and the SDK history
showing that revision still clamped the expert SwiGLU with float32
bounds (51ea0c4b until f2eb29b8).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(provider): restamp the GPT-OSS bf16 docs

hardware-support.md, inference.md, prefix-cache.md and configuration.md
changed for the bf16 GPT-OSS activations; set their freshness stamps to
the UTC date of the change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Gajesh2007 added a commit that referenced this pull request Oct 22, 2026
* perf(native): fused causal SDPA for full-attention prompt chunks

Bump libs/mlx-swift-lm to the CBv2 change that attends a full-attention
prompt chunk with one `.causal` SDPA call whenever MLX serves the head
geometry with a fused kernel (head_dim 64/72/80/96/128 on every Apple
GPU; head_dim 256 on NAX from 1024 queries), instead of 128-query blocks
with explicit masks. GPT-OSS full layers and the Qwen full-attention
layers of M5 solo prefill stripes take the new route; Gemma 4 does not.

The SDK pin moves from 19634dd8 to ff327738: SDK main (#316, #312, #315,
#317, #318) plus the change. SDK main requires mlx-swift 81f58d79
(nested MLX 71271f08), so libs/mlx-swift moves from 6923a80f and
libs/mlx from cb77239b; the Metal library built from the nested MLX is
byte-identical.

Document the SDK-read kill switch DARKBLOOM_TTFT_FUSED_CAUSAL_PREFILL=0
in the configuration reference and the prompt-chunk attention route in
the inference architecture, and add a changelog fragment.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(native): name the unmeasured models the fused causal route reaches

Refactor pass over the fused causal prefill change.

Pin libs/mlx-swift-lm to fd17d026, the head of the paired SDK branch: one
refactor commit over ff327738 that changes comments and the route's test,
not compiled code.

The route follows layer geometry, so it also reaches the Nemotron 3.5
Lightning attention layers (head_dim 128, every chip) and the head_dim
256 full-attention layers of the other Qwen-family models in M5 solo
prefill stripes. The changelog fragment now names them and says they were
not measured. The inference and configuration rows note that Qwen4 QSA
blocks build no absolute mask and that live packed paged KV keeps its own
prompt path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Pin libs/mlx-swift-lm to the SDK change on master's SDK commit

The paired SDK PR branch (ttft/fused-causal-prefill) was published on SDK main 0351444e, which
also carries mlx-swift-lm #323 and #325 that d-inference master does not pin
yet. Pin ttft/fused-causal-prefill-pin (6d1321ce) instead: the same commits cherry-picked onto
0351444e, the SDK commit master pins, so this PR adds only this change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Revert "Pin libs/mlx-swift-lm to the SDK change on master's SDK commit"

d-inference master now pins SDK main 0351444e (#1531), the base the paired SDK
PR branch (ttft/fused-causal-prefill) was published on, so the PR head is already the right pin and
the cherry-picked ttft/fused-causal-prefill-pin copy is redundant.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Re-pin libs/mlx-swift-lm to the merged SDK change (#327)

Layr-Labs/mlx-swift-lm#327 squash-merged as 1bee5728 ("perf(cbv2): one fused causal SDPA per full-attention prompt chunk (#327)").
Move the gitlink from the PR branch head fd17d026 to that commit on SDK main.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(provider): document fused causal prefill memory in hardware support

The fused causal prompt-attention route lowers the prefill transient
(Qwen3.5-9B on M5 Ultra at 32K: 13.86 -> 12.03 GB peak) but only
inference.md described it. Record in hardware-support.md what the route
drops, and that the activation reserve, measured floors, minimum load KV
and slot grants intentionally stay unchanged, with the reasons.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(provider): restamp the fused causal prefill docs

inference.md and configuration.md changed for the fused causal prompt
attention route; set their freshness stamps to the UTC date of the
change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Gajesh2007 added a commit that referenced this pull request Oct 22, 2026
…unchd (#1536)

* Pin mlx-swift-lm to the bit-exact Qwen GDN prompt kernels

Qwen3.5/3.6/3.8 and Bonsai 2 prompt windows of 16 or more unmasked
positions run their Gated DeltaNet recurrence on four-row kernels that
reproduce the stock gated_delta_step bit for bit, so outputs and recurrent
checkpoints do not change. On M5 Ultra the recurrence is 1.64x (9B and
35B-A3B geometry) and 1.70x (27B geometry) faster per layer at a
4,096-token chunk. The first prompt window of each kernel instantiation
checks bit parity on the GPU and keeps the stock kernel where no candidate
matches. DARKBLOOM_TTFT_GDN_BLOCKED=0 restores the stock kernel; the
configuration reference and the inference architecture page describe the
switch and the check.

The SDK commit sits on mlx-swift-lm main, which already carries
mlx-swift-lm #316 and the Nemotron Super stack (mlx-swift-lm #312, #315,
#317). Its Package.swift requires mlx-swift 81f58d79, whose
GPU.CommandBufferLimits (mlx-swift #57) MLXLMCommon uses, so libs/mlx-swift
moves to that commit and libs/mlx to its nested MLX 71271f08 (mlx #36).
That MLX change is host-side only: mlx.metallib built from it is
byte-identical to the current one (SHA-256 fb1ba8f9...).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Re-pin the GDN SDK head and tighten its docs

Moves libs/mlx-swift-lm from 1c9c255e to 1ec827e0. The two added SDK
commits change only comments and the formatting of one string literal
(format Qwen4ExpGDNBlocked.swift; correct two GDN kernel-selection
comments), so no code or kernel changes.

docs/architecture/inference.md: the Gated DeltaNet paragraph now follows
the native Qwen3.5 vision paragraph instead of separating it from the
Bonsai adapter paragraph it was written with, and says that the probe
tries the candidates in order. The changelog fragment gives the cold
time-to-first-token saving as the estimate it is, and says that a new
kernel runs only where the GPU check finds it bit-exact.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Re-pin the GDN dispatch cleanup and name the probe candidates

Moves libs/mlx-swift-lm from 1ec827e0 to 2debb5e8. The added SDK commit
gives the prompt-kernel dispatch the value head width once instead of
twice and adds a test of the bit comparator that the probe relies on.
The kernel sources, the probe and every dispatch decision are unchanged.

docs/architecture/inference.md now names the two kernels the probe tries
(packed, then rows), says that every process probes each kernel
instantiation once, and says which kernels the switch can force.

docs/reference/configuration.md moves the DARKBLOOM_TTFT_GDN_BLOCKED row
after DARKBLOOM_GEMMA4_PREFILL_CHUNK_EVAL, the other model-specific
prefill control, so that it no longer splits the MTP rows. The row's
text is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Re-pin libs/mlx-swift-lm to the merged SDK change (#324)

Layr-Labs/mlx-swift-lm#324 squash-merged as 921bfa69 ("Run Qwen GDN prompt windows on bit-exact four-row kernels (#324)").
Move the gitlink from the PR branch head f4be1ba1 to that commit on SDK main.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(provider): forward the GDN prompt-kernel rollback to launchd

The SDK keeps a four-row Qwen GDN prompt kernel wherever its parity probe
finds it bit-exact on the GPU; the probe compares bits, not speed. Where a
kept kernel is slower, DARKBLOOM_TTFT_GDN_BLOCKED=0 is the recovery, but
launchd does not inherit the installing shell, so the export reached only a
foreground provider: the background provider job kept probing, and restarts
and watchdog recovery reuse its saved plist. Add the key to
LaunchAgent.inferencePassthroughEnvKeys so darkbloom start persists it into
the provider plist. The watchdog plist stays without it: it never runs
inference.

The key is spelled out because its SDK reader (GatedDeltaPrefill.mode) is
internal to MLXLLM. The new LaunchAgentEnvironmentTests case reads the SDK's
own key and parser through @testable import MLXLLM: for unset, empty, 0,
" OFF ", packed, rows and an unknown value, the provider plist resolves the
same mode as the foreground shell, so renaming the key fails it.

Docs: the configuration row says the key is forwarded and that the probe
does not compare speed; the CLI reference lists it among the forwarded
variables; the changelog fragment no longer says the LaunchAgent does not
receive it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs: qualify the GDN prompt kernels by GPU in hardware support

docs/AGENTS.md section 7 has native-inference changes move
architecture/hardware-support.md with architecture/inference.md and record an
external capacity compatibility review; this PR only touched inference.md.
Add a "GDN prompt kernels by GPU" section after "Cross-repository agreement":

- Qualification: no chip list selects the kernel. In each process the first
  eligible window of each kernel instantiation compares the candidates with
  gated_delta_step on a fixed 32-position window on that GPU and keeps the
  first bit-exact one, or the stock kernel (GatedDeltaPrefill.probe), so every
  chip keeps the stock kernel's bits. The probe does not compare speed, which
  is what DARKBLOOM_TTFT_GDN_BLOCKED restores.
- Measured: M5 Ultra per-layer recurrence 1.45-1.70x faster, with packed kept
  at the 9B, 27B and 35B-A3B head geometries; M3 Ultra Qwen3.5-9B cold prefill
  1.1-1.3% less time at 2K/8K/32K (A/B/A on one binary). Every other GPU is
  unmeasured; GatedDeltaPrefillTests prints per-layer timings with
  DARKBLOOM_GDN_PREFILL_BENCH=1.
- Capacity: the selected kernel has the stock kernel's inputs, outputs and
  fp32 state; the probe is transient, once per instantiation and process, at
  most about 16 MiB at Qwen3.8-27B (four 3 MiB fp32 states and a 32-position
  window). No full-load quotation, activation floor, KV grant or reported
  capacity field changes, so platform admission needs no change.

The changelog fragment's "Speed on M1-M4 GPUs is unmeasured" now records the
M3 Ultra measurement.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(provider): restamp the docs last edited on 2026-10-22 UTC

The GDN rollback forwarding and the hardware-support GPU qualification
were committed at 2026-10-22T01:10:38Z, but the pages they edit still
said 2026-10-21. Restamp them with `make docs-stamp` (today, UTC):

- docs/architecture/hardware-support.md
- docs/provider/cli-reference.md
- docs/reference/configuration.md

docs/architecture/inference.md keeps 2026-10-21. This branch last edited
it at 2026-10-21T23:11:14Z; the later merges from master changed it only
by bringing in master's own content, with no hand edits.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

This branch had an error being deployed

1 failed and 3 active deployments
Preview – d-inference — aa99ab3c Deployed Jun 11, 2026 by vercel[bot]
Preview – d-inference-console-ui-dev — aa99ab3c Deployed Jun 11, 2026 by vercel[bot]
Preview – d-inference-landing — aa99ab3c Deployed Jun 11, 2026 by vercel[bot]
benchmarks — aa99ab3c Deployed Jun 11, 2026 by anupsv via E2E Benchmarks #768
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.

3 participants