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 (claude): fix permanent replenish stall after draining a primed cache to zero

[._.]/ Adam Eivy8620fef8740b
diff --git a/server/services/meatspacePostDrillCache.js b/server/services/meatspacePostDrillCache.js
index 5a6625602c..a6dbfc65aa 100644
--- a/server/services/meatspacePostDrillCache.js
+++ b/server/services/meatspacePostDrillCache.js
@@ -27,12 +27,20 @@ const delay = ms => new Promise(r => setTimeout(r, ms));
let cache = {}; // { type: [drill, drill, ...] }
let replenishing = new Map(); // type -> Promise (in-flight replenishment)
let saveQueued = false;
+// Tracks which types have ever been successfully filled. "Cold" must be
+// derived from this, NOT from the live cache count — a type that drains to
+// 0 between consumption and replenishment (e.g. the user consumes faster
+// than the background top-up produces new items) would otherwise look
+// "never primed" again and permanently stop replenishing (see
+// meatspacePostDrillCache.test.js "stays warm after draining to zero").
+const primedTypes = new Set();
async function loadCache() {
const raw = await readFile(CACHE_FILE, 'utf-8').catch(() => '{}');
cache = safeJSONParse(raw, {});
for (const type of CACHEABLE_TYPES) {
if (!Array.isArray(cache[type])) cache[type] = [];
+ if (cache[type].length > 0) primedTypes.add(type);
}
}
@@ -68,6 +76,7 @@ function replenishType(type, providerId, model) {
});
if (drill) {
cache[type].push(drill);
+ primedTypes.add(type);
generated++;
consecutiveFailures = 0;
} else {
@@ -103,12 +112,13 @@ export function getCachedDrill(type) {
return result;
}
-// A type is "cold" when it has never been filled (0 cached). This is the one
-// place that defines cold vs. warm — triggerReplenish and getCacheStats both
-// read it, so a future change to the threshold (e.g. < MIN_PER_TYPE) can't
+// A type is "cold" until it has been successfully filled at least once —
+// tracked via primedTypes, not the live cache count (see the primedTypes
+// comment above for why). This is the one place that defines cold vs. warm —
+// triggerReplenish and getCacheStats both read it, so a future change can't
// drift between the background-replenish guard and what the client is told.
function isCacheCold(type) {
- return !cache[type]?.length;
+ return !primedTypes.has(type);
}
/**
diff --git a/server/services/meatspacePostDrillCache.test.js b/server/services/meatspacePostDrillCache.test.js
new file mode 100644
index 0000000000..a9690af1f9
--- /dev/null
+++ b/server/services/meatspacePostDrillCache.test.js
@@ -0,0 +1,88 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+
+// Mock file I/O so tests never touch disk. readFile rejects (no cache file
+// on disk yet) so loadCache() starts every CACHEABLE_TYPES entry at [].
+vi.mock('fs/promises', () => ({
+ readFile: vi.fn().mockRejectedValue(new Error('ENOENT')),
+}));
+
+vi.mock('../lib/fileUtils.js', () => ({
+ atomicWrite: vi.fn().mockResolvedValue(undefined),
+ ensureDir: vi.fn().mockResolvedValue(undefined),
+ PATHS: { data: '/tmp/test-data', meatspace: '/tmp/test-data/meatspace' },
+ safeJSONParse: (str, defaultValue) => {
+ try { return JSON.parse(str); } catch { return defaultValue; }
+ },
+}));
+
+vi.mock('./meatspacePostLlm.js', () => ({
+ generateLlmDrill: vi.fn(),
+}));
+
+import { generateLlmDrill } from './meatspacePostLlm.js';
+import {
+ initDrillCache, getCachedDrill, triggerReplenish, requestCacheFill, getCacheStats,
+} from './meatspacePostDrillCache.js';
+
+describe('meatspacePostDrillCache', () => {
+ beforeEach(async () => {
+ vi.clearAllMocks();
+ generateLlmDrill.mockImplementation(async (type) => ({ type, challenges: [{ rootWord: 'fire' }] }));
+ vi.useFakeTimers();
+ await initDrillCache();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('reports a never-filled type as cold with zero count', () => {
+ expect(getCacheStats()['compound-chain']).toEqual({ count: 0, cold: true });
+ });
+
+ it('triggerReplenish is a no-op on a cold (never-filled) type — no LLM calls without consent', async () => {
+ triggerReplenish('compound-chain', null, null);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(generateLlmDrill).not.toHaveBeenCalled();
+ expect(getCacheStats()['compound-chain'].cold).toBe(true);
+ });
+
+ it('requestCacheFill primes a type so it is no longer cold', async () => {
+ requestCacheFill(['compound-chain'], null, null);
+ await vi.advanceTimersByTimeAsync(20000);
+ const stats = getCacheStats()['compound-chain'];
+ expect(stats.cold).toBe(false);
+ expect(stats.count).toBeGreaterThan(0);
+ expect(generateLlmDrill).toHaveBeenCalled();
+ });
+
+ it('keeps replenishing after draining a primed type back to zero (regression)', async () => {
+ // Prime the type and let the fill batch fully complete.
+ requestCacheFill(['compound-chain'], null, null);
+ await vi.advanceTimersByTimeAsync(20000);
+ expect(getCacheStats()['compound-chain'].count).toBeGreaterThan(0);
+
+ // Drain every cached drill via normal consumption.
+ let drained;
+ do { drained = getCachedDrill('compound-chain'); } while (drained);
+ expect(getCacheStats()['compound-chain'].count).toBe(0);
+
+ // A type that has been primed at least once must stay "warm" even after
+ // draining to zero — the whole point is that background top-ups keep
+ // working silently going forward. Before the fix, isCacheCold() read the
+ // live (post-drain) count instead of a persistent primed flag, so this
+ // was misclassified as cold and permanently skipped replenishment.
+ expect(getCacheStats()['compound-chain'].cold).toBe(false);
+
+ generateLlmDrill.mockClear();
+ triggerReplenish('compound-chain', null, null);
+ await vi.advanceTimersByTimeAsync(20000);
+ expect(generateLlmDrill).toHaveBeenCalled();
+ expect(getCacheStats()['compound-chain'].count).toBeGreaterThan(0);
+ });
+
+ it('requestCacheFill ignores unknown drill types', () => {
+ const triggered = requestCacheFill(['not-a-real-type'], null, null);
+ expect(triggered).toEqual([]);
+ });
+});