Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

## Unreleased

- Fix `ensureDaemon()`, the CLI and MCP killing a daemon they had just asked to leave. After the daemon answers the quiesce request with `draining`, the client now waits up to 60 s for it to exit by itself and clean up its registration, so plugin disposal and lease finalization finish (on Windows a signal ends the process outright, and on POSIX a drain longer than 3 s was killed). A daemon still running at the deadline that fails its liveness probes is force-retired; one that still answers is left running and the call fails with `details.reason: 'daemon-drain-timeout'`, with a hint naming `agent-device daemon stop --state-dir <path>`.
- Behavior change: the CLI and MCP now call `ensureDaemon()` explicitly once their config is resolved, then attach to the daemon it leaves. A command that finds a daemon from another version or build replaces it only if the daemon reports no request, session, repair session or live lease. A resumable upload still streaming and a host human-control hold that names no lease are not counted, so a replacement can end them. A daemon that answers nothing on any transport is retired after repeated failed liveness probes, which cannot show it idle. A busy one fails the command with `details.reason: 'daemon-busy'` instead of being replaced with its sessions, and a daemon from a release that predates quiescing fails it with `'daemon-incompatible'`; stop either with `agent-device daemon stop --state-dir <path>`. The takeover notice moves from `Replacing daemon … : <reason>` to `Replaced idle daemon …` (an incompatible daemon) or `Replaced unreachable daemon …` (one that answered nothing). A request that times out no longer retires an unresponsive daemon from the CLI or MCP; the error names `agent-device daemon stop --state-dir <path>`. A one-shot `replay` or `test` with an explicit `--state-dir` leaves the daemon it started running until its idle reap instead of stopping it. Remote `--daemon-base-url` connections and replay on its private ephemeral daemon are unchanged. Node.js clients keep `daemonLifecycle: 'managed'` until 0.22.
- Add `ensureDaemon({ stateDir })` and the client config `daemonLifecycle: 'attach' | 'managed'`. An `attach` client connects to the daemon registered in the state directory and never starts, replaces or kills one, including after a request times out. It fails with `details.reason: 'daemon-not-running'` (the hint points at `ensureDaemon()`) or `'daemon-incompatible'` (both identities in `details`, the hint names `agent-device daemon stop`). `ensureDaemon()` starts a missing daemon and replaces an incompatible one that answers only through an authenticated quiesce request the daemon answers itself (a resumable upload still streaming and a human-control hold that names no lease are not counted, so a replacement can end them): it refuses with `daemon-busy` while any request is in flight or any session, repair session or live lease exists, and a daemon from a release before this one is never replaced. A registered daemon that answers nothing is retired, as is one that times out on the quiesce request and then fails repeated liveness probes; neither can be asked. A remote `daemonBaseUrl` connection never starts or retires a local daemon in either mode. `managed` stays the default and behaves as before until 0.22.
- Add `uninstall <app>` and `client.apps.uninstall({ app })` to remove an installed app on adb-backed Android targets, iOS simulators, and CoreDevice iOS devices. Both report `wasInstalled`. A package name or bundle id that is not installed succeeds with `wasInstalled: false`. Other targets, Appium and Limrun sessions included, refuse it before anything runs.
Expand Down
10 changes: 8 additions & 2 deletions docs/adr/0006-daemon-rpc-protocol-version.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,8 +103,14 @@ refuses with `daemon-busy` and reopens admission in that same step. Otherwise it
it joins neither the in-flight count nor the command registry.

The daemon accepts a quiesce only when it can prove its own start time and the request names both
the pid and that start time; a daemon that cannot is never addressed. A client never signals a
daemon that did not accept one, except to retire it after it answered `draining`.
the pid and that start time; a daemon that cannot is never addressed.

After `draining` the client signals nothing and waits, up to a bounded deadline, for the daemon to
exit by itself and release its registration: the daemon runs its own shutdown, which a signal would
cut short. Only a daemon still running at the deadline that also fails its liveness probes is
force-retired, and only when its command line proves it is a daemon process. A daemon that still
answers is left alone and the call fails with `daemon-drain-timeout`. A client never signals a
daemon that did not accept a quiesce, except an unreachable one it retires deliberately.

