Skip to content

Commit 04fb582

Browse files
authored
Merge pull request #1128 from antvis/codex/follow-up-cli-cancellation
补齐 CLI 会话升级、释放与查询取消(基于 #1123)
2 parents 449d548 + 1d76a26 commit 04fb582

33 files changed

Lines changed: 1052 additions & 382 deletions

File tree

‎.github/workflows/build.yml‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,9 @@ jobs:
3636
- name: Build
3737
run: npm run build
3838

39+
- name: Test CLI session lifecycle
40+
run: node --test __tests__/cli-session.e2e.cjs
41+
3942
- name: Load package entry points in Node
4043
run: |
4144
node --input-type=module -e "const { sourceInputSchema } = await import('@antv/ava'); sourceInputSchema.parse({ type: 'json', options: { data: [] } })"
@@ -53,6 +56,8 @@ jobs:
5356
node-version: 22.x
5457
- run: npm install --legacy-peer-deps
5558
- run: npm run build:cjs
59+
- name: Test CLI session lifecycle
60+
run: node --test __tests__/cli-session.e2e.cjs
5661
- name: Smoke test a dataset session
5762
shell: pwsh
5863
run: |

‎__tests__/cancellation.test.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,23 @@ describe('cancellation', () => {
6464
expect(generateText).toHaveBeenCalledWith(expect.objectContaining({ abortSignal: controller.signal }));
6565
});
6666

67+
it('does not cache schema returned by an engine after cancellation', async () => {
68+
const controller = new AbortController();
69+
const reason = new Error('Client disconnected');
70+
const model = { models: [], relationships: [] };
71+
const schema = vi.spyOn(ava.engine!, 'schema').mockImplementationOnce(async () => {
72+
controller.abort(reason);
73+
return model;
74+
});
75+
76+
await expect(ava.translate('Rows', controller.signal)).rejects.toBe(reason);
77+
expect(schema).toHaveBeenCalledExactlyOnceWith(controller.signal);
78+
expect(generateText).not.toHaveBeenCalled();
79+
80+
expect((await ava.schema()).models).toHaveLength(1);
81+
expect(schema).toHaveBeenLastCalledWith();
82+
});
83+
6784
it('forwards the signal to query execution', async () => {
6885
const execute = vi.spyOn(ava.engine!, 'execute');
6986
const controller = new AbortController();

‎__tests__/cli-connection.test.ts‎

Lines changed: 1 addition & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { EventEmitter } from 'events';
22

33
import { describe, expect, it, vi } from 'vitest';
44

5-
import { DISPOSE_EXIT_DEADLINE_MS, handleConnection } from '../src/cli/session/connection';
5+
import { handleConnection } from '../src/cli/session/connection';
66

77
import type { Socket } from 'net';
88

@@ -11,8 +11,6 @@ class FakeSocket extends EventEmitter {
1111
destroyed = false;
1212
written: string[] = [];
1313
timeouts: number[] = [];
14-
/** Set to false to simulate a client that never drains the response. */
15-
flushes = true;
1614

1715
setTimeout(ms: number): this {
1816
this.timeouts.push(ms);
@@ -32,7 +30,6 @@ class FakeSocket extends EventEmitter {
3230

3331
end(chunk?: string): this {
3432
if (chunk) this.written.push(chunk);
35-
if (this.flushes) this.emit('finish');
3633
return this;
3734
}
3835
}
@@ -90,37 +87,6 @@ describe('session connection', () => {
9087
expect(onBusy.mock.calls).toEqual([[true], [false]]);
9188
});
9289

93-
it('exits once the dispose response is flushed', async () => {
94-
const { socket, net } = connect();
95-
const exit = vi.fn();
96-
97-
handleConnection(net, { dispatch: vi.fn().mockResolvedValue({ disabled: true, disposed: true }), exit });
98-
socket.emit('data', '{"command":"dispose"}\n');
99-
100-
await vi.waitFor(() => expect(exit).toHaveBeenCalledWith(0));
101-
expect(socket.written).toHaveLength(1);
102-
expect(JSON.parse(socket.written[0].trim())).toEqual({ ok: true, result: { disabled: true, disposed: true } });
103-
});
104-
105-
it('bounds the exit of an unflushed dispose response', async () => {
106-
vi.useFakeTimers();
107-
try {
108-
const { socket, net } = connect();
109-
const exit = vi.fn();
110-
socket.flushes = false;
111-
112-
handleConnection(net, { dispatch: vi.fn().mockResolvedValue({ disposed: true }), exit });
113-
socket.emit('data', '{"command":"dispose"}\n');
114-
await vi.advanceTimersByTimeAsync(0);
115-
116-
expect(exit).not.toHaveBeenCalled();
117-
await vi.advanceTimersByTimeAsync(DISPOSE_EXIT_DEADLINE_MS);
118-
expect(exit).toHaveBeenCalledWith(0);
119-
} finally {
120-
vi.useRealTimers();
121-
}
122-
});
123-
12490
it('answers an invalid request with an error instead of running it', async () => {
12591
const { socket, net } = connect();
12692
const dispatch = vi.fn();

‎__tests__/cli-session.e2e.cjs‎

Lines changed: 179 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,179 @@
1+
const assert = require('node:assert/strict');
2+
const { fork } = require('node:child_process');
3+
const { randomBytes } = require('node:crypto');
4+
const { on, once } = require('node:events');
5+
const { access, mkdtemp, readFile, rm } = require('node:fs/promises');
6+
const { createServer } = require('node:http');
7+
const { tmpdir } = require('node:os');
8+
const { join } = require('node:path');
9+
const { test } = require('node:test');
10+
const { setTimeout: wait } = require('node:timers/promises');
11+
const { ClickHouseLogLevel } = require('@clickhouse/client');
12+
13+
const { request } = require('../lib/cli/session/client');
14+
const { connectSession, prepareSession } = require('../lib/cli/session/transport');
15+
16+
async function startSession(t, startup, pauseDisposal) {
17+
const id = `ds_${randomBytes(12).toString('hex')}`;
18+
const directory = await prepareSession(id);
19+
const child = fork(join(__dirname, '../lib/cli/session/server.js'), [id], {
20+
execArgv: pauseDisposal ? ['--require', join(__dirname, 'fixtures/cli-session-dispose.cjs')] : [],
21+
env: { ...process.env, AVA_TEST_PAUSE_DISPOSAL: pauseDisposal ?? '' },
22+
stdio: ['ignore', 'ignore', 'inherit', 'ipc'],
23+
});
24+
const exited = once(child, 'exit');
25+
const messages = on(child, 'message', { signal: t.signal });
26+
t.after(async () => {
27+
if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL');
28+
await exited;
29+
await messages.return();
30+
await rm(directory, { recursive: true, force: true });
31+
});
32+
child.send(startup);
33+
const {
34+
value: [ready],
35+
} = await messages.next();
36+
assert.deepEqual(ready, { ok: true, result: null });
37+
return { id, directory, child, exited, messages };
38+
}
39+
40+
test(
41+
'concurrent dispose requests share one cleanup that can finish after the reply timeout',
42+
{ timeout: 15_000 },
43+
async (t) => {
44+
const { id, directory, child, exited, messages } = await startSession(
45+
t,
46+
{
47+
sources: [{ type: 'json', options: { data: [{ amount: 42 }] } }],
48+
llm: { model: 'unused' },
49+
engine: 'javascript',
50+
},
51+
'engine'
52+
);
53+
54+
const replies = Promise.allSettled([request(id, { command: 'dispose' }), request(id, { command: 'dispose' })]);
55+
const started = [];
56+
for (let i = 0; i < 3; i++) {
57+
const {
58+
value: [received],
59+
} = await messages.next();
60+
started.push(received);
61+
}
62+
assert.deepEqual(started.sort(), ['cleanup-started', 'dispose-received', 'dispose-received']);
63+
for (const reply of await replies) {
64+
assert.equal(reply.status, 'rejected');
65+
assert.equal(reply.reason.message, 'Dataset cleanup timed out after 2000 ms.');
66+
}
67+
assert.equal(child.exitCode, null, 'The daemon must keep cleaning up after its clients time out');
68+
child.send('release-cleanup');
69+
const event = await Promise.race([
70+
messages.next().then(({ value: [message] }) => message),
71+
exited.then(() => 'daemon-exited'),
72+
]);
73+
assert.equal(event, 'cleanup-finished');
74+
assert.deepEqual(await exited, [0, null]);
75+
await assert.rejects(access(directory), { code: 'ENOENT' });
76+
}
77+
);
78+
79+
test(
80+
'disconnecting during analysis cancels ClickHouse catalog I/O and frees the session',
81+
{ timeout: 15_000 },
82+
async (t) => {
83+
const queries = [];
84+
const api = createServer((req, res) => {
85+
let sql = '';
86+
req.setEncoding('utf8').on('data', (chunk) => {
87+
sql += chunk;
88+
});
89+
req.on('end', () => {
90+
queries.push(sql);
91+
if (queries.length === 1) api.emit('query-started', res);
92+
else if (sql.includes('SELECT 42 AS amount')) res.end('{"amount":42}\n');
93+
else res.writeHead(500).end('Unexpected request after cancellation');
94+
});
95+
});
96+
api.listen(0, '127.0.0.1');
97+
t.after(() => {
98+
api.closeAllConnections();
99+
api.close();
100+
});
101+
await once(api, 'listening', { signal: t.signal });
102+
const url = `http://127.0.0.1:${api.address().port}`;
103+
const { id, directory, child, messages, exited } = await startSession(
104+
t,
105+
{
106+
sources: [
107+
{ type: 'clickhouse', options: { url, database: 'default', log: { level: ClickHouseLogLevel.OFF } } },
108+
],
109+
llm: { model: 'unused', apiKey: 'local-test', baseURL: `${url}/v1` },
110+
},
111+
'directory'
112+
);
113+
const started = once(api, 'query-started', { signal: t.signal });
114+
const socket = await connectSession(
115+
id,
116+
JSON.stringify({ command: 'analyze', strategy: 'direct', query: 'What is the total?' })
117+
);
118+
socket.on('error', () => socket.destroy());
119+
t.after(() => socket.destroy());
120+
const [response] = await started;
121+
const disconnected = once(response, 'close', { signal: t.signal });
122+
assert.match(queries[0], /FROM system\.tables/i);
123+
124+
socket.destroy();
125+
await disconnected;
126+
const result = await request(id, { command: 'query', dsl: 'SELECT 42 AS amount' });
127+
assert.deepEqual(result.data, [{ amount: 42 }]);
128+
assert.equal(queries.length, 2);
129+
const disposed = request(id, { command: 'dispose' });
130+
const {
131+
value: [cleanupStarted],
132+
} = await messages.next();
133+
assert.equal(cleanupStarted, 'directory-cleanup-started');
134+
assert.deepEqual(await disposed, { datasetId: id, disposed: true });
135+
child.send('release-cleanup');
136+
assert.deepEqual(await exited, [0, null]);
137+
await assert.rejects(access(directory), { code: 'ENOENT' });
138+
}
139+
);
140+
141+
test(
142+
'disconnecting reaps the Python subprocess and frees the session',
143+
{ skip: process.env.AVA_PYTHON_LOCAL_TEST !== '1', timeout: 15_000 },
144+
async (t) => {
145+
const directory = await mkdtemp(join(tmpdir(), 'ava-python-abort-'));
146+
t.after(() => rm(directory, { recursive: true, force: true }));
147+
const marker = join(directory, 'pid');
148+
const { id, exited } = await startSession(t, {
149+
sources: [{ type: 'json', options: { data: [{ amount: 42 }] } }],
150+
llm: { model: 'unused' },
151+
engine: 'python',
152+
});
153+
const dsl = `import os, signal, time
154+
from pathlib import Path
155+
signal.signal(signal.SIGTERM, signal.SIG_IGN)
156+
Path(${JSON.stringify(marker)}).write_text(str(os.getpid()))
157+
time.sleep(20)
158+
result = df`;
159+
const socket = await connectSession(id, JSON.stringify({ command: 'query', dsl }));
160+
socket.on('error', () => socket.destroy());
161+
t.after(() => socket.destroy());
162+
let pid;
163+
while (!pid) {
164+
const value = await readFile(marker, 'utf8').catch((error) => {
165+
if (error.code !== 'ENOENT') throw error;
166+
return '';
167+
});
168+
pid = Number(value);
169+
if (!pid) await wait(25, undefined, { signal: t.signal });
170+
}
171+
172+
socket.destroy();
173+
const next = await request(id, { command: 'schema' });
174+
assert.equal(next.models[0].name, 'data');
175+
assert.throws(() => process.kill(pid, 0), { code: 'ESRCH' });
176+
await request(id, { command: 'dispose' });
177+
assert.deepEqual(await exited, [0, null]);
178+
}
179+
);

‎__tests__/cli-session.test.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,30 @@ describe('dataset engine and language', () => {
116116
vi.restoreAllMocks();
117117
});
118118

119+
it('waits for in-progress startup before disposing the engine', async () => {
120+
const { getEngineClass } = await import('../src/engines');
121+
const Engine = getEngineClass('javascript');
122+
let completeLoad!: () => void;
123+
const load = vi.spyOn(Engine.prototype, 'load').mockReturnValue(
124+
new Promise<void>((resolve) => {
125+
completeLoad = resolve;
126+
})
127+
);
128+
const dispose = vi.spyOn(Engine.prototype, 'dispose');
129+
const starting = datasets.createDataset([source], llm, 'javascript');
130+
try {
131+
await vi.waitFor(() => expect(load).toHaveBeenCalledOnce());
132+
const closing = datasets.disposeDataset();
133+
await Promise.resolve();
134+
expect(dispose).not.toHaveBeenCalled();
135+
completeLoad();
136+
await Promise.all([starting, closing]);
137+
expect(dispose).toHaveBeenCalledOnce();
138+
} finally {
139+
completeLoad();
140+
}
141+
});
142+
119143
it.each<{
120144
source: DataSourceConfig;
121145
engine: EngineConfig['type'];

0 commit comments

Comments
 (0)