feat(logging): complete runtime trace diagnostics

Complete byte-level diagnostics for network, upload, runtime lifecycle, authenticated write, and background operation paths.

Preserve streaming behavior, file-storage boundaries, and default log volume while making failures, retries, cancellation, and final outcomes independently diagnosable.

Add focused regression coverage for correlation, partial data, resource context ownership, and terminal-state accuracy.
This commit is contained in:
DrSmoothl committed 2026-07-31 11:21:12 +08:00
1 parent 0ed85e7745
commit a67614fa09
27 files changed
+4029 -352

No files matched your search

+189 -3
View File
@@ -5,21 +5,39 @@ import os from 'os';
import path from 'path';
import { HookManager, shouldAutoLoadPid } from '../src/hook-manager';
import { PipeWatcher } from '../src/pipe-watcher';
import type { ManualMapHandle } from '../src/injector';
import type { HookInjectResult, ManualMapHandle } from '../src/injector';
import type { BridgeManagerSink } from '../src/hook-manager';
import type { QqHookClient } from '../src/qq-hook-client';
import { createLogger } from '@snowluma/common/logger';
import {
createLogger,
getLogLevel,
setLogLevel,
subscribeLogs,
type LogEntry,
} from '@snowluma/common/logger';
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
const flush = () => new Promise<void>(r => setImmediate(r));
const previousLogLevel = getLogLevel();
function managerTrace(entries: LogEntry[]): LogEntry[] {
return entries.filter(
(entry) => entry.level === 'trace' && entry.scope === 'Hook',
);
}
function makeManager(opts: {
autoLoadOnDiscovery?: boolean;
processes?: number[];
onSessionsChanged?: () => void;
inject?: (pid: number) => HookInjectResult | Promise<HookInjectResult>;
}) {
let pids = opts.processes ?? [];
const live = new Set<number>();
const inject = vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE }));
const inject = vi.fn(opts.inject ?? (() => ({
method: 'loadModuleManual' as const,
handle: DUMMY_HANDLE,
})));
const unload = vi.fn();
const pipeWatcher = new PipeWatcher({
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
@@ -48,6 +66,7 @@ function makeManager(opts: {
injector: { inject, unload },
makeClient,
autoLoadOnDiscovery: opts.autoLoadOnDiscovery,
onSessionsChanged: opts.onSessionsChanged,
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
});
return {
@@ -58,6 +77,173 @@ function makeManager(opts: {
};
}
afterEach(() => {
setLogLevel(previousLogLevel);
});
describe('HookManager runtime TRACE', () => {
it('records discovery and process-gone facts while unchanged ticks stay silent', async () => {
const entries: LogEntry[] = [];
const sessionsChanged = vi.fn();
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const ctx = makeManager({
autoLoadOnDiscovery: false,
processes: [],
onSessionsChanged: sessionsChanged,
});
try {
await ctx.pipeWatcher.start();
const baseline = managerTrace(entries).length;
await ctx.pipeWatcher.tickNow();
await ctx.pipeWatcher.tickNow();
expect(managerTrace(entries)).toHaveLength(baseline);
ctx.setProcesses([4242]);
await ctx.pipeWatcher.tickNow();
ctx.setProcesses([]);
await ctx.pipeWatcher.tickNow();
await flush();
const facts = managerTrace(entries).filter(
(entry) => entry.message.startsWith('hook_manager_fact '),
);
expect(facts.map((entry) => entry.message)).toEqual([
expect.stringContaining('hook_manager_fact event=process_discovered pid=4242'),
'hook_manager_fact event=process_gone pid=4242 tracked=true',
]);
expect(facts.every((entry) => entry.req !== undefined)).toBe(true);
} finally {
unsubscribe();
ctx.manager.dispose();
}
});
it('records bounded transient retries and recovery as separate attempts', async () => {
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
ctx.inject
.mockImplementationOnce(() => {
throw new Error(
'target process does not map /lib/x86_64-linux-gnu/libc.so.6 while resolving mmap',
);
})
.mockImplementationOnce(() => ({
method: 'loadModuleManual' as const,
handle: DUMMY_HANDLE,
}));
try {
await ctx.pipeWatcher.start();
await flush();
await flush();
await ctx.pipeWatcher.tickNow();
await flush();
await flush();
const attempts = managerTrace(entries).filter(
(entry) => entry.message.startsWith('hook_autoload_'),
);
expect(attempts.map((entry) => entry.message)).toEqual([
'hook_autoload_start pid=4242 attempt=1 maxAttempts=3',
expect.stringMatching(/^hook_autoload_terminal pid=4242 attempt=1 outcome=failed reason=retry_pending error=.*elapsedMs=\d+$/),
'hook_autoload_start pid=4242 attempt=2 maxAttempts=3',
expect.stringMatching(/^hook_autoload_terminal pid=4242 attempt=2 outcome=completed reason=recovered state=.*elapsedMs=\d+$/),
]);
expect(attempts[0]!.req).toBe(attempts[1]!.req);
expect(attempts[2]!.req).toBe(attempts[3]!.req);
expect(attempts[0]!.req).not.toBe(attempts[2]!.req);
} finally {
unsubscribe();
ctx.manager.dispose();
}
});
it('ends an in-flight auto-load as dropped when a manual load supersedes it', async () => {
const entries: LogEntry[] = [];
let resolveInjection!: (result: HookInjectResult) => void;
const injection = new Promise<HookInjectResult>((resolve) => {
resolveInjection = resolve;
});
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const ctx = makeManager({
autoLoadOnDiscovery: true,
processes: [4242],
inject: () => injection,
});
try {
await ctx.pipeWatcher.start();
await flush();
const manualLoad = ctx.manager.loadProcess(4242);
resolveInjection({ method: 'loadModuleManual', handle: DUMMY_HANDLE });
await manualLoad;
await flush();
const attempts = managerTrace(entries).filter(
(entry) => entry.message.startsWith('hook_autoload_'),
);
expect(attempts.map((entry) => entry.message)).toEqual([
'hook_autoload_start pid=4242 attempt=1 maxAttempts=3',
expect.stringMatching(
/^hook_autoload_terminal pid=4242 attempt=1 outcome=dropped reason=superseded elapsedMs=\d+$/,
),
]);
expect(attempts[0]!.req).toBe(attempts[1]!.req);
} finally {
unsubscribe();
ctx.manager.dispose();
}
});
it.each([
{
name: 'permanent failure',
error: 'ptrace denied',
ticks: 1,
attempts: 1,
reason: 'permanent_failure',
},
{
name: 'retry exhaustion',
error: 'target process does not map /lib/libc.so.6 while resolving mmap',
ticks: 4,
attempts: 3,
reason: 'retry_exhausted',
},
])('records $name terminal', async ({ error, ticks, attempts, reason }) => {
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
ctx.inject.mockImplementation(() => { throw new Error(error); });
try {
await ctx.pipeWatcher.start();
await flush();
await flush();
for (let tick = 0; tick < ticks; tick += 1) {
await ctx.pipeWatcher.tickNow();
await flush();
await flush();
}
const starts = managerTrace(entries).filter(
(entry) => entry.message.startsWith('hook_autoload_start '),
);
const terminals = managerTrace(entries).filter(
(entry) => entry.message.startsWith('hook_autoload_terminal '),
);
expect(starts).toHaveLength(attempts);
expect(terminals).toHaveLength(attempts);
expect(terminals.at(-1)!.message).toContain(`reason=${reason}`);
} finally {
unsubscribe();
ctx.manager.dispose();
}
});
});
describe('HookManager.autoLoadOnDiscovery', () => {
it('does NOT inject on process-discovered when flag is off', async () => {
const ctx = makeManager({ autoLoadOnDiscovery: false, processes: [4242] });
+198 -1
View File
@@ -1,4 +1,4 @@
import { describe, it, expect, vi } from 'vitest';
import { afterEach, describe, it, expect, vi } from 'vitest';
import { EventEmitter } from 'events';
import { HookSession } from '../src/hook-session';
import type { ManualMapHandle } from '../src/injector';
@@ -6,6 +6,24 @@ import type { QqHookClient, QqHookPacket } from '../src/qq-hook-client';
import type { QqPortLoginInfo } from '../src/qq-port-probe';
import type { PacketSender } from '@snowluma/common/packet-sender';
import type { PacketSink } from '@snowluma/common/protocol-types';
import {
getLogLevel,
setLogLevel,
subscribeLogs,
type LogEntry,
} from '@snowluma/common/logger';
const previousLogLevel = getLogLevel();
function sessionTrace(entries: LogEntry[]): LogEntry[] {
return entries.filter(
(entry) => entry.level === 'trace' && entry.scope === 'HookSession',
);
}
afterEach(() => {
setLogLevel(previousLogLevel);
});
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
@@ -95,6 +113,185 @@ function makeSession(opts: {
const flush = () => new Promise<void>(r => setImmediate(r));
describe('HookSession — runtime TRACE', () => {
it('records injection and existing-pipe load branches with unique terminals', async () => {
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
try {
const injected = makeSession({ pid: 7101, pipeLive: false });
const reconnect = makeSession({ pid: 7102, pipeLive: true });
await injected.session.load();
await reconnect.session.load();
const messages = sessionTrace(entries).map((entry) => entry.message);
expect(messages).toEqual(expect.arrayContaining([
expect.stringContaining('hook_session_start pid=7101 operation=load'),
'hook_session_branch pid=7101 operation=load branch=inject_begin',
'hook_session_branch pid=7101 operation=load branch=inject_completed method="loadModuleManual"',
expect.stringMatching(/^hook_session_terminal pid=7101 operation=load outcome=completed reason=load_settled state=.*elapsedMs=\d+$/),
expect.stringContaining('hook_session_start pid=7102 operation=load'),
'hook_session_branch pid=7102 operation=load branch=existing_pipe method="reconnect"',
expect.stringMatching(/^hook_session_terminal pid=7102 operation=load outcome=completed reason=load_settled state=.*elapsedMs=\d+$/),
]));
for (const pid of [7101, 7102]) {
expect(messages.filter(
(message) => message.startsWith(`hook_session_terminal pid=${pid} operation=load `),
)).toHaveLength(1);
}
} finally {
unsubscribe();
}
});
it('records load and connection failures with truthful settled state', async () => {
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
try {
const injector = {
inject: vi.fn(() => { throw new Error('fixture inject failure'); }),
unload: vi.fn(),
};
const failedLoad = new HookSession(7103, {
injector,
makeClient: () => new FakeClient() as unknown as QqHookClient,
pipeWatcher: { isPipeLive: () => false },
});
await failedLoad.load();
const failedConnect = makeSession({
pid: 7104,
pipeLive: true,
clientFailsConnect: true,
});
await failedConnect.session.load();
failedConnect.session.onPipeUp();
await flush();
const messages = sessionTrace(entries).map((entry) => entry.message);
expect(messages).toEqual(expect.arrayContaining([
expect.stringMatching(/^hook_session_terminal pid=7103 operation=load outcome=failed reason=load_failed error="fixture inject failure" state=.*elapsedMs=\d+$/),
expect.stringContaining('hook_session_connect_start pid=7104'),
expect.stringMatching(/^hook_session_connect_terminal pid=7104 outcome=failed reason=connect_failed error="connect failed" state=.*elapsedMs=\d+$/),
]));
expect(messages.filter(
(message) => message.startsWith('hook_session_connect_terminal pid=7104 '),
)).toHaveLength(1);
} finally {
unsubscribe();
}
});
it('records login, disconnect, and process-gone only when state changes', async () => {
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const ctx = makeSession({ pid: 7105, pipeLive: true });
try {
await ctx.session.load();
ctx.session.onPipeUp();
await flush();
ctx.currentClient().fireLogin('10001');
ctx.currentClient().fireLogin('10001');
ctx.session.onPipeDown();
await flush();
ctx.session.onPipeDown();
await flush();
ctx.session.notifyProcessGone();
await flush();
const messages = sessionTrace(entries).map((entry) => entry.message);
expect(messages.filter(
(message) => message.startsWith('hook_session_login_terminal pid=7105 '),
)).toHaveLength(1);
expect(messages.filter(
(message) => message.startsWith('hook_session_disconnect_terminal pid=7105 '),
)).toHaveLength(1);
expect(messages.filter(
(message) => message.startsWith('hook_session_process_terminal pid=7105 '),
)).toHaveLength(1);
expect(messages).toEqual(expect.arrayContaining([
expect.stringMatching(/^hook_session_login_terminal pid=7105 outcome=completed reason=login_detected previousUin="0" uin="10001" state=.*elapsedMs=\d+$/),
expect.stringMatching(/^hook_session_disconnect_terminal pid=7105 outcome=completed reason=pipe_down wasLoggedIn=true state=.*elapsedMs=\d+$/),
expect.stringMatching(/^hook_session_process_terminal pid=7105 outcome=completed reason=process_gone wasLoggedIn=false state=.*elapsedMs=\d+$/),
]));
} finally {
unsubscribe();
ctx.session.dispose();
}
});
it('records failed terminals when lifecycle listeners throw', async () => {
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const login = makeSession({ pid: 7107, pipeLive: true });
const disconnect = makeSession({ pid: 7108, pipeLive: true });
const processGone = makeSession({ pid: 7109, pipeLive: true });
try {
await login.session.load();
login.session.onPipeUp();
await flush();
login.session.on('login', () => { throw new Error('login listener boom'); });
expect(() => login.currentClient().fireLogin('10001')).toThrow('login listener boom');
await disconnect.session.load();
disconnect.session.onPipeUp();
await flush();
disconnect.currentClient().fireLogin('10002');
disconnect.session.on('disconnected', () => { throw new Error('disconnect listener boom'); });
disconnect.session.onPipeDown();
await flush();
processGone.session.on('disposed', () => { throw new Error('dispose listener boom'); });
processGone.session.notifyProcessGone();
await flush();
const messages = sessionTrace(entries).map((entry) => entry.message);
expect(messages.filter((message) =>
message.startsWith('hook_session_login_terminal pid=7107 '))).toEqual([
expect.stringMatching(/^hook_session_login_terminal pid=7107 outcome=failed reason=listener_failed error="login listener boom" state=.*elapsedMs=\d+$/),
]);
expect(messages.filter((message) =>
message.startsWith('hook_session_disconnect_terminal pid=7108 '))).toEqual([
expect.stringMatching(/^hook_session_disconnect_terminal pid=7108 outcome=failed reason=listener_failed error="disconnect listener boom" state=.*elapsedMs=\d+$/),
]);
expect(messages.filter((message) =>
message.startsWith('hook_session_process_terminal pid=7109 '))).toEqual([
expect.stringMatching(/^hook_session_process_terminal pid=7109 outcome=failed reason=listener_failed error="dispose listener boom" state=.*elapsedMs=\d+$/),
]);
} finally {
unsubscribe();
login.session.dispose();
disconnect.session.dispose();
processGone.session.dispose();
}
});
it('records unload verification failure as a failed terminal', async () => {
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const ctx = makeSession({ pid: 7106, pipeLive: false });
try {
await ctx.session.load();
ctx.setPipeLive(true);
await ctx.session.unload();
const terminals = sessionTrace(entries).filter(
(entry) => entry.message.startsWith('hook_session_terminal pid=7106 operation=unload '),
);
expect(terminals).toHaveLength(1);
expect(terminals[0]!.message).toMatch(
/^hook_session_terminal pid=7106 operation=unload outcome=failed reason=unload_verification_failed error=.*state=.*elapsedMs=\d+$/,
);
} finally {
unsubscribe();
}
});
});
describe('HookSession — load', () => {
it('with no live pipe: injects, status → connecting, method from inject result', async () => {
const { session, injector } = makeSession({ pipeLive: false });
@@ -4,6 +4,7 @@ import os from 'os';
import path from 'path';
import { Duplex } from 'stream';
import {
currentRequestId,
getLogLevel,
runWithRequestId,
setLogLevel,
@@ -106,6 +107,12 @@ function traceMessages(entries: LogEntry[]): string[] {
.map((entry) => entry.message);
}
function runtimeTrace(entries: LogEntry[]): LogEntry[] {
return entries.filter(
(entry) => entry.level === 'trace' && entry.scope === 'QQHook.Runtime',
);
}
afterEach(async () => {
setLogLevel(previousLogLevel);
vi.restoreAllMocks();
@@ -140,6 +147,136 @@ describe('listLiveLinuxPipePids', () => {
});
});
describe('QqHookClient — runtime TRACE', () => {
it('records control and receive pipe hello lifecycles under the parent request', async () => {
const pid = 778820;
const entries: LogEntry[] = [];
let connectionIndex = 0;
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const createConnection = vi.spyOn(net, 'createConnection').mockImplementation((() => {
const kind = connectionIndex === 0 ? 'control' : 'recv';
connectionIndex += 1;
const socket = new Duplex({
read() { /* peer data is injected with emit('data') */ },
}) as net.Socket;
queueMicrotask(() => {
socket.emit('connect');
queueMicrotask(() => socket.emit('data', pipeFrame({
op: PipeOp.hello,
value0: BigInt(pid),
message: `${kind}-fixture`,
})));
});
return socket;
}) as typeof net.createConnection);
const client = new QqHookClient(pid);
try {
await runWithRequestId(4201, () => client.connectAll());
const trace = runtimeTrace(entries);
expect(trace).toHaveLength(6);
expect(trace.every((entry) => entry.req === 4201)).toBe(true);
expect(trace.map((entry) => entry.message)).toEqual([
expect.stringMatching(/^hook_pipe_start pid=778820 kind=control pipeName=.*$/),
expect.stringMatching(/^hook_pipe_branch pid=778820 kind=control branch=socket_connected$/),
expect.stringMatching(/^hook_pipe_terminal pid=778820 kind=control outcome=completed reason=hello_received hello=\{pipeName:"control-fixture",pid:778820,recvPipe:false\} elapsedMs=\d+$/),
expect.stringMatching(/^hook_pipe_start pid=778820 kind=recv pipeName=.*$/),
expect.stringMatching(/^hook_pipe_branch pid=778820 kind=recv branch=socket_connected$/),
expect.stringMatching(/^hook_pipe_terminal pid=778820 kind=recv outcome=completed reason=hello_received hello=\{pipeName:"recv-fixture",pid:778820,recvPipe:true\} elapsedMs=\d+$/),
]);
} finally {
unsubscribe();
client.close();
createConnection.mockRestore();
}
});
it('records a pre-request connection failure without a pipe request id', async () => {
const pid = 778821;
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const createConnection = vi.spyOn(net, 'createConnection').mockImplementation((() => {
const socket = new Duplex({ read() { /* no peer */ } }) as net.Socket;
queueMicrotask(() => socket.emit('error', new Error('fixture connect failure')));
return socket;
}) as typeof net.createConnection);
const client = new QqHookClient(pid);
try {
await expect(client.connect()).rejects.toThrow('fixture connect failure');
const trace = runtimeTrace(entries);
expect(trace).toHaveLength(2);
expect(trace.every((entry) => entry.req !== undefined)).toBe(true);
expect(trace[0]!.req).toBe(trace[1]!.req);
expect(trace.map((entry) => entry.message)).toEqual([
expect.stringMatching(/^hook_pipe_start pid=778821 kind=control pipeName=.*$/),
expect.stringMatching(/^hook_pipe_terminal pid=778821 kind=control outcome=failed reason=connect_failed error="fixture connect failure" elapsedMs=\d+$/),
]);
expect(trace.map((entry) => entry.message).join('\n')).not.toContain('requestId=');
} finally {
unsubscribe();
client.close();
createConnection.mockRestore();
}
});
it('assigns fresh request contexts to material login and close events only', async () => {
const pid = 778822;
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const connection = mockControlPipe(pid, () => { /* no packet writes */ });
const client = new QqHookClient(pid);
const eventRequestIds: Array<{ event: 'login' | 'close'; req: number | undefined }> = [];
client.on('loginState', () => {
eventRequestIds.push({ event: 'login', req: currentRequestId() });
});
client.on('close', () => {
eventRequestIds.push({ event: 'close', req: currentRequestId() });
});
try {
await runWithRequestId(4202, () => client.connect());
const controlSocket = connection.mock.results[0]!.value as net.Socket;
controlSocket.emit('data', pipeFrame({
op: PipeOp.loginState,
status: 1,
value0: 123456n,
message: '123456',
}));
controlSocket.emit('data', pipeFrame({
op: PipeOp.loginState,
status: 1,
value0: 123456n,
message: '123456',
}));
controlSocket.destroy();
await new Promise<void>((resolve) => setImmediate(resolve));
const facts = runtimeTrace(entries).filter(
(entry) => entry.message.startsWith('hook_runtime_fact pid=778822 '),
);
expect(facts).toHaveLength(2);
expect(facts.every((entry) => entry.req !== undefined)).toBe(true);
expect(facts[0]!.req).not.toBe(facts[1]!.req);
expect(facts.map((entry) => entry.message)).toEqual([
'hook_runtime_fact pid=778822 event=login_state_changed previousLoggedIn=false previousUin="0" loggedIn=true uin="123456"',
'hook_runtime_fact pid=778822 event=pipe_closed kind=control loggedIn=true uin="123456"',
]);
expect(eventRequestIds).toEqual([
{ event: 'login', req: facts[0]!.req },
{ event: 'login', req: undefined },
{ event: 'close', req: facts[1]!.req },
]);
} finally {
unsubscribe();
client.close();
connection.mockRestore();
}
});
});
describe('QqHookClient — packet TRACE', () => {
it('records complete request and reply bodies with the real pipe request id', async () => {
const pid = 778810;