Skip to content

Private AI meeting notes that stay on your computer. No meeting bot. Free and open source for Mac, Windows and Linux. An alternative to Granola, Otter and Fireflies.

Linux: notes no longer crash on the processor. A small shim, preloaded into the notes engine only, sends llama.cpp's allocations of 256 MiB and up to mmap instead of Electron's allocator, which traps on anything over 2 GiB (#32)

christianmat491cbb14f20b
diff --git a/.github/workflows/engine-real.yml b/.github/workflows/engine-real.yml
index 18e76184..79f3f901 100644
--- a/.github/workflows/engine-real.yml
+++ b/.github/workflows/engine-real.yml
@@ -46,6 +46,8 @@ jobs:
if: inputs.run_id == ''
run: |
cd app && pnpm exec electron-vite build
+ # Linux: the notes engine's allocator shim (#32), as scripts/native.mjs builds it
+ if [ "$RUNNER_OS" = Linux ]; then mkdir -p resources/bin && gcc -O2 -fPIC -shared -Wall -Wextra -Werror -o resources/bin/libyogurt-bigalloc.so native/bigalloc/bigalloc.c; fi
echo "ASAR=$GITHUB_WORKSPACE/app" >> "$GITHUB_ENV"
- name: The preview installer
if: inputs.run_id != ''
diff --git a/app/native/bigalloc/bigalloc.c b/app/native/bigalloc/bigalloc.c
new file mode 100644
index 00000000..a77cf5be
--- /dev/null
+++ b/app/native/bigalloc/bigalloc.c
@@ -0,0 +1,31 @@
+// Linux only (#32). Loaded into the notes engine with LD_PRELOAD (src/main/engine.ts), never into the app itself.
+//
+// Electron's own allocator (PartitionAlloc, exported as malloc from the Electron binary) deliberately crashes the
+// process (SIGILL) on a single allocation over about 2 GiB. llama.cpp makes allocations that big when the model runs on
+// the processor: the repacked weights (CPU_REPACK, 2.1 GB for Gemma 4 E4B, 13 GB for 26B) and a big context.
+// They all go through ggml_aligned_malloc in libggml-base.so, which calls it through its PLT, so this copy wins.
+// Big blocks are mmapped (what glibc would do); the rest go to posix_memalign like ggml's own Linux code.
+// Recheck after a node-llama-cpp update: this relies on ggml keeping these two functions, exported, with this signature.
+#define _GNU_SOURCE
+#include <stdlib.h>
+#include <sys/mman.h>
+
+#define BIG ((size_t)256 << 20)
+
+void *ggml_aligned_malloc(size_t size) {
+ if (size == 0) return NULL;
+ if (size >= BIG) {
+ // page aligned, which covers ggml's 64 bytes
+ void *p = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
+ return p == MAP_FAILED ? NULL : p;
+ }
+ void *p = NULL;
+ return posix_memalign(&p, 64, size) == 0 ? p : NULL;
+}
+
+// ggml frees with the size it allocated (its Mac code relies on that too), so the size says which way it went
+void ggml_aligned_free(void *ptr, size_t size) {
+ if (!ptr) return;
+ if (size >= BIG) munmap(ptr, size);
+ else free(ptr);
+}
diff --git a/app/native/bigalloc/test.c b/app/native/bigalloc/test.c
new file mode 100644
index 00000000..12b0e458
--- /dev/null
+++ b/app/native/bigalloc/test.c
@@ -0,0 +1,31 @@
+// The shim's own check (scripts/native.mjs runs it after building): big blocks are mmapped, small ones aligned.
+#include <stdint.h>
+#include <stdio.h>
+#include <string.h>
+
+void *ggml_aligned_malloc(size_t size);
+void ggml_aligned_free(void *ptr, size_t size);
+
+#define CHECK(c) do { if (!(c)) { fprintf(stderr, "bigalloc: %s failed\n", #c); return 1; } } while (0)
+
+int main(void) {
+ // over 2 GiB, the size that crashes Electron's allocator; mmap only touches the pages written
+ size_t big = (size_t)3 << 30;
+ unsigned char *p = ggml_aligned_malloc(big);
+ CHECK(p != NULL);
+ CHECK((uintptr_t)p % 4096 == 0);
+ p[0] = 1; p[big - 1] = 2;
+ CHECK(p[0] == 1 && p[big - 1] == 2);
+ ggml_aligned_free(p, big);
+
+ unsigned char *s = ggml_aligned_malloc(1000);
+ CHECK(s != NULL);
+ CHECK((uintptr_t)s % 64 == 0);
+ memset(s, 7, 1000);
+ ggml_aligned_free(s, 1000);
+
+ CHECK(ggml_aligned_malloc(0) == NULL);
+ ggml_aligned_free(NULL, 0);
+ puts("bigalloc: ok");
+ return 0;
+}
diff --git a/app/scripts/engine-model-smoke.cjs b/app/scripts/engine-model-smoke.cjs
index cf1a4039..b3ce6c0e 100644
--- a/app/scripts/engine-model-smoke.cjs
+++ b/app/scripts/engine-model-smoke.cjs
@@ -3,9 +3,9 @@
// app's context sizes, and writes a few words. Each step's time is printed, so a stall shows where it stopped.
// CI only (preview.yml, engine-real.yml): no real profile, microphone or meeting is opened.
const { app, utilityProcess } = require('electron')
-const { mkdtempSync, rmSync, existsSync } = require('node:fs')
+const { mkdtempSync, rmSync, existsSync, readFileSync } = require('node:fs')
const { tmpdir } = require('node:os')
-const { join, resolve } = require('node:path')
+const { dirname, join, resolve } = require('node:path')
const [archive, model] = process.argv.slice(2).filter((a) => !a.startsWith('--'))
const gpuOff = process.argv.includes('--gpu-off')
@@ -20,8 +20,14 @@ app.setName('Yogurt Engine Model Smoke')
app.setPath('userData', profile)
app.whenReady().then(async () => {
+ // Linux: the allocator shim (#32), next to an installed app.asar or in this commit's resources/bin, preloaded as the app does
+ const shim = process.platform === 'linux'
+ ? [join(dirname(resolve(archive)), 'bin'), join(resolve(archive), 'resources', 'bin')].map((d) => join(d, 'libyogurt-bigalloc.so')).find(existsSync)
+ : undefined
+ if (process.platform === 'linux' && !shim) throw new Error('libyogurt-bigalloc.so was not found next to the app')
+ const env = { ...(shim ? { LD_PRELOAD: shim } : {}), ...(gpuOff ? { YOGURT_ENGINE_GPU: 'off' } : {}) }
const child = utilityProcess.fork(join(resolve(archive), 'out/main/engine.js'), [], {
- serviceName: 'Yogurt Engine Model Smoke', stdio: 'pipe', ...(gpuOff ? { env: { ...process.env, YOGURT_ENGINE_GPU: 'off' } } : {}),
+ serviceName: 'Yogurt Engine Model Smoke', stdio: 'pipe', ...(Object.keys(env).length ? { env: { ...process.env, ...env } } : {}),
})
child.stdout.on('data', (c) => process.stdout.write(`[engine] ${c}`))
child.stderr.on('data', (c) => process.stderr.write(`[engine] ${c}`))
@@ -52,6 +58,9 @@ app.whenReady().then(async () => {
let failed = null
try {
await timed('probe', { type: 'probe' })
+ // the utility process must really have loaded the shim (it answered, so it is running)
+ if (shim && !readFileSync(`/proc/${child.pid}/maps`, 'utf8').includes(shim)) throw new Error(`The notes engine did not load ${shim}`)
+ if (shim) console.log(`The notes engine loaded ${shim}`)
await timed('load', { type: 'load', modelPath: resolve(model), contextSize: CONTEXT, minContext: MIN_CONTEXT })
const answer = await timed('chat', { type: 'chat', messages: [{ role: 'user', content: 'Say hello in five words.' }], thoughtBudget: 0, maxTokens: 24 })
if (!String(answer).trim()) throw new Error('The model wrote nothing')
diff --git a/app/scripts/engine-smoke.cjs b/app/scripts/engine-smoke.cjs
index 243ff1e6..519e6e91 100644
--- a/app/scripts/engine-smoke.cjs
+++ b/app/scripts/engine-smoke.cjs
@@ -1,9 +1,9 @@
// Run with Electron, never the packaged app's main entry. No models, microphone or real profile are opened.
// electron scripts/engine-smoke.cjs /path/to/app.asar
const { app, utilityProcess } = require('electron')
-const { mkdtempSync, rmSync, existsSync } = require('node:fs')
+const { mkdtempSync, rmSync, existsSync, readFileSync } = require('node:fs')
const { tmpdir } = require('node:os')
-const { join, resolve } = require('node:path')
+const { dirname, join, resolve } = require('node:path')
const archive = process.argv[2]
if (!archive || !existsSync(archive)) throw new Error('Pass the packaged app.asar path')
@@ -12,7 +12,11 @@ app.setName('Yogurt Engine Smoke')
app.setPath('userData', profile)
app.whenReady().then(() => {
- const child = utilityProcess.fork(join(resolve(archive), 'out/main/engine.js'), [], { serviceName: 'Yogurt Engine Smoke', stdio: 'pipe' })
+ // Linux: the shipped allocator shim (#32), preloaded the way src/main/engine.ts does it
+ const shim = process.platform === 'linux' ? join(dirname(resolve(archive)), 'bin', 'libyogurt-bigalloc.so') : undefined
+ if (shim && !existsSync(shim)) throw new Error(`${shim} is not in the package`)
+ const env = shim ? { env: { ...process.env, LD_PRELOAD: shim } } : {}
+ const child = utilityProcess.fork(join(resolve(archive), 'out/main/engine.js'), [], { serviceName: 'Yogurt Engine Smoke', stdio: 'pipe', ...env })
let stderr = '', settled = false
child.stderr.on('data', (chunk) => { stderr = (stderr + chunk.toString()).slice(-16_384) })
child.stdout.resume()
@@ -32,7 +36,11 @@ app.whenReady().then(() => {
child.on('message', (event) => {
if (event.id !== 1) return
// The expected error proves the real worker reached its handler without loading a model.
- finish(event.type === 'error' && event.message === 'No model loaded' ? null : `Unexpected packaged engine response: ${JSON.stringify(event)}`)
+ if (event.type !== 'error' || event.message !== 'No model loaded') return finish(`Unexpected packaged engine response: ${JSON.stringify(event)}`)
+ // the utility process must really have loaded it: Electron passes env to it at exec
+ if (shim && !readFileSync(`/proc/${child.pid}/maps`, 'utf8').includes(shim)) return finish(`The notes engine did not load ${shim}`)
+ if (shim) console.log(`The notes engine loaded ${shim}`)
+ finish(null)
})
child.postMessage({ id: 1, type: 'count', texts: ['packaged startup check'] })
}).catch((error) => { console.error(error); rmSync(profile, { recursive: true, force: true }); app.exit(1) })
diff --git a/app/scripts/helpers-smoke.mjs b/app/scripts/helpers-smoke.mjs
index 2d06452e..28b29153 100644
--- a/app/scripts/helpers-smoke.mjs
+++ b/app/scripts/helpers-smoke.mjs
@@ -22,6 +22,8 @@ const run = (exe, args, env = {}) => spawnSync(exe, args, { encoding: 'utf8', ti
for (const name of ['yogurt-audio', 'yogurt-system', 'yogurt-mcp']) check(existsSync(bin(name)), `${name} is installed`, bin(name))
check(existsSync(join(a.resources, 'dict', 'words')), 'the word list is installed')
+// Linux: the notes engine's allocator shim (#32)
+if (process.platform === 'linux') check(existsSync(bin('libyogurt-bigalloc.so')), 'the notes engine\'s allocator shim is installed', bin('libyogurt-bigalloc.so'))
if (!a['no-whisper']) {
check(existsSync(bin('whisper-server')), 'whisper-server is installed', bin('whisper-server'))
check(existsSync(join(a.resources, 'vad', 'ggml-silero-v6.2.0.bin')), 'the VAD model is installed')
diff --git a/app/scripts/native.mjs b/app/scripts/native.mjs
index 2b0750a0..1e6ed51e 100644
--- a/app/scripts/native.mjs
+++ b/app/scripts/native.mjs
@@ -6,6 +6,7 @@
import { spawnSync } from 'node:child_process'
import { createHash } from 'node:crypto'
import { chmodSync, copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
@@ -59,6 +60,22 @@ for (const [crate, name] of CRATES) {
console.log(`built ${out}`)
}
+// Linux: the notes engine's allocator shim (#32, native/bigalloc), with the system's gcc. Checked before it ships: it
+// exports both functions, and its own test passes.
+if (!win) {
+ const src = join(app, 'native', 'bigalloc')
+ const so = join(bin, 'libyogurt-bigalloc.so')
+ run('gcc', ['-O2', '-fPIC', '-shared', '-Wall', '-Wextra', '-Werror', '-o', so, join(src, 'bigalloc.c')])
+ const syms = spawnSync('nm', ['-D', '--defined-only', so], { encoding: 'utf8' }).stdout ?? ''
+ for (const name of ['ggml_aligned_malloc', 'ggml_aligned_free']) {
+ if (!new RegExp(`\\sT ${name}$`, 'm').test(syms)) { console.error(`${so} doesn't export ${name}`); process.exit(1) }
+ }
+ const test = join(tmpdir(), 'yogurt-bigalloc-test')
+ run('gcc', ['-O2', '-Wall', '-Werror', '-o', test, join(src, 'test.c'), so, `-Wl,-rpath,${bin}`])
+ run(test, [])
+ console.log(`built ${so}`)
+}
+
// The word list a Mac has in /usr/share/dict/words (Webster's Second International, 1934, public domain), from FreeBSD at a
// pinned commit: lowercase respelling (main/vocab.ts) needs to know everyday words, and Windows has no list of its own
const WORDS_URL = 'https://raw.githubusercontent.com/freebsd/freebsd-src/72f0bc868bf00586cba1e50057d8f1998b4abe80/share/dict/web2'
diff --git a/app/src/main/engine.ts b/app/src/main/engine.ts
index d4254792..a22d0f3a 100644
--- a/app/src/main/engine.ts
+++ b/app/src/main/engine.ts
@@ -16,6 +16,16 @@ type Limits = typeof WATCH
/** Vulkan's "the graphics card was reset" (a driver hang): the process that saw it can never use the card again */
export const deviceLost = (message: string): boolean => /ErrorDeviceLost|VK_ERROR_DEVICE_LOST/i.test(message)
+/**
+ * Linux (#32): Electron's own allocator traps (SIGILL, code 132) on one allocation over 2 GiB, and llama.cpp makes one
+ * when the model runs on the processor (its repacked weights, a big context). libyogurt-bigalloc.so (native/bigalloc)
+ * sends those to mmap instead. Only the notes engine gets it, and only when it was shipped.
+ */
+export const SHIM = 'libyogurt-bigalloc.so'
+export const engineShim = (platform: string, candidates: string[], exists: (p: string) => boolean): string | undefined =>
+ // LD_PRELOAD splits on spaces and colons, so a path with one would never load
+ platform === 'linux' ? candidates.find((p) => !/[\s:]/.test(p) && exists(p)) : undefined
+
export type ChatRequest = { messages: EngineMessage[]; maxTokens?: number; thoughtBudget?: number; /** instead of the family's sampling temperature */ temperature?: number }
export interface Engine {
@@ -55,10 +65,11 @@ export class UtilityEngine implements Engine {
private limits: Limits
/**
- * cpuCrashes (Linux): the engine dies on the processor alone (code 132: Electron's allocator refuses llama.cpp's
- * single > 2 GiB weight buffer), so a lost graphics card starts the engine again on the card, not without it.
+ * cpuCrashes (Linux without the shim): the engine dies on the processor alone (code 132: Electron's allocator refuses
+ * llama.cpp's single > 2 GiB weight buffer), so a lost graphics card starts the engine again on the card, not without it.
+ * preload: the shim that prevents that crash (engineShim), put in the engine's LD_PRELOAD.
*/
- constructor(private workerPath: string, private opts: { gpuFallback?: boolean; cpuCrashes?: boolean } & Partial<Limits> = {}) {
+ constructor(private workerPath: string, private opts: { gpuFallback?: boolean; cpuCrashes?: boolean; preload?: string } & Partial<Limits> = {}) {
this.limits = { ...WATCH, ...opts }
}
@@ -92,7 +103,13 @@ export class UtilityEngine implements Engine {
private ensure(): UtilityProcess {
if (this.proc) return this.proc
- const proc = utilityProcess.fork(this.workerPath, [], { serviceName: 'Yogurt Notes', ...(this.cpuOnly ? { env: { ...process.env, YOGURT_ENGINE_GPU: 'off' } } : {}) })
+ const { preload } = this.opts
+ const env = preload || this.cpuOnly ? {
+ ...process.env,
+ ...(preload ? { LD_PRELOAD: [preload, process.env.LD_PRELOAD].filter(Boolean).join(':') } : {}),
+ ...(this.cpuOnly ? { YOGURT_ENGINE_GPU: 'off' } : {}),
+ } : undefined
+ const proc = utilityProcess.fork(this.workerPath, [], { serviceName: 'Yogurt Notes', ...(env ? { env } : {}) })
this.loaded = false
proc.on('message', (e: EngineEvent) => {
const p = this.pending.get(e.id)
diff --git a/app/src/main/index.ts b/app/src/main/index.ts
index 6f2f8e1a..754aabb8 100644
--- a/app/src/main/index.ts
+++ b/app/src/main/index.ts
@@ -70,7 +70,7 @@ import { setJargon, setOwnerName } from './vocab'
import { cleanJargon } from '../shared/jargon'
import { setGenericTitles } from './titles'
import { installAppMenu } from './appMenu'
-import { UtilityEngine } from './engine'
+import { engineShim, SHIM, UtilityEngine } from './engine'
import { createNotesModel } from './notes/model'
import { FakeEngine } from './notes/fake'
import { hookNotes } from './notes'
@@ -703,7 +703,10 @@ app.whenReady().then(() => {
// 32 GB and up: the notes model reads each meeting in as it happens (notes/readAhead.ts)
const readsAhead = !isFake() && readAheadAllowed(os.totalmem())
// the notes model: one job at a time, recording first; loaded when needed, the best one downloaded
- const engine = isFake() ? new FakeEngine() : new UtilityEngine(join(__dirname, 'engine.js'), { gpuFallback: process.platform !== 'darwin', cpuCrashes: process.platform === 'linux' })
+ // Linux: the shim that keeps the engine from crashing on the processor (#32); without it, the card is the only way
+ const shim = engineShim(process.platform, [process.resourcesPath && join(process.resourcesPath, 'bin', SHIM), join(__dirname, '../../resources/bin', SHIM)].filter((x): x is string => !!x), existsSync)
+ if (process.platform === 'linux') console.info('NOTES', shim ? `big allocations go through ${shim}` : `${SHIM} is missing: the notes engine can crash on the processor`)
+ const engine = isFake() ? new FakeEngine() : new UtilityEngine(join(__dirname, 'engine.js'), { gpuFallback: process.platform !== 'darwin', cpuCrashes: process.platform === 'linux' && !shim, ...(shim ? { preload: shim } : {}) })
if (engine instanceof UtilityEngine) probeGpu = () => engine.probe().then((g) => {
console.info('NOTES', `graphics: ${g.gpuType || 'none'}${g.gpuNames.length ? ` (${g.gpuNames.join(', ')})` : ''}, ${g.vramTotalGB.toFixed(1)} GB`)
return g
diff --git a/app/test/engineWatchdog.test.ts b/app/test/engineWatchdog.test.ts
index f9a8f65a..8e36402e 100644
--- a/app/test/engineWatchdog.test.ts
+++ b/app/test/engineWatchdog.test.ts
@@ -13,7 +13,7 @@ class Proc extends EventEmitter {
}
const procs: Proc[] = []
vi.mock('electron', () => ({ utilityProcess: { fork: (_p: string, _a: string[], o: { env?: Record<string, string> }) => { const p = new Proc(o.env); procs.push(p); return p } } }))
-const { UtilityEngine, GraphicsGaveUpError } = await import('../src/main/engine')
+const { UtilityEngine, GraphicsGaveUpError, engineShim } = await import('../src/main/engine')
const limits = { probeMs: 1000, loadMs: 1000, firstTokenMs: 1000, cpuLoadMs: 5000, cpuFirstTokenMs: 5000 }
const chat = { messages: [{ role: 'user' as const, content: 'hi' }] }
@@ -157,3 +157,39 @@ describe('the notes engine off a Mac: a graphics card that is lost, and a proces
expect(procs[2].env?.YOGURT_ENGINE_GPU).toBeUndefined()
})
})
+
+describe('Linux: big allocations kept away from Electron\'s allocator (#32)', () => {
+ it('the shim is used on Linux only, and only when it was shipped', () => {
+ const has = () => true, none = () => false
+ expect(engineShim('linux', ['/r/bin/libyogurt-bigalloc.so'], has)).toBe('/r/bin/libyogurt-bigalloc.so')
+ expect(engineShim('linux', ['/r/bin/libyogurt-bigalloc.so'], none)).toBeUndefined()
+ expect(engineShim('darwin', ['/r/bin/libyogurt-bigalloc.so'], has)).toBeUndefined()
+ expect(engineShim('win32', ['/r/bin/libyogurt-bigalloc.so'], has)).toBeUndefined()
+ // LD_PRELOAD splits on spaces and colons: such a path would never load, so the next one (or none) is used
+ expect(engineShim('linux', ['/My Apps/bin/libyogurt-bigalloc.so', '/a:b/libyogurt-bigalloc.so', '/r/bin/libyogurt-bigalloc.so'], has)).toBe('/r/bin/libyogurt-bigalloc.so')
+ })
+
+ it('with the shim, every engine process gets it in LD_PRELOAD, on the card or not, next to one already set', async () => {
+ const before = process.env.LD_PRELOAD
+ process.env.LD_PRELOAD = '/home/me/other.so'
+ try {
+ const e = new UtilityEngine('engine.js', { gpuFallback: true, preload: '/r/bin/libyogurt-bigalloc.so', ...limits })
+ void e.load('m.gguf', 32768, 8192).catch(() => {})
+ expect(procs[0].env?.LD_PRELOAD).toBe('/r/bin/libyogurt-bigalloc.so:/home/me/other.so')
+ expect(procs[0].env?.YOGURT_ENGINE_GPU).toBeUndefined()
+ procs[0].emit('exit', 132)
+ void e.load('m.gguf', 32768, 8192).catch(() => {})
+ expect(procs[1].env?.LD_PRELOAD).toBe('/r/bin/libyogurt-bigalloc.so:/home/me/other.so')
+ expect(procs[1].env?.YOGURT_ENGINE_GPU).toBe('off')
+ } finally {
+ if (before === undefined) delete process.env.LD_PRELOAD
+ else process.env.LD_PRELOAD = before
+ }
+ })
+
+ it('without it (a Mac, Windows) the engine starts with the app\'s own environment, as before', async () => {
+ const e = new UtilityEngine('engine.js', { gpuFallback: true, ...limits })
+ void e.load('m.gguf', 32768, 8192).catch(() => {})
+ expect(procs[0].env).toBeUndefined()
+ })
+})