Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

truncate embeddings to model context (+retry) and stop long memory cards overflowing

[._.]/ Adam Eivy5b70d5ce4856
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 2ce83422ac..6c42a627b4 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -58,6 +58,8 @@
## Fixed
+- **Long memories embed reliably (no more "input exceeds context length" NULLs), and oversized transcript cards stop overflowing the page** — Two issues surfaced reprocessing a large ChatGPT import. (1) The embedder truncated input to a flat 8000 chars, but small local embedding models like Ollama's `nomic-embed-text` cap at a **2048-token context**, and dense transcripts (code/JSON/non-English) run ~3 chars/token — so the longest conversations overflowed and embedded to NULL (unsearchable). The embedder now budgets input against the model's real context (`embeddingMaxTokens`, default 2048) at a conservative chars-per-token with headroom, and if the backend *still* reports an overflow it **halves and retries** before giving up; a batch that overflows **falls back to per-item embedding** so one oversized member can't null the whole batch. (2) In Brain → Memory, an imported conversation containing a long unbroken code block (e.g. a giant binary string) blew the card's width out and pushed its action buttons off-screen — the content row now shrinks correctly (`min-w-0` so unbreakable content wraps instead of expanding) and the transcript preview is height-capped with an internal scroll. (`server/services/memoryEmbeddings.js`, `server/services/memoryConfig.js`, `client/src/components/brain/tabs/MemoryTab.jsx`)
+
- **Bulk brain-record creates no longer fire a thundering herd of embedding calls** — The Brain→Memory bridge (which mirrors every brain record into the pgvector memory table so agents can semantically search them) handled each `{type}:upserted` event inline with a fire-and-forget `syncBrainRecord` — fine for human-paced single edits, but a **bulk producer** like the new ChatGPT import (creating ~1,400 conversations back-to-back) fired that many `:upserted` events in a tight loop, launching ~1,400 **concurrent** embedding HTTP calls + Postgres writes. That saturated the embedding backend (most calls time out and the embedding is swallowed to `null`, so the records persist **silently unsearchable**) and exhausted the PG pool. The peer-sync `sync:applied` path already solved this with a debounced (250 ms) + sequential + deduped `queueResync` drain; the direct entity events now route through that same machinery. Because `queueResync` re-reads each record's **canonical** stored state (`resyncBrainRecord`), the archived/deleted/tombstoned branches are handled uniformly and a now-stale event payload still converges correctly. (`server/services/brainMemoryBridge.js`)
- **Test runner can no longer write to the real `portos` database through a transaction (the last guard hole)** — The `query()` row-write backstop added in the previous incident fix guarded only PortOS's own pool wrapper, but **`withTransaction()` hands its callback a raw `pg` client whose `client.query()` bypasses `query()` entirely** — and nearly every store mutation (`updateAuthor`/`deleteAuthor`/`mergeAuthorsFromSync`, universe runs, catalog, writers-room, story-builder, creative-director) issues its `INSERT`/`UPDATE`/`DELETE` *inside* a transaction. So a suite running under VITEST against the real `portos` DB (a CoS-agent worktree with `NODE_ENV` unset, or any non-DB suite that reaches a transaction write path) still wrote straight into production, unguarded — the DB-backed `*.db.test.js` suites skipped correctly via `checkHealth()`, but the transaction door was wide open. Fix: the shared backstop is factored into `assertWriteAllowed()` and `withTransaction()` now wraps its client in a `Proxy` that runs every `client.query()` through it (the SQL is read from both the string and `{ text }` call forms; `BEGIN`/`COMMIT`/`ROLLBACK` and `SELECT … FOR UPDATE` pass through). Verified: a transaction `INSERT` against `portos` under VITEST now throws `Refusing to mutate` and leaves no row, while all 14 DB-backed suites (109 tests) still pass against `portos_test`. (`server/lib/db.js`, `server/lib/db.guards.test.js`)
diff --git a/client/src/components/brain/tabs/MemoryTab.jsx b/client/src/components/brain/tabs/MemoryTab.jsx
index 8555b4f603..66d2b05d87 100644
--- a/client/src/components/brain/tabs/MemoryTab.jsx
+++ b/client/src/components/brain/tabs/MemoryTab.jsx
@@ -452,7 +452,11 @@ export default function MemoryTab({ onRefresh }) {
return (
<div key={record.id} className="p-4 bg-port-card border border-port-border rounded-lg hover:border-port-border/80 transition-colors">
<div className="flex items-start justify-between gap-2">
- <div className="flex-1">
+ {/* min-w-0: without it a flex child won't shrink below its content's
+ intrinsic width, so a long unbreakable code block in an imported
+ transcript blows the row out and shoves the action buttons off
+ the page. */}
+ <div className="flex-1 min-w-0">
{activeType === 'people' && (
<>
<h3 className="font-medium text-white">{record.name}</h3>
@@ -523,11 +527,13 @@ export default function MemoryTab({ onRefresh }) {
</div>
{record.content && (
// Imported ChatGPT transcripts carry markdown (inline images,
- // asset links) — render them rich. Hand-written memories stay
- // plain pre-wrap text.
+ // asset links) — render them rich, but cap the height with an
+ // internal scroll so a long transcript preview doesn't make
+ // the card a mile tall (the full thread is in the viewer).
+ // Hand-written memories stay plain pre-wrap text.
record.source === 'chatgpt-import'
- ? <div className="text-sm text-gray-400 mt-1"><MarkdownOutput content={record.content} /></div>
- : <p className="text-sm text-gray-400 mt-1 whitespace-pre-wrap">{record.content}</p>
+ ? <div className="text-sm text-gray-400 mt-1 max-h-72 overflow-y-auto pr-1"><MarkdownOutput content={record.content} /></div>
+ : <p className="text-sm text-gray-400 mt-1 whitespace-pre-wrap break-words">{record.content}</p>
)}
{record.source === 'chatgpt-import' && record.sourceRef && (
<button
diff --git a/server/services/memoryConfig.js b/server/services/memoryConfig.js
index 3b4e0c3ebc..550482af0b 100644
--- a/server/services/memoryConfig.js
+++ b/server/services/memoryConfig.js
@@ -12,6 +12,12 @@ export const DEFAULT_MEMORY_CONFIG = {
embeddingEndpoint: 'http://localhost:1234/v1/embeddings',
embeddingModel: 'text-embedding-nomic-embed-text-v2-moe',
embeddingDimension: 768,
+ // Token context window of the embedding model. nomic-embed-text (and most
+ // small local embedders) cap at 2048; we truncate input to a safe fraction
+ // of this before embedding. A too-long input is rejected outright by the
+ // backend ("input length exceeds the context length") and yields a NULL
+ // embedding, so this must stay at/under the real model context.
+ embeddingMaxTokens: 2048,
maxMemories: 10000,
maxContextTokens: 2000,
minRelevanceThreshold: 0.7,
diff --git a/server/services/memoryEmbeddings.js b/server/services/memoryEmbeddings.js
index 51eeef779a..eadd3c8dab 100644
--- a/server/services/memoryEmbeddings.js
+++ b/server/services/memoryEmbeddings.js
@@ -224,7 +224,55 @@ export async function checkAvailability() {
}
/**
- * Generate embedding for a single text
+ * Embedding-input budgeting.
+ *
+ * The embedding model has a hard token context (config.embeddingMaxTokens —
+ * 2048 for nomic-embed-text). Input over it is REJECTED ("input length exceeds
+ * the context length") → a NULL embedding, not a truncated one. Our token
+ * estimate (~4 chars/token) is optimistic for dense transcripts (code/JSON/
+ * non-English run ~3 chars/token), so we budget against a conservative
+ * chars-per-token AND only fill a fraction of the context, leaving headroom for
+ * the few prompt tokens the backend wraps around the input.
+ */
+const EMBED_CONTEXT_FILL = 0.85; // use ≤85% of the model context
+const CONSERVATIVE_CHARS_PER_TOKEN = 3; // dense text floor (vs the 4 estimate)
+
+function embeddingCharBudget(config) {
+ const maxTokens = config.embeddingMaxTokens || 2048;
+ return Math.floor(maxTokens * EMBED_CONTEXT_FILL * CONSERVATIVE_CHARS_PER_TOKEN);
+}
+
+const isContextOverflowError = (msg) =>
+ /context length|context window|too (?:long|large)|exceeds? .*length|maximum context/i.test(String(msg || ''));
+
+const clampToChars = (text, maxChars) => (text.length > maxChars ? text.slice(0, maxChars) : text);
+
+/**
+ * POST one input to the embedding endpoint. Returns
+ * { ok, embedding, error, overflow } so callers can decide whether to shrink
+ * and retry on a context-overflow rejection.
+ */
+async function postEmbedding(config, input) {
+ const response = await fetch(config.embeddingEndpoint, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ model: config.embeddingModel, input }),
+ signal: AbortSignal.timeout(30000)
+ });
+ if (!response.ok) {
+ const error = await response.text();
+ return { ok: false, error, overflow: isContextOverflowError(error) };
+ }
+ const data = await readResponseJson(response);
+ return { ok: true, data };
+}
+
+/**
+ * Generate embedding for a single text. Truncates to the model's context
+ * budget up front, and if the backend still reports a context overflow (our
+ * char estimate undershot for very dense text), halves the input and retries a
+ * couple of times before giving up — so a pathological doc still embeds rather
+ * than landing NULL.
*/
export async function generateEmbedding(text) {
await initConfig();
@@ -241,32 +289,29 @@ export async function generateEmbedding(text) {
);
}
- // Truncate very long texts to prevent issues
- const maxChars = 8000;
- const truncatedText = text.length > maxChars ? text.substring(0, maxChars) : text;
-
- const response = await fetch(config.embeddingEndpoint, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- model: config.embeddingModel,
- input: truncatedText
- }),
- signal: AbortSignal.timeout(30000)
- });
-
- if (!response.ok) {
- const error = await response.text();
- console.error(`❌ Embedding generation failed: ${error}`);
+ let maxChars = embeddingCharBudget(config);
+ for (let attempt = 0; attempt < 3; attempt++) {
+ const result = await postEmbedding(config, clampToChars(text, maxChars));
+ if (result.ok) return result.data.data?.[0]?.embedding || null;
+ if (result.overflow && maxChars > 500) {
+ maxChars = Math.floor(maxChars / 2); // undershoot — shrink and retry
+ console.warn(`⚠️ Embedding input over context; retrying at ${maxChars} chars`);
+ continue;
+ }
+ console.error(`❌ Embedding generation failed: ${result.error}`);
return null;
}
-
- const data = await readResponseJson(response);
- return data.data?.[0]?.embedding || null;
+ console.error('❌ Embedding generation failed: input still over context after shrinking');
+ return null;
}
/**
- * Generate embeddings for multiple texts (batch)
+ * Generate embeddings for multiple texts (batch).
+ *
+ * A batch shares one request, so one over-long member would 400 the WHOLE
+ * batch. We can't selectively retry inside a batch response, so on a
+ * context-overflow rejection we fall back to embedding each input individually
+ * (generateEmbedding handles per-item shrink/retry) rather than nulling all.
*/
export async function generateBatchEmbeddings(texts) {
await initConfig();
@@ -283,31 +328,26 @@ export async function generateBatchEmbeddings(texts) {
);
}
- // LM Studio supports batch embeddings via array input
- const maxChars = 8000;
- const truncatedTexts = texts.map(t => t.length > maxChars ? t.substring(0, maxChars) : t);
-
- const response = await fetch(config.embeddingEndpoint, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- model: config.embeddingModel,
- input: truncatedTexts
- }),
- signal: AbortSignal.timeout(30000)
- });
-
- if (!response.ok) {
- const error = await response.text();
- console.error(`❌ Batch embedding generation failed: ${error}`);
+ const maxChars = embeddingCharBudget(config);
+ const truncatedTexts = texts.map(t => clampToChars(t, maxChars));
+
+ const result = await postEmbedding(config, truncatedTexts);
+ if (!result.ok) {
+ if (result.overflow) {
+ // One member still overflowed — re-embed each individually so the rest
+ // aren't lost to a single oversized input.
+ console.warn('⚠️ Batch embedding over context; falling back to per-item embedding');
+ const out = [];
+ for (const t of texts) out.push(await generateEmbedding(t));
+ return out;
+ }
+ console.error(`❌ Batch embedding generation failed: ${result.error}`);
return texts.map(() => null);
}
- const data = await readResponseJson(response);
-
// Sort by index to maintain order
const embeddings = new Array(texts.length).fill(null);
- for (const item of data.data || []) {
+ for (const item of result.data.data || []) {
embeddings[item.index] = item.embedding;
}
diff --git a/server/services/memoryEmbeddings.test.js b/server/services/memoryEmbeddings.test.js
index 2e816c1b6c..6babeeaf6b 100644
--- a/server/services/memoryEmbeddings.test.js
+++ b/server/services/memoryEmbeddings.test.js
@@ -13,6 +13,7 @@ vi.mock('./memoryBackend.js', () => ({
embeddingEndpoint: 'http://localhost:1234/v1/embeddings',
embeddingModel: 'text-embedding-nomic-embed-text-v2-moe',
embeddingDimension: 768,
+ embeddingMaxTokens: 2048,
},
}));
@@ -130,3 +131,87 @@ describe('memoryEmbeddings — provider-aware config (Ollama vs LM Studio)', ()
expect(status.error).toContain('503');
});
});
+
+describe('memoryEmbeddings — context-budget truncation + overflow retry', () => {
+ beforeEach(() => {
+ getCosConfig.mockResolvedValue({ embeddingProviderId: 'ollama', embeddingModel: 'nomic-embed-text' });
+ getProviderById.mockResolvedValue({ id: 'ollama', endpoint: 'http://localhost:11434/v1' });
+ });
+
+ // readResponseJson() reads the body via `.text()`, so the payload must be the
+ // JSON STRING (not just `.json()`).
+ const embedOk = () => {
+ const body = JSON.stringify({ data: [{ index: 0, embedding: [0.1, 0.2, 0.3] }] });
+ return { ok: true, json: async () => JSON.parse(body), text: async () => body };
+ };
+ const contextOverflow = () => ({
+ ok: false, status: 400,
+ text: async () => JSON.stringify({ error: { message: 'the input length exceeds the context length' } }),
+ json: async () => ({}),
+ });
+ const notLmStudio = () => Promise.resolve({ ok: false, status: 404, text: async () => '', json: async () => ({}) });
+
+ // Route the LM-Studio native probe to a 404 (so the backend is recognized as
+ // Ollama and the load dance is skipped); delegate the /v1/embeddings POSTs to
+ // a per-test queue of responses.
+ const wireFetch = (embedResponses) => {
+ let i = 0;
+ fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation((url) => {
+ if (String(url).includes('/api/v0/models')) return notLmStudio();
+ const r = embedResponses[Math.min(i, embedResponses.length - 1)];
+ i += 1;
+ return Promise.resolve(typeof r === 'function' ? r() : r);
+ });
+ };
+ // Only the /v1/embeddings POST calls, in order (filters out the probe).
+ const embedCalls = () => fetchSpy.mock.calls.filter(c => String(c[0]).includes('/embeddings'));
+
+ it('truncates a long input to the model context budget before sending', async () => {
+ const longText = 'x'.repeat(50000);
+ wireFetch([embedOk]);
+
+ const emb = await embeddings.generateEmbedding(longText);
+
+ expect(emb).toEqual([0.1, 0.2, 0.3]);
+ const body = JSON.parse(embedCalls()[0][1].body);
+ expect(body.input.length).toBe(Math.floor(2048 * 0.85 * 3)); // 5222 chars
+ expect(body.input.length).toBeLessThan(50000);
+ });
+
+ it('shrinks and retries when the backend still reports a context overflow', async () => {
+ wireFetch([contextOverflow, embedOk]);
+
+ const emb = await embeddings.generateEmbedding('x'.repeat(50000));
+
+ expect(emb).toEqual([0.1, 0.2, 0.3]);
+ const calls = embedCalls();
+ expect(calls.length).toBe(2);
+ const firstLen = JSON.parse(calls[0][1].body).input.length;
+ const secondLen = JSON.parse(calls[1][1].body).input.length;
+ expect(secondLen).toBe(Math.floor(firstLen / 2)); // halved on retry
+ });
+
+ it('returns null (not a throw) when input stays over context after shrinking', async () => {
+ wireFetch([contextOverflow]);
+ const emb = await embeddings.generateEmbedding('x'.repeat(50000));
+ expect(emb).toBeNull();
+ expect(embedCalls().length).toBeLessThanOrEqual(3); // bounded retries
+ });
+
+ it('does NOT shrink on a non-overflow error — fails fast with null', async () => {
+ wireFetch([{ ok: false, status: 500, text: async () => 'internal error', json: async () => ({}) }]);
+ const emb = await embeddings.generateEmbedding('short text');
+ expect(emb).toBeNull();
+ expect(embedCalls().length).toBe(1); // no retry on a non-context error
+ });
+
+ it('batch: falls back to per-item embedding when the batch overflows', async () => {
+ // Batch POST overflows; then each of the 2 items embeds individually.
+ wireFetch([contextOverflow, embedOk, embedOk]);
+
+ const out = await embeddings.generateBatchEmbeddings(['a', 'b']);
+
+ expect(out).toEqual([[0.1, 0.2, 0.3], [0.1, 0.2, 0.3]]);
+ expect(embedCalls().length).toBe(3);
+ });
+});