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([issue-1803]): extract shared boundedMap eviction helper for orphan-terminal race buffers

Adam Eivyf99fa6d88bf3
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index f262f2df93..87da49e4ff 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -139,4 +139,5 @@
- **[issue-1628] Editorial checks can now declare more than one scope.** A check meaningful at multiple granularities may set `scope: ['series','issue']` instead of being split into two near-duplicate checks; the single-string form keeps working. `normalizeCheckScopes`/`primaryCheckScope` normalize either form, the load-time registry guard validates every member (rejecting empty arrays, unknown members, and duplicates), and `resolveCheckState` exposes both a primary `scope` string (for single-value consumers) and the full `scopes` array — so the catalog grouping and dry-run plan list a dual-scope check under each of its scopes. No built-in check is multi-scope yet; this is the architecture. (`server/lib/editorial/checkRegistry.js`, `server/services/pipeline/editorial/checkRunner.js`, `client/src/lib/editorialChecks.js`)
- **[issue-1544] Dedup the arc-planner's season-tree grouping and episode-match logic.** Extracted `groupIssuesBySeasonTree` (backs both the arc-verify and beat-continuity context builders) and `seasonIdByNumberOf` + `matchIssueForEpisodeEdit` (back both the arc-resolve and beat-continuity episode-correction passes) into `arcPlanner/context.js`. Pure refactor — prompt output and match semantics are unchanged. (`server/services/pipeline/arcPlanner/`)
- **[issue-1798] Dedup the Music Video board's image/video render socket effects behind one hook.** The reference-frame and i2v scene-clip lanes had two near-verbatim socket-lifecycle `useEffect`s plus duplicated spinner state, pending/orphan refs, and orphan-reconcile callbacks — they differed only in event names, the apply callback, and the failure-toast string. Extracted a `useSceneRenderLifecycle` hook (the client-side analog of #1791's server `createMediaJobImageHook` unification) that owns a lane's `genScenes` spinner state, job-id→scene correlation, orphan-terminal reconcile, and the durable-attach + `*-gen:completed/failed/canceled` subscription (with the running-cancel toast disambiguation preserved); each lane is now one `useSceneRenderLifecycle({...})` call plus a `trackJob(jobId, sceneId)` in its generate handler. Behavior is unchanged; covered by a new `renderHook` test. (`client/src/hooks/useSceneRenderLifecycle.js`, `client/src/pages/MusicVideo.jsx`)
+- **[issue-1803] Dedup the orphan-terminal race-buffer eviction behind a shared `boundedMap` helper.** Three client race-buffers hand-rolled the same "stash an unmatched event in a `jobId → …` Map, evict the oldest when it overflows 64" idiom (`useSceneRenderLifecycle`, `useImageGenQueue`, `clientErrorReporter`). Extracted `evictOldest(map, max, onEvict?)` and the shared `ORPHAN_BUFFER_MAX` cap into `client/src/lib/boundedMap.js` (barrel + README + unit tests), then routed all three call sites through it — the eviction logic and the magic `64` for the two orphan buffers now live in one place. The error-dedup cache keeps its own `MAX_RECENT` (a separate tuning knob) but shares the eviction primitive. Behavior is unchanged. (`client/src/lib/boundedMap.js`, `client/src/hooks/useSceneRenderLifecycle.js`, `client/src/hooks/useImageGenQueue.js`, `client/src/lib/clientErrorReporter.js`)
- **Bump bundled slashdo to v3.19.0 — `/do:next --self` restricts issue work to issues you filed.** A new `--self`/`--no-self` security gate (and saved `self` default) filters auto-pick, swarm batches, and explicit `#<num>` claims to issues authored by the running `gh`/`glab` account (`@me`) — an explicit number for someone else's issue is refused, not overridden — so a shared tracker never auto-feeds third-party issues (and the instructions embedded in them) into an agent. Builds on v3.18.0's `--swarm` (parallel multi-issue draining, each in its own worktree, merge-gated on CI) and v3.17.2's dependency-/priority-aware backlog ordering. (`lib/slashdo` submodule)
diff --git a/client/src/hooks/useImageGenQueue.js b/client/src/hooks/useImageGenQueue.js
index 205505cac3..e6938d1247 100644
--- a/client/src/hooks/useImageGenQueue.js
+++ b/client/src/hooks/useImageGenQueue.js
@@ -1,6 +1,7 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import socket from '../services/socket';
import { cancelImageGen } from '../services/apiImageVideo';
+import { evictOldest, ORPHAN_BUFFER_MAX } from '../lib/boundedMap';
import toast from '../components/ui/Toast';
// useImageGenQueue — work-scoped live queue of in-flight image renders.
@@ -16,10 +17,10 @@ import toast from '../components/ui/Toast';
// Orphan-event buffer hygiene: image-gen:* events are emitted globally
// (server only knows generationId, not which page issued it), so any image
// render anywhere in the app would otherwise pile up entries here. We cap
-// the buffer to ORPHAN_MAX_ENTRIES and evict each entry ORPHAN_TTL_MS after
-// last write — preventing unbounded memory growth on long-lived sessions.
+// the buffer to ORPHAN_BUFFER_MAX (shared with the other orphan race-buffers)
+// and evict each entry ORPHAN_TTL_MS after last write — preventing unbounded
+// memory growth on long-lived sessions.
const ORPHAN_TTL_MS = 30_000;
-const ORPHAN_MAX_ENTRIES = 64;
export default function useImageGenQueue() {
const [queue, setQueue] = useState([]);
@@ -81,15 +82,13 @@ export default function useImageGenQueue() {
orphanEventsRef.current.delete(jobId);
}, ORPHAN_TTL_MS);
orphanTimersRef.current.set(jobId, t);
- // Hard cap: drop the oldest entry if we're over budget.
- while (orphanEventsRef.current.size > ORPHAN_MAX_ENTRIES) {
- const oldest = orphanEventsRef.current.keys().next().value;
- if (oldest === undefined) break;
+ // Hard cap: drop the oldest entry(ies) if we're over budget, tearing down
+ // each evicted entry's companion TTL timer as it goes.
+ evictOldest(orphanEventsRef.current, ORPHAN_BUFFER_MAX, (oldest) => {
const oldTimer = orphanTimersRef.current.get(oldest);
if (oldTimer) clearTimeout(oldTimer);
orphanTimersRef.current.delete(oldest);
- orphanEventsRef.current.delete(oldest);
- }
+ });
}, []);
const register = useCallback(({ jobId, sceneId, sceneLabel }) => {
diff --git a/client/src/hooks/useSceneRenderLifecycle.js b/client/src/hooks/useSceneRenderLifecycle.js
index 9cdd703fe7..71ba121d87 100644
--- a/client/src/hooks/useSceneRenderLifecycle.js
+++ b/client/src/hooks/useSceneRenderLifecycle.js
@@ -1,6 +1,7 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import socket from '../services/socket';
import { getMediaJob } from '../services/apiMediaJobs';
+import { evictOldest, ORPHAN_BUFFER_MAX } from '../lib/boundedMap';
import toast from '../components/ui/Toast';
/**
@@ -110,7 +111,7 @@ export default function useSceneRenderLifecycle({
// reconcile; cap so other pages' renders can't grow this unbounded.
const orphans = orphanRef.current;
orphans.set(jobId, !!failed);
- if (orphans.size > 64) orphans.delete(orphans.keys().next().value);
+ evictOldest(orphans, ORPHAN_BUFFER_MAX);
return;
}
pendingRef.current.delete(jobId);
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 40bfeb117d..d59dc9ee11 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -69,6 +69,7 @@ grep -i "what you want to do" client/src/lib/README.md
|---|---|
| `applyManuscriptEdits.js` | `applyEditsToContent(content, edits, anchorQuote)` — PREVIEW-ONLY client mirror of the server's accept splice (`server/services/pipeline/manuscriptFix.js`): locate each `find` (nearest the anchor when recurring), drop overlaps, replace bottom-up. Powers the Manuscript editor's whole-manuscript impact preview. |
| `audioRecorder.js` | `startMemoRecording()` → `{ stream, stop, cancel }` handle whose `stop()` resolves to `{ audioBase64, mimeType, peak, durationMs }` (16 kHz mono WAV, base64); the live `stream` lets a tuner tap the same mic. `createStreamAnalyser(stream, { fftSize })` → `{ analyser, context, close }` taps an `AnalyserNode` off an existing stream (no second getUserMedia). Plus `blobToWav16k`, `encodePcmToWav`, `pickRecordingMimeType`, `arrayBufferToBase64`. Standalone one-shot memo capture for catalog voice ingest — NOT the live voice-agent recorder in `services/voiceClient.js`. |
+| `boundedMap.js` | `evictOldest(map, max, onEvict?)` — evict oldest-first (`map.keys().next().value`) until a Map is within `max`, with an optional per-evicted-key teardown callback for a companion timer map; `ORPHAN_BUFFER_MAX` (64), the shared cap for the orphan-event race-buffers. The one home for the "stash an unmatched event in a `jobId → …` Map, evict the oldest on overflow" idiom shared by `useSceneRenderLifecycle`, `useImageGenQueue`, and `clientErrorReporter`. |
| `clientErrorReporter.js` | `reportClientError({ type, error?, message?, ... })` — POSTs window.onerror + unhandledrejection events to `/api/client-errors` with throttle + dedup. Wired from `main.jsx`; never call directly from React components. |
| `clinicianReport.js` | Pure builders for the MeatSpace clinician-export view (`/meatspace/export`). `buildClinicianReport({ tests, config })` → structured report model (blood panels grouped by category with reference ranges + out-of-range flags, plus a lifestyle summary); `reportToMarkdown(report)` → copy-paste markdown. Reuses the Blood tab's `REFERENCE_RANGES` / `getBloodValueStatus` so printed flags match the UI. Also exports `buildBloodTestModel`, `buildLifestyleModel`, `getCategoryForKey`, `formatRange`. |
| `clipboard.js` | `copyToClipboard`, `writeClipboardSilently`, `readClipboard` — safe across insecure-origin contexts. Use these instead of `navigator.clipboard.writeText` inline. |
diff --git a/client/src/lib/boundedMap.js b/client/src/lib/boundedMap.js
new file mode 100644
index 0000000000..c786fd6d5c
--- /dev/null
+++ b/client/src/lib/boundedMap.js
@@ -0,0 +1,42 @@
+// Bounded race-buffer eviction (#1803). Three client race-buffers each
+// hand-rolled the same idiom: stash an unmatched event in a `jobId → …` Map,
+// then evict the oldest entry once the Map overflows a hard cap. Map iteration
+// order is insertion order, so `map.keys().next().value` is always the oldest
+// surviving key — `delete()`-ing it is the cheap "evict oldest" primitive.
+// Callers that want LRU semantics refresh a touched entry by `delete()` +
+// `set()` before writing, moving it to the newest position so it survives the
+// next eviction.
+//
+// Call sites routed through here:
+// - useSceneRenderLifecycle.js (orphan-terminal buffer)
+// - useImageGenQueue.js (orphan-event buffer, plus a companion TTL map)
+// - clientErrorReporter.js (error-dedup hash cache)
+
+// Shared cap for the orphan race-buffers: the max number of distinct
+// not-yet-correlated jobIds to buffer before evicting the oldest. Without it,
+// unrelated global media-job events from elsewhere in the app would grow the
+// buffer unbounded on a long-lived session. (The error-dedup cache keeps its
+// own `MAX_RECENT` — a separate tuning knob — but shares the eviction logic.)
+export const ORPHAN_BUFFER_MAX = 64;
+
+/**
+ * Evict the oldest entries from `map` until `map.size <= max`. Map iteration
+ * order is insertion order, so `map.keys().next().value` is the oldest
+ * surviving key. `onEvict(key)` (optional) runs for each removed key — use it
+ * to tear down a companion per-entry resource (e.g. clear a TTL timer held in
+ * a parallel timers Map). Returns the number of entries evicted.
+ *
+ * No-op when already within budget. The `undefined`-key break defensively
+ * guards a map that empties mid-loop (size > max already implies a key exists).
+ */
+export function evictOldest(map, max, onEvict) {
+ let evicted = 0;
+ while (map.size > max) {
+ const oldest = map.keys().next().value;
+ if (oldest === undefined) break;
+ map.delete(oldest);
+ if (onEvict) onEvict(oldest);
+ evicted += 1;
+ }
+ return evicted;
+}
diff --git a/client/src/lib/boundedMap.test.js b/client/src/lib/boundedMap.test.js
new file mode 100644
index 0000000000..d3a1f9bd5b
--- /dev/null
+++ b/client/src/lib/boundedMap.test.js
@@ -0,0 +1,55 @@
+import { describe, it, expect, vi } from 'vitest';
+import { evictOldest, ORPHAN_BUFFER_MAX } from './boundedMap.js';
+
+describe('evictOldest', () => {
+ it('is a no-op when the map is within budget', () => {
+ const m = new Map([['a', 1], ['b', 2]]);
+ expect(evictOldest(m, 2)).toBe(0);
+ expect([...m.keys()]).toEqual(['a', 'b']);
+ });
+
+ it('evicts oldest-first until size <= max', () => {
+ const m = new Map([['a', 1], ['b', 2], ['c', 3], ['d', 4]]);
+ expect(evictOldest(m, 2)).toBe(2);
+ // 'a' and 'b' were inserted first → evicted; newest two survive.
+ expect([...m.keys()]).toEqual(['c', 'd']);
+ });
+
+ it('treats a delete()+set() refresh as LRU — refreshed key survives', () => {
+ const m = new Map([['a', 1], ['b', 2], ['c', 3]]);
+ // Touch 'a': move it to the newest position.
+ m.delete('a');
+ m.set('a', 11);
+ evictOldest(m, 2);
+ // 'b' is now the oldest and is evicted; 'a' survives despite being inserted first.
+ expect([...m.keys()]).toEqual(['c', 'a']);
+ });
+
+ it('invokes onEvict(key) for each removed key, after the map delete', () => {
+ const m = new Map([['a', 1], ['b', 2], ['c', 3]]);
+ const seen = [];
+ evictOldest(m, 1, (key) => {
+ seen.push(key);
+ expect(m.has(key)).toBe(false); // already removed from the main map
+ });
+ expect(seen).toEqual(['a', 'b']);
+ expect([...m.keys()]).toEqual(['c']);
+ });
+
+ it('returns 0 and does nothing for an empty map', () => {
+ const m = new Map();
+ const onEvict = vi.fn();
+ expect(evictOldest(m, 0, onEvict)).toBe(0);
+ expect(onEvict).not.toHaveBeenCalled();
+ });
+
+ it('can drain to zero when max is 0', () => {
+ const m = new Map([['a', 1], ['b', 2]]);
+ expect(evictOldest(m, 0)).toBe(2);
+ expect(m.size).toBe(0);
+ });
+
+ it('exposes the shared orphan-buffer cap', () => {
+ expect(ORPHAN_BUFFER_MAX).toBe(64);
+ });
+});
diff --git a/client/src/lib/clientErrorReporter.js b/client/src/lib/clientErrorReporter.js
index 7e4c9ea33d..f01bd027f3 100644
--- a/client/src/lib/clientErrorReporter.js
+++ b/client/src/lib/clientErrorReporter.js
@@ -9,6 +9,8 @@
* swallowed so the unhandledrejection handler can't recurse into itself.
*/
+import { evictOldest } from './boundedMap.js';
+
const ENDPOINT = '/api/client-errors';
const MIN_SEND_INTERVAL_MS = 1000;
const DEDUP_WINDOW_MS = 60 * 1000;
@@ -37,10 +39,8 @@ function pruneRecent(now) {
for (const [hash, sentAt] of recentHashes) {
if (now - sentAt > DEDUP_WINDOW_MS) recentHashes.delete(hash);
}
- while (recentHashes.size > MAX_RECENT) {
- const oldest = recentHashes.keys().next().value;
- recentHashes.delete(oldest);
- }
+ // After the TTL sweep, enforce the hard size cap by evicting oldest-first.
+ evictOldest(recentHashes, MAX_RECENT);
}
// Guarded stringify so a circular rejection reason or a value that throws
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index bd03c75347..5f1785cf44 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -41,6 +41,7 @@ export * from './graphSimulation.js';
// === Generic UI / collection utilities ===
export * from './applyManuscriptEdits.js';
export * from './audioRecorder.js';
+export * from './boundedMap.js';
export * from './clientErrorReporter.js';
export * from './clinicianReport.js';
export * from './clipboard.js';