Skip to content

AI, fully local on your computer.

36.0 KB
Raw Blame
import { describe, it, expect, vi, afterEach } from 'vitest'
import { LlamaReranker } from '../../src/main/services/reranker/llama'
import {
  cpuRequestCeilingFor,
  resolveRerankerDevicePosture,
  snapshotRerankerOccupancy,
  createPendingModelSwitchCounter
} from '../../src/main/services/rag/device-posture'
import { DEFAULT_SETTINGS } from '../../src/shared/types'
import type { RerankerDevice } from '../../src/main/services/rag/rerank-profile'
import { isEngineCannotRunError, resetEngineProblemsForTest } from '../../src/main/services/runtime/engine-load'
import { committingRuntime } from '../helpers/chat-runtime-stub'
import { CARDS, CATALOG_MANIFESTS } from '../helpers/gpu-fixtures'
import { until } from '../helpers/hang-budget'
import { FakeChild, GatedChild, exitingChild, fakeSpawn, loadingSidecar } from '../helpers/fake-sidecar'

// Wave 8 (step 4-8, resolving the scoped Opus review of step 4-7's finding C3): option B', the
// use-time re-check (Q), the CPU request ceiling (G), and the lifecycle hardening (single-flight
// teardown + dead-handle recovery + abort classification). Driven at the SAME level as
// reranker.test.ts — a real LlamaReranker over a fake spawn + fake loopback fetch — because the
// mechanism under test lives entirely inside `resolveServer`/`ensureStarted`/`beginOrJoinTeardown`.

/** /health ok, /v1/rerank returns one ascending score per document (order-preserving is not the
 *  point here — the lifecycle/race mechanics are). */
function rerankFetch(): typeof fetch {
  return (async (url: string | URL, init?: RequestInit) => {
    const u = String(url)
    if (u.endsWith('/health')) return { ok: true, status: 200 } as Response
    if (u.endsWith('/v1/rerank')) {
      const body = JSON.parse(String(init?.body)) as { documents: string[] }
      return {
        ok: true,
        status: 200,
        json: async () => ({ results: body.documents.map((_d, index) => ({ index, relevance_score: index })) })
      } as Response
    }
    throw new Error(`unexpected url ${u}`)
  }) as typeof fetch
}

const base = {
  id: 'bge-reranker-v2-m3-f16',
  binPath: '/bin/llama-server',
  modelPath: '/models/reranker.gguf',
  findPort: async () => 53000,
  healthIntervalMs: 1
}

function docs(n: number): string[] {
  return Array.from({ length: n }, (_, i) => `doc ${i}`)
}

// ---- Ruling (b)(G): the CPU posture's per-call request ceiling -------------------------------

describe('Wave 8 ruling (b)(G): the CPU request ceiling', () => {
  it('refuses a CPU-posture request above the default ceiling (cpuRequestCeilingFor, 48), BEFORE any start, and never latches startFailed', async () => {
    const ceiling = cpuRequestCeilingFor(DEFAULT_SETTINGS) // the real formula, default settings -> 48
    expect(ceiling).toBe(48)
    const { spawn, calls } = fakeSpawn()
    const reranker = new LlamaReranker({
      ...base,
      spawn,
      fetchImpl: rerankFetch(),
      devicePosture: () => 'cpu',
      cpuRequestCeiling: () => ceiling
    })
    await expect(reranker.rerank('q', docs(ceiling + 1))).rejects.toThrow(/refused/i)
    expect(calls.length).toBe(0) // thrown before any start
    // Not latched: a request AT the ceiling succeeds right after, on the same instance.
    const hits = await reranker.rerank('q', docs(ceiling))
    expect(hits).toHaveLength(ceiling)
    expect(calls.length).toBe(1)
    await reranker.stop()
  })

  // Module-mocked finite CPU_HI_MIN_THREADS (the rerank-profile.test.ts pattern) + a mocked
  // defaultThreadCount (CI's real core count is unpredictable) so cpuRequestCeilingFor's OWN
  // formula, not a hand-typed 72, decides the top48-class ceiling under the wide-scope opt-in.
  it('cpuRequestCeilingFor follows the cpu-hi profile under the wide-scope opt-in (72) and stays 48 without it (module-mocked finite CPU_HI_MIN_THREADS)', async () => {
    vi.resetModules()
    vi.doMock('../../src/shared/rerank-rules', () => ({ CPU_HI_MIN_THREADS: 8 }))
    vi.doMock('../../src/main/services/runtime/sidecar', async (importOriginal) => {
      const actual = await importOriginal<typeof import('../../src/main/services/runtime/sidecar')>()
      return { ...actual, defaultThreadCount: () => 8 }
    })
    try {
      const mod = await import('../../src/main/services/rag/device-posture')
      const wideSettings = { ...DEFAULT_SETTINGS, ragRerankWideScope: true }
      expect(mod.cpuRequestCeilingFor(wideSettings)).toBe(72) // 2*12 (ragTopKInitial) + totalCandidateCapFor('top48') (48)
      expect(mod.cpuRequestCeilingFor(DEFAULT_SETTINGS)).toBe(48) // opt-in off -> still 'capped'
    } finally {
      vi.doUnmock('../../src/shared/rerank-rules')
      vi.doUnmock('../../src/main/services/runtime/sidecar')
      vi.resetModules()
    }
  })

  // Verification 2's hole B-1: a Q/G check separated by an await from the start it guards. Set up
  // a resident 'cpu' sidecar, then let devicePosture answer 'gpu' (triggering Q's restart) on the
  // FIRST call of this rerank() and 'cpu' again on the SECOND (post-restart-await) call -- a
  // posture that flips TWICE inside one rerank(). G must refuse the oversized request on the
  // fresh, post-await read, not admit it on the strength of the momentary 'gpu' reading.
  it('re-applies G after the await inside Q\'s own restart, on a posture that flipped during that await', async () => {
    const { spawn, calls } = fakeSpawn()
    const postures: RerankerDevice[] = ['cpu'] // cold start #1: cpu
    let call = 0
    const devicePosture = (): RerankerDevice => {
      const p = postures[Math.min(call, postures.length - 1)]!
      call++
      return p
    }
    const reranker = new LlamaReranker({
      ...base,
      spawn,
      fetchImpl: rerankFetch(),
      devicePosture,
      cpuRequestCeiling: () => 48
    })
    await reranker.rerank('warm', docs(1)) // cold start #1, recorded 'cpu'
    expect(calls.length).toBe(1)

    // Now make the NEXT rerank() see 'gpu' first (mismatch -> Q restarts), then 'cpu' again
    // (G must catch the oversized request on THIS second, post-await read).
    postures.length = 0
    postures.push('gpu', 'cpu')
    call = 0
    await expect(reranker.rerank('wide', docs(100))).rejects.toThrow(/refused/i)
    // The mismatch tore the cpu sidecar down (Q's restart), but G refused before any respawn.
    expect(calls.length).toBe(1)
    expect(reranker.isLoaded()).toBe(false)
    await reranker.stop()
  })
})

