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

address review (ollama): fix the cache silently persisting nothing after its first flush

[._.]/ Adam Eivy6ab1ffd5c936
diff --git a/server/lib/fetchErrorChain.js b/server/lib/fetchErrorChain.js
index d33c39cb85..afa3041973 100644
--- a/server/lib/fetchErrorChain.js
+++ b/server/lib/fetchErrorChain.js
@@ -46,18 +46,24 @@ export function describeFetchError(err) {
* same request generally succeeds immediately on a fresh socket, which is what
* makes them worth one replay via `fetchWithTimeout`'s `shouldRetry`.
*
- * Deliberately narrow. It excludes timeouts (`AbortError`, `\btimeout\b`) that
- * broader classifiers like `ollamaManager`'s `isTransientPullError` include:
- * that one is retrying a multi-GB streamed download over a flaky link, where a
- * timeout really is worth another go, while a request-per-item probe loop that
- * retried timeouts would hand a merely-slow host double the traffic. Callers
- * needing the wider net should keep their own predicate over
- * `describeFetchError`.
+ * Deliberately narrow, and the exclusions are the load-bearing part. It matches
+ * NO timeout — not our own `AbortError`, not a bare `timeout`, and not the
+ * TCP-level `ETIMEDOUT`. Broader classifiers like `ollamaManager`'s
+ * `isTransientPullError` do include timeouts, correctly: that one is retrying a
+ * multi-GB streamed download over a flaky link, where another go is worth it.
+ * Here the caller is a per-item probe loop, so retrying a timeout would hand a
+ * merely-slow host double the traffic — the opposite of the politeness this
+ * whole path exists to provide. Callers needing the wider net should keep their
+ * own predicate over `describeFetchError`.
+ *
+ * `ECONNREFUSED` is kept despite not being a reuse artifact: nothing is
+ * listening, so the replay fails in milliseconds and costs the host nothing,
+ * and it genuinely recovers a request that raced a server restart.
*
* @param {unknown} err
* @returns {boolean}
*/
export function isReplayableConnectionError(err) {
- return /GOAWAY|ECONNRESET|EPIPE|ETIMEDOUT|ECONNREFUSED|socket hang up|other side closed|UND_ERR_SOCKET/i
+ return /GOAWAY|ECONNRESET|EPIPE|ECONNREFUSED|socket hang up|other side closed|UND_ERR_SOCKET/i
.test(describeFetchError(err));
}
diff --git a/server/services/huggingFaceCatalog.test.js b/server/services/huggingFaceCatalog.test.js
index 25eb2194cf..4e8efc501a 100644
--- a/server/services/huggingFaceCatalog.test.js
+++ b/server/services/huggingFaceCatalog.test.js
@@ -982,17 +982,18 @@ describe('huggingFaceCatalog', () => {
expect(calls).toBe(2) // one retry, not an unbounded loop
})
- it('does not retry a timeout — a slow hub must not get double the traffic', async () => {
+ // Every flavour of timeout, not just our own AbortController's. A per-item
+ // probe loop that retried timeouts would hand a merely-slow Hub double the
+ // traffic — the opposite of the politeness this whole path exists to provide.
+ it.each([
+ ['our AbortController firing', () => Object.assign(new Error('The operation was aborted'), { name: 'AbortError' }), /aborted/i],
+ ['a TCP-level ETIMEDOUT', () => Object.assign(new TypeError('fetch failed'), { cause: Object.assign(new Error('connect ETIMEDOUT'), { code: 'ETIMEDOUT' }) }), /fetch failed/i]
+ ])('does not retry %s — a slow hub must not get double the traffic', async (_label, makeErr, expected) => {
let calls = 0
- fetch.mockImplementation(async () => {
- calls += 1
- const err = new Error('The operation was aborted')
- err.name = 'AbortError'
- throw err
- })
+ fetch.mockImplementation(async () => { calls += 1; throw makeErr() })
- await expect(searchHuggingFaceModels({ backend: 'lmstudio', query: 'timeout-not-retried' }))
- .rejects.toThrow(/aborted/i)
+ await expect(searchHuggingFaceModels({ backend: 'lmstudio', query: `timeout-${calls}` }))
+ .rejects.toThrow(expected)
expect(calls).toBe(1)
})
diff --git a/server/services/huggingFaceRepoCache.js b/server/services/huggingFaceRepoCache.js
index 49c6a9a278..eca8ff3a68 100644
--- a/server/services/huggingFaceRepoCache.js
+++ b/server/services/huggingFaceRepoCache.js
@@ -87,7 +87,16 @@ async function flush() {
// ~5 KB apiece — so on a long-lived server heavy search use would grow the
// process by tens of MB that never came back, while every flush re-sorted the
// whole set to write only the top 500.
- entries = new Map(capped)
+ //
+ // Prune IN PLACE — never `entries = new Map(capped)`. `load()` is memoized on
+ // its promise, so every reader and writer holds the Map instance that promise
+ // resolved to; rebinding here would leave them writing into the old Map while
+ // subsequent flushes serialized the new one, so nothing written after the
+ // first flush would ever persist. Regression-tested.
+ const keep = new Set(capped.map(([repoId]) => repoId))
+ for (const repoId of [...entries.keys()]) {
+ if (!keep.has(repoId)) entries.delete(repoId)
+ }
await ensureDir(join(PATHS.data, 'cache'))
await atomicWrite(CACHE_FILE, {
schemaVersion: CACHE_SCHEMA_VERSION,
@@ -104,25 +113,20 @@ function scheduleSave() {
saveTimer = setTimeout(() => {
flush().catch((err) => console.error(`❌ Failed to persist Hugging Face repo cache: ${err.message}`))
}, SAVE_DEBOUNCE_MS)
- // unref'd so a pending cache write never holds the process open — but that
- // means a restart landing inside the debounce window drops the batch and the
- // next boot re-pays the whole burst, which is the one cost this module exists
- // to remove. The shutdown flush below closes that window without giving up the
- // unref.
+ // unref'd so a pending cache write never holds the process open. A shutdown
+ // landing inside the debounce window therefore drops that batch and the next
+ // boot re-fetches it.
+ //
+ // Deliberately NOT closed with a SIGTERM/SIGINT handler. Registering a signal
+ // listener OVERRIDES Node's default terminate-on-signal, so a leaf cache
+ // module doing it would quietly take part-ownership of process shutdown —
+ // and in any context without another handler that calls `process.exit`
+ // (a script, a test, a one-off import) the process would stop dying on Ctrl-C.
+ // That is a severe failure mode to trade for a 2-second window whose entire
+ // cost is re-fetching a cache. Process lifecycle belongs to server/index.js.
saveTimer.unref?.()
}
-// Persist a pending batch on shutdown. Fire-and-forget by necessity — the signal
-// handler can't await — but atomicWrite's temp+rename means a half-written file
-// is never observable, and a dropped write only costs a refetch. `once` per
-// signal so repeated SIGTERMs don't stack handlers.
-for (const signal of ['SIGTERM', 'SIGINT']) {
- process.once(signal, () => {
- if (!dirty) return
- flush().catch((err) => console.error(`❌ Failed to flush Hugging Face repo cache on ${signal}: ${err.message}`))
- })
-}
-
/**
* Read a cached repo record.
* @returns {Promise<{ hit: boolean, model: object|null }>} `hit: false` on a miss
diff --git a/server/services/huggingFaceRepoCache.test.js b/server/services/huggingFaceRepoCache.test.js
index 01c9b2e10b..6a498090eb 100644
--- a/server/services/huggingFaceRepoCache.test.js
+++ b/server/services/huggingFaceRepoCache.test.js
@@ -78,6 +78,24 @@ describe('huggingFaceRepoCache', () => {
expect(Object.keys(onDisk.entries).sort()).toEqual(['new/Repo', 'third/Repo']);
});
+ // Regression: the prune in flush() must not swap the Map instance. load() is
+ // memoized on its PROMISE, so every reader/writer holds the Map that promise
+ // resolved to — rebinding `entries` left writes going into the old Map while
+ // flush() serialized the new one, silently persisting nothing after the first
+ // flush and serving evicted entries forever.
+ it('keeps persisting writes made after an earlier flush', async () => {
+ await cache.writeCachedRepoModel('first/Repo', { id: 'first/Repo' });
+ await cache.__flushRepoCache();
+
+ await cache.writeCachedRepoModel('second/Repo', { id: 'second/Repo' });
+ await cache.__flushRepoCache();
+
+ const onDisk = JSON.parse(await readFile(cacheFile(), 'utf8'));
+ expect(Object.keys(onDisk.entries).sort()).toEqual(['first/Repo', 'second/Repo']);
+ // ...and the reader must see it too, not a stale pre-flush Map.
+ expect(await cache.readCachedRepoModel('second/Repo')).toEqual({ hit: true, model: { id: 'second/Repo' } });
+ });
+
it('ignores a cache file written by a different schema version', async () => {
await mkdir(join(tempRoot, 'cache'), { recursive: true });
await writeFile(cacheFile(), JSON.stringify({