Skip to content

Commit 180ee97

Browse files
committed
fix: observe only the current daemon registration owner
1 parent 2c76dab commit 180ee97

5 files changed

Lines changed: 81 additions & 29 deletions

File tree

‎src/daemon-client/__tests__/daemon-client-lifecycle.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -446,6 +446,7 @@ test('daemon acquisition reclaims a proven reused owner before publication', asy
446446
if (freshLock.state === 'held') assert.notEqual(freshLock.owner.startTime, 'stale-start-time');
447447
assert.deepEqual(daemon.seenPaths, ['GET /health', 'POST /rpc']);
448448
} finally {
449+
if (stale.status === 'acquired') await stale.acquisition.release();
449450
await closeLoopbackServer(daemon.server);
450451
await finishRegisteredDaemonFixture(stateDir);
451452
}

‎src/daemon-client/__tests__/daemon-client-startup-race.test.ts‎

Lines changed: 29 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,10 @@ for (const command of ['devices', 'test']) {
7676
fs.writeFileSync(deferred, 'wait');
7777
const winner = spawnRegisteredDaemonFixture(paths, fields(http.port), { stdio: 'ignore' });
7878
await awaitFile(path.join(paths.baseDir, 'registration-held'));
79+
fs.writeFileSync(
80+
paths.infoPath,
81+
JSON.stringify({ ...fields(http.port, '0.0.1'), pid: 999_999_999, processStartTime: 'old' }),
82+
);
7983
let joined = false;
8084
let genuineExit: ExecDetachedExit | undefined;
8185
let contender: ReturnType<typeof runCmdDetachedMonitored> | undefined;
@@ -250,7 +254,10 @@ for (const held of [true, false]) {
250254
});
251255
}
252256