The census counts what the contract names and nothing else. A resumable upload still streaming and
a host-administration human-control hold that names no lease are outside it, the same boundary
Expand Down
213 changes: 213 additions & 0 deletions src/daemon-client/__tests__/daemon-client-ensure-drain.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,213 @@
import assert from 'node:assert/strict';
import { afterEach, test, vi } from 'vitest';
import { closeLoopbackServer, supportsLoopbackBind } from '@agent-device/test-kit';
import { AppError } from '@agent-device/kernel/errors';
import { isProcessAlive } from '@agent-device/host-kit/process';
import { finishRegisteredDaemonFixtures } from '../../__tests__/test-utils/registered-daemon-fixture.ts';
import {
draining,
launchesFreshDaemonAt,
okResult,
registerDaemon,
startScriptedDaemon,
stateDirAndPaths,
} from './explicit-lifecycle-fixture.ts';

vi.mock('@agent-device/host-kit/command', async (importOriginal) => ({
...(await importOriginal<typeof import('@agent-device/host-kit/command')>()),
runCmdDetachedMonitored: vi.fn(),
}));
vi.mock('@agent-device/host-kit/retry', async (importOriginal) => ({
...(await importOriginal<typeof import('@agent-device/host-kit/retry')>()),
sleep: vi.fn(),
}));
import { runCmdDetachedMonitored } from '@agent-device/host-kit/command';
import { sleep } from '@agent-device/host-kit/retry';
import { ensureDaemon } from '../daemon-client-ensure.ts';

// A daemon that accepted a quiesce request is leaving by itself. These tests give the drain a
// virtual clock that starts when the daemon says `draining`, so a drain of any length costs no real
// time, and watch which signals the client sends while it waits.

const spawn = vi.mocked(runCmdDetachedMonitored);
const actualRetry = await vi.importActual<typeof import('@agent-device/host-kit/retry')>(
'@agent-device/host-kit/retry',
);
const realNow = Date.now.bind(Date);
const actualKill = process.kill.bind(process);

// What the old retirement waited before it escalated to SIGKILL; a healthy drain may outlast it.
const OLD_GRACE_MS = 3_000;
// `DRAIN_DEADLINE_MS` in `daemon-client-ensure.ts`.
const DRAIN_DEADLINE_MS = 60_000;

afterEach(async () => {
vi.restoreAllMocks();
spawn.mockReset();
vi.mocked(sleep).mockReset();
await finishRegisteredDaemonFixtures();
});

type VirtualDrain = {
/** Virtual milliseconds since the daemon answered `draining`. */
elapsedMs: () => number;
/** Starts the clock; called by the stand-in daemon as it answers. */
begin: (leavesAfterMs: number | undefined) => void;
/** Ends the virtual phase and returns to the real clock. */
end: () => void;
signals: Array<{ signal: NodeJS.Signals | number; atMs: number }>;
};

/**
* Time only moves while the client waits for the drain, and signals to \`pid\` are recorded with the
* virtual time they arrived at. \`leavesAfterMs\` is when the daemon finishes leaving by itself.
*/
function installVirtualDrain(pid: () => number): VirtualDrain {
let virtual = false;
let now = 0;
let startedAt = 0;
let leavesAt: number | undefined;
const signals: VirtualDrain['signals'] = [];
vi.spyOn(Date, 'now').mockImplementation(() => (virtual ? now : realNow()));
vi.mocked(sleep).mockImplementation(async (ms: number) => {
if (!virtual) return await actualRetry.sleep(ms);
now += ms;
if (leavesAt !== undefined && now >= leavesAt) {
leavesAt = undefined;
actualKill(pid(), 'SIGTERM');
await waitForExit(pid());
virtual = false;
}
});
vi.spyOn(process, 'kill').mockImplementation(((
target: number,
signal?: NodeJS.Signals | number,
) => {
if (target === pid() && signal !== undefined && signal !== 0) {
signals.push({ signal, atMs: now - startedAt });
virtual = false;
}
return actualKill(target, signal ?? 'SIGTERM');
}) as typeof process.kill);
return {
elapsedMs: () => now - startedAt,
begin: (leavesAfterMs) => {
now = realNow();
startedAt = now;
leavesAt = leavesAfterMs === undefined ? undefined : now + leavesAfterMs;
virtual = true;
},
end: () => {
virtual = false;
},
signals,
};
}

async function waitForExit(pid: number): Promise<void> {
for (let polls = 0; isProcessAlive(pid) && polls < 500; polls += 1) {
await actualRetry.sleep(10);
}
}

async function withLoopback(t: { skip: (note: string) => void }): Promise<boolean> {
if (await supportsLoopbackBind()) return true;
t.skip('loopback listeners are not permitted in this environment');
return false;
}

