Skip to content

Commit b1176fd

Browse files
mchwangclaude
andcommitted
removeByName's reports name the stage and the command run (#189)
Review round 36: removeByName takes a when prefix, as removeLabelledObjects does, and names the command it ran (docker rm, docker container inspect). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 6497cf7 commit b1176fd

5 files changed

Lines changed: 28 additions & 27 deletions

File tree

‎test/agent-container.test.ts‎

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -158,9 +158,9 @@ afterEach(async () => {
158158
afterAll(async () => {
159159
try {
160160
// By exact name: some are named like the start of another object's ID.
161-
for (const container of containers) removeByName('container', container);
162-
for (const network of networks) removeByName('network', network);
163-
for (const volume of volumes) removeByName('volume', volume);
161+
for (const container of containers) removeByName('container', container, 'afterAll');
162+
for (const network of networks) removeByName('network', network, 'afterAll');
163+
for (const volume of volumes) removeByName('volume', volume, 'afterAll');
164164
// Each step, even when an earlier one fails: storage left here is found by the sweep below only by its label, and
165165
// every failure is reported.
166166
const failures: unknown[] = [];
@@ -832,17 +832,17 @@ describe('real Docker agent isolation', () => {
832832
// is gone says nothing.
833833
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
834834
try {
835-
for (const [kind, name] of byName) removeByName(kind, name);
835+
for (const [kind, name] of byName) removeByName(kind, name, 'test');
836836
expect(byName.filter(([kind, name]) => spawnSync('docker', [kind, 'inspect', name], { stdio: 'ignore' }).status === 0)).toEqual([]);
837-
for (const [kind, name] of byName) removeByName(kind, name);
837+
for (const [kind, name] of byName) removeByName(kind, name, 'test');
838838
expect(warn).not.toHaveBeenCalled();
839839
} finally { warn.mockRestore(); }
840840
// A missing name that Docker resolves to a live object's ID, as a tracked name gone since would be: removeByName
841841
// must leave that object alone. The network has no endpoints, so Docker would remove it if asked.
842842
expect(docker('network', 'inspect', '--format', '{{.Id}}', lookalike.slice(0, 12))).toBe(lookalike);
843-
removeByName('network', lookalike.slice(0, 12));
843+
removeByName('network', lookalike.slice(0, 12), 'test');
844844
expect(docker('container', 'inspect', '--format', '{{.Id}}', bystanders[0]!.slice(0, 12))).toBe(bystanders[0]);
845-
removeByName('container', bystanders[0]!.slice(0, 12));
845+
removeByName('container', bystanders[0]!.slice(0, 12), 'test');
846846
const exists = (kind: string, ref: string) => spawnSync('docker', [kind, 'inspect', ref], { stdio: 'ignore' }).status === 0;
847847
for (const holder of holders) expect(exists('container', holder)).toBe(false);
848848
expect([exists('network', network), exists('network', prefixNamed), exists('volume', volume)]).toEqual([false, false, false]);
@@ -853,7 +853,7 @@ describe('real Docker agent isolation', () => {
853853
} finally {
854854
// By exact name: some are named like the start of another object's ID. Containers first, as they hold the rest.
855855
for (const { kind, ref } of [...made.filter(object => object.kind === 'container'), ...made.filter(object => object.kind !== 'container')])
856-
removeByName(kind, ref);
856+
removeByName(kind, ref, 'finally');
857857
}
858858
// The budget covers the sweep's worst case (5.5 minutes) and ordinary Docker calls, removals by name included, not
859859
// every call at its own limit.

‎test/agent-network.test.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ afterAll(async () => {
4848
for (const { kind, name, file } of unlabelled) {
4949
// A record holds one name per line: should a test time out with its shim still on PATH, later creates add theirs.
5050
for (const ref of name ? [name] : file && existsSync(file) ? readFileSync(file, 'utf8').split('\n').filter(Boolean) : [])
51-
removeByName(kind, ref);
51+
removeByName(kind, ref, 'afterAll');
5252
}
5353
if (network) await removeVendorNetwork(network);
5454
}
@@ -128,7 +128,7 @@ describe('vendor-only egress', () => {
128128
foreign = made[0] ?? '';
129129
// afterAll reads the record again: the object may land after this removal (#189).
130130
if (foreign) survived = spawnSync('docker', ['network', 'inspect', foreign], { stdio: 'ignore' }).status === 0;
131-
for (const name of made) removeByName('network', name);
131+
for (const name of made) removeByName('network', name, 'finally');
132132
rmSync(shim, { recursive: true, force: true });
133133
}
134134
// The refused create is reported as itself, with no cleanup left to retry, and the foreign network survives.
@@ -184,7 +184,7 @@ describe('vendor-only egress', () => {
184184
foreign = made[0] ?? '';
185185
// afterAll reads the record again: the object may land after this removal (#189).
186186
if (foreign) survived = spawnSync('docker', ['container', 'inspect', foreign], { stdio: 'ignore' }).status === 0;
187-
for (const name of made) removeByName('container', name);
187+
for (const name of made) removeByName('container', name, 'finally');
188188
rmSync(shim, { recursive: true, force: true });
189189
}
190190
// The refused create is reported as itself: our network was removed, nothing is left to retry or report.
@@ -240,7 +240,7 @@ describe('vendor-only egress', () => {
240240
impostor = made[0] ?? '';
241241
// afterAll reads the record again: the object may land after this removal (#189).
242242
if (impostor) survived = spawnSync('docker', ['container', 'inspect', impostor], { stdio: 'ignore' }).status === 0;
243-
for (const name of made) removeByName('container', name);
243+
for (const name of made) removeByName('container', name, 'finally');
244244
rmSync(shim, { recursive: true, force: true });
245245
}
246246
expect(impostor).toMatch(/^codeboost-proxy-/);

‎test/agent-supervisor.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -388,7 +388,7 @@ describe('container invocation supervisor', () => {
388388
it('releases its own resources, and leaves a same-named container another invocation owns', async () => {
389389
const current = await profile(fixture(), 'finite-output', 'foreign-name');
390390
// Removed by name when the test finishes, timeouts included: its label value is shared across runs (#189).
391-
onTestFinished(() => removeByName('container', current.name), 90_000); // two calls of up to 30 s
391+
onTestFinished(() => removeByName('container', current.name, 'onTestFinished'), 90_000); // two calls of up to 30 s
392392
try {
393393
// Inside the try, so its removal runs even if the create's client fails after the daemon made it (#189).
394394
execFileSync('docker', ['create', '--name', current.name, '--label', 'io.codeboost.invocation=foreign',
@@ -443,7 +443,7 @@ describe('container invocation supervisor', () => {
443443
const current = await profile(fixture(), 'noop');
444444
// A foreign container occupies the deterministic name, so container-level cleanup could never settle.
445445
// Removed by name when the test finishes, timeouts included: its label value is shared across runs (#189).
446-
onTestFinished(() => removeByName('container', current.name), 90_000); // two calls of up to 30 s
446+
onTestFinished(() => removeByName('container', current.name, 'onTestFinished'), 90_000); // two calls of up to 30 s
447447
try {
448448
execFileSync('docker', ['create', '--name', current.name, '--label', 'io.codeboost.invocation=someone-else',
449449
'--entrypoint', 'true', imageId], { stdio: 'ignore' });

‎test/docker-sweep.test.ts‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -80,18 +80,18 @@ it('removes by name only an object of exactly that name, and reports failures ot
8080
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
8181
const objects = [['container', 'gone'], ['network', 'gone'], ['volume', 'gone'], ['container', 'prefix'], ['network', 'prefix'],
8282
['container', 'busy'], ['network', 'busy'], ['volume', 'busy'], ['container', 'killed'], ['container', 'lost']] as const;
83-
for (const [kind, name] of objects) removeByName(kind, name, join(root, 'docker'));
83+
for (const [kind, name] of objects) removeByName(kind, name, 'test', join(root, 'docker'));
8484
// Only the exact names are removed, by full ID (a volume's name is its ID).
8585
expect(readFileSync(calls, 'utf8').split('\n').filter(line => / rm |^rm /.test(line)))
8686
.toEqual([`rm --force ${id}`, `network rm ${other}`, 'volume rm --force busy']);
8787
expect(warn.mock.calls).toEqual([
88-
['removing container busy: docker container rm failed:',
88+
['test: removing container busy: docker rm failed:',
8989
`Error response from daemon: removal of container ${id} is already in progress`],
90-
['removing network busy: docker network rm failed:',
90+
['test: removing network busy: docker network rm failed:',
9191
`Error response from daemon: error while removing network: network busy id ${other} has active endpoints`],
92-
['removing volume busy: docker volume rm failed:', `Error response from daemon: remove busy: volume is in use - [${id}]`],
93-
['removing container killed: docker inspect failed:', 'killed by SIGKILL'],
94-
['removing container lost: docker inspect failed:',
92+
['test: removing volume busy: docker volume rm failed:', `Error response from daemon: remove busy: volume is in use - [${id}]`],
93+
['test: removing container killed: docker container inspect failed:', 'killed by SIGKILL'],
94+
['test: removing container lost: docker container inspect failed:',
9595
'Failed to initialize: unable to resolve docker endpoint: context "x": context not found: open /x/meta.json: no such file or directory'],
9696
]);
9797
});
@@ -107,7 +107,7 @@ it('talks to the daemon set when it loaded, though a test changed DOCKER_HOST or
107107
vi.stubEnv('DOCKER_HOST', 'unix:///codeboost-missing.sock');
108108
vi.stubEnv('DOCKER_CONTEXT', 'codeboost-missing');
109109
try {
110-
removeByName('container', 'x', join(root, 'docker'));
110+
removeByName('container', 'x', 'test', join(root, 'docker'));
111111
removeLabelledObjects(TEST_RUN_LABEL, 'x', 'test', join(root, 'docker'));
112112
} finally { vi.unstubAllEnvs(); }
113113
const lines = readFileSync(seen, 'utf8').split('\n').filter(Boolean);

‎test/fixtures/docker-sweep.ts‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -35,26 +35,27 @@ export const TEST_FILE_LABEL = 'io.codeboost.test-file';
3535
/**
3636
* Removes the container, network or volume named exactly `name`, by its full ID (a volume by its name, which is its
3737
* ID). Docker would read a missing name as an ID prefix, so an object found under another name is left alone. It
38-
* reports a failed call, other than an inspect that finds no such object, and never throws; each call has a 30 s limit.
38+
* reports a failed call, other than an inspect that finds no such object, prefixed with `when`, and never throws; each
39+
* call has a 30 s limit.
3940
*/
40-
export function removeByName(kind: 'container' | 'network' | 'volume', name: string, docker = REAL_DOCKER): void {
41+
export function removeByName(kind: 'container' | 'network' | 'volume', name: string, when: string, docker = REAL_DOCKER): void {
4142
const options = { encoding: 'utf8' as const, timeout: 30_000, killSignal: 'SIGKILL' as const, env: dockerEnv() };
42-
const failed = (result: SpawnSyncReturns<string>, what: string) => console.warn(`removing ${kind} ${name}: docker ${what} failed:`,
43+
const failed = (result: SpawnSyncReturns<string>, what: string) => console.warn(`${when}: removing ${kind} ${name}: docker ${what} failed:`,
4344
result.error?.message ?? (result.signal ? `killed by ${result.signal}` : result.stderr.trim()));
4445
// As JSON: a network's name may hold spaces. Only a container's name comes with a leading slash.
4546
const found = spawnSync(docker, [kind, 'inspect', '--format', kind === 'volume' ? '{{json .Name}}' : '{{json .Id}} {{json .Name}}', name], options);
4647
// Docker 27.4's answers for a missing object, each naming it, so a failure before the daemon (an unknown context's
4748
// "context not found: … no such file or directory") is still reported.
4849
const missing = { container: `No such container: ${name}`, network: `network ${name} not found`, volume: `get ${name}: no such volume` }[kind];
49-
if (found.error || found.status !== 0) { if (found.status === null || !found.stderr.includes(missing)) failed(found, 'inspect'); return; }
50+
if (found.error || found.status !== 0) { if (found.status === null || !found.stderr.includes(missing)) failed(found, `${kind} inspect`); return; }
5051
let id: unknown, actual: unknown;
5152
try {
5253
const at = found.stdout.indexOf(' ');
5354
[id, actual] = kind === 'volume' ? [name, JSON.parse(found.stdout)] : [JSON.parse(found.stdout.slice(0, at)), JSON.parse(found.stdout.slice(at + 1))];
54-
} catch { console.warn(`removing ${kind} ${name}: docker printed what is not JSON:`, found.stdout); return; }
55+
} catch { console.warn(`${when}: removing ${kind} ${name}: docker printed what is not JSON:`, found.stdout); return; }
5556
if (typeof id !== 'string' || typeof actual !== 'string' || (kind === 'container' ? actual.replace(/^\//, '') : actual) !== name) return;
5657
const removed = spawnSync(docker, kind === 'container' ? ['rm', '--force', id] : [kind, 'rm', ...(kind === 'volume' ? ['--force'] : []), id], options);
57-
if (removed.error || removed.status !== 0) failed(removed, `${kind} rm`);
58+
if (removed.error || removed.status !== 0) failed(removed, kind === 'container' ? 'rm' : `${kind} rm`);
5859
}
5960

6061
/**

0 commit comments

Comments
 (0)