// ---- Ruling (b)(Q): the four race rules -------------------------------------------------------

describe('Wave 8 ruling (b)(Q): the four race rules', () => {
  // Rule (i) proper: a STARTING sidecar recorded 'gpu' is being torn down by a lock; an ask that now
  // resolves 'cpu' hits the mismatch branch while `tearingDown` is set and must refuse at once — joining
  // the pass would wait for the aborted start's kill (escalated to SIGKILL at the end of its 2 s grace,
  // the exit is gated), then refuse anyway via rule (ii).
  it('rule (i): a posture-mismatched ask during a teardown it did not start refuses at once, never joins it', async () => {
    const { spawn, calls, children } = fakeSpawn(() => new GatedChild())
    const { fetchImpl, state } = loadingSidecar(rerankFetch()) // never healthy: the start stays in flight
    let posture: RerankerDevice = 'gpu'
    const reranker = new LlamaReranker({ ...base, spawn, fetchImpl, devicePosture: () => posture })
    const coldAsk = reranker.rerank('q', docs(1)).catch((e: unknown) => e) // starting, recorded 'gpu'
    await until(() => state.probes > 0, 'the cold start polling /health')
    const suspendP = reranker.suspend() // aborts the start; its stop() parks on the gated exit
    await until(() => children[0]!.killed, 'the teardown killing the starting child')
    let escalated = false
    const kill = children[0]!.kill.bind(children[0]!)
    children[0]!.kill = () => {
      escalated = true
      return kill()
    }
    posture = 'cpu'
    const outcome = await reranker.rerank('q2', docs(1)).catch((e: unknown) => ({ error: e, escalatedBefore: escalated }))
    expect(outcome).toMatchObject({ escalatedBefore: false })
    expect((outcome as { error: Error }).error.message).toMatch(/suspending/i)
    expect(calls.length).toBe(1)
    children[0]!.releaseExit()
    await suspendP
    await coldAsk
    await reranker.stop()
  })

  // Hole B-2 (verification 2): a lock JOINING a Q-initiated teardown, under a posture that keeps
  // changing, must still leave NOTHING resident afterwards -- Q must not respawn just because its
  // own await settled.
  it('rule (ii): a lock joining a Q-initiated teardown under a changing posture leaves nothing resident', async () => {
    const { spawn, calls, children } = fakeSpawn(() => new GatedChild())
    let posture: RerankerDevice = 'gpu'
    const reranker = new LlamaReranker({ ...base, spawn, fetchImpl: rerankFetch(), devicePosture: () => posture })
    await reranker.rerank('q', docs(1)) // resident, recorded 'gpu'
    expect(calls.length).toBe(1)

    posture = 'cpu' // a real occupancy change -- Q must restart on the next call
    const askP = reranker.rerank('q2', docs(1)) // detects the mismatch, initiates the teardown pass
    // Let Q's own beginOrJoinTeardown() run (kill() called on child #1) before the lock joins.
    await until(() => children[0]!.killed, "Q's teardown killing child #1")
    const lockP = reranker.suspend() // the LOCK joins the SAME single-flight pass (requesterCount -> 2)
    children[0]!.releaseExit() // let the shared pass settle
    await lockP
    await expect(askP).rejects.toThrow(/suspending/i) // rule (ii): another caller joined -> refuse
    expect(calls.length).toBe(1) // Q never got to respawn
    expect(reranker.isLoaded()).toBe(false) // the lock's intent — nothing resident — holds
    await reranker.stop()
  })

  it('rule (ii): the caller\'s OWN aborted signal ends the ask instead of landing on the fallback', async () => {
    const { spawn, children } = fakeSpawn(() => new GatedChild())
    let posture: RerankerDevice = 'gpu'
    const reranker = new LlamaReranker({ ...base, spawn, fetchImpl: rerankFetch(), devicePosture: () => posture })
    await reranker.rerank('q', docs(1))
    posture = 'cpu'
    const controller = new AbortController()
    const askP = reranker.rerank('q2', docs(1), { signal: controller.signal })
    await until(() => children[0]!.killed, "Q's teardown killing child #1")
    // The teardown's `server.stop()` escalates to SIGKILL at the end of its 2 s grace (the exit is
    // gated) and settles right after it, so an ask that waited for the teardown settles after it.
    let escalated = false
    const kill = children[0]!.kill.bind(children[0]!)
    children[0]!.kill = () => {
      escalated = true
      return kill()
    }
    const reason = new DOMException('Stopped by the user', 'AbortError')
    controller.abort(reason) // the CALLER's own signal — a lock would do this to the ask FIRST
    const outcome = await askP.catch((e: unknown) => ({ error: e, escalatedBefore: escalated }))
    // #635: the ask ended at once, with its own reason, while the teardown it began ran on.
    expect(outcome).toMatchObject({ escalatedBefore: false })
    expect((outcome as { error: unknown }).error).toBe(reason)
    children[0]!.releaseExit()
    await reranker.stop()
  })

  // Hole B-3 (verification 2): the ask that started a cold start ANOTHER caller's teardown aborts
  // must land on the fallback (a non-abort error), never end as if its OWN Stop had fired.
  it("rule (iv): an ask whose cold start another caller's teardown aborts lands on the fallback (a non-abort error), not ended", async () => {
    const { spawn, children } = fakeSpawn(() => new GatedChild())
    // /health never reports healthy on its own -- the ask's cold start is unblocked only by
    // the suspend's abort inside `waitForHealthy`'s per-iteration abort check, never by a
    // successful health probe (deterministic: no reliance on a raced release).
    const { fetchImpl } = loadingSidecar(rerankFetch())
    const reranker = new LlamaReranker({ ...base, spawn, fetchImpl, devicePosture: () => 'cpu' })
    const askP = reranker.rerank('q', docs(1)) // cold start begins; can never self-report healthy
    await until(() => children.length > 0, 'the cold start spawning its child')
    const suspendP = reranker.suspend() // ANOTHER caller's teardown aborts the in-flight start
    await until(() => children[0]!.killed, 'the teardown killing the starting child')
    children[0]!.releaseExit()
    const err = await askP.catch((e: unknown) => e)
    expect(err).toBeInstanceOf(Error)
    expect((err as Error).message).toMatch(/aborted by another operation/i)
    expect((err as Error).name).not.toBe('AbortError') // reclassified: not the DOMException name
    await suspendP
    await reranker.stop()
  })
})

