Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@ import { afterEach, test, vi } from 'vitest';
import { closeLoopbackServer, skipWhenLoopbackUnavailable } from '@agent-device/test-kit';
import { AppError } from '@agent-device/kernel/errors';
import { DAEMON_QUIESCE_COMMAND } from '@agent-device/daemon-contracts/daemon-resolution';
import { DAEMON_STARTUP_EXIT_CODES } from '@agent-device/daemon-contracts/daemon-registration-owner';
import { isProcessAlive } from '@agent-device/host-kit/process';
import { readVersion } from '@agent-device/host-kit/version';
import {
finishRegisteredDaemonFixtures,
spawnRegisteredDaemonFixture,
planRegisteredDaemonLaunches,
waitForRegisteredDaemonFixture,
} from './registered-daemon-fixture.ts';
import { currentDaemonCodeSignature } from './code-signature-fixture.ts';
Expand Down Expand Up @@ -45,9 +45,6 @@ import { ensureDaemon } from '../daemon-client-ensure.ts';
// so a kill or a spawn is observable as a dead pid or a call to the launch seam.

const spawn = vi.mocked(runCmdDetachedMonitored);
const actualCommand = await vi.importActual<typeof import('@agent-device/host-kit/command')>(
'@agent-device/host-kit/command',
);
const actualRetry = await vi.importActual<typeof import('@agent-device/host-kit/retry')>(
'@agent-device/host-kit/retry',
);
Expand Down Expand Up @@ -618,35 +615,43 @@ test('ensureDaemon quiesces an incompatible daemon that wins a startup race inst
fs.mkdirSync(paths.baseDir, { recursive: true });
vi.mocked(sleep).mockImplementation(actualRetry.sleep);
let winner: ReturnType<typeof spawnRegisteredDaemonFixture> | undefined;
spawn.mockImplementationOnce((_command, _args, options) => {
// An incompatible daemon registers just ahead of the one this call launches, which then exits busy.
winner = spawnRegisteredDaemonFixture(
paths,
spawn.mockImplementationOnce(
planRegisteredDaemonLaunches([
{
httpPort: stale.port,
token: 'local-secret',
version: '0.0.0-stale',
codeOrigin: 'checkout',
codeSignature: currentDaemonCodeSignature(),
capabilities: ['quiesce'],
kind: 'registered',
paths,
fields: {
httpPort: fresh.port,
token: 'local-secret',
version: readVersion(),
codeOrigin: 'checkout',
codeSignature: currentDaemonCodeSignature(),
},
acquisitionBarrier: barrier,
companions: [
{
kind: 'registered',
paths,
fields: {
httpPort: stale.port,
token: 'local-secret',
version: '0.0.0-stale',
codeOrigin: 'checkout',
codeSignature: currentDaemonCodeSignature(),
capabilities: ['quiesce'],
},
observe(child) {
winner = child;
leaver.pid = child.pid;
// Released whether or not the winner published, so the launched child never waits forever.
const release = () => fs.writeFileSync(barrier, 'go');
void waitForRegisteredDaemonFixture(paths, child).then(release, release);
},
},
],
},
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);
// Our launch loses the race once the winner is registered: it exits with the busy code.
return actualCommand.runCmdDetachedMonitored(
process.execPath,
[
'-e',
`const fs=require("fs");setInterval(()=>{if(fs.existsSync(process.argv[1]))process.exit(${DAEMON_STARTUP_EXIT_CODES.busy})},10)`,
barrier,
],
options,
);
});
]),
);
launchesFreshDaemonAt(paths, fresh.port);

try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import {
skipWhenLoopbackUnavailable,
} from '@agent-device/test-kit';
import {
spawnRegisteredDaemonFixture,
planRegisteredDaemonLaunches,
finishRegisteredDaemonFixture,
finishRegisteredDaemonFixtures,
} from './registered-daemon-fixture.ts';
Expand Down Expand Up @@ -142,40 +142,48 @@ function installSpawnedHttpDaemonAtOwnedStateDir(
onStateDir: (stateDir: string) => void,
): void {
mockSleep.mockImplementation(actualRetry.sleep);
mockRunCmdDetached.mockImplementation((_command, _args, options) => {
const ownedStateDir = String(options?.env?.AGENT_DEVICE_STATE_DIR);
onStateDir(ownedStateDir);
const ownedPaths = resolveDaemonPaths(ownedStateDir);
return spawnRegisteredDaemonFixture(
ownedPaths,
{
httpPort,
token: 'local-secret',
version: readVersion(),
codeOrigin: 'checkout',
codeSignature: currentDaemonCodeSignature(),
mockRunCmdDetached.mockImplementation(
planRegisteredDaemonLaunches([
(options) => {
const ownedStateDir = String(options?.env?.AGENT_DEVICE_STATE_DIR);
onStateDir(ownedStateDir);
const ownedPaths = resolveDaemonPaths(ownedStateDir);
return {
kind: 'registered',
paths: ownedPaths,
fields: {
httpPort,
token: 'local-secret',
version: readVersion(),
codeOrigin: 'checkout',
codeSignature: currentDaemonCodeSignature(),
},
};
},
options,
);
});
]),
);
}

function installSpawnedHttpDaemon(paths: DaemonPaths, httpPort: number): void {
mockSleep.mockImplementation(actualRetry.sleep);
mockRunCmdDetached.mockImplementation((_command, _args, options) => {
assert.equal(options?.env?.AGENT_DEVICE_STATE_DIR, paths.baseDir);
return spawnRegisteredDaemonFixture(
paths,
{
httpPort,
token: 'local-secret',
version: readVersion(),
codeOrigin: 'checkout',
codeSignature: currentDaemonCodeSignature(),
mockRunCmdDetached.mockImplementation(
planRegisteredDaemonLaunches([
(options) => {
assert.equal(options?.env?.AGENT_DEVICE_STATE_DIR, paths.baseDir);
return {
kind: 'registered',
paths,
fields: {
httpPort,
token: 'local-secret',
version: readVersion(),
codeOrigin: 'checkout',
codeSignature: currentDaemonCodeSignature(),
},
};
},
options,
);
});
]),
);
}

function mockSocketConnectionFailures(failingPort: number): {
Expand Down Expand Up @@ -279,14 +287,18 @@ test('sendToDaemon retains unknown metadata after a spawn failure', async () =>
vi.stubEnv('AGENT_DEVICE_STATE_DIR', stateDir);
let attempts = 0;

mockRunCmdDetached.mockImplementation((_command, _args, options) => {
attempts += 1;
assert.equal(options?.env?.AGENT_DEVICE_STATE_DIR, stateDir);
fs.mkdirSync(paths.baseDir, { recursive: true });
fs.writeFileSync(paths.infoPath, '{"partial":true}\n', 'utf8');
fs.writeFileSync(paths.lockPath, 'not-json\n', 'utf8');
throw new Error(`spawn failed ${attempts}`);
});
mockRunCmdDetached.mockImplementation(
planRegisteredDaemonLaunches([
(options) => {
attempts += 1;
assert.equal(options?.env?.AGENT_DEVICE_STATE_DIR, stateDir);
fs.mkdirSync(paths.baseDir, { recursive: true });
fs.writeFileSync(paths.infoPath, '{"partial":true}\n', 'utf8');
fs.writeFileSync(paths.lockPath, 'not-json\n', 'utf8');
return { kind: 'refuse', error: new Error(`spawn failed ${attempts}`) };
},
]),
);

try {
let thrown: unknown;
Expand Down Expand Up @@ -326,17 +338,15 @@ test('sendToDaemon reports early daemon exit with log tail and startup paths', a
vi.stubEnv('AGENT_DEVICE_STATE_DIR', stateDir);
let attempts = 0;

mockRunCmdDetached.mockImplementation((_command, _args, options) => {
const earlyExit = (options: Parameters<typeof runCmdDetachedMonitored>[2]) => {
attempts += 1;
const stderrFd = options?.stdio?.[2];
if (typeof stderrFd === 'number') {
fs.writeSync(stderrFd, `early daemon failure ${attempts}\n`);
}
return {
pid: 43_200 + attempts,
exited: Promise.resolve({ pid: 43_200 + attempts, exitCode: 1 }),
};
});
return { kind: 'exit' as const, exit: { pid: 43_200 + attempts, exitCode: 1 } };
};
mockRunCmdDetached.mockImplementation(planRegisteredDaemonLaunches([earlyExit, earlyExit]));

try {
let thrown: unknown;
Expand Down
Loading
Loading