Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Services run in the core when the data folder is too deep for its socket (#960)

Dee284b4fdcb8a8
diff --git a/cli/e2e/noSocket.e2e.ts b/cli/e2e/noSocket.e2e.ts
new file mode 100644
index 000000000..01d9bfec9
--- /dev/null
+++ b/cli/e2e/noSocket.e2e.ts
@@ -0,0 +1,43 @@
+/**
+ * A data folder too deep for the daemon's local socket: a socket path has 96 bytes at most
+ * (lib/localSocket.ts), so `<data>/daemon-<port>.sock` past that leaves the daemon serving on its port
+ * alone. The services that run in processes of their own reach the core only through that socket, so the
+ * master runs them in the core's process instead, and every one still answers.
+ */
+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, describe, expect, it, onTestFailed } from 'vitest'
+import { LocalClient } from './harness/client.js'
+import { IsolatedDaemon, until } from './harness/daemon.js'
+
+describe('a data folder too deep for the local socket', () => {
+ let daemon: IsolatedDaemon | undefined
+ let deep = ''
+ afterEach(async () => {
+ await daemon?.close()
+ daemon = undefined
+ if (deep) rmSync(deep, { recursive: true, force: true })
+ })
+
+ it('runs the services in the core, where they answer, instead of in processes that cannot reach it', async () => {
+ deep = mkdtempSync(join(tmpdir(), 'harness-deep-'))
+ const dataDir = join(deep, 'a-data-folder-whose-path-is-longer-than-a-unix-socket-path-may-be', 'data')
+ mkdirSync(dataDir, { recursive: true })
+ expect(Buffer.byteLength(join(dataDir, 'daemon-18473.sock'))).toBeGreaterThan(96)
+ const d = await IsolatedDaemon.create({ dataDir })
+ daemon = d
+ onTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-150).join('\n')}`) })
+ // No socket to wait for: the port, and start-up done.
+ await d.start({ ready: 'none' })
+ await until('the daemon to finish starting', () => /\[cli\] ready/.test(d.log()) || null, 90_000, 200)
+ const client = await LocalClient.connect(d, { tcp: true })
+ // Search, the monitor and the project readers answer, from the core's own process.
+ expect(await client.request('session_search', { query: 'anything' }, 30_000)).not.toHaveProperty('error')
+ expect(await client.request('machine_resources', {}, 30_000)).not.toHaveProperty('error')
+ expect(await client.request('fs_list_dir', {}, 30_000)).not.toHaveProperty('error')
+ // And no service process is left crashing on every start because it cannot reach the core.
+ expect(d.log()).not.toMatch(/the core has no local socket to reach/)
+ client.close()
+ })
+})
diff --git a/cli/src/masterProcess.spec.ts b/cli/src/masterProcess.spec.ts
index 73b2dddd8..007608049 100644
--- a/cli/src/masterProcess.spec.ts
+++ b/cli/src/masterProcess.spec.ts
@@ -12,7 +12,7 @@ const leanBundle = vi.hoisted(() => ({ read: vi.fn((_bundle: Buffer): LeanBundle
vi.mock('./harnessd/leanBundle.js', async (real) => ({ ...await real<object>(), readLeanBundle: (bundle: Buffer) => leanBundle.read(bundle) }))
const {
- BUNDLE_ENV, BUNDLE_SHA256_ENV, LEAN_DIR, LEAN_FINGERPRINT_ENV, LEAN_OFF_FILE, probeLean, probeThisMaster, processBundleDeps, startMaster, startMasterFromBundle, startMasterInForeground,
+ BUNDLE_ENV, BUNDLE_SHA256_ENV, LEAN_DIR, LEAN_FINGERPRINT_ENV, LEAN_OFF_FILE, masterEnv, probeLean, probeThisMaster, processBundleDeps, startMaster, startMasterFromBundle, startMasterInForeground,
} = await import('./masterProcess.js')
type Deps = Parameters<typeof startMasterFromBundle>[1] & object
@@ -177,6 +177,31 @@ describe('starting the master', () => {
expect(LEAN_OFF_FILE).toMatch(/[\\/]lean-off$/)
})
+ it('keeps the services in the core when the core will have no local socket for them to reach it by', () => {
+ const given = { HOME: '/home/someone' }
+ const logs: string[] = []
+ // A socket: the master runs on its environment as it is, the services in their own processes.
+ expect(masterEnv(given, '/data/daemon-18473.sock', (line) => logs.push(line))).toBe(given)
+ // None (a data folder too deep for one): every service in the core's process, and the log says why.
+ expect(masterEnv(given, null, (line) => logs.push(line))).toEqual({ HOME: '/home/someone', HARNESSD_SERVICES: 'none' })
+ expect(given).toEqual({ HOME: '/home/someone' })
+ expect(logs).toEqual([expect.stringMatching(/\[harnessd\] this data folder is too deep for the daemon's local socket/)])
+ // Already none: nothing to change or say.
+ const none = { HARNESSD_SERVICES: 'none' }
+ expect(masterEnv(none, null, (line) => logs.push(line))).toBe(none)
+ expect(logs).toHaveLength(1)
+ // Its own log line goes to the master's console, which is the daemon's log.
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})
+ try {
+ masterEnv({}, null)
+ expect(log).toHaveBeenCalledWith(expect.stringMatching(/the services run in the core's process$/))
+ } finally { log.mockRestore() }
+ // startMaster hands runMaster an environment: this one's, or this one's with the services kept in.
+ runMaster.mockClear()
+ startMaster({ scriptPath: '/cli/cli.js' })
+ expect((runMaster.mock.calls[0][0] as { env: NodeJS.ProcessEnv }).env).toMatchObject({ PATH: process.env.PATH })
+ })
+
it('gives up its claim on the lean bundle as it exits cleanly', () => {
const folder = mkdtempSync(join(tmpdir(), 'lean-claim-'))
try {
diff --git a/cli/src/masterProcess.ts b/cli/src/masterProcess.ts
index acb2cf840..46735ef1b 100644
--- a/cli/src/masterProcess.ts
+++ b/cli/src/masterProcess.ts
@@ -19,6 +19,7 @@ import { PROBE_ANSWER, PROBE_TIMEOUT_MS } from './harnessd/reexec.js'
import { ensureUtf8Locale } from './lib/childLocale.js'
import { DAEMON_LOG_FILE, HARNESSD_STATUS_FILE, PID_FILE } from './lib/daemonState.js'
import { isInstalledCopy } from './lib/installedCopy.js'
+import { localSocketPath } from './lib/localSocket.js'
import { leanFingerprint, readLeanBundle, releaseLeanClaim, writeLeanBundle, type LeanBundle } from './harnessd/leanBundle.js'
import { ts } from './lib/log.js'
import { confirm as confirmUpdate, restore as restoreUpdate, unjudgedUpdate } from './lib/selfUpdate.js'
@@ -50,6 +51,19 @@ export interface MasterStart {
leanFingerprint?: string
}
+/**
+ * The master's environment, with the services kept in the core's process when the core will have no local
+ * socket for them to reach it by: its path in this data folder is too long for one (lib/localSocket.ts, 96
+ * bytes) or the platform has none. Every service process reaches the core only through that socket, and one
+ * started without it exits at once, again and again until the master parks it: on such a machine search, the
+ * viewers, the gateway and every other service answered SERVICE_UNAVAILABLE for good (e2e/noSocket.e2e.ts).
+ */
+export function masterEnv(given: NodeJS.ProcessEnv, socketPath: string | null, log: (line: string) => void = (line) => console.log(line)): NodeJS.ProcessEnv {
+ if (socketPath !== null || given.HARNESSD_SERVICES === 'none') return given
+ log(`${ts()} [harnessd] this data folder is too deep for the daemon's local socket — the services run in the core's process`)
+ return { ...given, HARNESSD_SERVICES: 'none' }
+}
+
/** Run the master. */
export function startMaster(start: MasterStart, exit: (code: number) => void = (code) => process.exit(code)): ReturnType<typeof runMaster> {
// Before it starts anything: on Linux an absent locale makes tmux and ps mangle their output, and the
@@ -58,6 +72,7 @@ export function startMaster(start: MasterStart, exit: (code: number) => void = (
ensureUtf8Locale()
const { serviceScriptPath } = start
return runMaster({
+ env: masterEnv(process.env, localSocketPath(env.ADAPTER_DATA_DIR, env.PORT)),
nodePath: baseNode(process.execPath),
execArgv: process.execArgv,
runtimeDir: env.ADAPTER_RUNTIME_DIR,
diff --git a/cli/src/serviceProcess.spec.ts b/cli/src/serviceProcess.spec.ts
index 59efc8807..a18bee3a2 100644
--- a/cli/src/serviceProcess.spec.ts
+++ b/cli/src/serviceProcess.spec.ts
@@ -106,4 +106,21 @@ describe('a service in its own process', () => {
await expect(startServiceProcess('nope', { runners: new Map() })).rejects.toThrow('process.exit 2')
expect(processExit).toHaveBeenCalledWith(2)
})
+
+ it('runs the updater with no socket, since it speaks to the master alone, but nothing named with it that needs one', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {})
+ const exit = vi.fn((code: number): never => { throw new Error(`exit ${code}`) })
+ const seen: ServiceProcessOptions[] = []
+ const runners = new Map([
+ ['updater', async () => (options: ServiceProcessOptions) => { seen.push(options); return { stop: () => {} } }],
+ ['search', async () => () => ({ stop: () => {} })],
+ ])
+ const { host, hosted } = fakeHost()
+ local.socket = null
+ await startServiceProcess('updater', { runners, host, exit })
+ expect(seen).toEqual([expect.objectContaining({ socketPath: '' })])
+ expect(hosted[0].options).toEqual({ name: 'updater', services: ['updater'] })
+ await expect(startServiceProcess('updater,search', { runners, host, exit })).rejects.toThrow('exit 2')
+ expect(error).toHaveBeenCalledWith('[service] updater,search: the core has no local socket to reach')
+ })
})
diff --git a/cli/src/serviceProcess.ts b/cli/src/serviceProcess.ts
index 326dd2abb..66955e61e 100644
--- a/cli/src/serviceProcess.ts
+++ b/cli/src/serviceProcess.ts
@@ -23,6 +23,9 @@ export interface ServiceProcessOptions {
}
type Runner = (options: ServiceProcessOptions) => ServiceProcess
+/** The processes the master runs that speak only to it, never to the core: they need no local socket. */
+const BESIDE_THE_CORE: ReadonlySet<string> = new Set(['updater'])
+
/** Every service this build can run in its own process, and how to load its runner alone. */
export const SERVICE_RUNNERS: ReadonlyMap<string, () => Promise<Runner>> = new Map<string, () => Promise<Runner>>([
['search', async () => (await import('./services/searchProcess.js')).runSearchService],
@@ -71,7 +74,9 @@ export async function startServiceProcess(named: string | undefined, deps: Servi
console.error(`[service] ${unknown}: no such service in this build`)
return exit(2)
}
- if (!socketPath) {
+ // The updater never reaches the core: it tells the master. Without a socket (a data folder too deep for
+ // one) it still runs, or that machine would never get the update that fixes it.
+ if (!socketPath && names.some((name) => !BESIDE_THE_CORE.has(name))) {
console.error(`[service] ${names.join(',')}: the core has no local socket to reach`)
return exit(2)
}
@@ -90,7 +95,7 @@ export async function startServiceProcess(named: string | undefined, deps: Servi
const loaded = await Promise.all(names.map(async (name) => [name, await runners.get(name)!()] as const))
const options: ServiceProcessOptions = {
dataDir: env.ADAPTER_DATA_DIR,
- socketPath,
+ socketPath: socketPath ?? '',
machineId: readOrMintComputerId(env.ADAPTER_COMPUTER_ID_FILE, env.ADAPTER_COMPUTER_ID),
token: process.env.HARNESSD_SERVICE_TOKEN ?? '',
}