// ---- Ruling (c): sidecar lifecycle hardening ---------------------------------------------------

describe('Wave 8 ruling (c): sidecar lifecycle hardening', () => {
  it.each([{ joiner: 'suspend' as const }, { joiner: 'stop' as const }])(
    '(i) an overlapping $joiner() joins the in-flight suspend() pass and settles only after the shared kill (no orphan on quit)',
    async ({ joiner }) => {
      const { spawn, children } = fakeSpawn(() => new GatedChild())
      const reranker = new LlamaReranker({ ...base, spawn, fetchImpl: rerankFetch(), devicePosture: () => 'cpu' })
      await reranker.rerank('q', docs(1))
      const suspendP = reranker.suspend()
      let joinerSettled = false
      const joinerP = reranker[joiner]().then(() => {
        joinerSettled = true
      })
      // One macrotask hop, no observable to gate on (justified): a joiner that did NOT join runs its own
      // empty teardown and settles within microtasks; the shared pass stays parked on the gated exit
      // (the kill's 2 s grace is far away).
      await new Promise((r) => setImmediate(r))
      expect(joinerSettled).toBe(false)
      children[0]!.releaseExit()
      await Promise.all([suspendP, joinerP])
      expect(children).toHaveLength(1)
      expect(children[0]!.killed).toBe(true)
      expect(reranker.isLoaded()).toBe(false)
      await reranker.stop()
    }
  )

  it('(ii) one unexpected exit drops the dead handle and the next rerank() cold-starts with a freshly resolved posture', async () => {
    const { spawn, calls, children } = fakeSpawn()
    let posture: RerankerDevice = 'cpu'
    const reranker = new LlamaReranker({ ...base, spawn, fetchImpl: rerankFetch(), devicePosture: () => posture })
    await reranker.rerank('q', docs(1))
    expect(reranker.isLoaded()).toBe(true)
    children[0]!.crash() // a healthy child dying on its own -- NOT via stop()/suspend()
    expect(reranker.isLoaded()).toBe(false) // the dead handle is dropped synchronously

    posture = 'gpu' // the freshly resolved posture for the lazy restart
    const hits = await reranker.rerank('q2', docs(1))
    expect(hits).toHaveLength(1)
    expect(calls.length).toBe(2) // re-spawned, not served from the dead handle
    expect(calls[1]!.args).not.toContain('--device') // used the NEW posture
    await reranker.stop()
  })

  it('(ii) a SECOND unexpected exit in the same session latches like a permanent load fault', async () => {
    const { spawn, calls, children } = fakeSpawn()
    const reranker = new LlamaReranker({ ...base, spawn, fetchImpl: rerankFetch(), devicePosture: () => 'cpu' })
    await reranker.rerank('q', docs(1))
    children[0]!.crash() // exit #1 -- drops the handle, does not latch
    await reranker.rerank('q2', docs(1)) // lazily restarts fine
    expect(calls.length).toBe(2)
    children[1]!.crash() // exit #2 -- latches
    await expect(reranker.rerank('q3', docs(1))).rejects.toThrow(/twice/i)
    expect(calls.length).toBe(2) // no third spawn attempted — fails fast
    await reranker.stop()
  })
})

