AI, fully local on your computer.
TypeScript aiai-toolskiwixllama-cpplocal-ailocal-llmofflineoffline-aioffline-firstprivacy-firstragwikipediazim
import { describe, it, expect, vi, afterEach } from 'vitest'
import { t } from '../../src/shared/i18n'
// Benchmark persistence on a drive that TRAVELS (benchmark.md "Persistence" / "History per
// machine"; PR #303 audit M2 / M4 / M6 / L2):
// - identity before ranking: a foreign persisted effective-read sample is never carried into
// this machine's benchmark, its warning, or the #107 estimate; an unknown identity on
// either side stays eligible (G3, compatibility) and never earns a history entry;
// - the upgrade backfill: an outgoing `lastBenchmark` from another computer is filed into
// the history before a run, a restore, or a manual run replaces it — exactly once, and the
// cap evicts the oldest OTHER machine, never the one being restored;
// - a sample landing mid-run (drive or speed leg) survives the run's own persist;
// - the observer writes a sample to EVERY eligible destination, retries a failed or
// deferred write, and repairs a stale history entry beside an up-to-date headline.
vi.mock('electron', () => ({
ipcMain: {
handle: () => undefined,
removeHandler: () => undefined
},
app: { getVersion: () => '0.0.0-test' }
}))
import { runAndPersistBenchmark } from '../../src/main/ipc/registerBenchmarkIpc'
import { effectiveReadOrPersisted, persistEffectiveRead, registerModelIpc } from '../../src/main/ipc/registerModelIpc'
import { upsertSlowReadWarning } from '../../src/main/services/benchmark'
import type { Db } from '../../src/main/services/db'
import { machineKey, upsertHistory } from '../../src/main/services/performance'
import { latestEffectiveRead, latestEffectiveReadBySource, recordChecksumRead } from '../../src/main/services/read-speed'
import { getSettings, updateSettings } from '../../src/main/services/settings'
import { MAX_BENCHMARK_HISTORY, type BenchmarkProgressStep, type EffectiveReadSample } from '../../src/shared/types'
import { effectiveReadSample } from '../helpers/benchmark-records'
import {
closePerformanceFixture,
ctxWith,
firstBenchmarkNow,
freshRoot,
hereKey,
hereResult,
loadSample,
result,
seededDb,
stubChatRuntime
} from '../helpers/performance-fixture'
/** A model-load sample measured on some other computer (slow enough to carry the #110 warning). */
const foreignSample = effectiveReadSample({
mbps: 70,
bytes: 3_000_000_000,
ms: 42_857,
source: 'model_load',
modelId: 'foreign-model',
at: '2026-08-01T00:00:00Z'
})
const slowReadWarning = (mbps: number): string => t('en', 'main.benchmark.warnSlowRead', { mbps })
const hasSlowReadWarning = (warnings: readonly string[]): boolean =>
warnings.some((w) => w.includes('model starts will be slow'))
/** A DB whose FIRST settings write fails (the INSERT prepare throws), then behaves. */
function failingFirstWrite(db: Db): Db {
let armed = true
return new Proxy(db, {
get(target, prop) {
if (prop === 'prepare') {
return (sql: string) => {
if (armed && /^INSERT INTO settings/.test(sql.trim())) {
armed = false
throw new Error('simulated write failure')
}
return target.prepare(sql)
}
}
const value = Reflect.get(target, prop, target)
return typeof value === 'function' ? value.bind(target) : value
}
})
}
// TH2: every root/DB here comes from the fixture's `freshRoot`/`seededDb`; its teardown resets the
// session latches and observers, closes the DBs and removes the roots.
afterEach(closePerformanceFixture)
describe('identity before ranking (M2)', () => {
it('a NEW computer does not inherit a foreign persisted model-load sample, nor its warning', async () => {
const root = freshRoot()
const db = seededDb(root)
const foreign = result({ effectiveRead: foreignSample, warnings: [slowReadWarning(70)] })
updateSettings(db, { lastBenchmark: foreign })
const fresh = await runAndPersistBenchmark(ctxWith(root, db))
expect(fresh.effectiveRead).toBeNull()
expect(hasSlowReadWarning(fresh.warnings)).toBe(false)
expect(getSettings(db).lastBenchmark?.effectiveRead).toBeNull()
// …while the outgoing computer, filed by the run's backfill, keeps its own warning.
const kept = getSettings(db).benchmarkHistory.find((e) => e.cpuModel === foreign.cpuModel)
expect(kept?.warnings).toEqual([slowReadWarning(70)])
})
it('a local checksum sample beats a foreign persisted model-load sample', () => {
const root = freshRoot()
const db = seededDb(root)
updateSettings(db, { lastBenchmark: result({ effectiveRead: foreignSample }) })
recordChecksumRead(3_000_000_000, 30_000, 'local-model')
expect(effectiveReadOrPersisted(ctxWith(root, db))?.modelId).toBe('local-model')
})
it('same machine: a persisted model_load outranks a session checksum; a newer same-source sample wins', () => {
const root = freshRoot()
const db = seededDb(root)
const persisted: EffectiveReadSample = { ...foreignSample, modelId: 'persisted-load', mbps: 400 }
updateSettings(db, { lastBenchmark: hereResult({ effectiveRead: persisted }) })
const ctx = ctxWith(root, db)
recordChecksumRead(3_000_000_000, 30_000, 'session-checksum')
expect(effectiveReadOrPersisted(ctx)?.modelId).toBe('persisted-load')
loadSample('session-load')
expect(effectiveReadOrPersisted(ctx)?.modelId).toBe('session-load')
})
it("this machine's history entry supplies the sample when lastBenchmark is foreign", () => {
const root = freshRoot()
const db = seededDb(root)
const mine: EffectiveReadSample = { ...foreignSample, modelId: 'my-load', mbps: 450, at: '2026-07-01T00:00:00Z' }
const foreign = result({ effectiveRead: foreignSample })
updateSettings(db, { lastBenchmark: foreign, benchmarkHistory: [foreign, hereResult({ effectiveRead: mine })] })
expect(effectiveReadOrPersisted(ctxWith(root, db))?.modelId).toBe('my-load')
})
it('G3: an unkeyed legacy result stays eligible (compatibility) and never earns a history entry', async () => {
const root = freshRoot()
const db = seededDb(root)
const legacy = hereResult({ cpuModel: '', effectiveRead: { ...foreignSample, modelId: 'legacy-load' } })
expect(machineKey(legacy)).toBeNull()
updateSettings(db, { lastBenchmark: legacy })
const ctx = ctxWith(root, db)
registerModelIpc(ctx)
// Carried forward: unknown identity on the persisted side reads as "this machine".
expect(effectiveReadOrPersisted(ctx)?.modelId).toBe('legacy-load')
// The observer updates the unkeyed headline in place, but files nothing under a key.
loadSample('local-load')
expect(getSettings(db).lastBenchmark?.effectiveRead?.modelId).toBe('local-load')
expect(getSettings(db).benchmarkHistory).toEqual([])
// A run keeps the (now local) sample and files only ITS keyed result.
const fresh = await runAndPersistBenchmark(ctx)
expect(fresh.effectiveRead?.modelId).toBe('local-load')
const history = getSettings(db).benchmarkHistory
expect(history).toHaveLength(1)
expect(machineKey(history[0])).toBe(hereKey())
})
})
describe('upgrade backfill (M4)', () => {
it('first move with NO history row keeps the old computer', async () => {
const root = freshRoot()
const db = seededDb(root)
const foreign = result()
updateSettings(db, { lastBenchmark: foreign })
db.prepare("DELETE FROM settings WHERE key = 'benchmarkHistory'").run()
expect(getSettings(db).benchmarkHistory).toEqual([])
// TH2: a direct call with an obtainable handle — await the scheduler's own outcome (P7)
// instead of polling for the state it guarantees on 'ran'.
await expect(firstBenchmarkNow(ctxWith(root, db))).resolves.toBe('ran')
expect(machineKey(getSettings(db).lastBenchmark)).toBe(hereKey())
const history = getSettings(db).benchmarkHistory
expect(history).toHaveLength(2)
expect(history.filter((e) => machineKey(e) === machineKey(foreign))).toHaveLength(1)
expect(history.find((e) => machineKey(e) === machineKey(foreign))).toEqual(foreign)
})
it('a manual first move (runAndPersistBenchmark, no history) keeps the old computer', async () => {
const root = freshRoot()
const db = seededDb(root)
const foreign = result()
updateSettings(db, { lastBenchmark: foreign })
const fresh = await runAndPersistBenchmark(ctxWith(root, db))
const s = getSettings(db)
expect(s.lastBenchmark?.ranAt).toBe(fresh.ranAt)
expect(s.benchmarkHistory.map((e) => e.cpuModel)).toEqual([fresh.cpuModel, foreign.cpuModel])
})
it('same machine: the startup branch seeds the history without a rerun', async () => {
const root = freshRoot()
const db = seededDb(root)
const mine = hereResult()
updateSettings(db, { lastBenchmark: mine })
const ctx = ctxWith(root, db)
// Nothing owed: the outcome says no run was scheduled at all.
await expect(firstBenchmarkNow(ctx)).resolves.toBe('not-needed')
// Seeded, headline untouched.
expect(getSettings(db).benchmarkHistory).toEqual([mine])
expect(getSettings(db).lastBenchmark).toEqual(mine)
})
it('restore (A→B→A) brings back the NEWEST outgoing sample, the one that landed mid-run', async () => {
const root = freshRoot()
const db = seededDb(root)
const mine = hereResult({ effectiveRead: { ...foreignSample, modelId: 'before-run', mbps: 300 } })
updateSettings(db, { lastBenchmark: mine, benchmarkHistory: [mine] })
const ctx = ctxWith(root, db)
registerModelIpc(ctx)
// On A: a model load lands while the benchmark runs.
const ran = await runAndPersistBenchmark(ctx, (step) => {
if (step === 'drive') loadSample('mid-run')
})
expect(ran.effectiveRead?.modelId).toBe('mid-run')
// The drive goes to B (its run replaces the headline and files B).
const b = result()
updateSettings(db, { lastBenchmark: b, benchmarkHistory: upsertHistory(getSettings(db).benchmarkHistory, b) })
expect(getSettings(db).lastBenchmark?.cpuModel).toBe(b.cpuModel)
// …and back to A.
await expect(firstBenchmarkNow(ctx)).resolves.toBe('not-needed')
const restored = getSettings(db).lastBenchmark
expect(restored?.ranAt).toBe(ran.ranAt)
expect(restored?.effectiveRead?.modelId).toBe('mid-run')
expect(getSettings(db).benchmarkHistory).toHaveLength(2)
})
it('restore backfills a foreign outgoing headline that the history does not hold yet', async () => {
const root = freshRoot()
const db = seededDb(root)
const known = hereResult()
const foreign = result()
updateSettings(db, { lastBenchmark: foreign, benchmarkHistory: [known] })
await expect(firstBenchmarkNow(ctxWith(root, db))).resolves.toBe('not-needed')
expect(getSettings(db).lastBenchmark).toEqual(known)
expect(getSettings(db).benchmarkHistory.map((e) => e.cpuModel)).toEqual([foreign.cpuModel, known.cpuModel])
})
it('at capacity, a restore keeps the restored entry and evicts the oldest OTHER machine', async () => {
const root = freshRoot()
const db = seededDb(root)
const others = Array.from({ length: MAX_BENCHMARK_HISTORY - 1 }, (_, i) =>
result({ cpuModel: `other-${i + 1}`, ranAt: `2026-0${i + 1}-01T00:00:00Z` })
)
const known = hereResult({ ranAt: '2026-04-15T00:00:00Z' })
// Newest first, this machine in the middle of the pack.
const history = [...others, known].sort((a, b) => (a.ranAt < b.ranAt ? 1 : -1))
expect(history).toHaveLength(MAX_BENCHMARK_HISTORY)
const outgoing = result({ cpuModel: 'outgoing', ranAt: '2026-08-01T00:00:00Z' })
updateSettings(db, { lastBenchmark: outgoing, benchmarkHistory: history })
await expect(firstBenchmarkNow(ctxWith(root, db))).resolves.toBe('not-needed')
const after = getSettings(db).benchmarkHistory
expect(getSettings(db).lastBenchmark).toEqual(known)
expect(after).toHaveLength(MAX_BENCHMARK_HISTORY)
expect(after.some((e) => machineKey(e) === hereKey())).toBe(true)
expect(after.some((e) => e.cpuModel === 'outgoing')).toBe(true)
expect(after.some((e) => e.cpuModel === 'other-1')).toBe(false)
expect(after.map((e) => e.ranAt)).toEqual([...after.map((e) => e.ranAt)].sort().reverse())
})
it('at capacity, a run on a new machine keeps the outgoing computer and this one; the oldest others go', async () => {
const root = freshRoot()
const db = seededDb(root)
const others = Array.from({ length: MAX_BENCHMARK_HISTORY }, (_, i) =>
result({ cpuModel: `other-${i + 1}`, ranAt: `2026-0${i + 1}-01T00:00:00Z` })
).reverse()
const outgoing = result({ cpuModel: 'outgoing', ranAt: '2026-09-01T00:00:00Z' })
updateSettings(db, { lastBenchmark: outgoing, benchmarkHistory: others })
await runAndPersistBenchmark(ctxWith(root, db))
const after = getSettings(db).benchmarkHistory
expect(after).toHaveLength(MAX_BENCHMARK_HISTORY)
expect(machineKey(after[0])).toBe(hereKey())
expect(after[1].cpuModel).toBe('outgoing')
expect(after.some((e) => e.cpuModel === 'other-1')).toBe(false)
expect(after.some((e) => e.cpuModel === 'other-2')).toBe(false)
expect(after.some((e) => e.cpuModel === 'other-3')).toBe(true)
})
})
describe('a sample landing mid-run survives the persist (M6)', () => {
it('at the drive step boundary — the result, the headline and the history carry it, with its warning', async () => {
const root = freshRoot()
const db = seededDb(root)
const mine = hereResult({ effectiveRead: { ...foreignSample, modelId: 'before-run', mbps: 300 } })
updateSettings(db, { lastBenchmark: mine, benchmarkHistory: [mine] })
const ctx = ctxWith(root, db)
registerModelIpc(ctx)
let observedPersist = false
const fresh = await runAndPersistBenchmark(ctx, (step) => {
if (step === 'drive') {
loadSample('mid-run', 50_000) // 60 MB/s: below the #110 gate
observedPersist = getSettings(db).lastBenchmark?.effectiveRead?.modelId === 'mid-run'
}
})
expect(observedPersist).toBe(true)
expect(latestEffectiveRead()?.modelId).toBe('mid-run')
expect(fresh.effectiveRead?.modelId).toBe('mid-run')
expect(fresh.warnings).toContain(slowReadWarning(60))
const s = getSettings(db)
expect(s.lastBenchmark).toEqual(fresh)
expect(s.benchmarkHistory).toHaveLength(1)
expect(s.benchmarkHistory[0]).toEqual(fresh)
})
it('at the speed step boundary (a runtime is up, so the speed leg runs)', async () => {
const root = freshRoot()
const db = seededDb(root)
const mine = hereResult({ effectiveRead: { ...foreignSample, modelId: 'before-run', mbps: 300 } })
updateSettings(db, { lastBenchmark: mine, benchmarkHistory: [mine] })
// ONE runtime object, handed out on every call — `RuntimeManager.active()` returns
// `this.current`, a single instance per committed start, and since #393 the speed leg's busy
// predicate compares the runtime it captured against what the manager holds now.
const running = stubChatRuntime()
const ctx = ctxWith(root, db, { runtime: running })
registerModelIpc(ctx)
const steps: BenchmarkProgressStep[] = []
const fresh = await runAndPersistBenchmark(ctx, (step) => {
steps.push(step)
if (step === 'speed') loadSample('after-speed')
})
expect(steps).toEqual(['system', 'drive', 'speed', 'done'])
expect(fresh.tokensPerSecond).toBe(20)
expect(fresh.effectiveRead?.modelId).toBe('after-speed')
expect(getSettings(db).lastBenchmark?.effectiveRead?.modelId).toBe('after-speed')
expect(getSettings(db).benchmarkHistory[0].effectiveRead?.modelId).toBe('after-speed')
})
})
describe('the observer persists to every eligible destination (L2)', () => {
it('updates both lastBenchmark and the matching history entry', () => {
const root = freshRoot()
const db = seededDb(root)
const mine = hereResult()
updateSettings(db, { lastBenchmark: mine, benchmarkHistory: [mine] })
registerModelIpc(ctxWith(root, db))
loadSample('local-model')
const s = getSettings(db)
expect(s.lastBenchmark?.effectiveRead?.modelId).toBe('local-model')
expect(s.benchmarkHistory[0].effectiveRead?.modelId).toBe('local-model')
// A sample-only update is not a new run.
expect(s.lastBenchmark?.ranAt).toBe(mine.ranAt)
expect(s.benchmarkHistory[0].ranAt).toBe(mine.ranAt)
})
it('foreign lastBenchmark + local history: the history entry only, the foreign headline untouched', () => {
const root = freshRoot()
const db = seededDb(root)
const foreign = result({ effectiveRead: foreignSample })
const mine = hereResult()
updateSettings(db, { lastBenchmark: foreign, benchmarkHistory: [foreign, mine] })
registerModelIpc(ctxWith(root, db))
loadSample('local-model')
const s = getSettings(db)
expect(s.lastBenchmark).toEqual(foreign)
expect(s.benchmarkHistory.find((e) => machineKey(e) === hereKey())?.effectiveRead?.modelId).toBe('local-model')
expect(s.benchmarkHistory.find((e) => e.cpuModel === foreign.cpuModel)).toEqual(foreign)
})
it('repairs a stale history entry beside a headline that already carries the sample', () => {
const root = freshRoot()
const db = seededDb(root)
loadSample('local-model') // no observer registered: latched only
const sample = latestEffectiveRead()!
updateSettings(db, {
lastBenchmark: hereResult({ effectiveRead: sample }),
benchmarkHistory: [hereResult()]
})
persistEffectiveRead(ctxWith(root, db))
const s = getSettings(db)
expect(s.benchmarkHistory[0].effectiveRead).toEqual(sample)
expect(s.lastBenchmark?.effectiveRead).toEqual(sample)
})
it('a same-machine model_load destination keeps its sample against a session checksum', () => {
const root = freshRoot()
const db = seededDb(root)
const persisted: EffectiveReadSample = { ...foreignSample, modelId: 'persisted-load', mbps: 400 }
const mine = hereResult({ effectiveRead: persisted })
updateSettings(db, { lastBenchmark: mine, benchmarkHistory: [mine] })
registerModelIpc(ctxWith(root, db))
recordChecksumRead(3_000_000_000, 30_000, 'session-checksum')
const s = getSettings(db)
expect(s.lastBenchmark?.effectiveRead?.modelId).toBe('persisted-load')
expect(s.benchmarkHistory[0].effectiveRead?.modelId).toBe('persisted-load')
})
it('with no eligible destination nothing is written and the sample is NOT marked handled', () => {
const root = freshRoot()
const db = seededDb(root)
const foreign = result({ effectiveRead: foreignSample })
updateSettings(db, { lastBenchmark: foreign })
const ctx = ctxWith(root, db)
registerModelIpc(ctx)
loadSample('local-model')
expect(getSettings(db)).toMatchObject({ lastBenchmark: foreign, benchmarkHistory: [] })
// A local entry appears later (a restore, an upgrade seed): the retry lands the sample.
updateSettings(db, { benchmarkHistory: [foreign, hereResult()] })
persistEffectiveRead(ctx)
expect(getSettings(db).lastBenchmark).toEqual(foreign)
expect(getSettings(db).benchmarkHistory[1].effectiveRead?.modelId).toBe('local-model')
})
it('retries after a failed write (the first INSERT throws) — the next call persists', () => {
const root = freshRoot()
const db = seededDb(root)
const mine = hereResult()
updateSettings(db, { lastBenchmark: mine, benchmarkHistory: [mine] })
const ctx = ctxWith(root, failingFirstWrite(db))
registerModelIpc(ctx)
loadSample('local-model') // observer-time write fails
expect(getSettings(db).lastBenchmark?.effectiveRead).toBeNull()
persistEffectiveRead(ctx) // the post-start/list/verify retry
expect(getSettings(db).lastBenchmark?.effectiveRead?.modelId).toBe('local-model')
expect(getSettings(db).benchmarkHistory[0].effectiveRead?.modelId).toBe('local-model')
})
it('retries after a deferred write (the workspace was locked at observer time)', () => {
const root = freshRoot()
const db = seededDb(root)
const mine = hereResult()
updateSettings(db, { lastBenchmark: mine, benchmarkHistory: [mine] })
let locked = true
const ctx = ctxWith(root, db)
// The real context resolves `db` through the vault (`requireDb`), which throws while locked.
Object.defineProperty(ctx, 'db', {
get: () => {
if (locked) throw new Error('Workspace is locked')
return db
}
})
registerModelIpc(ctx)
loadSample('local-model')
expect(getSettings(db).lastBenchmark?.effectiveRead).toBeNull()
locked = false
persistEffectiveRead(ctx)
expect(getSettings(db).lastBenchmark?.effectiveRead?.modelId).toBe('local-model')
expect(getSettings(db).benchmarkHistory[0].effectiveRead?.modelId).toBe('local-model')
})
it('the memo is scoped to the DB handle: a re-opened workspace re-evaluates the same sample', () => {
const rootA = freshRoot()
const dbA = seededDb(rootA)
updateSettings(dbA, { lastBenchmark: hereResult() })
registerModelIpc(ctxWith(rootA, dbA))
loadSample('local-model')
const sample = latestEffectiveRead()!
expect(getSettings(dbA).lastBenchmark?.effectiveRead).toEqual(sample)
// A second workspace (a lock/unlock yields a new handle) with a bare result of its own.
const rootB = freshRoot()
const dbB = seededDb(rootB)
updateSettings(dbB, { lastBenchmark: hereResult(), benchmarkHistory: [hereResult()] })
persistEffectiveRead(ctxWith(rootB, dbB))
const s = getSettings(dbB)
expect(s.lastBenchmark?.effectiveRead).toEqual(sample)
expect(s.benchmarkHistory[0].effectiveRead).toEqual(sample)
})
})
describe('unchanged #110: the slow-read warning tracks the eligible sample only', () => {
it('a slow local sample re-keys the warning on both destinations; a fast one removes it', () => {
const root = freshRoot()
const db = seededDb(root)
const tiny = t('en', 'main.benchmark.warnTiny')
const mine = hereResult({ warnings: [tiny] })
updateSettings(db, { lastBenchmark: mine, benchmarkHistory: [mine] })
registerModelIpc(ctxWith(root, db))
loadSample('slow', 50_000) // 60 MB/s
let s = getSettings(db)
expect(s.lastBenchmark?.warnings).toEqual([tiny, slowReadWarning(60)])
expect(s.benchmarkHistory[0].warnings).toEqual([tiny, slowReadWarning(60)])
loadSample('fast', 6_000) // 500 MB/s
s = getSettings(db)
expect(s.lastBenchmark?.warnings).toEqual([tiny])
expect(s.benchmarkHistory[0].warnings).toEqual([tiny])
expect(s.lastBenchmark?.ranAt).toBe(mine.ranAt)
})
})
describe('strictly increasing sample timestamps (A-D4): same-millisecond samples stay distinct to the persister', () => {
/** Both destinations this machine's, the observer registered, the clock FROZEN at one instant. */
function frozenSession(): { db: Db; frozen: Date } {
const root = freshRoot()
const db = seededDb(root)
const mine = hereResult()
updateSettings(db, { lastBenchmark: mine, benchmarkHistory: [mine] })
registerModelIpc(ctxWith(root, db))
const frozen = new Date('2026-09-06T12:00:00.000Z')
vi.useFakeTimers({ toFake: ['Date'] })
vi.setSystemTime(frozen) // the same reading for every sample
return { db, frozen }
}
afterEach(() => {
vi.useRealTimers()
})
it('a model load in the same millisecond as the checksum before it reaches BOTH destinations', () => {
const { db, frozen } = frozenSession()
recordChecksumRead(3_000_000_000, 30_000, 'hash-first')
const first = getSettings(db).lastBenchmark?.effectiveRead
expect(first).toMatchObject({ modelId: 'hash-first', at: frozen.toISOString() })
// Outranks the checksum — but it used to carry the SAME `at`, so the handled memo (and each
// destination's "already carries this sample" check) read it as the one already written.
loadSample('load-second')
const s = getSettings(db)
expect(s.lastBenchmark?.effectiveRead).toMatchObject({ modelId: 'load-second', source: 'model_load' })
expect(s.benchmarkHistory[0].effectiveRead).toMatchObject({ modelId: 'load-second', source: 'model_load' })
expect(s.lastBenchmark!.effectiveRead!.at > first!.at).toBe(true)
})
it('a checksum in the same millisecond as the model load before it is a distinct, lower-ranked sample: both destinations keep the load', () => {
const { db } = frozenSession()
loadSample('load-first')
recordChecksumRead(3_000_000_000, 30_000, 'hash-second')
const s = getSettings(db)
expect(s.lastBenchmark?.effectiveRead?.modelId).toBe('load-first')
expect(s.benchmarkHistory[0].effectiveRead?.modelId).toBe('load-first')
// The observed rows still tell the two apart.
expect(latestEffectiveReadBySource('checksum')!.at > latestEffectiveReadBySource('model_load')!.at).toBe(true)
})
})
// #392: the hash-then-start journey. The Models screen hashed the weight (before #382 it hashed
// the whole corpus before a model could be chosen; since #382 the "Check all model files" action
// does), the start hits the size+mtime cache so nothing suppressed its window, the #114 prefetch
// pulled RAM, and the resulting model_load sample
// (589 MB/s for a 28 MB/s stick — #334 leg B1) outranked the honest checksum FOREVER:
// `preferCandidate` never lets a checksum displace a model_load, on the latch or on any
// persisted destination. So the 100 MB/s slow-read warning was dropped on the exact machine
// class the feature exists for.
describe('a weight hashed this session never persists a page-cache load figure (#392)', () => {
const WEIGHT = '/models/corpus/w.gguf'
it('the checksum figure survives the start that follows it — on both destinations, warning intact', () => {
const root = freshRoot()
const db = seededDb(root)
const mine = hereResult()
updateSettings(db, { lastBenchmark: mine, benchmarkHistory: [mine] })
registerModelIpc(ctxWith(root, db))
// The Models screen hashes the weight: 3 GB in 100 s = 30 MB/s, well under the #110 gate.
recordChecksumRead(3_000_000_000, 100_000, 'corpus-model', WEIGHT)
// …then the user starts that model. Page-cache-warm: 300 MB/s of RAM, not of the stick.
loadSample('corpus-model', 10_000, WEIGHT)
expect(latestEffectiveRead()?.source).toBe('checksum')
const s = getSettings(db)
expect(s.lastBenchmark?.effectiveRead).toMatchObject({ source: 'checksum', mbps: 30 })
expect(s.benchmarkHistory[0].effectiveRead).toMatchObject({ source: 'checksum', mbps: 30 })
expect(hasSlowReadWarning(s.lastBenchmark!.warnings)).toBe(true)
expect(hasSlowReadWarning(s.benchmarkHistory[0].warnings)).toBe(true)
})
it('a start of a weight nothing hashed still persists its model_load sample', () => {
const root = freshRoot()
const db = seededDb(root)
const mine = hereResult()
updateSettings(db, { lastBenchmark: mine, benchmarkHistory: [mine] })
registerModelIpc(ctxWith(root, db))
// 3 GB in 20 s = 150 MB/s. #404 made the SPEED of this unrelated incumbent load-bearing:
// a checksum under SLOW_READ_MBPS is media-bound and a model_load no longer displaces it,
// so the original 100 s (30 MB/s) would now assert #404's rule instead of this test's own
// subject — that a start of a weight NOTHING hashed still samples.
recordChecksumRead(3_000_000_000, 20_000, 'other-model', '/models/corpus/other.gguf')
loadSample('corpus-model', 10_000, WEIGHT)
const s = getSettings(db)
expect(s.lastBenchmark?.effectiveRead).toMatchObject({ source: 'model_load', modelId: 'corpus-model' })
expect(hasSlowReadWarning(s.lastBenchmark!.warnings)).toBe(false)
})
})
// #404: the WARM RELAUNCH, one session later. Nothing hashes on a relaunch — the checksum store
// answers from (size, mtime) — so #392's suppression has nothing to fire on, and the auto-start's
// load window times the OS page cache. Before #404 that page-cache figure displaced the honest
// media-bound checksum sample on both destinations, and the #110 slow-read warning went with it;
// every relaunch re-persisted it, so the state oscillated for as long as the drive stayed slow.
describe('a warm relaunch never displaces a media-bound checksum figure (#404)', () => {
const WEIGHT = '/models/corpus/w.gguf'
it('the persisted 30 MB/s checksum survives a page-cache load on BOTH destinations, warning intact', () => {
const root = freshRoot()
const db = seededDb(root)
const mine = hereResult()
// Session 1 hashed the weight and persisted the honest figure to both destinations.
const honest: EffectiveReadSample = {
mbps: 30,
bytes: 3_000_000_000,
ms: 100_000,
source: 'checksum',
modelId: 'corpus-model',
at: '2026-09-07T09:00:00.000Z'
}
const carried = { ...mine, effectiveRead: honest, warnings: upsertSlowReadWarning(mine.warnings, 30) }
updateSettings(db, { lastBenchmark: carried, benchmarkHistory: [carried] })
registerModelIpc(ctxWith(root, db))
// Session 2: a warm relaunch. Nothing hashed, so the start's own install check is a cache
// hit and its window measures RAM — 3 GB in 10 s = 300 MB/s for a 30 MB/s stick.
loadSample('corpus-model', 10_000, WEIGHT)
const s = getSettings(db)
expect(s.lastBenchmark?.effectiveRead).toMatchObject({ source: 'checksum', mbps: 30 })
expect(s.benchmarkHistory[0].effectiveRead).toMatchObject({ source: 'checksum', mbps: 30 })
expect(hasSlowReadWarning(s.lastBenchmark!.warnings)).toBe(true)
expect(hasSlowReadWarning(s.benchmarkHistory[0].warnings)).toBe(true)
// The live latch agrees with what was persisted (one ranking rule, four call sites).
expect(effectiveReadOrPersisted(ctxWith(root, db))).toMatchObject({ source: 'checksum', mbps: 30 })
// The observed rows still show the load the session actually did.
expect(latestEffectiveReadBySource('model_load')?.modelId).toBe('corpus-model')
})
it('half 1 repairs a machine that already carries a page-cache figure', () => {
const root = freshRoot()
const db = seededDb(root)
const mine = hereResult()
// The pre-#404 state: 589 MB/s persisted for a 28 MB/s stick (#334 leg B1), no warning.
const inflated: EffectiveReadSample = {
mbps: 589,
bytes: 3_000_000_000,
ms: 5_093,
source: 'model_load',
modelId: 'corpus-model',
at: '2026-09-07T09:00:00.000Z'
}
const carried = { ...mine, effectiveRead: inflated }
updateSettings(db, { lastBenchmark: carried, benchmarkHistory: [carried] })
registerModelIpc(ctxWith(root, db))
// One "Check all model files" pass (or any cold hash) is enough to correct it.
recordChecksumRead(3_000_000_000, 100_000, 'corpus-model', WEIGHT)
const s = getSettings(db)
expect(s.lastBenchmark?.effectiveRead).toMatchObject({ source: 'checksum', mbps: 30 })
expect(s.benchmarkHistory[0].effectiveRead).toMatchObject({ source: 'checksum', mbps: 30 })
expect(hasSlowReadWarning(s.lastBenchmark!.warnings)).toBe(true)
})
})