327 lines
14 KiB
TypeScript
327 lines
14 KiB
TypeScript
import fs from 'fs';
|
|
import path from 'path';
|
|
import http from 'http';
|
|
import assert from 'assert';
|
|
import app from './src/index';
|
|
import { config } from './src/config';
|
|
import { configStore } from './src/configStore';
|
|
import { RequestLogger } from './src/logger';
|
|
import { StatsTracker } from './src/stats';
|
|
import {
|
|
compressZstdSync,
|
|
decompressZstdSync,
|
|
readLogFileContentSync,
|
|
listLogFilesSync
|
|
} from './src/logCompression';
|
|
import { runCli } from './src/inspectLogs';
|
|
|
|
async function runLogCompressionTests() {
|
|
console.log('🧪 Starting Persistent Log Compression (Zstandard) & History Tests...\n');
|
|
|
|
const tmpLogDir = path.join(__dirname, 'logs', `test-zstd-${Date.now()}`);
|
|
fs.mkdirSync(tmpLogDir, { recursive: true });
|
|
|
|
try {
|
|
// 1. Test Zstandard round-trip compression & high compression ratio on JSONL
|
|
console.log('1. Testing Zstandard (level 19) round-trip compression & ratio...');
|
|
const sampleLines: string[] = [];
|
|
for (let i = 0; i < 50; i++) {
|
|
sampleLines.push(
|
|
JSON.stringify({
|
|
timestamp: `2026-10-20T12:00:${String(i).padStart(2, '0')}.000Z`,
|
|
requestId: `req_sample_${i}`,
|
|
type: 'request',
|
|
data: {
|
|
path: '/v1/chat/completions',
|
|
method: 'POST',
|
|
body: {
|
|
model: 'gemini-flash-lite-latest',
|
|
messages: [{ role: 'user', content: `Sample repeated prompt text number ${i} for compression testing.` }]
|
|
}
|
|
}
|
|
})
|
|
);
|
|
}
|
|
const rawPayload = sampleLines.join('\n') + '\n';
|
|
const compressed = compressZstdSync(rawPayload, 19);
|
|
const decompressed = decompressZstdSync(compressed).toString('utf8');
|
|
|
|
assert.strictEqual(decompressed, rawPayload, 'Decompressed Zstd content must match original byte-for-byte');
|
|
assert.ok(
|
|
compressed.byteLength < Buffer.byteLength(rawPayload, 'utf8') * 0.25,
|
|
`Expected >75% compression on JSONL logs (raw=${Buffer.byteLength(rawPayload)}B, compressed=${compressed.byteLength}B)`
|
|
);
|
|
console.log(
|
|
` ✓ Zstandard round-trip verified (${Buffer.byteLength(rawPayload)}B -> ${compressed.byteLength}B, ${((1 - compressed.byteLength / Buffer.byteLength(rawPayload)) * 100).toFixed(1)}% reduction).`
|
|
);
|
|
|
|
// 2. Test startup compression of historical logs & daily rollover compression
|
|
console.log('\n2. Testing startup compression and automatic daily date rollover...');
|
|
const day1File = path.join(tmpLogDir, 'api-logs-2026-10-20.json');
|
|
const day2File = path.join(tmpLogDir, 'api-logs-2026-10-21.json');
|
|
|
|
const day1Entry1 = JSON.stringify({
|
|
timestamp: '2026-10-20T10:00:00.000Z',
|
|
requestId: 'req_day1_1',
|
|
type: 'response',
|
|
data: {
|
|
statusCode: 200,
|
|
response: {
|
|
streaming: false,
|
|
content: 'Day 1 response',
|
|
usage: { prompt_tokens: 10, completion_tokens: 20, total_tokens: 30 }
|
|
}
|
|
}
|
|
});
|
|
const day2Entry1 = JSON.stringify({
|
|
timestamp: '2026-10-21T11:00:00.000Z',
|
|
requestId: 'req_day2_1',
|
|
type: 'error',
|
|
data: { message: 'Simulated error on day 2' }
|
|
});
|
|
|
|
fs.writeFileSync(day1File, day1Entry1 + '\n', 'utf8');
|
|
fs.writeFileSync(day2File, day2Entry1 + '\n', 'utf8');
|
|
|
|
let currentDay = '2026-10-22';
|
|
const logger = new RequestLogger(tmpLogDir, () => currentDay);
|
|
|
|
// Day 1 and Day 2 should now be .json.zst, and original .json removed
|
|
assert.strictEqual(fs.existsSync(day1File), false, 'Day 1 uncompressed .json should be deleted');
|
|
assert.strictEqual(fs.existsSync(`${day1File}.zst`), true, 'Day 1 .json.zst should exist');
|
|
assert.strictEqual(fs.existsSync(day2File), false, 'Day 2 uncompressed .json should be deleted');
|
|
assert.strictEqual(fs.existsSync(`${day2File}.zst`), true, 'Day 2 .json.zst should exist');
|
|
|
|
// Write to Day 3 (active day: 2026-10-22)
|
|
logger.logRequest('req_day3_1', { path: '/v1/chat/completions', method: 'POST' });
|
|
logger.logResponse('req_day3_1', {
|
|
statusCode: 200,
|
|
response: {
|
|
streaming: false,
|
|
content: 'Day 3 active response',
|
|
usage: { prompt_tokens: 15, completion_tokens: 25, total_tokens: 40 }
|
|
}
|
|
});
|
|
|
|
const day3File = path.join(tmpLogDir, 'api-logs-2026-10-22.json');
|
|
assert.strictEqual(fs.existsSync(day3File), true, 'Active day .json must remain uncompressed');
|
|
assert.strictEqual(fs.existsSync(`${day3File}.zst`), false, 'Active day must not be compressed yet');
|
|
|
|
// Roll over to Day 4 (2026-10-23)
|
|
currentDay = '2026-10-23';
|
|
logger.logRequest('req_day4_1', { path: '/v1/models', method: 'GET' });
|
|
|
|
const day4File = path.join(tmpLogDir, 'api-logs-2026-10-23.json');
|
|
assert.strictEqual(fs.existsSync(day3File), false, 'Rolled-over Day 3 .json must be deleted after compression');
|
|
assert.strictEqual(fs.existsSync(`${day3File}.zst`), true, 'Rolled-over Day 3 .json.zst must be created');
|
|
assert.strictEqual(fs.existsSync(day4File), true, 'New active Day 4 .json must exist uncompressed');
|
|
console.log(' ✓ Startup compression and automatic rollover compression verified.');
|
|
|
|
// 3. Test safe merge when both .json and .json.zst exist for a past date
|
|
console.log('\n3. Testing lossless merge when late .json entries exist alongside .json.zst...');
|
|
const day1LateEntry = JSON.stringify({
|
|
timestamp: '2026-10-20T23:59:59.000Z',
|
|
requestId: 'req_day1_late',
|
|
type: 'response',
|
|
data: {
|
|
statusCode: 200,
|
|
response: {
|
|
streaming: true,
|
|
content: 'Late day 1 response',
|
|
usage: { prompt_tokens: 5, completion_tokens: 5, total_tokens: 10 }
|
|
}
|
|
}
|
|
});
|
|
// Write both duplicate entry1 and new lateEntry into uncompressed day1File
|
|
fs.writeFileSync(day1File, day1Entry1 + '\n' + day1LateEntry + '\n', 'utf8');
|
|
logger.compressOldLogs();
|
|
|
|
assert.strictEqual(fs.existsSync(day1File), false, 'Merged .json file should be deleted');
|
|
const mergedDay1Entries = logger.readLogEntries(`${day1File}.zst`);
|
|
assert.strictEqual(mergedDay1Entries.length, 2, 'Merged .json.zst must contain exactly 2 deduplicated entries');
|
|
assert.strictEqual(mergedDay1Entries[0].requestId, 'req_day1_1');
|
|
assert.strictEqual(mergedDay1Entries[1].requestId, 'req_day1_late');
|
|
console.log(' ✓ Lossless merge & deduplication into existing .json.zst archive verified.');
|
|
|
|
// 4. Test StatsTracker rebuildFromExistingLogs across .json.zst and .json
|
|
console.log('\n4. Testing StatsTracker.rebuildFromExistingLogs() with compressed .json.zst archives...');
|
|
const customStats = new StatsTracker(tmpLogDir);
|
|
const summary = customStats.getStatsSummary();
|
|
// Expected:
|
|
// - Day 1 (.zst): 2 successful responses (10+20=30 tok, 5+5=10 tok) -> 2 wentThrough, 40 tok
|
|
// - Day 2 (.zst): 1 error -> 1 failed
|
|
// - Day 3 (.zst): 1 successful response (15+25=40 tok) -> 1 wentThrough, 40 tok
|
|
// - Day 4 (.json): 1 request only (no response yet)
|
|
assert.strictEqual(summary.requests.wentThrough, 3, 'Should count 3 successful responses across .zst archives');
|
|
assert.strictEqual(summary.requests.failed, 1, 'Should count 1 failed request from .zst archive');
|
|
assert.strictEqual(summary.requests.total, 4, 'Total completed/failed requests should be 4');
|
|
assert.strictEqual(summary.tokens.input, 30, 'Input tokens should be 10 + 5 + 15 = 30');
|
|
assert.strictEqual(summary.tokens.output, 50, 'Output tokens should be 20 + 5 + 25 = 50');
|
|
assert.strictEqual(summary.tokens.total, 80, 'Total tokens should be 80');
|
|
console.log(' ✓ StatsTracker transparently rebuilt stats from compressed .json.zst archives.');
|
|
|
|
// 5. Test CLI Inspector (--list and --decompress)
|
|
console.log('\n5. Testing CLI log inspector utility...');
|
|
runCli(['--list'], tmpLogDir);
|
|
runCli(['--decompress', '2026-10-21'], tmpLogDir);
|
|
assert.strictEqual(fs.existsSync(day2File), true, '--decompress should restore .json file from .json.zst');
|
|
const restoredContent = readLogFileContentSync(day2File);
|
|
assert.ok(restoredContent.includes('req_day2_1'), 'Restored .json file should contain original entry');
|
|
console.log(' ✓ CLI log inspector (--list and --decompress) verified.');
|
|
|
|
// 6. Test full completion text persistence on POST /v1/chat/completions (non-streaming and streaming)
|
|
console.log('\n6. Testing full completion text persistence in saved response logs...');
|
|
const upstreamServer = http.createServer((req, res) => {
|
|
let bodyStr = '';
|
|
req.on('data', chunk => (bodyStr += chunk));
|
|
req.on('end', () => {
|
|
const parsed = JSON.parse(bodyStr || '{}');
|
|
if (parsed.stream) {
|
|
res.writeHead(200, { 'Content-Type': 'text/event-stream' });
|
|
res.write(
|
|
`data: ${JSON.stringify({
|
|
id: 'chatcmpl-stream-log',
|
|
object: 'chat.completion.chunk',
|
|
created: Math.floor(Date.now() / 1000),
|
|
model: parsed.model,
|
|
choices: [{ index: 0, delta: { content: 'Persistent ' }, finish_reason: null }]
|
|
})}\n\n`
|
|
);
|
|
res.write(
|
|
`data: ${JSON.stringify({
|
|
id: 'chatcmpl-stream-log',
|
|
object: 'chat.completion.chunk',
|
|
created: Math.floor(Date.now() / 1000),
|
|
model: parsed.model,
|
|
choices: [{ index: 0, delta: { content: 'stream history!' }, finish_reason: 'stop' }]
|
|
})}\n\n`
|
|
);
|
|
res.write('data: [DONE]\n\n');
|
|
res.end();
|
|
} else {
|
|
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
res.end(
|
|
JSON.stringify({
|
|
id: 'chatcmpl-nonstream-log',
|
|
object: 'chat.completion',
|
|
created: Math.floor(Date.now() / 1000),
|
|
model: parsed.model,
|
|
choices: [
|
|
{
|
|
index: 0,
|
|
message: { role: 'assistant', content: 'Persistent non-stream history!' },
|
|
finish_reason: 'stop'
|
|
}
|
|
],
|
|
usage: { prompt_tokens: 8, completion_tokens: 6, total_tokens: 14 }
|
|
})
|
|
);
|
|
}
|
|
});
|
|
});
|
|
|
|
await new Promise<void>(resolve => upstreamServer.listen(0, resolve));
|
|
const upstreamPort = (upstreamServer.address() as any).port;
|
|
|
|
const appServer = http.createServer(app);
|
|
await new Promise<void>(resolve => appServer.listen(0, resolve));
|
|
const appPort = (appServer.address() as any).port;
|
|
|
|
const testProvider = configStore.saveProvider({
|
|
name: 'Log History Test Provider',
|
|
type: 'custom',
|
|
baseUrl: `http://localhost:${upstreamPort}/v1`,
|
|
keys: ['sk-log-history-test']
|
|
});
|
|
const testModelName = `log-history-model-${Date.now()}`;
|
|
const testModel = configStore.saveCustomModel({
|
|
name: testModelName,
|
|
isDefault: false,
|
|
tiers: [{ tierIndex: 0, name: 'Main', targets: [{ providerId: testProvider.id, model: 'mock-model' }] }]
|
|
});
|
|
|
|
try {
|
|
// Non-streaming request
|
|
const nonStreamRes = await fetch(`http://localhost:${appPort}/v1/chat/completions`, {
|
|
method: 'POST',
|
|
headers: {
|
|
Authorization: `Bearer ${config.apiPassword}`,
|
|
'Content-Type': 'application/json'
|
|
},
|
|
body: JSON.stringify({
|
|
model: testModelName,
|
|
stream: false,
|
|
messages: [{ role: 'user', content: 'Record my non-stream response' }]
|
|
})
|
|
});
|
|
assert.strictEqual(nonStreamRes.status, 200);
|
|
await nonStreamRes.json();
|
|
|
|
// Streaming request
|
|
const streamRes = await fetch(`http://localhost:${appPort}/v1/chat/completions`, {
|
|
method: 'POST',
|
|
headers: {
|
|
Authorization: `Bearer ${config.apiPassword}`,
|
|
'Content-Type': 'application/json'
|
|
},
|
|
body: JSON.stringify({
|
|
model: testModelName,
|
|
stream: true,
|
|
messages: [{ role: 'user', content: 'Record my stream response' }]
|
|
})
|
|
});
|
|
assert.strictEqual(streamRes.status, 200);
|
|
await streamRes.text();
|
|
|
|
const activeLogPath = path.join(config.logDir, `api-logs-${new Date().toISOString().split('T')[0]}.json`);
|
|
const activeEntries = logger.readLogEntries(activeLogPath);
|
|
const recentResponses = activeEntries.filter(e => e.type === 'response').slice(-2);
|
|
|
|
assert.strictEqual(recentResponses.length, 2, 'Should have logged 2 recent responses');
|
|
assert.strictEqual(
|
|
recentResponses[0].data.response.content,
|
|
'Persistent non-stream history!',
|
|
'Non-streaming response log must include full completion content'
|
|
);
|
|
assert.ok(
|
|
recentResponses[0].data.response.fullResponse,
|
|
'Non-streaming response log must include fullResponse payload'
|
|
);
|
|
assert.strictEqual(
|
|
recentResponses[1].data.response.content,
|
|
'Persistent stream history!',
|
|
'Streaming response log must include full assembled completion content'
|
|
);
|
|
|
|
// Also verify that historical logs in ./logs prior to today were automatically compressed to .json.zst
|
|
const prodLogFiles = listLogFilesSync(config.logDir);
|
|
const todayFileName = `api-logs-${new Date().toISOString().split('T')[0]}.json`;
|
|
for (const file of prodLogFiles) {
|
|
if (file !== todayFileName) {
|
|
assert.ok(
|
|
file.endsWith('.json.zst'),
|
|
`Historical log file ${file} in ${config.logDir} should be compressed as .json.zst`
|
|
);
|
|
}
|
|
}
|
|
|
|
console.log(' ✓ Full completion text persistence (streaming & non-streaming) and ./logs archive state verified.');
|
|
} finally {
|
|
configStore.deleteCustomModel(testModel.id);
|
|
configStore.deleteProvider(testProvider.id);
|
|
appServer.close();
|
|
upstreamServer.close();
|
|
}
|
|
|
|
console.log('\n🎉 ALL PERSISTENT LOG COMPRESSION TESTS PASSED!');
|
|
} finally {
|
|
if (fs.existsSync(tmpLogDir)) {
|
|
fs.rmSync(tmpLogDir, { recursive: true, force: true });
|
|
}
|
|
}
|
|
}
|
|
|
|
runLogCompressionTests().catch(err => {
|
|
console.error('❌ Log compression test failed:', err);
|
|
process.exit(1);
|
|
});
|