// ---- #474: GPU→CPU demotion (translation runtime's issue-#42 session fallback latch, ported) ---

describe('#474: GPU->CPU demotion (session fallback latch)', () => {
  it('a GPU-attempt cold-start failure falls back to CPU WITHIN the same rerank() and latches the session', async () => {
    // Child 0 (the GPU attempt) dies immediately (a genuine load fault); every later child is
    // healthy. The fake fetch refuses connections while attempt 1 is live (the genuine load-fault
    // fixture of reranker.test.ts's F7 latch test, translation-runtime.test.ts's ladder test).
    let n = 0
    const { spawn, calls } = fakeSpawn(() => (++n === 1 ? exitingChild(1) : new FakeChild()))
    const good = rerankFetch()
    const fetchImpl = (async (url: string | URL, init?: RequestInit) => {
      if (calls.length < 2) throw new Error('connection refused') // the dying GPU attempt
      return good(url, init)
    }) as typeof fetch
    const fallbacks: string[] = []
    const reranker = new LlamaReranker({
      ...base,
      spawn,
      fetchImpl,
      devicePosture: () => 'gpu',
      onDeviceFallback: (reason) => fallbacks.push(reason)
    })
    expect(reranker.gpuDemoted()).toBe(false) // nothing has failed yet
    const hits = await reranker.rerank('q', docs(1)) // GPU rung fails -> CPU rung serves it
    expect(hits).toHaveLength(1)
    expect(calls.length).toBe(2)
    expect(calls[0]!.args).not.toContain('--device') // rung 1: GPU (no device arg)
    expect(calls[1]!.args).toContain('--device') // rung 2: forced CPU, same call
    expect(fallbacks.length).toBe(1)
    expect(fallbacks[0]).toMatch(/GPU-attempt start failed/)
    // #495 follow-up: the PURE read of the latch the ask site folds into its occupancy snapshot.
    expect(reranker.gpuDemoted()).toBe(true)

    // The session latch: devicePosture() now reports 'cpu' even though the injected callback
    // still says 'gpu' -- and a LATER cold start (post-suspend) pins CPU directly, no repeated
    // GPU health timeout per ask.
    expect(reranker.devicePosture()).toBe('cpu')
    await reranker.suspend()
    await reranker.rerank('q2', docs(1))
    expect(calls.length).toBe(3)
    expect(calls[2]!.args).toContain('--device')
    expect(fallbacks.length).toBe(1) // the latch arms (and reports) once
    await reranker.stop()
  })

  it('only the CPU rung failing arms the permanent startFailed latch (a genuinely broken setup)', async () => {
    const { spawn, calls } = fakeSpawn(() => exitingChild(1)) // EVERY child dies -- a truly broken GGUF
    const reranker = new LlamaReranker({
      ...base,
      spawn,
      fetchImpl: (async () => {
        throw new Error('connection refused')
      }) as unknown as typeof fetch,
      devicePosture: () => 'gpu'
    })
    await expect(reranker.rerank('q', docs(1))).rejects.toThrow()
    expect(calls.length).toBe(2) // walked BOTH rungs (gpu, then cpu) before latching
    expect(calls[0]!.args).not.toContain('--device')
    expect(calls[1]!.args).toContain('--device')
    await expect(reranker.rerank('q2', docs(1))).rejects.toThrow() // latched
    expect(calls.length).toBe(2) // no third spawn
    await reranker.stop()
  })

  it('a transient bind race on the GPU attempt does NOT fall back or latch -- the retry re-attempts GPU', async () => {
    const { spawn, calls } = fakeSpawn(() => exitingChild(1, 'error: bind: address already in use\n'))
    const { fetchImpl } = loadingSidecar(rerankFetch()) // never healthy: every child loses the port first
    const fallbacks: string[] = []
    const reranker = new LlamaReranker({
      ...base,
      spawn,
      fetchImpl,
      devicePosture: () => 'gpu',
      onDeviceFallback: (reason) => fallbacks.push(reason)
    })
    // Doubly-unlucky startup: both the initial start and its single internal bind-retry lose the
    // port (LlamaServer's own retry policy) -- never reaches OUR ladder's GPU/CPU decision.
    await expect(reranker.rerank('q', docs(1))).rejects.toThrow(/address already in use/)
    expect(fallbacks.length).toBe(0) // a port steal is not a device fault
    expect(calls.length).toBeGreaterThanOrEqual(2)
    expect(calls.every((c) => !c.args.includes('--device'))).toBe(true) // every spawn kept GPU
    await reranker.stop()
  })

  it('a SECOND unexpected exit under GPU demotes to CPU instead of latching; the CPU posture then gets its own two-strikes budget', async () => {
    const { spawn, calls, children } = fakeSpawn()
    const fallbacks: string[] = []
    const reranker = new LlamaReranker({
      ...base,
      spawn,
      fetchImpl: rerankFetch(),
      devicePosture: () => 'gpu',
      onDeviceFallback: (reason) => fallbacks.push(reason)
    })
    await reranker.rerank('q', docs(1)) // resident on GPU
    children[0]!.crash() // exit #1 under GPU -- drops the handle, no latch, no demotion yet
    await reranker.rerank('q2', docs(1)) // lazily restarts fine, still GPU (not yet demoted)
    expect(calls.length).toBe(2)
    expect(calls[1]!.args).not.toContain('--device')

    children[1]!.crash() // exit #2 under GPU -- demotes instead of latching
    expect(fallbacks.length).toBe(1)
    expect(fallbacks[0]).toMatch(/exited unexpectedly twice/)
    const hits = await reranker.rerank('q3', docs(1)) // NOT latched -- cold-starts on the now-forced CPU
    expect(hits).toHaveLength(1)
    expect(calls.length).toBe(3)
    expect(calls[2]!.args).toContain('--device')

    // The safety net survives the demotion: the CPU posture gets its OWN two-strikes budget.
    children[2]!.crash() // 1st CPU exit -- drops the handle, no latch
    await reranker.rerank('q4', docs(1)) // lazily restarts fine, still CPU (gpuFellBack stays armed)
    expect(calls.length).toBe(4)
    children[3]!.crash() // 2nd CPU exit -- NOW latches (a genuinely broken setup)
    await expect(reranker.rerank('q5', docs(1))).rejects.toThrow(/twice/i)
    expect(calls.length).toBe(4) // no fifth spawn attempted -- fails fast
    expect(fallbacks.length).toBe(1) // the GPU->CPU latch armed (and reported) exactly once
    await reranker.stop()
  })

  // #495 follow-up: the demoting call itself bypassed G. The ask site
  // picks GPU_RERANK_SCOPE for a 'gpu' posture, so a genuine GPU cold-start failure could demote
  // to CPU and then hand the CPU-pinned sidecar the FULL gpu-sized request instead of refusing it
  // -- the very path the ceiling exists to protect, and the one path none of the four tests above
  // (all `docs(1)`, none injecting `cpuRequestCeiling`) reached.
  it('#495 follow-up: the ceiling is re-applied when the ladder itself demotes gpu->cpu mid-call -- a 60-document request is refused and the CPU-pinned sidecar never receives it', async () => {
    let n = 0
    const { spawn, calls } = fakeSpawn(() => (++n === 1 ? exitingChild(1) : new FakeChild())) // the GPU rung dies
    const good = rerankFetch()
    const rerankDocCounts: number[] = []
    const fetchImpl = (async (url: string | URL, init?: RequestInit) => {
      const u = String(url)
      if (calls.length < 2) throw new Error('connection refused') // the dying GPU attempt's own health check
      if (u.endsWith('/v1/rerank')) {
        const body = JSON.parse(String(init?.body)) as { documents: string[] }
        rerankDocCounts.push(body.documents.length)
      }
      return good(url, init)
    }) as typeof fetch
    const reranker = new LlamaReranker({
      ...base,
      spawn,
      fetchImpl,
      devicePosture: () => 'gpu',
      cpuRequestCeiling: () => 48
    })
    await expect(reranker.rerank('q', docs(60))).rejects.toThrow(/refused/i)
    // Both rungs were walked -- the demotion itself is unavoidable mid-ladder, discovered only
    // once the GPU attempt fails -- but the CPU-pinned sidecar the ladder just started never saw
    // the oversized /v1/rerank request: the refusal fires from resolveServer's own re-check
    // before rerank() ever calls server.fetch.
    expect(calls.length).toBe(2)
    expect(calls[0]!.args).not.toContain('--device')
    expect(calls[1]!.args).toContain('--device')
    expect(rerankDocCounts).toHaveLength(0)
    expect(reranker.devicePosture()).toBe('cpu') // demoted, not latched
    // Not latched -- a request AT the ceiling on the now-resident CPU sidecar succeeds right
    // after, on the same instance, with no new spawn.
    const hits = await reranker.rerank('q2', docs(48))
    expect(hits).toHaveLength(48)
    expect(calls.length).toBe(2)
    await reranker.stop()
  })

  // #495 follow-up: the re-check above shares nothing with rule (iii)'s own `restarted` flag any
  // more, because a call that already spent `restarted` on an ORDINARY posture-flip restart (a
  // chat start finishing mid-session, not a fault) could still demote genuinely inside that SAME
  // call and skip the re-check entirely. This fixture drives exactly that composite path: a
  // resident CPU-recorded sidecar (posture 'cpu', mirroring `occupancy.chatStartBusy`), then the
  // posture callback flips to 'gpu' (the chat start finishing), which triggers the ORDINARY
  // mismatch-restart (rule iii) -- and the fresh GPU rung the restart cold-starts then fails
  // genuinely, demoting to CPU within the very same call.
  it("#495 follow-up: the ceiling is re-applied even when this call's own mismatch-restart already spent rule (iii)'s flag before the ladder demotes -- a 60-document request is refused after a cpu->gpu restart that itself falls back to cpu", async () => {
    let posture: RerankerDevice = 'cpu' // simulates occupancy.chatStartBusy resolving 'cpu' on the first ask
    let n = 0
    const { spawn, calls } = fakeSpawn(() => (++n === 2 ? exitingChild(1) : new FakeChild())) // the GPU rung dies
    const good = rerankFetch()
    const rerankDocCounts: number[] = []
    const fetchImpl = (async (url: string | URL, init?: RequestInit) => {
      const u = String(url)
      if (calls.length === 2) throw new Error('connection refused') // the dying GPU attempt's own health check
      if (u.endsWith('/v1/rerank')) {
        const body = JSON.parse(String(init?.body)) as { documents: string[] }
        rerankDocCounts.push(body.documents.length)
      }
      return good(url, init)
    }) as typeof fetch
    const reranker = new LlamaReranker({
      ...base,
      spawn,
      fetchImpl,
      devicePosture: () => posture,
      cpuRequestCeiling: () => 48
    })
    await reranker.rerank('q1', docs(1)) // cold start #1: resident, recorded 'cpu'
    expect(calls.length).toBe(1)
    expect(calls[0]!.args).toContain('--device')
    rerankDocCounts.length = 0 // only the SECOND call's own /v1/rerank traffic matters below

    posture = 'gpu' // the chat start finished -- the NEXT ask resolves 'gpu' on both sides
    await expect(reranker.rerank('q2', docs(60))).rejects.toThrow(/refused/i)
    // Three spawns: the resident CPU sidecar torn down by the ORDINARY mismatch restart (rule
    // iii, which spends `restarted` -- not the demotion re-check), a GPU rung that then fails
    // genuinely, and the ladder's own CPU retry -- yet the ceiling still refuses THIS call's
    // 60-document request before it ever reaches that newly-demoted sidecar.
    expect(calls.length).toBe(3)
    expect(calls[1]!.args).not.toContain('--device') // the failing GPU rung
    expect(calls[2]!.args).toContain('--device') // the ladder's own CPU retry
    expect(rerankDocCounts).toHaveLength(0)
    expect(reranker.devicePosture()).toBe('cpu') // demoted, not latched

    // Not latched -- a follow-up call AT the ceiling is served by the now-resident CPU sidecar,
    // no further spawn.
    const hits2 = await reranker.rerank('q3', docs(48))
    expect(hits2).toHaveLength(48)
    expect(calls.length).toBe(3)
    await reranker.stop()
  })

  // #495 follow-up: only handleUnexpectedExit's OWN demotion branch reset unexpectedExitCount;
  // startLadder's demotion (a genuine cold-start failure) did not. So a GPU exit followed by a
  // genuine cold-start failure that demotes carried a STALE count into the newly-forced CPU
  // posture, and a single CPU exit afterwards wrongly latched permanently (the CPU posture never
  // got its own two-strikes budget the doc comment and commit message promise).
  it('#495 follow-up: the exit counter resets on the LADDER demotion path too -- one GPU exit, then a genuine cold-start failure that demotes, then ONE CPU exit is not latched', async () => {
    let n = 0
    // spawn #2: the failing GPU retry
    const { spawn, calls, children } = fakeSpawn(() => (++n === 2 ? exitingChild(1) : new FakeChild()))
    const good = rerankFetch()
    const fetchImpl = (async (url: string | URL, init?: RequestInit) => {
      if (calls.length === 2) throw new Error('connection refused') // spawn #2's own health check
      return good(url, init)
    }) as typeof fetch
    const fallbacks: string[] = []
    const reranker = new LlamaReranker({
      ...base,
      spawn,
      fetchImpl,
      devicePosture: () => 'gpu',
      onDeviceFallback: (reason) => fallbacks.push(reason)
    })
    await reranker.rerank('q1', docs(1)) // spawn #1: resident GPU sidecar
    children[0]!.crash() // unexpected exit #1 under GPU -- drops the handle; unexpectedExitCount = 1, no latch
    expect(fallbacks.length).toBe(0)

    // Cold-starts fresh on GPU (spawn #2), which fails genuinely and demotes to CPU (spawn #3)
    // WITHIN this same call -- the LADDER's demotion path, not handleUnexpectedExit's two-strikes.
    // Pre-fix this path never reset unexpectedExitCount, leaving the stale count of 1 in place.
    await reranker.rerank('q2', docs(1))
    expect(calls.length).toBe(3)
    expect(calls[1]!.args).not.toContain('--device')
    expect(calls[2]!.args).toContain('--device')
    expect(fallbacks.length).toBe(1)
    expect(fallbacks[0]).toMatch(/GPU-attempt start failed/)

    children[2]!.crash() // ONE unexpected exit under the now-demoted CPU posture.
    // Must NOT be latched -- the CPU posture gets its own two-strikes budget, same as a fresh
    // demotion; this only latches if the counter carried over the stale GPU-side count of 1.
    const hits = await reranker.rerank('q3', docs(1))
    expect(hits).toHaveLength(1)
    expect(calls.length).toBe(4) // lazily restarted CPU fine, no latch
    expect(calls[3]!.args).toContain('--device')
    await reranker.stop()
  })
})

