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

refactor([extract-single-flight-map-helper]): extract createSingleFlight() keyed coalescer

[._.]/ Adam Eivy3b150e530210
diff --git a/server/lib/README.md b/server/lib/README.md
index c7c3affe17..a50373812c 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -190,6 +190,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `errorHandler.js` | `ServerError` + `asyncHandler` middleware. |
| `mapWithConcurrency.js` | Generic bounded-concurrency async mapper that preserves input order while capping in-flight work. |
| `objects.js` | Object utilities — `deepMerge` (recursive merge w/ array replacement), `isPlainObject` (non-null, non-array `object` guard for JSON / LLM payloads), `POLLUTING_KEYS` (shared `__proto__`/`constructor`/`prototype` denylist for sanitizers), `canonicalStringify` (recursive sorted-key JSON serialization for cross-machine content hashing), `isEmptyScalar` (true for null/undefined/whitespace-string/empty-array — merge gap-fill gate). |
+| `singleFlight.js` | `createSingleFlight()` → `run(key, fn)` — keyed in-flight coalescer: concurrent calls for the same key share one `fn()` execution and result; the slot auto-clears on settle. Minimal by design (no TTL/result cache layered on top, doesn't reject concurrent callers). Used by `promptRunner.js`'s fallback mark-and-pick. |
| `sseUtils.js` | Per-job SSE stream helpers (imageGen + others). |
| `uuid.js` | `v4()` thin wrapper over `crypto.randomUUID()`. |
diff --git a/server/lib/index.js b/server/lib/index.js
index 75fcddf51b..92bc7292c5 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -157,6 +157,7 @@ export * from './asyncMutex.js';
export * from './errorHandler.js';
export * from './mapWithConcurrency.js';
export * from './objects.js';
+export * from './singleFlight.js';
export * from './sseUtils.js';
export * from './uuid.js';
diff --git a/server/lib/promptRunner.js b/server/lib/promptRunner.js
index a9b8e38e77..c1747cb5fa 100644
--- a/server/lib/promptRunner.js
+++ b/server/lib/promptRunner.js
@@ -33,6 +33,7 @@ import { ServerError } from './errorHandler.js';
import { PROVIDER_TYPES } from './aiToolkit/constants.js';
import { analyzeError, ERROR_CATEGORIES } from './aiToolkit/errorDetection.js';
import { getAIToolkitInstance } from './aiToolkitState.js';
+import { createSingleFlight } from './singleFlight.js';
// noteFallbackHandled lives in services/autoFixer.js, which transitively
// pulls in services/cos.js (PM2 + fs + sockets). Importing it lazily on
@@ -320,9 +321,9 @@ export async function runPromptThroughProvider(args) {
// calls) every failure would otherwise independently re-read providers.json
// (pickFallbackProvider) and re-write provider-status.json (markUnavailable).
// Sharing the first failure's promise collapses that to a single read +
-// single write. The entry is deleted as soon as it settles, so a genuinely
-// new failure after the storm re-picks against fresh provider status.
-const _fallbackMarkAndPickInFlight = new Map();
+// single write. The slot clears as soon as it settles, so a genuinely new
+// failure after the storm re-picks against fresh provider status.
+const _fallbackMarkAndPick = createSingleFlight();
/**
* Mark the failed provider unavailable and pick its fallback, coalescing
@@ -337,29 +338,14 @@ const _fallbackMarkAndPickInFlight = new Map();
* @returns {Promise<{ provider: object, model: string|null }|null>}
*/
function coalesceFallbackMarkAndPick(failed, firstError) {
- const existing = _fallbackMarkAndPickInFlight.get(failed.id);
- if (existing) return existing;
-
- const work = (async () => {
+ return _fallbackMarkAndPick.run(failed.id, async () => {
const picked = await pickFallbackProvider(failed);
if (!picked) return null;
await markProviderUnavailableFromError(failed, firstError.message, firstError.errorAnalysis).catch(err => {
console.error(`❌ markUnavailable failed for ${failed.id}: ${err.message}`);
});
return picked;
- })();
-
- // While `work` is in flight, concurrent callers return it without
- // overwriting the slot, so this entry is only ever cleared by its own
- // settle — a plain delete is safe. Use `then(cleanup, cleanup)` rather
- // than `finally`: `finally` re-raises a `work` rejection on the derived
- // promise, which nothing awaits → unhandledRejection. The two-arm `then`
- // handles both settle paths and swallows the cleanup branch's copy of the
- // rejection; the caller's own `await work` still sees the original reject.
- const clearSlot = () => { _fallbackMarkAndPickInFlight.delete(failed.id); };
- _fallbackMarkAndPickInFlight.set(failed.id, work);
- work.then(clearSlot, clearSlot);
- return work;
+ });
}
/**
diff --git a/server/lib/singleFlight.js b/server/lib/singleFlight.js
new file mode 100644
index 0000000000..72481c645a
--- /dev/null
+++ b/server/lib/singleFlight.js
@@ -0,0 +1,45 @@
+/**
+ * Keyed single-flight coalescer.
+ *
+ * `run(key, fn)` returns the in-flight promise already registered for `key`
+ * if one exists; otherwise it invokes `fn()`, stores the resulting promise
+ * under `key`, and auto-clears the slot once that promise settles (resolve
+ * OR reject). Concurrent callers for the same key therefore share one `fn()`
+ * execution and one result, and a genuinely-new call after the slot clears
+ * starts fresh work.
+ *
+ * Minimal by design — it coalesces keyed work and nothing more:
+ * - It does NOT layer a TTL / result cache on top. `aiToolkit/providers.js`
+ * keeps its own snapshot cache in FRONT of this (TTL check, then coalesce).
+ * - It does NOT reject concurrent callers. `sseDownload.js` deliberately uses
+ * the opposite "reject-if-busy" idiom (a second client can't share one
+ * client's SSE event stream, and it holds a kill handle rather than a
+ * shareable promise), so it is intentionally NOT built on this helper.
+ *
+ * Cleanup uses a two-arm `then(clear, clear)` rather than `.finally`: a
+ * `.finally` on the stored promise re-raises a rejection on a derived promise
+ * that nothing awaits → unhandledRejection. The two-arm `then` clears the slot
+ * on both settle paths and swallows the cleanup branch's copy of the rejection,
+ * while each caller's own `await run(...)` still observes the original reject.
+ *
+ * @returns {{ run: <T>(key: any, fn: () => Promise<T>) => Promise<T> }}
+ */
+export function createSingleFlight() {
+ const inFlight = new Map(); // key -> shared in-flight promise
+
+ function run(key, fn) {
+ const existing = inFlight.get(key);
+ if (existing) return existing;
+
+ const work = fn();
+ inFlight.set(key, work);
+ // Identity-guarded delete: `run` never overwrites a live slot, so the
+ // entry can only be the promise we set — but guarding on identity keeps
+ // a late settle from clobbering a fresh entry under the same key.
+ const clear = () => { if (inFlight.get(key) === work) inFlight.delete(key); };
+ work.then(clear, clear);
+ return work;
+ }
+
+ return { run };
+}
diff --git a/server/lib/singleFlight.test.js b/server/lib/singleFlight.test.js
new file mode 100644
index 0000000000..c4ad552ab1
--- /dev/null
+++ b/server/lib/singleFlight.test.js
@@ -0,0 +1,83 @@
+import { describe, it, expect } from 'vitest';
+import { createSingleFlight } from './singleFlight.js';
+
+const tick = () => new Promise(r => setTimeout(r, 0));
+
+describe('createSingleFlight', () => {
+ it('coalesces concurrent calls for the same key onto one fn execution', async () => {
+ const sf = createSingleFlight();
+ let calls = 0;
+ let release;
+ const fn = () => {
+ calls += 1;
+ return new Promise(r => { release = r; });
+ };
+
+ const a = sf.run('k', fn);
+ const b = sf.run('k', fn);
+ expect(calls).toBe(1);
+ expect(a).toBe(b); // same shared promise
+
+ release('value');
+ expect(await a).toBe('value');
+ expect(await b).toBe('value');
+ });
+
+ it('runs separate fns for distinct keys', async () => {
+ const sf = createSingleFlight();
+ const calls = [];
+ const make = (label) => () => { calls.push(label); return Promise.resolve(label); };
+
+ const [a, b] = await Promise.all([sf.run('x', make('x')), sf.run('y', make('y'))]);
+ expect(a).toBe('x');
+ expect(b).toBe('y');
+ expect(calls.sort()).toEqual(['x', 'y']);
+ });
+
+ it('clears the slot on resolve so a later call starts fresh work', async () => {
+ const sf = createSingleFlight();
+ let calls = 0;
+ const fn = () => { calls += 1; return Promise.resolve(calls); };
+
+ expect(await sf.run('k', fn)).toBe(1);
+ await tick();
+ expect(await sf.run('k', fn)).toBe(2); // slot cleared, fn ran again
+ expect(calls).toBe(2);
+ });
+
+ it('clears the slot on reject and propagates the original error to all callers', async () => {
+ const sf = createSingleFlight();
+ const err = new Error('boom');
+ let calls = 0;
+ const fn = () => { calls += 1; return Promise.reject(err); };
+
+ const a = sf.run('k', fn);
+ const b = sf.run('k', fn);
+ expect(calls).toBe(1);
+ await expect(a).rejects.toBe(err);
+ await expect(b).rejects.toBe(err);
+
+ await tick();
+ // Slot cleared after the rejection settled — a fresh call re-runs.
+ const c = sf.run('k', fn);
+ await expect(c).rejects.toBe(err);
+ expect(calls).toBe(2);
+ });
+
+ it('does not emit an unhandledRejection when no one awaits a rejecting slot', async () => {
+ const sf = createSingleFlight();
+ const seen = [];
+ const onUnhandled = (e) => seen.push(e);
+ process.on('unhandledRejection', onUnhandled);
+
+ // Fire-and-forget a rejecting run; attach no awaiter to the returned promise
+ // beyond a swallowing catch so Node's own bookkeeping stays quiet, then make
+ // sure the helper's internal cleanup arm didn't itself surface a rejection.
+ sf.run('k', () => Promise.reject(new Error('ignored'))).catch(() => {});
+ await tick();
+ await tick();
+
+ process.off('unhandledRejection', onUnhandled);
+ expect(seen).toEqual([]);
+ });
+});