Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions app/electron/agent/engine/cli.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,46 @@ async function main() {
assert.deepEqual(info, { family: 'Qwen3.8 Flash Next', modelType: 'qwen4_exp', format: '6-bit, group 32', contextTokens: 65536, weightsBytes: 12884901888, memoryFloorBytes: 12884901888 + 2 * 1024 ** 3 })
assert.throws(() => parseInfoOutput('Org/X is not in the Hugging Face cache; run: tensorfold pull Org/X\n'), /not in the Hugging Face cache/)

// Engine 1.3.0 prints a startup budget instead of the memory floor for priced families. The budget
// already covers weights, KV/state and the runtime reserve, so the printed GiB figure is the floor.
const qwen27 = parseInfoOutput([
'family: Qwen3.8-27B (qwen3_5)',
'format: 4-bit, group 64',
'context: 262144',
'weights: 14.95 GiB (16054541349 bytes)',
'startup budget: 16.20 GiB at --context 262144: weights, 2 streams of KV and state, 512-row prompt scratch (no drafter or images)',
'this Mac: fits beside its 8.0 GiB Metal working set and an 2 GiB margin',
].join('\n'))
assert.deepEqual(qwen27, { family: 'Qwen3.8-27B', modelType: 'qwen3_5', format: '4-bit, group 64', contextTokens: 262144, weightsBytes: 16054541349, memoryFloorBytes: Math.round(16.2 * 1024 ** 3) })
// Metal Flash Next prints the conservative plan plus a cold pack line the parser must ignore.
const flashNext = parseInfoOutput([
'family: Qwen3.8 Flash Next (qwen4_exp)',
'format: 4-bit, group 32',
'context: 262144',
'weights: 12.00 GiB (12884901888 bytes)',
'startup budget: 12.34 GiB (conservative raw/packed text weights, both prompt planes/selectors, KV/state, keepalive and 2 GiB runtime reserve; trained window)',
'cold pack budget: 14.56 GiB (source pages, one output phase and conversion scratch; skipped with a validated pack; vision and requested storage are additional at load)',
].join('\n'))
assert.deepEqual(flashNext, { family: 'Qwen3.8 Flash Next', modelType: 'qwen4_exp', format: '4-bit, group 32', contextTokens: 262144, weightsBytes: 12884901888, memoryFloorBytes: Math.round(12.34 * 1024 ** 3) })
// An unpriced budget is still a parse failure, reported as the first printed line.
assert.throws(() => parseInfoOutput([
'family: Qwen3.8-27B (qwen3_5)',
'format: 4-bit, group 64',
'context: 262144',
'weights: 14.95 GiB (16054541349 bytes)',
'startup budget: not priced (--context is past this checkpoint\'s max_position_embeddings)',
].join('\n')), /^Error: family: Qwen3\.8-27B \(qwen3_5\)$/)
// An unpriced budget with the floor still printed after it is the engine's exit-0 fallback: the floor wins.
const unpriced = parseInfoOutput([
'family: Qwen3.8-27B (qwen3_5)',
'format: 4-bit, group 64',
'context: 262144',
'weights: 14.95 GiB (16054541349 bytes)',
'startup budget: not priced (UnqualifiedQwenShape)',
'memory floor: 16.95 GiB (weights plus a 2.00 GiB runtime margin)',
].join('\n'))
assert.equal(unpriced.memoryFloorBytes, 16054541349 + 2 * 1024 ** 3, 'the memory floor sizes an unpriced checkpoint')

const caps = parseCapabilities('{"schema": 1, "engine": "zig", "version": "1.0.7", "chip": null, "backends": ["auto", "mlx"], "families": {"nemotron_h": ["mlx-q4g64"], "qwen3_5": ["mlx-q4g64"]}, "serve": {"flags": {"--host": {}, "--drafter": {}}}, "env": ["TENSORFOLD_API_KEY"]}\n')
assert.deepEqual(caps.families, { nemotron_h: ['mlx-q4g64'], qwen3_5: ['mlx-q4g64'] })
assert.deepEqual(caps.flags, ['--host', '--drafter'])
Expand Down
12 changes: 9 additions & 3 deletions app/electron/agent/engine/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,17 +60,23 @@ export function parseInfoOutput(text: string): ModelInfo {
const family = /^(.+) \(([A-Za-z0-9_.-]+)\)$/.exec(field('family') ?? '')
const weights = /\((\d+) bytes\)/.exec(field('weights') ?? '')
const floor = /^([\d.]+) GiB \(weights plus a ([\d.]+) GiB runtime margin\)$/.exec(field('memory floor') ?? '')
if (!family || !weights || !floor) throw new Error(text.trim().split(/\r?\n/)[0] || 'tensorfold-native info printed nothing.')
// 1.3.0 prints a startup budget instead of the floor for priced families; the budget already covers
// weights, KV/state and the runtime reserve, so its printed GiB figure is the floor. A trailing
// "cold pack budget:" line is not read. "startup budget: not priced (...)" matches neither.
const budget = /^(\d+(?:\.\d+)?) GiB\b/.exec(field('startup budget') ?? '')
if (!family || !weights || (!floor && !budget)) throw new Error(text.trim().split(/\r?\n/)[0] || 'tensorfold-native info printed nothing.')
const weightsBytes = Number(weights[1])
const context = Number(field('context'))
// Recompute from exact bytes: weights plus the printed runtime margin, or take the printed budget.
const memoryFloorBytes = floor ? weightsBytes + Math.round(Number(floor[2]) * GIB) : Math.round(Number(budget![1]) * GIB)
if (!Number.isFinite(memoryFloorBytes)) throw new Error(text.trim().split(/\r?\n/)[0] || 'tensorfold-native info printed nothing.')
return {
family: family[1],
modelType: family[2],
format: field('format'),
contextTokens: Number.isFinite(context) && context > 0 ? context : null,
weightsBytes,
// Recompute from exact bytes: weights plus the printed runtime margin.
memoryFloorBytes: weightsBytes + Math.round(Number(floor[2]) * GIB),
memoryFloorBytes,
}
}

Expand Down
87 changes: 87 additions & 0 deletions app/electron/agent/engine/service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@ import { promises as fs } from 'node:fs'
import path from 'node:path'
import os from 'node:os'
import type { EngineEvent } from '../types'
import { parseModelsOutput, runEngineCli } from './cli'
import { HF_ORIGIN } from './hub'
import { EngineService, engineChildEnv } from './service'
import { recordEnginePerformance, setEnginePerformanceRecorder } from './provider'
import { makeHarness, processAlive, seedModel, waitFor } from './test-fixtures/harness'
import { ModelRevisions } from './model-revisions'
import { repoCachedBytes } from './paths'

const GIB = 1024 ** 3
const SHA = 'd'.repeat(40)
Expand Down Expand Up @@ -107,6 +109,90 @@ async function liveEligibilityAndCacheScenarios() {
await h.cleanup()
}

// Issue #4407: engine 1.3.0's `startup budget` line must not drop a downloaded model from the
// installed list, and the drafter-only checkpoints 1.2.10 lists must not get a row of their own.
async function startupBudgetAndDrafterRows() {
const MODEL = 'TensorFold/Qwen3.8-27B-MLX-4bit'
const DRAFTER = 'z-lab/Qwen3.8-27B-DFlash2'
const DRAFTER_BYTES = 8192 // The seeded drafter's single weight file, added to its model's floor.
const h = await makeHarness({ FAKE_ENGINE_FAMILIES: 'qwen3:Qwen3.8-27B DFlash2 drafter', FAKE_INFO_BUDGET: '1' })
const service = new EngineService({ binaryPath: '/fake/tensorfold-native', binary: h.binary, appHome: h.root, childEnv: h.env, totalMemoryBytes: 32 * GIB, emit: () => {} })
try {
await seedModel(h.hub, MODEL, { checkpoint: true })
await seedModel(h.hub, DRAFTER, { checkpoint: true, dflash: true, bytes: DRAFTER_BYTES })
const listed = parseModelsOutput((await runEngineCli(h.binary, ['models'], h.env)).stdout).map((m) => m.repo)
assert.deepEqual(listed, [MODEL, DRAFTER], 'the fake mirrors 1.2.10 by listing the drafter row too')
// The `models` rows: the startup-budget model keeps its measured floor, the drafter has no row.
const rows = await service.installed()
assert.deepEqual(rows.map((m) => m.repo), [MODEL], 'the downloaded model survives and the drafter is left out')
const model = rows[0]
const infoText = (await runEngineCli(h.binary, ['info', MODEL], h.env)).stdout
assert.match(infoText, /^startup budget: /m, 'the fake prints the 1.3.0 line in place of the memory floor')
const printed = Number(/startup budget: ([\d.]+) GiB/.exec(infoText)![1])
assert.equal(model.memoryFloorBytes, Math.round(printed * GIB) + await repoCachedBytes(h.hub, DRAFTER), 'the printed budget, its reserve included, plus the drafter it drafts for')
assert.equal(model.source, 'cache')
assert.equal(model.family, 'Qwen3.5-2B or Qwen3.8-27B')
assert.equal(model.format, '4-bit, group 64')
assert.equal(model.fitsMemory, true, 'the parsed budget sized the model against this Mac')
// A pruned refs/main still resolves: the engine's own snapshot rule (hub.zig cachedSnapshot) names
// the newest snapshot with a config.json, so the drafter stays a companion and not a row.
const drafterRoot = path.join(h.hub, `models--${DRAFTER.replace('/', '--')}`)
const drafterSnapshot = path.join(drafterRoot, 'snapshots', 'a'.repeat(40))
await fs.rm(path.join(drafterRoot, 'refs', 'main'))
assert.deepEqual(parseModelsOutput((await runEngineCli(h.binary, ['models'], h.env)).stdout).map((m) => m.repo), [MODEL, DRAFTER], 'the fake follows the engine rule and still lists the drafter without a ref')
// The helpers answer with canonical paths, so the expectation is canonicalised too: under a macOS
// temp prefix (/var -> /private/var) the raw string and the realpath differ.
assert.equal(await (service as any).unpinnedSnapshot(drafterRoot), await fs.realpath(drafterSnapshot), 'the newest-snapshot rule resolves a pruned refs/main')
assert.deepEqual((await service.installed(true)).map((m) => m.repo), [MODEL], 'the pruned ref still leaves the drafter out')
// Same cache reached through a symlinked prefix, as macOS hands out /var/... : the helpers must
// canonicalise each step and then check containment, never compare a realpath against the raw path.
const linkedHub = path.join(h.root, 'hub-via-link')
await fs.symlink(h.hub, linkedHub)
const viaLink = new EngineService({ binaryPath: '/fake/tensorfold-native', binary: h.binary, appHome: h.root, childEnv: { ...h.env, HF_HUB_CACHE: linkedHub }, totalMemoryBytes: 32 * GIB, emit: () => {} })
try {
assert.equal(await (viaLink as any).isDrafterOnly(DRAFTER), true, 'a hub behind a symlink still reads the drafter config')
assert.equal(await (viaLink as any).unpinnedSnapshot(path.join(linkedHub, path.basename(drafterRoot))), await fs.realpath(drafterSnapshot), 'the newest-snapshot rule resolves through the symlinked prefix')
assert.deepEqual((await viaLink.installed(true)).map((m) => m.repo), [MODEL], 'the symlinked prefix still leaves the drafter out')
} finally { viaLink.shutdown() }
// The same two repos arriving through the selected-revisions map: still one row.
const revisions = new ModelRevisions(h.root, () => h.hub)
await revisions.commit([{ repo: MODEL, revision: 'a'.repeat(40) }, { repo: DRAFTER, revision: 'a'.repeat(40) }])
const pinned = await service.installed(true)
assert.deepEqual(pinned.map((m) => m.repo), [MODEL], 'a drafter in the revisions map is left out too')
assert.equal(pinned[0].source, 'download')
// And through the library scanner, whose drafter entry is not loadable.
await service.scanLibrary({ includeHuggingFace: true })
const scanned = await service.installed(true)
const library = (await service.librarySnapshot()).models
const local = library.find((m) => m.repo === MODEL)
const localDrafter = library.find((m) => m.repo === DRAFTER)
assert.equal(localDrafter?.complete, true, 'the drafter fixture is a complete checkpoint, not an invalid header')
assert.equal(localDrafter?.weightsBytes, DRAFTER_BYTES, 'its weights read through the snapshot link into blobs/')
assert.equal(localDrafter?.drafterOnly, true, "config.json's dflash_config marks it a companion")
assert.equal(localDrafter?.loadable, false, 'the scanner keeps the drafter out of the loadable rows')
assert.match(localDrafter?.reason ?? '', /drafter/, 'the reason names it a drafter checkpoint')
assert.ok(local?.loadable && scanned.some((m) => m.source === 'library' && m.repo === local.id), 'the scanned checkpoint still reaches the list')
assert.equal(scanned.filter((m) => m.repo === DRAFTER).length, 0, 'no source contributes a drafter row')
// Containment, negative: a snapshot's config.json that links out of this repo's blobs/ is never
// followed, so that checkpoint reads as "not known to be a drafter" and keeps its row.
const ESCAPING = 'Org/Escaping'
await seedModel(h.hub, ESCAPING, { checkpoint: true })
const escapingRoot = path.join(h.hub, `models--${ESCAPING.replace('/', '--')}`)
const escapingSnapshot = path.join(escapingRoot, 'snapshots', 'a'.repeat(40))
// Both files sit under the harness root, so h.cleanup() in the finally block takes them with it.
const escape = path.join(h.root, 'escape.json')
await fs.writeFile(escape, JSON.stringify({ model_type: 'qwen3', dflash_config: {} }))
await fs.rm(path.join(escapingSnapshot, 'config.json'))
await fs.symlink(escape, path.join(escapingSnapshot, 'config.json'))
assert.equal(await (service as any).isDrafterOnly(ESCAPING), false, 'the escaping link is not followed, so it is not known to be a drafter')
const kept = (await service.installed(true)).filter((m) => m.source !== 'library').map((m) => m.repo).sort()
assert.deepEqual(kept, [ESCAPING, MODEL].sort(), 'the escaping link keeps its row; only the contained drafter is dropped')
} finally {
service.shutdown()
await h.cleanup()
}
}

async function main() {
// Engine processes get OS values and the HF cache settings, never provider credentials.
const childEnv = engineChildEnv({ HOME: '/u', PATH: '/bin', HF_HOME: '/hf', OPENAI_API_KEY: 'sk-x', ANTHROPIC_API_KEY: 'x', TENSORFOLD_API_KEY: 'stale', NODE_OPTIONS: '--inspect', HF_TOKEN: 'hf_x' })
Expand Down Expand Up @@ -325,6 +411,7 @@ async function main() {
await waitFor(() => !processAlive(orphan.pid!), 5000, 'orphaned engine to be reaped')
await h.cleanup()
await liveEligibilityAndCacheScenarios()
await startupBudgetAndDrafterRows()
console.log('engine service tests passed')
}

Expand Down
Loading
Loading