// ---- Ruling (d): the resident sidecar's posture, read back -------------------------------------

describe('Wave 8 ruling (d): Reranker.devicePosture()', () => {
  it('reports the RESIDENT posture when loaded, and the posture a cold start would take now when not', async () => {
    const { spawn } = fakeSpawn()
    let posture: RerankerDevice = 'cpu'
    const reranker = new LlamaReranker({ ...base, spawn, fetchImpl: rerankFetch(), devicePosture: () => posture })
    expect(reranker.devicePosture()).toBe('cpu') // not loaded yet -- the posture a cold start would take
    await reranker.rerank('q', docs(1))
    posture = 'gpu' // an occupancy change AFTER this sidecar launched
    expect(reranker.devicePosture()).toBe('cpu') // the RESIDENT sidecar's actual (launch-time) posture
    await reranker.suspend()
    expect(reranker.devicePosture()).toBe('gpu') // nothing resident -- reports what a cold start would take now
    await reranker.stop()
  })
})

// ---- Scenarios S4, S5 (option B', the Wave 8 analysis §4) ---------------------------------------

// The project's own measured GTX 1070 Ti fixture (#391 leg 2, cited throughout opus-review-7.md
// and the Wave 8 analysis): {totalMb: 8273, freeMb: 7504}. qwen3.5-9b-ud-q4kxl needs ~7284.1 MiB
// (remainder 219.9 < the 2808.2 MiB floor) => posture 'cpu'. qwen3.5-4b-ud-q4kxl needs ~3837.4 MiB
// (remainder 3666.6 >= the floor) => posture 'gpu'.
const GTX_SETTINGS = {
  ...DEFAULT_SETTINGS,
  gpuMode: 'auto' as const,
  gpuAutoDisabled: false,
  gpuProbe: { devices: [CARDS.GTX_1070_TI], probedAt: new Date().toISOString() }
}
const NINE_B = 'qwen3.5-9b-ud-q4kxl'
const FOUR_B = 'qwen3.5-4b-ud-q4kxl'