test('a drain that outlasts the old kill window is waited out, not signaled', async (t) => {
if (!(await withLoopback(t))) return;
const { stateDir, paths } = stateDirAndPaths();
let childPid = 0;
const drain = installVirtualDrain(() => childPid);
const stale = await startScriptedDaemon(draining, { afterRpc: () => drain.begin(5_000) });
const fresh = await startScriptedDaemon(okResult({}));
const { child } = await registerDaemon(paths, {
httpPort: stale.port,
version: '0.0.0-stale',
capabilities: ['quiesce'],
});
childPid = child.pid;
launchesFreshDaemonAt(spawn, paths, fresh.port);

try {
const connection = await ensureDaemon({ stateDir, daemonTransport: 'http' });

assert.equal(connection.started, true);
assert.ok(drain.elapsedMs() >= 5_000, 'the drain ran for 5 virtual seconds');
assert.ok(drain.elapsedMs() > OLD_GRACE_MS);
assert.deepEqual(drain.signals, [], 'the client signaled nothing while the daemon drained');
assert.equal(isProcessAlive(childPid), false, 'the daemon left by itself');
assert.equal(spawn.mock.calls.length, 1, 'its successor started after it left');
} finally {
await closeLoopbackServer(stale.server);
await closeLoopbackServer(fresh.server);
}
});

test('a daemon still running past the deadline that answers no probe is force-retired', async (t) => {
if (!(await withLoopback(t))) return;
const { stateDir, paths } = stateDirAndPaths();
let childPid = 0;
const drain = installVirtualDrain(() => childPid);
// A draining daemon has closed its servers, so it answers no liveness probe.
const stale = await startScriptedDaemon(draining, {
afterRpc: () => {
drain.begin(undefined);
void closeLoopbackServer(stale.server);
},
});
const fresh = await startScriptedDaemon(okResult({}));
const { child } = await registerDaemon(paths, {
httpPort: stale.port,
version: '0.0.0-stale',
capabilities: ['quiesce'],
});
childPid = child.pid;
launchesFreshDaemonAt(spawn, paths, fresh.port);

try {
const connection = await ensureDaemon({ stateDir, daemonTransport: 'http' });

assert.equal(connection.started, true);
assert.equal(drain.signals.length > 0, true, 'the stuck daemon was signaled');
assert.ok(
drain.signals.every(({ atMs }) => atMs >= DRAIN_DEADLINE_MS),
`no signal before the deadline: ${JSON.stringify(drain.signals)}`,
);
assert.equal(isProcessAlive(childPid), false);
assert.equal(spawn.mock.calls.length, 1);
} finally {
await closeLoopbackServer(fresh.server);
}
});

