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

Add bounded failure context for owned test Chrome

[._.]/ Adam Eivy1c1b1374df25
diff --git a/server/services/htmlComposition/testBrowserCleanup.js b/server/services/htmlComposition/testBrowserCleanup.js
index 9c6989e689..f7dc8eb3f7 100644
--- a/server/services/htmlComposition/testBrowserCleanup.js
+++ b/server/services/htmlComposition/testBrowserCleanup.js
@@ -1,5 +1,6 @@
import { execFileSync } from '../../lib/childProcess.js';
-import { closeSync, existsSync, openSync, opendirSync, readSync } from 'node:fs';
+import { closeSync, existsSync, openSync, opendirSync, readSync, statfsSync } from 'node:fs';
+import { availableParallelism, tmpdir } from 'node:os';
import { basename, join } from 'node:path';
import { killWithEscalation } from '../../lib/killWithEscalation.js';
@@ -25,7 +26,9 @@ export function _selectTestChrome(candidates) {
// Failure-only Linux observations of this owned child and its current worker.
// Never read cmdline, environ, links, stacks, or arbitrary process output. A
-// fixed prefix per file and at most 16 threads bound both capture and output.
+// At most 23 prefixes of 4096 bytes (92 KiB), 17 directory entries and one
+// statfs call. These count/byte caps do not guarantee elapsed time. Samples
+// are non-atomic: wait categories and resource pressure do not prove a cause.
function readProcPrefix(path) {
const fd = openSync(path, 'r');
try {
@@ -39,7 +42,7 @@ function readThreadIds(path) {
const ids = [];
try {
let entry;
- while (ids.length < 17 && (entry = dir.readSync())) {
+ for (let entries = 0; entries < 17 && (entry = dir.readSync()); entries++) {
if (/^[1-9]\d*$/.test(entry.name)) ids.push(entry.name);
}
} finally { dir.closeSync(); }
@@ -47,9 +50,42 @@ function readThreadIds(path) {
}
const PROCESS_STATES = { R: 'runnable', S: 'sleeping', D: 'uninterruptible', Z: 'zombie', T: 'stopped', t: 'traced', X: 'dead', I: 'idle' };
+const WAIT_CATEGORIES = new Map([
+ ['none', ['0']],
+ ['futex', ['futex_wait_queue', 'futex_wait_queue_me', 'futex_wait']],
+ ['poll', ['ep_poll', 'do_epoll_wait', 'do_poll', 'poll_schedule_timeout', 'poll_schedule_timeout.constprop.0']],
+ ['pipe', ['pipe_read']],
+ ['child', ['do_wait', 'kernel_wait4']],
+ ['io', ['io_schedule', 'io_schedule_timeout', 'wait_on_page_bit_common']],
+ ['page', ['folio_wait_bit_common']],
+ ['completion', ['wait_for_common', 'do_wait_for_common', 'wait_for_completion']],
+ ['lock', ['rwsem_down_read_slowpath', 'rwsem_down_write_slowpath', '__mutex_lock', '__mutex_lock_slowpath']],
+].flatMap(([category, names]) => names.map(name => [name, category])));
+const safeInteger = value => Number.isSafeInteger(value) && value >= 0 ? value : 'unavailable';
+const attemptObservation = fn => { try { return fn(); } catch { return 'unavailable'; } };
+
+function resourceFacts(child, { read, cpus, usage, disk }) {
+ const worker = attemptObservation(usage);
+ const fs = attemptObservation(disk);
+ const pressure = kind => attemptObservation(() => {
+ const text = read(`/proc/pressure/${kind}`).slice(0, 4096);
+ const value = Number(text.match(/(?:^|\n)some avg10=(\d+(?:\.\d+)?)(?: |$)/)?.[1]);
+ return Number.isFinite(value) && value >= 0 && value <= 100 ? value : 'unavailable';
+ });
+ const memory = attemptObservation(() => safeInteger(Number(
+ read('/proc/meminfo').slice(0, 4096).match(/(?:^|\n)MemAvailable:\s+(\d+) kB(?:\n|$)/)?.[1],
+ )));
+ const freeBytes = Number.isSafeInteger(fs?.bavail) && fs.bavail >= 0 && Number.isSafeInteger(fs?.bsize) && fs.bsize > 0
+ ? safeInteger(fs.bavail * fs.bsize) : 'unavailable';
+ return `cpus=${attemptObservation(() => safeInteger(cpus()))} workerUserMicros=${safeInteger(worker?.userCPUTime)}`
+ + ` workerSystemMicros=${safeInteger(worker?.systemCPUTime)} workerMaxRssKiB=${safeInteger(worker?.maxRSS)} childCpuTicks=${child?.cpuTicks ?? 'unavailable'}`
+ + ` cpuAvg10=${pressure('cpu')} memoryAvg10=${pressure('memory')} ioAvg10=${pressure('io')}`
+ + ` memAvailableKiB=${memory} tmpFreeBytes=${freeBytes} tmpFreeInodes=${safeInteger(fs?.ffree)}`;
+}
export function _testChromeProcessFacts(proc, {
platform = process.platform, workerPid = process.pid, read = readProcPrefix, threads = readThreadIds,
+ cpus = availableParallelism, usage = () => process.resourceUsage(), disk = () => statfsSync(tmpdir()),
} = {}) {
if (platform !== 'linux') return 'os=unsupported';
if (!Number.isSafeInteger(proc?.pid) || proc.pid <= 0) return 'os=linux child=unavailable';
@@ -63,35 +99,32 @@ export function _testChromeProcessFacts(proc, {
if (end < 0) return null;
const fields = text.slice(end + 2).trim().split(/\s+/);
if (fields.length < 4 || !Object.hasOwn(PROCESS_STATES, fields[0]) || !fields.slice(1, 4).every(x => /^\d+$/.test(x))) return null;
- return { state: PROCESS_STATES[fields[0]], parent: fields[1], group: fields[2], session: fields[3] };
+ const cpuTicks = fields.slice(11, 13).length === 2 && fields.slice(11, 13).every(x => /^\d+$/.test(x))
+ ? safeInteger(Number(fields[11]) + Number(fields[12])) : 'unavailable';
+ return { state: PROCESS_STATES[fields[0]], parent: fields[1], group: fields[2], session: fields[3], cpuTicks };
} catch { return null; }
};
const child = stat(proc.pid);
const worker = stat(workerPid);
const same = (a, b) => a && b ? (a === b ? 'worker' : 'other') : 'unavailable';
- const waits = { none: 0, futex: 0, poll: 0, pipe: 0, child: 0, io: 0, other: 0, unavailable: 0 };
+ const waitCategory = path => attemptObservation(() => {
+ // Exact kernel names only; unfamiliar text never becomes log content.
+ // Zero also occurs when the kernel hides a wait; it doesn't prove runnable.
+ return WAIT_CATEGORIES.get(read(path).slice(0, 4096).trim()) ?? 'other';
+ });
+ const leadWait = waitCategory(`/proc/${proc.pid}/wchan`);
+ const waits = { none: 0, futex: 0, poll: 0, pipe: 0, child: 0, io: 0, page: 0, completion: 0, lock: 0, other: 0, unavailable: 0 };
let ids;
- try { ids = threads(`/proc/${proc.pid}/task`).filter(x => /^[1-9]\d*$/.test(x)).slice(0, 17); }
+ try { ids = threads(`/proc/${proc.pid}/task`).slice(0, 17).filter(x => /^[1-9]\d*$/.test(x)); }
catch { ids = null; }
for (const id of ids?.slice(0, 16) ?? []) {
- let category = 'unavailable';
- try {
- const wait = read(`/proc/${proc.pid}/task/${id}/wchan`).slice(0, 4096).trim();
- // Exact kernel names only: unfamiliar text never becomes log content.
- // Zero also occurs when the kernel hides a wait; it doesn't prove runnable.
- category = wait === '0' ? 'none'
- : ['futex_wait_queue', 'futex_wait_queue_me', 'futex_wait'].includes(wait) ? 'futex'
- : ['ep_poll', 'do_epoll_wait', 'do_poll', 'poll_schedule_timeout', 'poll_schedule_timeout.constprop.0'].includes(wait) ? 'poll'
- : wait === 'pipe_read' ? 'pipe'
- : ['do_wait', 'kernel_wait4'].includes(wait) ? 'child'
- : ['io_schedule', 'io_schedule_timeout', 'wait_on_page_bit_common'].includes(wait) ? 'io' : 'other';
- } catch { /* exited, permissions, or unavailable procfs */ }
- waits[category]++;
+ waits[waitCategory(`/proc/${proc.pid}/task/${id}/wchan`)]++;
}
return `os=linux child=${child?.state ?? 'unavailable'} worker=${worker?.state ?? 'unavailable'}`
+ ` parent=${same(child?.parent, String(workerPid))} group=${same(child?.group, worker?.group)} session=${same(child?.session, worker?.session)}`
- + ` threads=${ids ? Math.min(ids.length, 16) : 'unavailable'} threadLimit=${ids ? ids.length > 16 : 'unavailable'}`
- + ` waits=${Object.entries(waits).map(([name, count]) => `${name}:${count}`).join(',')}`;
+ + ` leadWait=${leadWait} threads=${ids ? Math.min(ids.length, 16) : 'unavailable'} threadLimit=${ids ? ids.length > 16 : 'unavailable'}`
+ + ` waits=${Object.entries(waits).map(([name, count]) => `${name}:${count}`).join(',')}`
+ + `; resources: ${resourceFacts(child, { read, cpus, usage, disk })}`;
}
function describeProcess(proc, observeProcess) {
diff --git a/server/services/htmlComposition/testBrowserCleanup.test.js b/server/services/htmlComposition/testBrowserCleanup.test.js
index 56d7f60c1f..6282d7cb9d 100644
--- a/server/services/htmlComposition/testBrowserCleanup.test.js
+++ b/server/services/htmlComposition/testBrowserCleanup.test.js
@@ -26,6 +26,20 @@ function startingChild() {
return proc;
}
+const syntheticResources = {
+ cpus: () => 4,
+ usage: () => ({ userCPUTime: 0, systemCPUTime: 12, maxRSS: 34 }),
+ disk: () => ({ bavail: 2, bsize: 4096, ffree: 5 }),
+};
+const resourceText = {
+ '/proc/pressure/cpu': 'some avg10=1.25 avg60=2.00 avg300=3.00 total=4',
+ '/proc/pressure/memory': 'some avg10=0.00 avg60=0.00 avg300=0.00 total=0',
+ '/proc/pressure/io': 'some avg10=3.50 avg60=4.00 avg300=5.00 total=6',
+ '/proc/meminfo': 'MemAvailable: 42 kB\n',
+};
+const resourceExpected = '; resources: cpus=4 workerUserMicros=0 workerSystemMicros=12 workerMaxRssKiB=34 childCpuTicks=23'
+ + ' cpuAvg10=1.25 memoryAvg10=0 ioAvg10=3.5 memAvailableKiB=42 tmpFreeBytes=8192 tmpFreeInodes=5';
+
function expectStartupClean(proc) {
expect(proc.listenerCount('spawn')).toBe(0);
expect(proc.listenerCount('error')).toBe(0);
@@ -36,30 +50,32 @@ function expectStartupClean(proc) {
describe('failure process observations', () => {
// Synthetic procfs only: no host process, command, environment or profile.
- const stat = (state, parent, group = 777, session = 888) => `123 (example-secret (wrapper)) ${state} ${parent} ${group} ${session} 0 0 0`;
+ const stat = (state, parent, group = 777, session = 888) => `123 (example-secret (wrapper)) ${state} ${parent} ${group} ${session} 0 0 0 0 0 0 0 12 11`;
it('classifies owned-child waits and worker ancestry with bounded, allowlisted output', () => {
const read = vi.fn(path => {
if (path === '/proc/123/stat') return stat('D', 456);
if (path === '/proc/456/stat') return stat('R', 999);
+ if (path === '/proc/123/wchan') return 'folio_wait_bit_common';
+ if (Object.hasOwn(resourceText, path)) return resourceText[path];
const id = path.split('/').at(-2);
return { 1: 'futex_wait_queue', 2: 'ep_poll', 3: 'do_wait', 4: 'io_schedule', 5: 'pipe_read', 6: '0' }[id]
?? '/private/example-secret --password=example-secret';
});
const threads = vi.fn(() => Array.from({ length: 200 }, (_, i) => String(i + 1)));
- const result = _testChromeProcessFacts({ pid: 123 }, { platform: 'linux', workerPid: 456, read, threads });
- expect(result).toBe('os=linux child=uninterruptible worker=runnable parent=worker group=worker session=worker threads=16 threadLimit=true waits=none:1,futex:1,poll:1,pipe:1,child:1,io:1,other:10,unavailable:0');
- expect(read).toHaveBeenCalledTimes(18);
- expect(read.mock.calls.every(([path]) => /^\/proc\/(123|456)\/(stat|task\/\d+\/wchan)$/.test(path))).toBe(true);
+ const result = _testChromeProcessFacts({ pid: 123 }, { platform: 'linux', workerPid: 456, read, threads, ...syntheticResources });
+ expect(result).toBe('os=linux child=uninterruptible worker=runnable parent=worker group=worker session=worker leadWait=page threads=16 threadLimit=true waits=none:1,futex:1,poll:1,pipe:1,child:1,io:1,page:0,completion:0,lock:0,other:10,unavailable:0' + resourceExpected);
+ expect(read).toHaveBeenCalledTimes(23);
+ expect(read.mock.calls.every(([path]) => /^\/proc\/(?:(123|456)\/(stat|wchan|task\/\d+\/wchan)|pressure\/(cpu|memory|io)|meminfo)$/.test(path))).toBe(true);
expect(result).not.toMatch(/123|456|777|888|999|example-secret|password|private/);
});
it('keeps absent, malformed and denied observations distinct from successful capture', () => {
const denied = () => { throw new Error('/private/example-secret'); };
- expect(_testChromeProcessFacts({ pid: 123 }, { platform: 'linux', read: denied, threads: denied }))
- .toContain('child=unavailable worker=unavailable parent=unavailable group=unavailable session=unavailable threads=unavailable threadLimit=unavailable');
+ expect(_testChromeProcessFacts({ pid: 123 }, { platform: 'linux', read: denied, threads: denied, cpus: denied, usage: denied, disk: denied }))
+ .toContain('child=unavailable worker=unavailable parent=unavailable group=unavailable session=unavailable leadWait=unavailable threads=unavailable threadLimit=unavailable');
for (const malformed of ['malformed example-secret', '123 (example-secret) R', '123 (example-secret) toString 1 2 3']) {
const read = path => path.endsWith('/stat') ? malformed : '0';
- const result = _testChromeProcessFacts({ pid: 123 }, { platform: 'linux', read, threads: () => [] });
+ const result = _testChromeProcessFacts({ pid: 123 }, { platform: 'linux', read, threads: () => [], ...syntheticResources });
expect(result).toContain('child=unavailable');
expect(result).toContain('threads=0 threadLimit=false');
expect(result).not.toContain('example-secret');
@@ -70,23 +86,69 @@ describe('failure process observations', () => {
const read = path => {
if (path === '/proc/123/stat') return stat('Z', 1, 2, 3);
if (path === '/proc/456/stat') return stat('S', 999);
+ if (Object.hasOwn(resourceText, path)) return resourceText[path];
if (path.endsWith('/1/wchan')) throw new Error('denied example-secret');
// The permitted prefix is complete, but the excess must be discarded.
return '0'.padEnd(4096, ' ') + 'example-secret';
};
- const result = _testChromeProcessFacts({ pid: 123 }, { platform: 'linux', workerPid: 456, read, threads: () => ['1', '2', '../example-secret'] });
- expect(result).toBe('os=linux child=zombie worker=sleeping parent=other group=other session=other threads=2 threadLimit=false waits=none:1,futex:0,poll:0,pipe:0,child:0,io:0,other:0,unavailable:1');
+ const result = _testChromeProcessFacts({ pid: 123 }, { platform: 'linux', workerPid: 456, read, threads: () => ['1', '2', '../example-secret'], ...syntheticResources });
+ expect(result).toBe('os=linux child=zombie worker=sleeping parent=other group=other session=other leadWait=none threads=2 threadLimit=false waits=none:1,futex:0,poll:0,pipe:0,child:0,io:0,page:0,completion:0,lock:0,other:0,unavailable:1' + resourceExpected);
+ });
+
+ it('keeps unknown wait symbols private instead of inferring a subsystem', () => {
+ const read = path => {
+ if (path.endsWith('/stat')) return stat('D', 456);
+ if (Object.hasOwn(resourceText, path)) return resourceText[path];
+ if (path === '/proc/123/wchan') return 'wait_for_completion';
+ return { 1: 'do_wait_for_common', 2: '__mutex_lock', 3: 'folio_wait_bit_common', 4: '__mutex_lock.example-secret' }[path.split('/').at(-2)];
+ };
+ const result = _testChromeProcessFacts({ pid: 123 }, {
+ platform: 'linux', workerPid: 456, read, threads: () => ['1', '2', '3', '4'], ...syntheticResources,
+ });
+ expect(result).toContain('child=uninterruptible');
+ expect(result).toContain('leadWait=completion');
+ expect(result).toContain('page:1,completion:1,lock:1,other:1,unavailable:0');
+ expect(result).not.toMatch(/example-secret|wait_for_completion|mutex|folio/);
+ });
+
+ it('preserves child facts when resources are denied, invalid or outside the prefix', () => {
+ const denied = () => { throw new Error('/private/example-secret'); };
+ const read = path => {
+ if (path.endsWith('/stat')) return stat('D', 456).replace('12 11', '99999999999999999999 11');
+ if (path === '/proc/pressure/cpu') return 'some avg10=101 avg60=0';
+ if (path === '/proc/pressure/memory') return 'some avg10=example-secret avg60=0';
+ if (path === '/proc/pressure/io') return ' '.repeat(4096) + 'some avg10=0';
+ if (path === '/proc/meminfo') return 'MemAvailable: 99999999999999999999 kB\n';
+ return '0';
+ };
+ const result = _testChromeProcessFacts({ pid: 123 }, {
+ platform: 'linux', workerPid: 456, read, threads: () => [], cpus: denied,
+ usage: () => ({ userCPUTime: 'example-secret', systemCPUTime: -1, maxRSS: Infinity }),
+ disk: () => ({ bavail: -2, bsize: -4096, ffree: NaN }),
+ });
+ expect(result).toContain('child=uninterruptible worker=uninterruptible');
+ expect(result).toContain('cpus=unavailable workerUserMicros=unavailable workerSystemMicros=unavailable workerMaxRssKiB=unavailable childCpuTicks=unavailable');
+ expect(result).toContain('cpuAvg10=unavailable memoryAvg10=unavailable ioAvg10=unavailable memAvailableKiB=unavailable tmpFreeBytes=unavailable tmpFreeInodes=unavailable');
+ expect(result).not.toMatch(/example-secret|private|NaN|Infinity/);
+ const unavailable = _testChromeProcessFacts({ pid: 123 }, {
+ platform: 'linux', read: path => path.endsWith('/stat') ? stat('S', 456) : denied(),
+ threads: () => [], cpus: denied, usage: denied, disk: denied,
+ });
+ expect(unavailable).toContain('child=sleeping');
+ expect(unavailable).toContain('tmpFreeBytes=unavailable');
});
it('does no reads on unsupported platforms or missing/settled child identity', () => {
const read = vi.fn();
const threads = vi.fn();
- expect(_testChromeProcessFacts({ pid: 123 }, { platform: 'darwin', read, threads })).toBe('os=unsupported');
- expect(_testChromeProcessFacts({}, { platform: 'linux', read, threads })).toBe('os=linux child=unavailable');
- expect(_testChromeProcessFacts({ pid: 123, exitCode: 0 }, { platform: 'linux', read, threads })).toBe('os=linux child=settled');
- expect(_testChromeProcessFacts({ pid: 123, signalCode: 'SIGTERM' }, { platform: 'linux', read, threads })).toBe('os=linux child=settled');
+ const resources = { cpus: vi.fn(), usage: vi.fn(), disk: vi.fn() };
+ expect(_testChromeProcessFacts({ pid: 123 }, { platform: 'darwin', read, threads, ...resources })).toBe('os=unsupported');
+ expect(_testChromeProcessFacts({}, { platform: 'linux', read, threads, ...resources })).toBe('os=linux child=unavailable');
+ expect(_testChromeProcessFacts({ pid: 123, exitCode: 0 }, { platform: 'linux', read, threads, ...resources })).toBe('os=linux child=settled');
+ expect(_testChromeProcessFacts({ pid: 123, signalCode: 'SIGTERM' }, { platform: 'linux', read, threads, ...resources })).toBe('os=linux child=settled');
expect(read).not.toHaveBeenCalled();
expect(threads).not.toHaveBeenCalled();
+ for (const observation of Object.values(resources)) expect(observation).not.toHaveBeenCalled();
});
});
@@ -146,14 +208,22 @@ describe('test Chrome startup', () => {
it('keeps the startup deadline and clears listeners on timeout', async () => {
const proc = startingChild();
- const observeProcess = vi.fn(() => 'os=linux child=sleeping');
+ proc.pid = 123;
+ const read = vi.fn(path => resourceText[path] ?? (path.endsWith('/stat') ? '123 (example-secret) D 456 777 888' : 'folio_wait_bit_common'));
+ const observeProcess = vi.fn(owned => _testChromeProcessFacts(owned, {
+ platform: 'linux', workerPid: 456, read, threads: () => [], ...syntheticResources,
+ }));
const ready = _waitForTestChrome(proc, 20000, undefined, { observeProcess });
- const rejected = expect(ready).rejects.toThrow('did not start within 20000ms; no stderr; process: os=linux child=sleeping');
+ const rejected = expect(ready).rejects.toThrow('did not start within 20000ms; no stderr; process: os=linux child=uninterruptible');
await vi.advanceTimersByTimeAsync(19999);
expect(observeProcess).not.toHaveBeenCalled();
+ expect(read).not.toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(1);
await rejected;
expect(observeProcess).toHaveBeenCalledExactlyOnceWith(proc);
+ await expect(ready).rejects.toThrow('leadWait=page');
+ await expect(ready).rejects.toThrow('cpuAvg10=1.25 memoryAvg10=0 ioAvg10=3.5');
+ await expect(ready).rejects.not.toThrow('example-secret');
expectStartupClean(proc);
});
});