/** The production posture callback on the GTX 1070 Ti fixture, over `runtime`'s committed model
 *  and the pending-switch counter. */
const gtxPosture =
  (
    runtime: ReturnType<typeof committingRuntime>,
    pending: ReturnType<typeof createPendingModelSwitchCounter>
  ) =>
  (): RerankerDevice =>
    resolveRerankerDevicePosture(GTX_SETTINGS, CATALOG_MANIFESTS, snapshotRerankerOccupancy(runtime, pending, () => null))

describe("Wave 8 scenarios S4, S5 (option B', the analysis §4)", () => {
  it('S4: 9B -> 4B; the FIRST ask after the commit restarts Q on the GPU', async () => {
    const { spawn, calls } = fakeSpawn()
    const runtime = committingRuntime(NINE_B)
    const pending = createPendingModelSwitchCounter()
    const reranker = new LlamaReranker({ ...base, spawn, fetchImpl: rerankFetch(), devicePosture: gtxPosture(runtime, pending) })
    await reranker.rerank('before', docs(1)) // resident, recorded 'cpu' (9B)
    expect(calls[0]!.args).toContain('--device')

    // The commit (startModelRuntime's suspend has already been awaited by this point --
    // posture-writers-wave8.test.ts's "placement" test).
    runtime.commit(FOUR_B)
    const hits = await reranker.rerank('first-after-commit', docs(1)) // Q detects the mismatch itself
    expect(hits).toHaveLength(1)
    expect(calls.length).toBe(2)
    expect(calls[1]!.args).not.toContain('--device') // restarted on the GPU
    await reranker.stop()
  })

  it("S5: mid-ask -- a wide ('all') set resolved on the resident 4B/gpu sidecar; Use on the 9B lands BEFORE this rerank() call -- G refuses the now-cpu-postured wide set", async () => {
    const { spawn, calls } = fakeSpawn()
    const runtime = committingRuntime(FOUR_B)
    const pending = createPendingModelSwitchCounter()
    const reranker = new LlamaReranker({
      ...base,
      spawn,
      fetchImpl: rerankFetch(),
      devicePosture: gtxPosture(runtime, pending),
      cpuRequestCeiling: () => 48
    })
    // BEFORE the Use click: a GPU rerank is correct for a wide (100-document) set.
    const before = await reranker.rerank('before-use', docs(100))
    expect(before).toHaveLength(100)
    expect(calls[0]!.args).not.toContain('--device')

    // Use on the 9B lands: startModelRuntime's pending counter goes up BEFORE this ask's own
    // rerank() call reaches the sidecar (the ask's retrieval/planning took long enough to overlap
    // it) -- during the pending window the posture is 'cpu' and G refuses the still-wide request.
    pending.increment()
    await expect(reranker.rerank('mid-ask-wide', docs(100))).rejects.toThrow(/refused/i)
    pending.decrement()
    expect(calls.length).toBe(1) // no GPU cold start beside the loading 9B, no CPU cold start either
    await reranker.stop()
  })
})