253-
test('a joined busy contender retires an older winner before relaunching', async (t) => {
257+
test.for([
258+
{ budget: 'ample', offset: 0, launches: 2, alive: false, rpcs: 1 },
259+
{ budget: 'near deadline', offset: 11_000, launches: 1, alive: true, rpcs: 0 },
260+
])('an older winner is replaced only with enough startup time ($budget)', async (expected, t) => {
254261
if (!(await supportsLoopbackBind())) return t.skip('loopback unavailable');
255262
const paths = resolveDaemonPaths(mkdtempForTestSync('daemon-start-older-winner-'));
256263
const http = await startHttpDaemonFixture({ devices: [] });
@@ -260,6 +267,9 @@ test('a joined busy contender retires an older winner before relaunching', async
260267
stdio: 'ignore',
261268
});
262269
await awaitFile(path.join(paths.baseDir, 'registration-held'));
270+
const wallTime = Date.now;
271+
let offset = 0;
272+
const clock = vi.spyOn(Date, 'now').mockImplementation(() => wallTime() + offset);
263273
let joined = false;
264274
spawn.mockImplementation((_command, _args, options) => {
265275
if (spawn.mock.calls.length > 1) assert.equal(joined, true);
@@ -272,20 +282,30 @@ test('a joined busy contender retires an older winner before relaunching', async
272282
return child;
273283
});
274284
pause.mockImplementation(async (ms) => {
275-
if (joined) fs.rmSync(deferred, { force: true });
276-
await actualRetry.sleep(ms);
285+
if (joined) {
286+
fs.rmSync(deferred, { force: true });
287+
if (expected.offset) offset = offset ? offset + ms : expected.offset;
288+
}
289+
await actualRetry.sleep(10);
277290
});
278291
const notice = vi.spyOn(process.stderr, 'write').mockImplementation(() => true);
279292
try {
280-
assert.equal((await sendToDaemon(request(paths))).ok, true);
281-
await winner.exited;
282-
assert.equal(isProcessAlive(winner.pid), false);
283-
assert.equal(spawn.mock.calls.length, 2);
284-
assert.equal(http.rpcRequests.length, 1);
285-
assert.ok(
293+
const pending = sendToDaemon(request(paths));
294+
if (expected.alive) await assert.rejects(pending);
295+
else {
296+
assert.equal((await pending).ok, true);
297+
await winner.exited;
298+
}
299+
assert.equal(joined, true);
300+
assert.equal(isProcessAlive(winner.pid), expected.alive);
301+
assert.equal(spawn.mock.calls.length, expected.launches);
302+
assert.equal(http.rpcRequests.length, expected.rpcs);
303+
assert.equal(
286304
notice.mock.calls.flat().join('').includes(`Replacing daemon (pid ${winner.pid}, v0.0.1)`),
305+
!expected.alive,
287306
);
288307
} finally {
308+
clock.mockRestore();
289309
notice.mockRestore();
290310
await closeLoopbackServer(http.server);
291311
}

‎src/daemon-client/daemon-client-lifecycle.ts‎

Lines changed: 50 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -66,9 +66,11 @@ export type EnsuredDaemon = {
6666
type DaemonStartupWaitResult =
6767
| { kind: 'ready'; daemon: EnsuredDaemon }
6868
| { kind: 'early_exit'; exit: ExecDetachedExit }
69-
| { kind: 'retry' | 'unproven' | 'timeout' };
69+
| { kind: 'unproven'; error: AppError }
70+
| { kind: 'retry' | 'timeout' };
7071

7172
const DAEMON_STARTUP_TIMEOUT_MS = 15_000;
73+
const MINIMUM_DAEMON_TAKEOVER_BUDGET_MS = 5_000;
7274
const LIVE_DAEMON_PROBE_RETRIES = 3;
7375
const LIVE_DAEMON_PROBE_RETRY_DELAY_MS = 200;
7476
const DAEMON_STARTUP_ATTEMPTS = 2;
@@ -191,16 +193,10 @@ async function readReusableLocalDaemon(
191193
deadline?: number,
192194
): Promise<DaemonInfo | null> {
193195
const inspection = inspectProcessLock(settings.paths.lockPath);
194-
if (inspection.state === 'unproven') {
195-
throw new AppError('COMMAND_FAILED', 'Daemon registration ownership could not be verified.', {
196-
reason: 'daemon_registration_unproven',
197-
inspection,
198-
stateDir: settings.paths.baseDir,
199-
hint: resolveDaemonStartupHint(getDaemonMetadataState(settings.paths), settings.paths),
200-
});
201-
}
196+
if (inspection.state === 'unproven') throw daemonRegistrationUnprovenError(settings, inspection);
202197
const existing = readDaemonInfo(settings.paths.infoPath);
203198
if (!existing) return null;
199+
if (!registrationAllowsDaemonObservation(inspection, existing)) return null;
204200

205201
const decision = await resolveDaemonTakeover(existing, {
206202
onClientTransport: () =>
@@ -212,12 +208,36 @@ async function readReusableLocalDaemon(
212208
throw newerDaemonRefusedError(existing, decision, settings.paths.baseDir);
213209
}
214210

215-
if (deadline !== undefined && Date.now() >= deadline) return null;
211+
if (remainingStartupBudget(deadline) < MINIMUM_DAEMON_TAKEOVER_BUDGET_MS) return null;
216212
emitDaemonTakeoverNotice(existing, decision.reason, settings.paths.baseDir);
217213
await retireDaemonForTakeover(existing, settings.paths);
218214
return null;
219215
}
220216

217+
function registrationAllowsDaemonObservation(
218+
inspection: ProcessLockInspection,
219+
info: DaemonInfo,
220+
): boolean {
221+
return (
222+
inspection.state === 'absent' ||
223+
(inspection.state === 'held' &&
224+
inspection.owner.pid === info.pid &&
225+
inspection.owner.startTime === (info.processStartTime ?? null))
226+
);
227+
}
228+
229+
function daemonRegistrationUnprovenError(
230+
settings: DaemonClientSettings,
231+
inspection?: ProcessLockInspection,
232+
): AppError {
233+
return new AppError('COMMAND_FAILED', 'Daemon registration ownership could not be verified.', {
234+
reason: 'daemon_registration_unproven',
235+
inspection,
236+
stateDir: settings.paths.baseDir,
237+
hint: resolveDaemonStartupHint(getDaemonMetadataState(settings.paths), settings.paths),
238+
});
239+
}
240+
221241
async function retireDaemonForTakeover(existing: DaemonInfo, paths: DaemonPaths): Promise<void> {
222242
const retirement = await stopAndRetireDaemon({
223243
paths: paths,
@@ -328,6 +348,7 @@ function emitDaemonTakeoverNotice(info: DaemonInfo, reason: string, stateDir: st
328348
type FailedDaemonStartup = {
329349
cleanup?: DaemonRetirementResult;
330350
startError?: string;
351+
startupError?: NormalizedError;
331352
daemonProcess?: ExecDetachedExit | { pid: number };
332353
retry: boolean;
333354
};
@@ -346,6 +367,7 @@ async function startLocalDaemon(settings: DaemonClientSettings): Promise<Ensured
346367
if (!result.retry) break;
347368
await sleep(Math.min(150, Math.max(0, deadline - Date.now())));
348369
}
370+
const { startError, startupError, daemonProcess }: Partial<FailedDaemonStartup> = failure ?? {};
349371
const state = getDaemonMetadataState(settings.paths);
350372
const daemonLogTail = readRecentLogTail(settings.paths.logPath);
351373
throw new AppError('COMMAND_FAILED', 'Failed to start daemon', {
@@ -357,8 +379,9 @@ async function startLocalDaemon(settings: DaemonClientSettings): Promise<Ensured
357379
startupTimeoutMs: DAEMON_STARTUP_TIMEOUT_MS,
358380
startupAttempts: attempts,
359381
cleanupResults,
360-
startError: failure?.startError,
361-
daemonProcess: failure?.daemonProcess,
382+
startError,
383+
startupError,
384+
daemonProcess,
362385
...(daemonLogTail ? { daemonLogTail } : {}),
363386
metadataState: state,
364387
hint: resolveDaemonStartupHint(state, settings.paths),
@@ -388,9 +411,11 @@ async function attemptLocalDaemonStartup(
388411
if (startup.kind === 'ready') return { daemon: startup.daemon };
389412
if (startup.kind === 'retry') return { retry: true };
390413
if (startup.kind === 'unproven') {
414+
const startupError = normalizeError(startup.error);
391415
return {
392416
retry: false,
393-
startError: 'Daemon registration ownership could not be verified.',
417+
startError: startupError.message,
418+
startupError,
394419
daemonProcess: { pid: launch.pid },
395420
};
396421
}
@@ -712,7 +737,8 @@ async function waitForDaemonStartup(
712737
while (Date.now() < deadline) {
713738
if (earlyExit) {
714739
const kind = classifyDaemonStartupExit(earlyExit);
715-
if (kind === 'unproven') return { kind: 'unproven' };
740+
if (kind === 'unproven')
741+
return { kind: 'unproven', error: daemonRegistrationUnprovenError(settings) };
716742
if (kind === 'failed') return { kind: 'early_exit', exit: earlyExit };
717743
const contender = await observeContendingDaemon(settings, deadline);
718744
if (contender) return contender;
@@ -741,11 +767,19 @@ async function observeContendingDaemon(
741767
settings: DaemonClientSettings,
742768
deadline: number,
743769
): Promise<DaemonStartupWaitResult | null> {
744-
const winner = await readReusableLocalDaemon(settings, deadline);
770+
let winner: DaemonInfo | null;
771+
try {
772+
winner = await readReusableLocalDaemon(settings, deadline);
773+
} catch (error) {
774+
if (error instanceof AppError && error.details?.reason === 'daemon_registration_unproven')
775+
return { kind: 'unproven', error };
776+
throw error;
777+
}
745778
if (Date.now() >= deadline) return null;
746779
if (winner) return { kind: 'ready', daemon: { info: winner, startedByClient: false } };
747780
const inspection = inspectProcessLock(settings.paths.lockPath);
748-
if (inspection.state === 'unproven') return { kind: 'unproven' };
781+
if (inspection.state === 'unproven')
782+
return { kind: 'unproven', error: daemonRegistrationUnprovenError(settings, inspection) };
749783
return isRegistrationAvailable(inspection) ? { kind: 'retry' } : null;
750784
}
751785

‎src/daemon-client/daemon-client-metadata.ts‎

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import fs from 'node:fs';
2-
import { inspectProcessLock, type ProcessLockInspection } from '@agent-device/host-kit/file';
32
import { AppError } from '@agent-device/kernel/errors';
43
import { stopDaemonProcess, type DaemonTerminationResult } from '../daemon-process.ts';
54

@@ -31,7 +30,6 @@ export type DaemonInfo = {
3130
export type DaemonMetadataState = {
3231
hasInfo: boolean;
3332
hasLock: boolean;
34-
registration: ProcessLockInspection;
3533
};
3634

3735
const DAEMON_TAKEOVER_TERM_TIMEOUT_MS = 3000;
@@ -99,7 +97,6 @@ export function getDaemonMetadataState(paths: DaemonPaths): DaemonMetadataState
9997
return {
10098
hasInfo: fs.existsSync(paths.infoPath),
10199
hasLock: fs.existsSync(paths.lockPath),
102-
registration: inspectProcessLock(paths.lockPath),
103100
};
104101
}
105102

‎website/docs/docs/installation.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -126,4 +126,4 @@ Startup refuses legacy lock files and unverified ownership. Confirm every user o
126126

127127
Packaged installs default to `~/.agent-device`; source checkouts use a worktree directory under `~/.agent-device/dev/`. `AGENT_DEVICE_STATE_DIR` or `--state-dir` overrides either default.
128128

129-
For source checkouts, `pnpm clean:daemon --prune-dev` selects development directories with no activity for 14 days, using their newest mtime. It retires only confirmed abandoned registration and retains shared directories, session artifacts and logs.
129+
For source checkouts, `pnpm clean:daemon --prune-dev` selects development directories with no activity for 14 days, using the newest mtime of the directory and its immediate children. It retires only registration it can confirm abandoned. Directories, session artifacts and logs remain.

0 commit comments

Comments
 (0)