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
fix([issue-3704]): cap background brctl children and key single-flight by encoding
Adam Eivy9b438784930a
diff --git a/server/lib/icloudFile.js b/server/lib/icloudFile.jsindex d6e0f36c4e..44297d4a34 100644--- a/server/lib/icloudFile.js+++ b/server/lib/icloudFile.js@@ -90,10 +90,17 @@ function markBrctlMissing() {}// Dedupe of in-flight background materializations, keyed by path, so repeated-// reads of the same evicted file don't spawn a `brctl` per request. Cleared when-// the child fails or exits non-zero so a later read can retry.+// reads of the same evicted file don't spawn a `brctl` per request. Entries clear+// when the child exits, so a later read can retry.const pendingDownloads = new Set();+// Hard cap on concurrent background downloads. Without it, a vault-wide walk over+// an evicted Obsidian vault (one read per note) would spawn one `brctl` child per+// note — thousands of processes for a large vault. Skipping the heal past the cap+// is safe: the read is refused either way, and the set drains as children exit so+// later reads pick up where this one stopped.+const MAX_PENDING_DOWNLOADS = 4;+/*** Fire-and-forget `brctl download <path>` so an evicted file heals in the* background. Detached + unref'd so a slow download can't keep the process@@ -103,6 +110,7 @@ const pendingDownloads = new Set();export function requestMaterialization(path, label = 'iCloud file') {if (process.platform !== 'darwin' || !path) return false;if (pendingDownloads.has(path)) return false;+ if (pendingDownloads.size >= MAX_PENDING_DOWNLOADS) return false;pendingDownloads.add(path);// try/catch at a child-process boundary (permitted by the repo's no-try/catch@@ -167,7 +175,10 @@ let readFlight = createSingleFlight();* doesn't starve the process.*/export async function readIfMaterialized(path, options = {}) {- return readFlight.run(path, () => guardedRead(path, options));+ const { encoding = 'utf-8' } = options;+ // Key on encoding too: two concurrent callers asking for different encodings+ // must not share one result (a utf-8 string is not a base64 string).+ return readFlight.run(`${encoding}\u0000${path}`, () => guardedRead(path, options));}async function guardedRead(path, options) {diff --git a/server/lib/icloudFile.test.js b/server/lib/icloudFile.test.jsindex ce10cc6408..355ef3c197 100644--- a/server/lib/icloudFile.test.js+++ b/server/lib/icloudFile.test.js@@ -257,3 +257,44 @@ describe('requestMaterialization', () => {expect(spawnMock).not.toHaveBeenCalled();});});++describe('background-download safety caps', () => {+ it('caps concurrent brctl children so an evicted vault walk cannot fork thousands', async () => {+ statMock.mockResolvedValue(datalessStats);+ // A vault walk hits a distinct path per note. Without a cap this would be one+ // `brctl download` child per note.+ for (let i = 0; i < 50; i++) {+ await icloud.readIfMaterialized(`${UBIQUITY_DIR}/note-${i}.md`).catch(() => {});+ }+ expect(spawnMock.mock.calls.length).toBeLessThanOrEqual(4);+ });++ it('resumes healing later notes once earlier downloads exit', async () => {+ statMock.mockResolvedValue(datalessStats);+ const children = [];+ spawnMock.mockImplementation(() => { const c = makeFakeChild(); children.push(c); return c; });++ for (let i = 0; i < 10; i++) {+ await icloud.readIfMaterialized(`${UBIQUITY_DIR}/a-${i}.md`).catch(() => {});+ }+ expect(spawnMock).toHaveBeenCalledTimes(4);++ // Drain the in-flight set; the next read is free to kick a download again.+ children.forEach(c => c.emit('exit', 0, null));+ await icloud.readIfMaterialized(`${UBIQUITY_DIR}/b.md`).catch(() => {});+ expect(spawnMock).toHaveBeenCalledTimes(5);+ });++ it('does not hand a base64 caller the utf-8 caller\'s result', async () => {+ statMock.mockResolvedValue(materializedStats);+ readFileMock.mockImplementation((_p, enc) => Promise.resolve(`body-as-${enc}`));++ const [utf8, b64] = await Promise.all([+ icloud.readIfMaterialized(ICLOUD_PATH),+ icloud.readIfMaterialized(ICLOUD_PATH, { encoding: 'base64' }),+ ]);++ expect(utf8).toBe('body-as-utf-8');+ expect(b64).toBe('body-as-base64');+ });+});diff --git a/server/services/obsidian.js b/server/services/obsidian.jsindex 860328ae11..760bb6c3d2 100644--- a/server/services/obsidian.js+++ b/server/services/obsidian.js@@ -238,7 +238,9 @@ export async function getNote(vaultId, notePath, { includeBacklinks = true } = {// Evicted, not missing — a distinct code so the UI can say "iCloud hasn't// downloaded this note yet" instead of claiming it doesn't exist. The read was// never issued, and a background `brctl download` is already in flight.- if (content === null) return { error: 'NOTE_EVICTED' };+ if (content === null) {+ return { error: 'NOTE_EVICTED', message: 'This note is stored in iCloud and has not been downloaded to this Mac yet. A download was requested — try again shortly.' };+ }const stats = await stat(fullPath);const { frontmatter, tags, wikilinks, body } = parseNoteMetadata(content);