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

fix: bound duration stats archive reads (#5124)

[._.]/ Adam Eivy18f429497c23
diff --git a/server/services/taskLearning/metrics.js b/server/services/taskLearning/metrics.js
index 69325e9b53..050e5b7cd2 100644
--- a/server/services/taskLearning/metrics.js
+++ b/server/services/taskLearning/metrics.js
@@ -7,7 +7,8 @@
* everything here mutates and persists `learning.json`.
*/
-import { existsSync, readdirSync } from 'fs';
+import { existsSync } from 'fs';
+import { readdir } from 'fs/promises';
import { join } from 'path';
import {
withLock,
@@ -30,11 +31,13 @@ import {
import { deriveFailureSignalAvoidance, isNonRoutableLearnedTier } from './routing.js';
import { recordCorrelationSample } from './correlationQuality.js';
import { isSkipLearningVerdict, toValidationVerdict } from '../../lib/learningVerdict.js';
+import { mapWithConcurrency } from '../../lib/mapWithConcurrency.js';
// Cap on retained per-category signature samples — bounds file growth the same
// way `recentUnknownErrors` does, while keeping enough recent context to spot
// trends (provider/model/tier correlation) without a full agent-archive scan.
const MAX_SIGNATURE_SAMPLES = 10;
+const ARCHIVE_READ_CONCURRENCY = 20;
// ENVIRONMENTAL_ERROR_CATEGORIES lives in store.js (the leaf module) so both
// this recorder and routing.js can consume it without deepening the existing
@@ -1006,22 +1009,25 @@ export async function recalculateDurationStats() {
let successCount = 0;
if (existsSync(AGENTS_DIR)) {
- const dateDirs = readdirSync(AGENTS_DIR, { withFileTypes: true })
+ const dateDirs = (await readdir(AGENTS_DIR, { withFileTypes: true }))
.filter(d => d.isDirectory() && /^\d{4}-\d{2}-\d{2}$/.test(d.name));
- // Collect all metadata paths then read in parallel
+ // Collect all metadata paths asynchronously, then cap reads so a large
+ // archive cannot exhaust file descriptors or spike memory.
const metaPaths = [];
for (const dateDir of dateDirs) {
const datePath = join(AGENTS_DIR, dateDir.name);
- const agentDirs = readdirSync(datePath, { withFileTypes: true })
+ const agentDirs = (await readdir(datePath, { withFileTypes: true }))
.filter(d => d.isDirectory());
for (const agentDir of agentDirs) {
metaPaths.push(join(datePath, agentDir.name, 'metadata.json'));
}
}
- const results = await Promise.all(
- metaPaths.map(p => tryReadFile(p))
+ const results = await mapWithConcurrency(
+ metaPaths,
+ ARCHIVE_READ_CONCURRENCY,
+ (path) => tryReadFile(path)
);
for (const raw of results) {
diff --git a/server/services/taskLearning/metricsDurationStats.test.js b/server/services/taskLearning/metricsDurationStats.test.js
index 08ab7daf1b..98713ea19e 100644
--- a/server/services/taskLearning/metricsDurationStats.test.js
+++ b/server/services/taskLearning/metricsDurationStats.test.js
@@ -13,8 +13,11 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
// The root is inlined in both factories below — `vi.mock` is hoisted above every
// top-level binding, so a shared const would be in its TDZ when they run.
vi.mock('fs', () => ({
- existsSync: vi.fn(() => true),
- readdirSync: vi.fn((path) => (
+ existsSync: vi.fn(() => true)
+}));
+
+vi.mock('fs/promises', () => ({
+ readdir: vi.fn(async (path) => (
path === '/tmp/portos-test-agents'
? [{ name: '2026-08-14', isDirectory: () => true }]
: [{ name: 'agent-a', isDirectory: () => true }, { name: 'agent-b', isDirectory: () => true }]
@@ -36,6 +39,7 @@ vi.mock('./store.js', async (importActual) => {
import { recalculateDurationStats } from './metrics.js';
import { tryReadFile, loadLearningData, saveLearningData } from './store.js';
import { SKIP_LEARNING_VERDICT } from '../../lib/learningVerdict.js';
+import { readdir } from 'fs/promises';
const makeData = () => ({
version: 1,
@@ -97,4 +101,33 @@ describe('recalculateDurationStats — skip verdict (#4107)', () => {
expect(saved.totals.successDurationMs).toBe(0);
});
+
+ it('uses async directory traversal and limits concurrent metadata reads', async () => {
+ const agentDirs = Array.from({ length: 25 }, (_, index) => ({
+ name: `agent-${index}`,
+ isDirectory: () => true
+ }));
+ readdir.mockImplementation(async (path) => (
+ path === '/tmp/portos-test-agents'
+ ? [{ name: '2026-08-14', isDirectory: () => true }]
+ : agentDirs
+ ));
+
+ let activeReads = 0;
+ let maxActiveReads = 0;
+ tryReadFile.mockImplementation(async () => {
+ activeReads += 1;
+ maxActiveReads = Math.max(maxActiveReads, activeReads);
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ activeReads -= 1;
+ return archived(undefined);
+ });
+
+ await recalculateDurationStats();
+
+ expect(readdir).toHaveBeenCalledWith('/tmp/portos-test-agents', { withFileTypes: true });
+ expect(readdir).toHaveBeenCalledWith('/tmp/portos-test-agents/2026-08-14', { withFileTypes: true });
+ expect(tryReadFile).toHaveBeenCalledTimes(25);
+ expect(maxActiveReads).toBe(20);
+ });
});