// ---- #530: the OS loader refused the engine program ---------------------------------------------

describe('#530: OS loader refusal is not a device fault', () => {
  afterEach(() => resetEngineProblemsForTest())

  /** The loader's line, as a program it refuses prints it before exiting 127. */
  const loaderLine =
    '/media/someone/HR/runtime/llama.cpp/linux/llama-server: error while loading shared libraries: libgomp.so.1: cannot open shared object file: No such file or directory\n'

  const refusingFetch = (async () => {
    throw new Error('connection refused')
  }) as unknown as typeof fetch

  it('on the gpu posture: ONE spawn, no CPU retry, gpuDemoted stays false, the latch holds', async () => {
    const { spawn, calls } = fakeSpawn(() => exitingChild(127, loaderLine))
    const fallbacks: string[] = []
    const reranker = new LlamaReranker({
      ...base,
      spawn,
      fetchImpl: refusingFetch,
      devicePosture: () => 'gpu',
      onDeviceFallback: (reason) => fallbacks.push(reason)
    })
    const err = await reranker.rerank('q', docs(1)).catch((e: unknown) => e)
    expect(isEngineCannotRunError(err)).toBe(true)
    expect(calls.length).toBe(1) // the same program would be refused again on the CPU rung
    expect(reranker.gpuDemoted()).toBe(false)
    expect(fallbacks).toEqual([])

    await expect(reranker.rerank('q2', docs(1))).rejects.toThrow() // latched
    expect(calls.length).toBe(1) // no second spawn
    await reranker.stop()
  })

  it('resetStartFailure() re-arms the latch: the next rerank spawns again', async () => {
    const { spawn, calls } = fakeSpawn(() => exitingChild(127, loaderLine))
    const reranker = new LlamaReranker({
      ...base,
      spawn,
      fetchImpl: refusingFetch,
      devicePosture: () => 'gpu'
    })
    await expect(reranker.rerank('q', docs(1))).rejects.toThrow()
    expect(calls.length).toBe(1)
    reranker.resetStartFailure()
    await expect(reranker.rerank('q2', docs(1))).rejects.toThrow() // still refused, but it TRIED
    expect(calls.length).toBe(2)
    await reranker.stop()
  })
})