test('a daemon still running past the deadline that answers a probe is left alone', async (t) => {
if (!(await withLoopback(t))) return;
const { stateDir, paths } = stateDirAndPaths();
let childPid = 0;
const drain = installVirtualDrain(() => childPid);
const stale = await startScriptedDaemon(draining, { afterRpc: () => drain.begin(undefined) });
const { child } = await registerDaemon(paths, {
httpPort: stale.port,
version: '0.0.0-stale',
capabilities: ['quiesce'],
});
childPid = child.pid;

try {
await assert.rejects(ensureDaemon({ stateDir, daemonTransport: 'http' }), (error: unknown) => {
assert.ok(error instanceof AppError);
assert.equal(error.details?.reason, 'daemon-drain-timeout');
assert.match(String(error.details?.hint), /agent-device daemon stop/);
return true;
});
assert.deepEqual(drain.signals, []);
assert.equal(isProcessAlive(childPid), true);
assert.equal(spawn.mock.calls.length, 0);
drain.end();
} finally {
await closeLoopbackServer(stale.server);
}
});
5 changes: 4 additions & 1 deletion src/daemon-client/__tests__/daemon-client-ensuring.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { isProcessAlive } from '@agent-device/host-kit/process';
import { finishRegisteredDaemonFixtures } from '../../__tests__/test-utils/registered-daemon-fixture.ts';
import {
busy,
createDaemonLeaver,
draining,
launchesFreshDaemonAt,
okResult,
Expand Down Expand Up @@ -78,13 +79,15 @@ test('the first request ensures a missing daemon once and every request attaches
test('an idle incompatible daemon is replaced, and the replacement is reported', async (t) => {
if (!(await supportsLoopbackBind())) return t.skip('loopback listeners are not permitted');
const { stateDir, paths } = stateDirAndPaths();
const stale = await startScriptedDaemon(draining);
const leaver = createDaemonLeaver();
const stale = await startScriptedDaemon(draining, { afterRpc: leaver.leave });
const fresh = await startScriptedDaemon(okResult({}));
const { child } = await registerDaemon(paths, {
httpPort: stale.port,
version: '0.0.0-stale',
capabilities: ['quiesce'],
});
leaver.pid = child.pid;
launchesFreshDaemonAt(spawn, paths, fresh.port);
const { sent, transport } = recordingTransport();
const replaced: Array<{ stateDir: string; pid: number; reason: string }> = [];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
import { currentDaemonCodeSignature } from '../../__tests__/test-utils/daemon-http-fixture.ts';
import {
busy,
createDaemonLeaver,
draining,
launchesFreshDaemonAt as launchSeamAnswersAt,
okResult,
Expand Down Expand Up @@ -232,13 +233,15 @@ test('ensureDaemon ignores a remote base URL in the environment', async (t) => {
test('ensureDaemon replaces an incompatible idle daemon through a fenced quiesce request', async (t) => {
if (!(await withLoopback(t))) return;
const { stateDir, paths } = stateDirAndPaths();
const stale = await startScriptedDaemon(draining);
const leaver = createDaemonLeaver();
const stale = await startScriptedDaemon(draining, { afterRpc: leaver.leave });
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
const fresh = await startScriptedDaemon(okResult({}));
const { child, info } = await registerDaemon(paths, {
httpPort: stale.port,
version: '0.0.0-stale',
capabilities: ['quiesce'],
});
leaver.pid = child.pid;
launchesFreshDaemonAt(paths, fresh.port);
const started: Array<[string, { pid: number; version?: string } | undefined]> = [];

Expand Down Expand Up @@ -432,12 +435,17 @@ const instanceMismatch = {
test('a live daemon on another transport is quiesced, never killed as unreachable', async (t) => {
if (!(await withLoopback(t))) return;
const { stateDir, paths } = stateDirAndPaths();
const live = await startScriptedSocketDaemon({ ok: true, data: { outcome: 'draining' } });
const leaver = createDaemonLeaver();
const live = await startScriptedSocketDaemon(
{ ok: true, data: { outcome: 'draining' } },
{ afterCommand: leaver.leave },
);
const fresh = await startScriptedDaemon(okResult({}));
const { child } = await registerDaemon(paths, {
socketPort: live.port,
capabilities: ['quiesce'],
});
leaver.pid = child.pid;
launchesFreshDaemonAt(paths, fresh.port);
const started: string[] = [];

Expand Down Expand Up @@ -486,13 +494,15 @@ test('a live daemon on another transport is left alone when it cannot be asked t
test('ensureDaemon judges again after the daemon it addressed turned out to be gone', async (t) => {
if (!(await withLoopback(t))) return;
const { stateDir, paths } = stateDirAndPaths();
const stale = await startScriptedDaemon(draining);
const leaver = createDaemonLeaver();
const stale = await startScriptedDaemon(draining, { afterRpc: leaver.leave });
const fresh = await startScriptedDaemon(okResult({}));
await registerDaemon(paths, {
const { child } = await registerDaemon(paths, {
httpPort: stale.port,
version: '0.0.0-stale',
capabilities: ['quiesce'],
});
leaver.pid = child.pid;
launchesFreshDaemonAt(paths, fresh.port);
const actualSend = transport.sendRequest;
vi.spyOn(transport, 'sendRequest').mockResolvedValueOnce(instanceMismatch);
Expand Down Expand Up @@ -566,7 +576,8 @@ test('ensureDaemon does not start a daemon over one it could not confirm retired
test('ensureDaemon quiesces an incompatible daemon that wins a startup race instead of retiring it', async (t) => {
if (!(await withLoopback(t))) return;
const { stateDir, paths } = stateDirAndPaths();
const stale = await startScriptedDaemon(draining);
const leaver = createDaemonLeaver();
const stale = await startScriptedDaemon(draining, { afterRpc: leaver.leave });
const fresh = await startScriptedDaemon(okResult({}));
const barrier = path.join(paths.baseDir, 'contender-barrier');
fs.mkdirSync(paths.baseDir, { recursive: true });
Expand All @@ -586,6 +597,7 @@ test('ensureDaemon quiesces an incompatible daemon that wins a startup race inst
},
undefined,
);
leaver.pid = winner.pid;
// Released whether or not the winner published, so the launched child never waits forever.
const release = () => fs.writeFileSync(barrier, 'go');
void waitForRegisteredDaemonFixture(paths, winner).then(release, release);
Expand Down
Loading
Loading