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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
refactor: route per-key write tails through createKeyCachedQueue (#2524)
Adam Eivy5734fd2ee394
diff --git a/server/lib/collectionStore.js b/server/lib/collectionStore.jsindex e02b0194a1..d1539382db 100644--- a/server/lib/collectionStore.js+++ b/server/lib/collectionStore.js@@ -88,6 +88,7 @@import { join } from 'path';import { readdir, lstat, rm } from 'fs/promises';import { atomicWrite, readJSONFile, ensureDir } from './fileUtils.js';+import { createFileWriteQueue, createRecordWriteQueue } from './fileWriteQueue.js';const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);@@ -166,39 +167,18 @@ export function createCollectionStore({// Per-record write queue. Tail-chained per `id` so two writes against the// same record serialize while writes against different records proceed in- // parallel. Mirrors `createFileWriteQueue` but keyed by id so the queue- // doesn't collapse to a single tail across the whole type.- //- // Map entries are pruned in `finally` once the chain settles to keep the- // map size bounded — see the `createFileWriteQueue` pattern for the same- // discipline at the single-tail level.- const recordTails = new Map();- function queueRecordWrite(id, fn) {+ // parallel. The shared `createRecordWriteQueue` helper carries the id-keyed+ // silence/self-prune discipline; the assert throws synchronously on a bad id+ // before anything is enqueued.+ const queueRecordWrite = createRecordWriteQueue((id) => {if (!isValidId(id)) {throw new Error(`collectionStore[${type}]: invalid record id "${id}" — must match ${idPattern}`);}- const prev = recordTails.get(id) || Promise.resolve();- const next = prev.then(fn, fn);- const silenced = next.catch(() => {});- recordTails.set(id, silenced);- silenced.finally(() => {- if (recordTails.get(id) === silenced) recordTails.delete(id);- });- return next;- }+ });// Type-index single-tail queue. Used by `saveTypeIndex` and by callers that// need a write-fence around config-slot updates (`runs[]`, feature flags).- let typeIndexTail = Promise.resolve();- function queueTypeIndexWrite(fn) {- const next = typeIndexTail.then(fn, fn);- const silenced = next.catch(() => {});- typeIndexTail = silenced;- silenced.finally(() => {- if (typeIndexTail === silenced) typeIndexTail = Promise.resolve();- });- return next;- }+ const queueTypeIndexWrite = createFileWriteQueue();const buildEmptyTypeIndex = () => ({schemaVersion,diff --git a/server/lib/fileWriteQueue.js b/server/lib/fileWriteQueue.jsindex 4f5d4f3b27..99970c531b 100644--- a/server/lib/fileWriteQueue.js+++ b/server/lib/fileWriteQueue.js@@ -1,3 +1,5 @@+import { createKeyCachedQueue } from './createKeyCachedQueue.js';+/*** File Write Queue — single-tail promise chain for serializing writes* against a shared JSON state file.@@ -60,16 +62,15 @@ export function createFileWriteQueue() {* Usage:* const queueRecordWrite = createRecordWriteQueue(assertValidId);* queueRecordWrite(id, () => saveOneNow(id, record));+ *+ * The per-key tail mechanics are `createKeyCachedQueue` — this is a thin wrapper+ * that adds the optional synchronous id validator (so a malformed id rejects+ * before it's ever enqueued).*/export function createRecordWriteQueue(assertId) {- const tails = new Map();+ const queue = createKeyCachedQueue();return function queueRecordWrite(id, fn) {if (assertId) assertId(id);- const prev = tails.get(id) || Promise.resolve();- const next = prev.then(fn, fn); // run fn even when prev rejects- const silenced = next.catch(() => {});- tails.set(id, silenced);- silenced.finally(() => { if (tails.get(id) === silenced) tails.delete(id); });- return next; // callers see the real resolve/reject+ return queue(id, fn); // callers see the real resolve/reject};}diff --git a/server/services/instances.js b/server/services/instances.jsindex 4408916bef..0b90a1969e 100644--- a/server/services/instances.js+++ b/server/services/instances.js@@ -10,6 +10,7 @@ import net from 'net';import crypto from 'crypto';import { dataPath, readJSONFile, ensureDir, PATHS, atomicWrite } from '../lib/fileUtils.js';import { createMutex } from '../lib/asyncMutex.js';+import { createKeyCachedQueue } from '../lib/createKeyCachedQueue.js';import { instanceEvents } from './instanceEvents.js';import { connectToPeer, disconnectFromPeer } from './peerSocketRelay.js';import { DEFAULT_PEER_PORT } from '../lib/ports.js';@@ -535,38 +536,31 @@ export async function updatePeer(id, updates) {// the peer and undo the newer change. Chaining per peer.id guarantees in-order// delivery, and each send re-reads the FRESHEST persisted category map (not a// value captured at enqueue time) so the final send always carries final state.-const reciprocalSyncTails = new Map();+// Per-peer serialization (silence prior + self-pruning tail) via the shared+// helper — `work` runs on both fulfil and reject of the prior send, so a failed+// send can't break the chain.+const reciprocalSyncQueue = createKeyCachedQueue();export function enqueueReciprocalSync(peerId) {- const prev = reciprocalSyncTails.get(peerId) || Promise.resolve();- const next = prev- .catch(() => {}) // a failed prior send must not break the chain- .then(async () => {- // Re-read the peer fresh at send time — the last enqueued send wins with- // the latest persisted syncCategories, regardless of enqueue order.- const data = await loadData();- const peer = data.peers.find(p => p.id === peerId);- if (!peer?.instanceId) return { ok: false, reason: 'no-peer-identity' };- // For a full-sync peer send the all-on category view (its stored- // syncCategories can be all-false underneath — sending that raw would tell- // the peer to DISABLE everything, since reciprocal-sync apply is an- // authoritative overlay; the all-on map also makes a peer too old to- // understand the fullSync flag still mirror every category) plus the- // fullSync flag. A regular peer keeps sending its raw partial map so a- // category it never set stays untouched on the peer (absent ≠ false).- const reciprocalCategories = peer.fullSync === true ? allSyncCategoriesOn() : (peer.syncCategories || {});- return requestReciprocalSync(peer, reciprocalCategories, { fullSync: peer.fullSync === true }).catch((err) => {- console.log(`⚠️ peer: reciprocal sync request failed: ${err.message}`);- return { ok: false, reason: err.message };- });+ return reciprocalSyncQueue(peerId, async () => {+ // Re-read the peer fresh at send time — the last enqueued send wins with+ // the latest persisted syncCategories, regardless of enqueue order.+ const data = await loadData();+ const peer = data.peers.find(p => p.id === peerId);+ if (!peer?.instanceId) return { ok: false, reason: 'no-peer-identity' };+ // For a full-sync peer send the all-on category view (its stored+ // syncCategories can be all-false underneath — sending that raw would tell+ // the peer to DISABLE everything, since reciprocal-sync apply is an+ // authoritative overlay; the all-on map also makes a peer too old to+ // understand the fullSync flag still mirror every category) plus the+ // fullSync flag. A regular peer keeps sending its raw partial map so a+ // category it never set stays untouched on the peer (absent ≠ false).+ const reciprocalCategories = peer.fullSync === true ? allSyncCategoriesOn() : (peer.syncCategories || {});+ return requestReciprocalSync(peer, reciprocalCategories, { fullSync: peer.fullSync === true }).catch((err) => {+ console.log(`⚠️ peer: reciprocal sync request failed: ${err.message}`);+ return { ok: false, reason: err.message };});- reciprocalSyncTails.set(peerId, next);- // Evict the tail once it settles and nothing newer has been chained, so the- // map doesn't grow unbounded across many peers/toggles.- next.finally(() => {- if (reciprocalSyncTails.get(peerId) === next) reciprocalSyncTails.delete(peerId);});- return next;}// --- Probing ---diff --git a/server/services/loraTraining/db.js b/server/services/loraTraining/db.jsindex d8330be39c..a8bcee20c1 100644--- a/server/services/loraTraining/db.js+++ b/server/services/loraTraining/db.js@@ -17,21 +17,14 @@import { query } from '../../lib/db.js';import { ServerError } from '../../lib/errorHandler.js';+import { createKeyCachedQueue } from '../../lib/createKeyCachedQueue.js';const rowToRun = (row) => row?.data ?? null;-// id → tail Promise. Serializes read-modify-write cycles for one run.-const writeTails = new Map();-function queueRunWrite(id, fn) {- const prev = writeTails.get(id) || Promise.resolve();- const next = prev.then(fn, fn);- const silenced = next.catch(() => {});- writeTails.set(id, silenced);- silenced.finally(() => {- if (writeTails.get(id) === silenced) writeTails.delete(id);- });- return next;-}+// id → tail Promise. Serializes read-modify-write cycles for one run; writes to+// different runs stay parallel. Same silence/prune discipline as the store+// facades — routed through the shared `createKeyCachedQueue` helper.+const queueRunWrite = createKeyCachedQueue();async function persist(run) {await query(diff --git a/server/services/pipeline/issues.js b/server/services/pipeline/issues.jsindex d2f7d6e98c..2f1a96b7e3 100644--- a/server/services/pipeline/issues.js+++ b/server/services/pipeline/issues.js@@ -21,6 +21,7 @@import { randomUUID } from 'crypto';import { getIssuesStore } from './issuesStore/store.js';import { isPlainObject } from '../../lib/objects.js';+import { createKeyCachedQueue } from '../../lib/createKeyCachedQueue.js';import { IMAGE_GEN_MODE } from '../imageGen/modes.js';import {LENGTH_PROFILE_NAMES, DEFAULT_LENGTH_PROFILE,@@ -53,17 +54,10 @@ export const issueStore = () => store();// so two concurrent writes to *different* issues in the same series could read a// stale index and clobber each other. A single tail per seriesId collapses that// race: each write awaits the previous one and merges against the freshest state.-const seriesIssueTails = new Map();+const seriesIssueQueue = createKeyCachedQueue();function queueSeriesIssuesWrite(seriesId, fn) {const key = typeof seriesId === 'string' && seriesId ? seriesId : '__unknown__';- const prev = seriesIssueTails.get(key) || Promise.resolve();- const next = prev.then(fn, fn);- const silenced = next.catch(() => {});- seriesIssueTails.set(key, silenced);- silenced.finally(() => {- if (seriesIssueTails.get(key) === silenced) seriesIssueTails.delete(key);- });- return next;+ return seriesIssueQueue(key, fn);}export const ERR_NOT_FOUND = 'PIPELINE_ISSUE_NOT_FOUND';diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.jsindex 709d25ca3c..164b0751cf 100644--- a/server/services/worktreeManager.js+++ b/server/services/worktreeManager.js@@ -14,6 +14,7 @@ import { readdir, rm, stat } from 'fs/promises';import { join } from 'path';import { ensureDir, PATHS, tryReadFile } from '../lib/fileUtils.js';import { execGit } from '../lib/execGit.js';+import { createKeyCachedQueue } from '../lib/createKeyCachedQueue.js';import { ensureInstanceId } from './instances.js';const WORKTREES_DIR = PATHS.worktrees;@@ -80,19 +81,12 @@ export function addWorktreeWithRetry(args, repo, attempt = 1, firstError = null)// settle before touching the shared `.git/worktrees` state. Keyed by// realpath-resolved repo path so /var vs /private/var (macOS) don't split the// tail into two lanes that can still collide.-const worktreeCreateTails = new Map();+const queueWorktreeCreateForKey = createKeyCachedQueue();function queueWorktreeCreate(repo, fn) {let key = repo;try { key = realpathSync(repo); } catch { /* repo may not resolve — fall back to the raw path */ }if (!key) key = '__unknown__';- const prev = worktreeCreateTails.get(key) || Promise.resolve();- const next = prev.then(fn, fn);- const silenced = next.catch(() => {});- worktreeCreateTails.set(key, silenced);- silenced.finally(() => {- if (worktreeCreateTails.get(key) === silenced) worktreeCreateTails.delete(key);- });- return next;+ return queueWorktreeCreateForKey(key, fn);}/**