Skip to content

Commit e2c1139

Browse files
committed
test: require the closed-session identity at the leak oracle's owning interface
Re-review of #1859: `closedSessions` was optional and defaulted to empty, so any caller — or the standalone CLI invoked with `--phase after-close` and no `--closed-session` — silently restored the vacuous checkpoint that accepts every unfinalized capture handle and reports clean. - phase and the identity that phase needs are now one discriminated shape: { phase: 'after-close'; closedSessions: NonEmpty<string> } | { phase: 'after-shutdown' }, so the empty case is not expressible and 'after-shutdown' is unchanged - the CLI refuses the same invocation with a typed INVALID_ARGS error and a hint naming what the missing identity would have cost, instead of degrading - daemon-leak-oracle-cli.test.ts drives the real CLI: the unnamed after-close invocation must fail without reporting, the named one finds the planted unfinalized handle, and after-shutdown is unaffected. Reverting the guard makes it print 'clean (after-close)' over that same handle and turns the test red Refs #1781 #1431
1 parent a1cf0c9 commit e2c1139

4 files changed

Lines changed: 185 additions & 66 deletions

File tree

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
import test from 'node:test';
2+
import assert from 'node:assert/strict';
3+
import fs from 'node:fs';
4+
import os from 'node:os';
5+
import path from 'node:path';
6+
import { runCmdSync } from '../../src/utils/exec.ts';
7+
8+
// #1781 B1: the oracle's `after-close` checkpoint is only meaningful when it can
9+
// name the sessions that closed — without them it would accept every unfinalized
10+
// capture handle and report clean, which is the vacuous mode the type system now
11+
// refuses in code. The standalone CLI is the one caller that builds options from
12+
// strings rather than types, so it must refuse the same invocation at runtime
13+
// instead of silently degrading to that mode.
14+
15+
const ORACLE_PATH = 'test/integration/support/daemon-leak-oracle.ts';
16+
17+
function runOracle(args: string[]) {
18+
return runCmdSync(process.execPath, ['--experimental-strip-types', ORACLE_PATH, ...args], {
19+
allowFailure: true,
20+
timeoutMs: 60_000,
21+
});
22+
}
23+
24+
test('the leak oracle CLI refuses an after-close checkpoint that names no session', (t) => {
25+
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-device-leak-oracle-cli-'));
26+
// A closed session that left an unfinalized capture handle: the exact residue
27+
// the refused invocation would have reported clean.
28+
const sessionDir = path.join(stateDir, 'sessions', 'closed-one');
29+
fs.mkdirSync(sessionDir, { recursive: true });
30+
fs.writeFileSync(
31+
path.join(sessionDir, 'screen-recording.resource.json'),
32+
`${JSON.stringify({ lifecycle: 'open' })}\n`,
33+
);
34+
t.after(() => fs.rmSync(stateDir, { recursive: true, force: true }));
35+
36+
const refused = runOracle(['--state-dir', stateDir, '--phase', 'after-close']);
37+
assert.notEqual(refused.exitCode, 0, `expected a refusal, got:\n${refused.stdout}`);
38+
assert.match(refused.stderr, /--phase after-close requires at least one --closed-session/);
39+
// A refusal, not a leak report: the checkpoint never ran.
40+
assert.doesNotMatch(refused.stdout, /daemon leak oracle:/);
41+
42+
// The same invocation, once it names the session, runs and finds the handle.
43+
const named = runOracle([
44+
'--state-dir',
45+
stateDir,
46+
'--phase',
47+
'after-close',
48+
'--closed-session',
49+
'closed-one',
50+
'--settle-ms',
51+
'0',
52+
]);
53+
assert.equal(named.exitCode, 1, `expected a leak report, got:\n${named.stdout}${named.stderr}`);
54+
assert.match(named.stdout, /LEAK \(after-close\)/);
55+
assert.match(named.stdout, /sessions\/closed-one\/screen-recording\.resource\.json/);
56+
57+
// `after-shutdown` needs no session identity and is unaffected by the guard.
58+
const shutdown = runOracle(['--state-dir', stateDir, '--settle-ms', '0']);
59+
assert.equal(shutdown.exitCode, 1, shutdown.stderr);
60+
assert.match(shutdown.stdout, /LEAK \(after-shutdown\)/);
61+
});

‎test/integration/support/daemon-leak-model.test.ts‎

Lines changed: 46 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,10 @@ import {
44
formatDaemonLeakReport,
55
hasDaemonLeaks,
66
type DaemonLeakObservation,
7-
type DaemonLeakPhase,
7+
type DaemonLeakObservationBase,
8+
type DaemonLeakPhaseSelection,
89
type HostProcess,
10+
type NonEmpty,
911
type StateEntry,
1012
} from './daemon-leak-model.ts';
1113

@@ -22,20 +24,35 @@ function proc(overrides: Partial<HostProcess> & Pick<HostProcess, 'pid'>): HostP
2224
return { ppid: 1, pgid: overrides.pid, command: 'unrelated', env: '', ...overrides };
2325
}
2426

