Skip to content

Commit 7f9500d

Browse files
committed
test(client,perf): make companion tunnel and perf-capture assertions discriminating
- Pin normalizeCloseCode's own output through the wire seam with a fractional 3000-4999 bridge code the second stage would pass through, and assert each expected close per stream instead of a sorted multiset. - Split the seven-scenario companion teardown chain into test.each cases, each with its own projectRoot, state file, pid, and mock outcome tables, so one failure cannot hide the later scenarios. - Correct the EPERM comment's daemon-stop path to src/daemon/daemon-stop.ts. - Assert the typed INVALID_ARGS code, not only the message, for a non-xctrace Apple perf kind.
1 parent b15c7c7 commit 7f9500d

3 files changed

Lines changed: 224 additions & 125 deletions

File tree

‎src/__tests__/client-companion-tunnel-worker.test.ts‎

Lines changed: 27 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -829,21 +829,37 @@ test('metro companion worker proxies bridge http requests to the local server',
829829
test('metro companion worker normalizes close codes the websocket client cannot send', async () => {
830830
// A WebSocket client may only close with 1000 or 3000-4999. Every other bridge code must reach
831831
// upstream as 3001 instead of throwing inside the worker and stranding the tunnel.
832+
//
833+
// The codes are asserted per stream, not as a sorted multiset, so each expected wire code is
834+
// pinned to the bridge code that produced it. `stream-fractional` is what makes the first
835+
// normalization stage observable: the second stage passes any 3000-4999 value through, so
836+
// without the non-integer rejection here the 3500.5 would reach the wire truncated to 3500
837+
// instead of being refused as 3001.
832838
const closeCodes: Record<string, number | undefined> = {
833839
'stream-1000': 1000,
834840
'stream-4000': 4000,
835841
'stream-1005': 1005,
836842
'stream-1001': 1001,
837843
'stream-none': undefined,
844+
'stream-fractional': 3500.5,
845+
};
846+
const expectedCloses: Record<string, CloseFrame> = {
847+
'stream-1000': { code: 1000, reason: 'bridge done' },
848+
'stream-4000': { code: 4000, reason: 'bridge requested close' },
849+
'stream-1005': { code: 3001, reason: 'bridge requested close' },
850+
'stream-1001': { code: 3001, reason: 'bridge requested close' },
851+
'stream-none': { code: 3001, reason: 'bridge requested close' },
852+
'stream-fractional': { code: 3001, reason: 'bridge requested close' },
838853
};
839854
const streamIds = Object.keys(closeCodes);
840-
const upstreamCloses: CloseFrame[] = [];
855+
const upstreamCloses = new Map<string, CloseFrame>();
841856
const upstreamClosed = createDeferred<void>();
842857
let upstreamSocketRef: Duplex | null = null;
843858

844859
const upstreamServer = http.createServer((_, res) => writeNotFound(res));
845860
upstreamServer.on('upgrade', (req, socket) => {
846-
if (!req.url?.startsWith('/echo/')) {
861+
const streamId = req.url?.startsWith('/echo/') ? req.url.slice('/echo/'.length) : undefined;
862+
if (!streamId || !(streamId in closeCodes)) {
847863
socket.destroy();
848864
return;
849865
}
@@ -855,8 +871,8 @@ test('metro companion worker normalizes close codes the websocket client cannot
855871
// This probe only answers close frames; text frames are not proxied here.
856872
},
857873
(frame) => {
858-
upstreamCloses.push(frame);
859-
if (upstreamCloses.length === streamIds.length) upstreamClosed.resolve();
874+
upstreamCloses.set(streamId, frame);
875+
if (upstreamCloses.size === streamIds.length) upstreamClosed.resolve();
860876
},
861877
);
862878
});
@@ -922,17 +938,14 @@ test('metro companion worker normalizes close codes the websocket client cannot
922938
earlyExit,
923939
]);
924940

941+
const expectedByStream = streamIds.map((streamId) => ({
942+
streamId,
943+
received: upstreamCloses.get(streamId),
944+
expected: expectedCloses[streamId],
945+
}));
925946
assert.deepEqual(
926-
upstreamCloses.map((frame) => frame.code).sort((left, right) => left! - right!),
927-
[1000, 3001, 3001, 3001, 4000],
928-
);
929-
assert.ok(
930-
upstreamCloses.some((frame) => frame.reason === 'bridge done'),
931-
'a bridge-provided reason must survive normalization',
932-
);
933-
assert.ok(
934-
upstreamCloses.some((frame) => frame.reason === 'bridge requested close'),
935-
'a missing bridge reason must fall back to the default',
947+
expectedByStream.map((entry) => [entry.streamId, entry.received]),
948+
expectedByStream.map((entry) => [entry.streamId, entry.expected]),
936949
);
937950

938951
// The worker keeps serving after the normalized closes.

‎src/__tests__/client-metro-companion.test.ts‎

Lines changed: 191 additions & 110 deletions
Original file line numberDiff line numberDiff line change
@@ -341,121 +341,202 @@ function errnoException(code: string): NodeJS.ErrnoException {
341341
return Object.assign(new Error(`simulated ${code}`), { code });
342342
}
343343

344-
test('stopping a companion survives every process-teardown race', async () => {
345-
const projectRoot = mkdtempForTestSync('agent-device-metro-companion-teardown-');
346-
const companionCommand = `${process.execPath} src/client/companion-tunnel.ts --agent-device-run-metro-companion`;
347-
try {
348-
// 1. The recorded pid is already gone: nothing to signal, and the artifacts are cleared.
349-
vi.mocked(isProcessAlive).mockReturnValueOnce(false);
350-
let statePath = writeOwnCompanionState(projectRoot, 4001);
351-
let killSpy = vi.spyOn(process, 'kill').mockReturnValue(true);
352-
assert.equal((await stopMetroCompanion({ projectRoot })).stopped, true);
353-
assert.equal(killSpy.mock.calls.length, 0);
354-
assert.equal(fs.existsSync(statePath), false);
355-
killSpy.mockRestore();
356-
357-
// 2. The process is alive but its command line is unreadable: never signal an unknown pid.
358-
vi.mocked(isProcessAlive).mockReturnValueOnce(true);
359-
vi.mocked(readProcessCommand).mockReturnValueOnce(null);
360-
statePath = writeOwnCompanionState(projectRoot, 4002);
361-
killSpy = vi.spyOn(process, 'kill').mockReturnValue(true);
362-
assert.equal((await stopMetroCompanion({ projectRoot })).stopped, true);
363-
assert.equal(killSpy.mock.calls.length, 0);
364-
killSpy.mockRestore();
365-
366-
// 3. SIGTERM is refused (EPERM). The shared stopper reads "signal refused" as
367-
// already-exited, so teardown reports stopped, skips the exit wait and SIGKILL,
368-
// and drops the state file without confirming an exit. EPERM can also mean a
369-
// companion still running under another owner, which is why the daemon's own
370-
// stopper keeps its registration instead (`signal-failed` in
371-
// src/daemon/process/daemon-stop.ts); companion teardown keeps the weaker
372-
// local-dev contract that a pid we cannot signal is not ours to keep tracking.
373-
vi.mocked(isProcessAlive).mockReturnValueOnce(true);
374-
vi.mocked(readProcessCommand).mockReturnValueOnce(companionCommand);
375-
killSpy = vi.spyOn(process, 'kill').mockImplementationOnce(() => {
376-
throw errnoException('EPERM');
377-
});
378-
statePath = writeOwnCompanionState(projectRoot, 4003);
379-
assert.equal((await stopMetroCompanion({ projectRoot })).stopped, true);
380-
assert.deepEqual(killSpy.mock.calls, [[4003, 'SIGTERM']]);
381-
assert.equal(vi.mocked(waitForProcessExit).mock.calls.length, 0);
382-
assert.equal(fs.existsSync(statePath), false);
383-
killSpy.mockRestore();
384-
385-
// 4. SIGTERM is ignored: escalate to SIGKILL and wait for the exit again.
386-
vi.mocked(waitForProcessExit).mockReset();
387-
vi.mocked(isProcessAlive).mockReturnValueOnce(true);
388-
vi.mocked(readProcessCommand).mockReturnValueOnce(companionCommand);
389-
killSpy = vi.spyOn(process, 'kill').mockReturnValue(true);
390-
vi.mocked(waitForProcessExit).mockResolvedValueOnce(false).mockResolvedValueOnce(true);
391-
statePath = writeOwnCompanionState(projectRoot, 4004);
392-
assert.equal((await stopMetroCompanion({ projectRoot })).stopped, true);
393-
assert.deepEqual(killSpy.mock.calls, [
394-
[4004, 'SIGTERM'],
395-
[4004, 'SIGKILL'],
396-
]);
397-
assert.deepEqual(
398-
vi.mocked(waitForProcessExit).mock.calls.map((call) => [call[0], call[1]]),
399-
[
344+
const COMPANION_TUNNEL_COMMAND = `${process.execPath} src/client/companion-tunnel.ts --agent-device-run-metro-companion`;
345+
346+
type CompanionTeardownCase = Readonly<{
347+
name: string;
348+
pid: number;
349+
processAlive: boolean;
350+
processCommand: string | null;
351+
/** One entry per `process.kill` call: an errno to throw, or true when the signal is accepted. */
352+
killOutcomes: Array<true | 'EPERM' | 'ESRCH' | 'EACCES'>;
353+
/** One entry per `waitForProcessExit` call: whether the companion exited in that window. */
354+
exitOutcomes: boolean[];
355+
expect: Readonly<{
356+
rejection?: string;
357+
stopped?: boolean;
358+
killCalls: Array<[number, 'SIGTERM' | 'SIGKILL']>;
359+
exitWaitCalls: Array<[number, number]>;
360+
keepsState: boolean;
361+
}>;
362+
}>;
363+
364+
const COMPANION_TEARDOWN_CASES: CompanionTeardownCase[] = [
365+
{
366+
// The recorded pid is already gone: nothing to signal, and the artifacts are cleared.
367+
name: 'clears artifacts when the recorded pid is already gone',
368+
pid: 4001,
369+
processAlive: false,
370+
processCommand: COMPANION_TUNNEL_COMMAND,
371+
killOutcomes: [],
372+
exitOutcomes: [],
373+
expect: { stopped: true, killCalls: [], exitWaitCalls: [], keepsState: false },
374+
},
375+
{
376+
// The process is alive but its command line is unreadable: never signal an unknown pid.
377+
name: 'never signals a pid whose command line is unreadable',
378+
pid: 4002,
379+
processAlive: true,
380+
processCommand: null,
381+
killOutcomes: [],
382+
exitOutcomes: [],
383+
expect: { stopped: true, killCalls: [], exitWaitCalls: [], keepsState: false },
384+
},
385+
{
386+
// SIGTERM is refused (EPERM). The shared stopper reads "signal refused" as already-exited, so
387+
// teardown reports stopped, skips the exit wait and SIGKILL, and drops the state file without
388+
// confirming an exit. EPERM can also mean a companion still running under another owner, which
389+
// is why the daemon's own stopper keeps its registration instead (`signal-failed` in
390+
// src/daemon/daemon-stop.ts); companion teardown keeps the weaker local-dev contract that a pid
391+
// we cannot signal is not ours to keep tracking.
392+
name: 'reads a refused SIGTERM as already exited',
393+
pid: 4003,
394+
processAlive: true,
395+
processCommand: COMPANION_TUNNEL_COMMAND,
396+
killOutcomes: ['EPERM'],
397+
exitOutcomes: [],
398+
expect: {
399+
stopped: true,
400+
killCalls: [[4003, 'SIGTERM']],
401+
exitWaitCalls: [],
402+
keepsState: false,
403+
},
404+
},
405+
{
406+
// SIGTERM is ignored: escalate to SIGKILL and wait for the exit again.
407+
name: 'escalates an ignored SIGTERM to SIGKILL',
408+
pid: 4004,
409+
processAlive: true,
410+
processCommand: COMPANION_TUNNEL_COMMAND,
411+
killOutcomes: [true, true],
412+
exitOutcomes: [false, true],
413+
expect: {
414+
stopped: true,
415+
killCalls: [
416+
[4004, 'SIGTERM'],
417+
[4004, 'SIGKILL'],
418+
],
419+
exitWaitCalls: [
400420
[4004, 1_000],
401421
[4004, 1_000],
402422
],
403-
);
404-
killSpy.mockRestore();
405-
406-
// 5. SIGKILL loses the race (ESRCH): stop without waiting on a pid that is already gone.
407-
vi.mocked(waitForProcessExit).mockReset().mockResolvedValueOnce(false);
408-
vi.mocked(isProcessAlive).mockReturnValueOnce(true);
409-
vi.mocked(readProcessCommand).mockReturnValueOnce(companionCommand);
410-
killSpy = vi
411-
.spyOn(process, 'kill')
412-
.mockReturnValueOnce(true)
413-
.mockImplementationOnce(() => {
414-
throw errnoException('ESRCH');
423+
keepsState: false,
424+
},
425+
},
426+
{
427+
// SIGKILL loses the race (ESRCH): stop without waiting on a pid that is already gone.
428+
name: 'skips the second exit wait when SIGKILL loses the race',
429+
pid: 4005,
430+
processAlive: true,
431+
processCommand: COMPANION_TUNNEL_COMMAND,
432+
killOutcomes: [true, 'ESRCH'],
433+
exitOutcomes: [false],
434+
expect: {
435+
stopped: true,
436+
killCalls: [
437+
[4005, 'SIGTERM'],
438+
[4005, 'SIGKILL'],
439+
],
440+
exitWaitCalls: [[4005, 1_000]],
441+
keepsState: false,
442+
},
443+
},
444+
{
445+
// A signalling failure that is not a race is reported, and the state file survives so the
446+
// companion can be retried instead of being orphaned silently.
447+
name: 'reports a non-race SIGTERM failure and keeps the state for retry',
448+
pid: 4006,
449+
processAlive: true,
450+
processCommand: COMPANION_TUNNEL_COMMAND,
451+
killOutcomes: ['EACCES'],
452+
exitOutcomes: [],
453+
expect: {
454+
rejection: 'simulated EACCES',
455+
killCalls: [[4006, 'SIGTERM']],
456+
exitWaitCalls: [],
457+
keepsState: true,
458+
},
459+
},
460+
{
461+
// The same holds when only the escalation fails for a non-race reason: the retry stops the
462+
// same still-recorded companion and fails on SIGKILL.
463+
name: 'reports a non-race SIGKILL escalation failure and keeps the state for retry',
464+
pid: 4007,
465+
processAlive: true,
466+
processCommand: COMPANION_TUNNEL_COMMAND,
467+
killOutcomes: [true, 'EACCES'],
468+
exitOutcomes: [false],
469+
expect: {
470+
rejection: 'simulated EACCES',
471+
killCalls: [
472+
[4007, 'SIGTERM'],
473+
[4007, 'SIGKILL'],
474+
],
475+
exitWaitCalls: [[4007, 1_000]],
476+
keepsState: true,
477+
},
478+
},
479+
];
480+
481+
// Each case owns its projectRoot, state file, pid, and mock outcomes, so one failure cannot hide
482+
// the later scenarios the way the original chained test allowed.
483+
test.each(COMPANION_TEARDOWN_CASES)(
484+
'stopping a companion survives the teardown race: $name',
485+
async ({
486+
pid,
487+
processAlive,
488+
processCommand,
489+
killOutcomes,
490+
exitOutcomes,
491+
expect: expectation,
492+
}) => {
493+
const projectRoot = mkdtempForTestSync('agent-device-metro-companion-teardown-');
494+
const statePath = writeOwnCompanionState(projectRoot, pid);
495+
try {
496+
vi.mocked(isProcessAlive).mockReturnValue(processAlive);
497+
vi.mocked(readProcessCommand).mockReturnValue(processCommand);
498+
let killIndex = 0;
499+
const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => {
500+
const outcome = killOutcomes[killIndex];
501+
if (outcome === undefined) {
502+
throw new Error(`unexpected process.kill call #${killIndex + 1}`);
503+
}
504+
killIndex += 1;
505+
if (outcome !== true) throw errnoException(outcome);
506+
return true;
415507
});
416-
statePath = writeOwnCompanionState(projectRoot, 4005);
417-
assert.equal((await stopMetroCompanion({ projectRoot })).stopped, true);
418-
assert.deepEqual(killSpy.mock.calls, [
419-
[4005, 'SIGTERM'],
420-
[4005, 'SIGKILL'],
421-
]);
422-
assert.equal(vi.mocked(waitForProcessExit).mock.calls.length, 1);
423-
killSpy.mockRestore();
424-
425-
// 6. A signalling failure that is not a race is reported, and the state file survives so the
426-
// companion can be retried instead of being orphaned silently.
427-
vi.mocked(isProcessAlive).mockReturnValueOnce(true);
428-
vi.mocked(readProcessCommand).mockReturnValueOnce(companionCommand);
429-
killSpy = vi.spyOn(process, 'kill').mockImplementationOnce(() => {
430-
throw errnoException('EACCES');
431-
});
432-
statePath = writeOwnCompanionState(projectRoot, 4006);
433-
await assert.rejects(() => stopMetroCompanion({ projectRoot }), /simulated EACCES/);
434-
assert.equal(fs.existsSync(statePath), true);
435-
killSpy.mockRestore();
436-
437-
// 7. The same holds when only the escalation fails for a non-race reason: the retry stops the
438-
// same still-recorded companion and fails on SIGKILL.
439-
vi.mocked(isProcessAlive).mockReturnValueOnce(true);
440-
vi.mocked(readProcessCommand).mockReturnValueOnce(companionCommand);
441-
killSpy = vi
442-
.spyOn(process, 'kill')
443-
.mockReturnValueOnce(true)
444-
.mockImplementationOnce(() => {
445-
throw errnoException('EACCES');
508+
let exitIndex = 0;
509+
vi.mocked(waitForProcessExit).mockImplementation(async () => {
510+
const outcome = exitOutcomes[exitIndex];
511+
if (outcome === undefined) {
512+
throw new Error(`unexpected waitForProcessExit call #${exitIndex + 1}`);
513+
}
514+
exitIndex += 1;
515+
return outcome;
446516
});
447-
vi.mocked(waitForProcessExit).mockResolvedValueOnce(false).mockResolvedValueOnce(true);
448-
await assert.rejects(() => stopMetroCompanion({ projectRoot }), /simulated EACCES/);
449-
assert.deepEqual(killSpy.mock.calls, [
450-
[4006, 'SIGTERM'],
451-
[4006, 'SIGKILL'],
452-
]);
453-
assert.equal(fs.existsSync(statePath), true);
454-
killSpy.mockRestore();
455-
} finally {
456-
fs.rmSync(projectRoot, { recursive: true, force: true });
457-
}
458-
});
517+
518+
if (expectation.rejection !== undefined) {
519+
await assert.rejects(
520+
() => stopMetroCompanion({ projectRoot }),
521+
new RegExp(expectation.rejection),
522+
);
523+
} else {
524+
assert.equal(
525+
(await stopMetroCompanion({ projectRoot })).stopped,
526+
expectation.stopped === true,
527+
);
528+
}
529+
assert.deepEqual(killSpy.mock.calls, expectation.killCalls);
530+
assert.deepEqual(
531+
vi.mocked(waitForProcessExit).mock.calls.map((call) => [call[0], call[1]]),
532+
expectation.exitWaitCalls,
533+
);
534+
assert.equal(fs.existsSync(statePath), expectation.keepsState);
535+
} finally {
536+
fs.rmSync(projectRoot, { recursive: true, force: true });
537+
}
538+
},
539+
);
459540

460541
test('legacy state without bridge scope is stopped before respawn', async () => {
461542
const projectRoot = mkdtempForTestSync('agent-device-metro-companion-legacy-');

0 commit comments

Comments
 (0)