25-
function observe(overrides: Partial<DaemonLeakObservation> = {}): DaemonLeakObservation {
27+
// The phase and its identity arrive together: `after-close` cannot be requested
28+
// without naming the sessions that closed, so these helpers cannot construct the
29+
// vacuous checkpoint either.
30+
function observe(
31+
overrides: Partial<DaemonLeakObservationBase> = {},
32+
selection: DaemonLeakPhaseSelection = { phase: 'after-shutdown' },
33+
): DaemonLeakObservation {
2634
return {
2735
stateDir: STATE_DIR,
2836
daemonPids: [DAEMON_PID],
2937
livePids: [],
30-
phase: 'after-shutdown',
3138
processes: [],
3239
excludedPids: [OBSERVER_PID],
33-
closedSessions: [],
3440
stateEntries: [],
3541
...overrides,
42+
...selection,
3643
};
3744
}
3845

46+
function observeAfterClose(
47+
closedSessions: NonEmpty<string>,
48+
overrides: Partial<DaemonLeakObservationBase> = {},
49+
): DaemonLeakObservation {
50+
return observe(
51+
{ livePids: [DAEMON_PID], ...overrides },
52+
{ phase: 'after-close', closedSessions },
53+
);
54+
}
55+
3956
function file(entryPath: string, descriptorLifecycle?: string): StateEntry {
4057
return { path: entryPath, kind: 'file', ...(descriptorLifecycle ? { descriptorLifecycle } : {}) };
4158
}
@@ -129,9 +146,7 @@ describe('surviving-daemon rule', () => {
129146

130147
test('a live daemon is expected while a session merely closed', () => {
131148
const snapshot = evaluateDaemonLeaks(
132-
observe({
133-
phase: 'after-close',
134-
livePids: [DAEMON_PID],
149+
observeAfterClose(['closed-one'], {
135150
stateEntries: [file('daemon.json'), file('daemon.lock')],
136151
}),
137152
);
@@ -141,51 +156,59 @@ describe('surviving-daemon rule', () => {
141156
});
142157

143158
describe('state-dir residue rules', () => {
144-
test.each<[string, StateEntry, DaemonLeakPhase, 'expected' | 'stray']>([
145-
['session event log', file('sessions/default/events.ndjson'), 'after-shutdown', 'expected'],
146-
['request diagnostics', file('sessions/d/requests/abc.ndjson'), 'after-shutdown', 'expected'],
147-
['shutdown report', file('daemon-shutdown.json'), 'after-shutdown', 'expected'],
148-
['torn publish temporary', file('device-claims/a.json.55.tmp'), 'after-shutdown', 'stray'],
159+
const AFTER_SHUTDOWN: DaemonLeakPhaseSelection = { phase: 'after-shutdown' };
160+
// A different session from the one this entry belongs to, so the row proves the
161+
// phase rule rather than the closed-session rule.
162+
const AFTER_CLOSE: DaemonLeakPhaseSelection = {
163+
phase: 'after-close',
164+
closedSessions: ['closed-one'],
165+
};
166+
167+
test.each<[string, StateEntry, DaemonLeakPhaseSelection, 'expected' | 'stray']>([
168+
['session event log', file('sessions/default/events.ndjson'), AFTER_SHUTDOWN, 'expected'],
169+
['request diagnostics', file('sessions/d/requests/abc.ndjson'), AFTER_SHUTDOWN, 'expected'],
170+
['shutdown report', file('daemon-shutdown.json'), AFTER_SHUTDOWN, 'expected'],
171+
['torn publish temporary', file('device-claims/a.json.55.tmp'), AFTER_SHUTDOWN, 'stray'],
149172
[
150173
'managed tool download',
151174
file('tools/agent-browser/0.27.1/dl.tmp'),
152-
'after-shutdown',
175+
AFTER_SHUTDOWN,
153176
'expected',
154177
],
155178
[
156179
'unswept artifact scaffold',
157180
{ path: 'sessions/d/artifacts/pending/', kind: 'empty-directory' },
158-
'after-shutdown',
181+
AFTER_SHUTDOWN,
159182
'stray',
160183
],
161184
[
162185
'unswept session scaffold',
163186
{ path: 'sessions/leaked/requests/', kind: 'empty-directory' },
164-
'after-shutdown',
187+
AFTER_SHUTDOWN,
165188
'stray',
166189
],
167-
['unknown artifact', file('sessions/d/mystery.bin'), 'after-shutdown', 'stray'],
190+
['unknown artifact', file('sessions/d/mystery.bin'), AFTER_SHUTDOWN, 'stray'],
168191
[
169192
'open capture descriptor',
170193
file('sessions/d/screen-recording.resource.json', 'open'),
171-
'after-shutdown',
194+
AFTER_SHUTDOWN,
172195
'stray',
173196
],
174197
[
175198
'completed capture descriptor',
176199
file('sessions/d/screen-recording.resource.json', 'completed'),
177-
'after-shutdown',
200+
AFTER_SHUTDOWN,
178201
'expected',
179202
],
180203
[
181204
"another session's open capture during close",
182205
file('sessions/other/screen-recording.resource.json', 'open'),
183-
'after-close',
206+
AFTER_CLOSE,
184207
'expected',
185208
],
186-
['legacy app-log marker', file('sessions/d/app-log.pid'), 'after-shutdown', 'stray'],
187-
])('%s is %s at %s', (_name, entry, phase, verdict) => {
188-
const snapshot = evaluateDaemonLeaks(observe({ phase, stateEntries: [entry] }));
209+
['legacy app-log marker', file('sessions/d/app-log.pid'), AFTER_SHUTDOWN, 'stray'],
210+
])('%s is %s', (_name, entry, selection, verdict) => {
211+
const snapshot = evaluateDaemonLeaks(observe({ stateEntries: [entry] }, selection));
189212

190213
expect(snapshot.strayStateEntries).toEqual(verdict === 'stray' ? [entry.path] : []);
191214
});
@@ -210,12 +233,7 @@ describe('closed-session capture handles', () => {
210233
const closedSessionCapture = (lifecycle: string) =>
211234
file('sessions/closed-one/screen-recording.resource.json', lifecycle);
212235
const afterClose = (stateEntries: StateEntry[]): DaemonLeakObservation =>
213-
observe({
214-
phase: 'after-close',
215-
livePids: [DAEMON_PID],
216-
closedSessions: ['closed-one'],
217-
stateEntries,
218-
});
236+
observeAfterClose(['closed-one'], { stateEntries });
219237

220238
test('the closed session must have finalized its capture handle', () => {
221239
const snapshot = evaluateDaemonLeaks(afterClose([closedSessionCapture('open')]));

‎test/integration/support/daemon-leak-model.ts‎

Lines changed: 22 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -88,24 +88,32 @@ export type OwnedProcess = {
8888
reasons: OwnershipReason[];
8989
};
9090

91-
export type DaemonLeakObservation = {
91+
export type NonEmpty<T> = readonly [T, ...T[]];
92+
93+
/**
94+
* The phase and the identity it needs, as one shape. An `after-close`
95+
* checkpoint that cannot name the sessions that closed cannot tell their
96+
* unfinalized capture handles from another session's legitimately live one, so
97+
* it would accept every open handle and certify nothing. The identity is
98+
* therefore part of the phase rather than an option a caller may omit, and the
99+
* typechecker refuses the empty case.
100+
*/
101+
export type DaemonLeakPhaseSelection =
102+
| { phase: 'after-shutdown' }
103+
| { phase: 'after-close'; closedSessions: NonEmpty<string> };
104+
105+
export type DaemonLeakObservationBase = {
92106
stateDir: string;
93107
daemonPids: readonly number[];
94108
livePids: readonly number[];
95-
phase: DaemonLeakPhase;
96109
processes: readonly HostProcess[];
97110
/** Pids never treated as owned: the observer and its own ancestors. */
98111
excludedPids: readonly number[];
99-
/**
100-
* Session directory names closed at this checkpoint. Their capture handles
101-
* must be finalized; other sessions may still hold live ones. A checkpoint
102-
* that cannot say which session closed cannot tell an unfinalized handle from
103-
* a legitimately live one, so `after-close` callers always pass them.
104-
*/
105-
closedSessions: readonly string[];
106112
stateEntries: readonly StateEntry[];
107113
};
108114

115+
export type DaemonLeakObservation = DaemonLeakPhaseSelection & DaemonLeakObservationBase;
116+
109117
export type DaemonLeakSnapshot = {
110118
stateDir: string;
111119
daemonPids: number[];
@@ -150,7 +158,7 @@ export function evaluateDaemonLeaks(observation: DaemonLeakObservation): DaemonL
150158
classifyStateEntry(entry, {
151159
phase: observation.phase,
152160
daemonLegitimatelyAlive,
153-
closedSessions: observation.closedSessions,
161+
closedSessions: closedSessionsOf(observation),
154162
}) === 'stray',
155163
)
156164
.map((entry) => entry.path)
@@ -258,6 +266,10 @@ function classifyCaptureEntry(entry: StateEntry, context: StateEntryContext): 'e
258266
return entry.descriptorLifecycle === 'completed' ? 'expected' : 'stray';
259267
}
260268

269+
function closedSessionsOf(observation: DaemonLeakObservation): readonly string[] {
270+
return observation.phase === 'after-close' ? observation.closedSessions : [];
271+
}
272+
261273
function sessionDirectoryOf(entryPath: string): string | undefined {
262274
return /^sessions\/([^/]+)\//.exec(entryPath)?.[1];
263275
}

0 commit comments

Comments
 (0)