bailinghub 0.9.1 → 0.9.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/README.en.md +6 -6
  2. package/README.md +6 -6
  3. package/docker-compose.images.yml +2 -2
  4. package/docs/CHANGELOG.en.md +23 -1
  5. package/docs/CHANGELOG.md +23 -1
  6. package/docs/CORE_RELIABILITY.en.md +79 -0
  7. package/docs/CORE_RELIABILITY.md +79 -0
  8. package/docs/DEPLOYMENT_DIAGNOSTICS.en.md +78 -0
  9. package/docs/DEPLOYMENT_DIAGNOSTICS.md +78 -0
  10. package/docs/IMPLEMENTATION_STATUS.en.md +27 -15
  11. package/docs/IMPLEMENTATION_STATUS.md +27 -15
  12. package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
  13. package/docs/INDEPENDENT_VALIDATION.md +4 -4
  14. package/docs/KERNEL_HOST_API.en.md +2 -0
  15. package/docs/KERNEL_HOST_API.md +2 -0
  16. package/docs/MODEL_BILLING.en.md +4 -0
  17. package/docs/MODEL_BILLING.md +4 -0
  18. package/docs/MODEL_PROCESS_RECOVERY.en.md +32 -0
  19. package/docs/MODEL_PROCESS_RECOVERY.md +37 -0
  20. package/docs/OPERATIONS.en.md +13 -0
  21. package/docs/OPERATIONS.md +12 -0
  22. package/docs/README.en.md +7 -0
  23. package/docs/README.md +7 -0
  24. package/docs/RELEASE_NOTES_v0.9.2.en.md +45 -0
  25. package/docs/RELEASE_NOTES_v0.9.2.md +45 -0
  26. package/docs/RELEASE_NOTES_v0.9.3.en.md +51 -0
  27. package/docs/RELEASE_NOTES_v0.9.3.md +51 -0
  28. package/docs/TOOLS_DESIGN.md +1 -0
  29. package/docs/UPGRADE_v0.9.2.en.md +62 -0
  30. package/docs/UPGRADE_v0.9.2.md +62 -0
  31. package/docs/UPGRADE_v0.9.3.en.md +63 -0
  32. package/docs/UPGRADE_v0.9.3.md +63 -0
  33. package/package.json +7 -3
  34. package/scripts/check-doc-links.mjs +4 -0
  35. package/scripts/check-image-tags.sh +1 -1
  36. package/scripts/check-release-consistency.test.mjs +2 -2
  37. package/scripts/doctor-deployment.test.ts +419 -0
  38. package/scripts/doctor-deployment.ts +357 -0
  39. package/scripts/doctor.ts +8 -1
  40. package/scripts/install-secrets.test.mjs +185 -0
  41. package/scripts/install.sh +10 -6
  42. package/scripts/publish-images.sh +1 -1
  43. package/scripts/release-audit.mjs +8 -0
  44. package/scripts/verify-github-repo.mjs +8 -0
  45. package/security/dependency-audit-exceptions.json +1 -1
  46. package/sql/065_usage_reconciliation_scan.sql +4 -0
  47. package/sql/066_approval_continuations.sql +15 -0
  48. package/sql/067_delivery_dlq_replay.sql +10 -0
  49. package/sql/README.en.md +6 -0
  50. package/sql/README.md +15 -0
  51. package/src/adapters/llm/file.test.ts +59 -0
  52. package/src/adapters/llm/file.ts +11 -4
  53. package/src/app/agent-tool-invocations.test.ts +3 -1
  54. package/src/app/approval-continuations.mysql.test.ts +138 -0
  55. package/src/app/approval-continuations.test.ts +351 -0
  56. package/src/app/approval-continuations.ts +148 -0
  57. package/src/app/channels-attachments.test.ts +63 -0
  58. package/src/app/channels.ts +7 -4
  59. package/src/app/delivery-dlq-replay.mysql.test.ts +139 -0
  60. package/src/app/delivery-dlq-replay.test.ts +75 -0
  61. package/src/app/delivery-dlq-replay.ts +41 -0
  62. package/src/app/delivery.ts +3 -2
  63. package/src/app/http-server.ts +3 -0
  64. package/src/app/kernel-model-process-crash.mysql.test.ts +377 -0
  65. package/src/app/kernel-notification-lifecycle.test.ts +49 -0
  66. package/src/app/kernel.ts +22 -0
  67. package/src/app/notification-outbound.test.ts +53 -0
  68. package/src/app/operational-metrics.test.ts +37 -1
  69. package/src/app/operational-metrics.ts +25 -2
  70. package/src/app/outbound.ts +13 -2
  71. package/src/app/runtime-evidence-maintenance.test.ts +55 -0
  72. package/src/app/runtime-lifecycle-default.ts +7 -0
  73. package/src/app/runtime-lifecycle.test.ts +89 -0
  74. package/src/app/runtime-lifecycle.ts +52 -11
  75. package/src/app/tool-approvals.ts +2 -1
  76. package/src/core/contracts/approval-continuation.ts +43 -0
  77. package/src/core/contracts/delivery-replay.ts +41 -0
  78. package/src/core/contracts/tools-idempotency.test.ts +121 -5
  79. package/src/core/contracts/tools.ts +21 -11
  80. package/src/core/contracts/types.ts +4 -0
  81. package/src/core/observability/openmetrics.test.ts +28 -0
  82. package/src/core/observability/openmetrics.ts +91 -0
  83. package/src/core/platform/http-body.test.ts +185 -0
  84. package/src/core/platform/http-body.ts +58 -0
  85. package/src/core/runtime/finish-runtime.test.ts +2 -0
  86. package/src/core/runtime/finish-runtime.ts +10 -7
  87. package/src/core/runtime/notification-background-work.test.ts +50 -0
  88. package/src/core/runtime/notification-background-work.ts +101 -0
  89. package/src/core/state/approval-continuation.ts +22 -0
  90. package/src/core/state/delivery-replay.ts +19 -0
  91. package/src/core/state/state-codec.ts +2 -0
  92. package/src/core/state/state-contracts.ts +6 -0
  93. package/src/infrastructure/config/config-approval-ledger.ts +75 -0
  94. package/src/infrastructure/config/config-delivery-dlq-ledger.ts +36 -10
  95. package/src/infrastructure/config/configstore.ts +4 -3
  96. package/src/infrastructure/state/state-jsonl.ts +56 -11
  97. package/src/infrastructure/state/state-mysql.ts +54 -0
  98. package/src/modules/usage/background-work.test.ts +28 -0
  99. package/src/modules/usage/background-work.ts +43 -7
  100. package/src/modules/usage/billing-reconciliation.mysql.test.ts +163 -0
  101. package/src/modules/usage/billing-reconciliation.test.ts +85 -0
  102. package/src/modules/usage/billing-repository.ts +63 -11
  103. package/src/modules/usage/maintenance.test.ts +78 -0
  104. package/src/modules/usage/maintenance.ts +39 -0
  105. package/src/modules/usage/model-gateway.ts +2 -1
  106. package/src/routes/admin-default.ts +2 -2
  107. package/src/routes/admin-runtime-default.ts +2 -2
  108. package/src/routes/admin-runtime.test.ts +1 -1
  109. package/src/routes/admin-runtime.ts +39 -18
  110. package/src/routes/admin.ts +1 -1
  111. package/src/routes/approvals-default.ts +2 -2
  112. package/src/routes/approvals.ts +30 -33
  113. package/src/routes/critical-routes.test.ts +16 -3
  114. package/src/test-support/approval-continuation-crash-child.ts +24 -0
  115. package/src/test-support/model-process-crash-child.ts +78 -0
@@ -0,0 +1,377 @@
1
+ import assert from 'node:assert/strict';
2
+ import test, { before, after } from 'node:test';
3
+ import { createHash, randomUUID } from 'node:crypto';
4
+ import { execFile, spawn, type ChildProcess } from 'node:child_process';
5
+ import { promisify } from 'node:util';
6
+ import { mkdtempSync, rmSync } from 'node:fs';
7
+ import { tmpdir } from 'node:os';
8
+ import { join } from 'node:path';
9
+ import { fileURLToPath } from 'node:url';
10
+ import { createServer } from 'node:http';
11
+ import { createServer as createTcpServer, connect, type AddressInfo, type Socket } from 'node:net';
12
+ import { setTimeout as delay } from 'node:timers/promises';
13
+ import { createPool, type Pool } from 'mysql2/promise';
14
+ import type { AppConfig } from '../core/config/config';
15
+ import { migrateBailingHubCoreSchema } from '../infrastructure/schema/core-schema-migrator';
16
+ import { UsageRepository } from '../modules/usage/repository';
17
+ import { getUsageIdentity } from '../modules/usage/identity';
18
+ import { getBillingRepository } from '../modules/usage/billing-repository';
19
+ import type { CrashChildInit, CrashPoint, CrashStage } from '../test-support/model-process-crash-child';
20
+
21
+ // Opt-in destructive tests own a fresh Docker instance, schemas and child processes.
22
+ // No deployment configuration, existing SQL server or external model is used.
23
+ const enabled = process.env.BAILING_USAGE_PROCESS_CRASH_TEST === '1';
24
+ const mysqlImage = 'mysql:8.4@sha256:85b9bf2e29cf836ecb8c2a15a935d4ba0c606631dff1dd79531a11983c638f2a';
25
+ const execute = promisify(execFile);
26
+ const childPath = fileURLToPath(new URL('../test-support/model-process-crash-child.ts', import.meta.url));
27
+ const children = new Set<ChildProcess>();
28
+ let containerId: string | undefined, mysqlPort: number;
29
+ const mysql = () => ({ host: '127.0.0.1', port: mysqlPort, user: 'root', password: '', connectionLimit: 8 });
30
+
31
+ function gate() {
32
+ let release!: () => void;
33
+ const promise = new Promise<void>(resolve => { release = resolve; });
34
+ return { promise, release };
35
+ }
36
+ async function until(predicate: () => boolean | Promise<boolean>, message: string, timeoutMs = 10000) {
37
+ const end = Date.now() + timeoutMs;
38
+ do { if (await predicate()) return; await delay(20); } while (Date.now() < end);
39
+ throw new Error(message);
40
+ }
41
+ async function deadline<T>(promise: Promise<T>, message: string, timeoutMs = 10000): Promise<T> {
42
+ let timer: ReturnType<typeof setTimeout> | undefined;
43
+ try { return await Promise.race([promise, new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new Error(message)), timeoutMs); })]); }
44
+ finally { clearTimeout(timer); }
45
+ }
46
+ async function kill(child: ChildProcess) {
47
+ if (child.exitCode !== null || child.signalCode !== null) { children.delete(child); return; }
48
+ const exit = new Promise<string | null>(resolve => child.once('exit', (_code, signal) => resolve(signal)));
49
+ assert.equal(child.kill('SIGKILL'), true);
50
+ assert.equal(await deadline(exit, 'SIGKILL child did not exit'), 'SIGKILL');
51
+ children.delete(child);
52
+ }
53
+
54
+ before(async () => {
55
+ if (!enabled) return;
56
+ const name = `bailinghub-process-crash-${randomUUID().replaceAll('-', '')}`;
57
+ const started = await execute('docker', ['run', '--detach', '--rm', '--pull=never', '--name', name,
58
+ '--label', 'org.bailinghub.test=model-process-crash', '--memory=768m', '--cpus=2',
59
+ '--publish', '127.0.0.1::3306', '--env', 'MYSQL_ALLOW_EMPTY_PASSWORD=yes', '--env', 'MYSQL_ROOT_HOST=%', mysqlImage]);
60
+ containerId = started.stdout.trim();
61
+ assert.match(containerId, /^[a-f0-9]{64}$/);
62
+ const image = await execute('docker', ['inspect', '--format', '{{.Image}}', containerId]);
63
+ const port = await execute('docker', ['port', containerId, '3306/tcp']);
64
+ assert.match(port.stdout.trim(), /^127\.0\.0\.1:\d+$/);
65
+ mysqlPort = Number(port.stdout.trim().split(':')[1]);
66
+ process.stdout.write(`# isolated_fixture ${JSON.stringify({ containerId, name, imageReference: mysqlImage, image: image.stdout.trim(), host: '127.0.0.1', port: mysqlPort })}\n`);
67
+ await until(async () => {
68
+ const pool = createPool(mysql());
69
+ try { await pool.query('SELECT 1'); return true; } catch { return false; } finally { await pool.end(); }
70
+ }, 'Fresh isolated MySQL did not become ready', 60000);
71
+ const versionPool = createPool(mysql());
72
+ try {
73
+ const [version] = await versionPool.query<any[]>('SELECT VERSION() version');
74
+ process.stdout.write(`# isolated_mysql ${JSON.stringify({ version: version[0].version })}\n`);
75
+ } finally { await versionPool.end(); }
76
+ });
77
+ after(async () => {
78
+ const errors: unknown[] = [];
79
+ for (const result of await Promise.allSettled([...children].map(kill))) {
80
+ if (result.status === 'rejected') errors.push(result.reason);
81
+ }
82
+ if (containerId) {
83
+ let removed = false;
84
+ try {
85
+ const label = await execute('docker', ['inspect', '--format', '{{index .Config.Labels "org.bailinghub.test"}}', containerId]);
86
+ assert.equal(label.stdout.trim(), 'model-process-crash');
87
+ await execute('docker', ['rm', '--force', containerId]);
88
+ removed = true;
89
+ } catch (error) { errors.push(error); }
90
+ process.stdout.write(`# cleanup ${JSON.stringify({ containerId, removed, trackedChildren: children.size, failures: errors.length })}\n`);
91
+ }
92
+ if (errors.length) throw new AggregateError(errors, 'Synthetic process cleanup failed');
93
+ });
94
+
95
+ /** Drops an actual MySQL COMMIT OK packet while preserving the committed database state. */
96
+ async function commitAckProxy(target: CrashStage) {
97
+ const observed = gate(), sockets = new Set<Socket>();
98
+ let withheld = false;
99
+ const stageFor = (sql: string): CrashStage | undefined => {
100
+ if (/INSERT INTO bz_usage_billing_requests\(/i.test(sql)) return 'admitted';
101
+ if (/UPDATE bz_usage_billing_requests SET state='dispatch_committed'/i.test(sql)) return 'dispatch';
102
+ if (/UPDATE bz_usage_billing_requests SET state='(?:completed|cancelled)',result_state=/i.test(sql)) return 'result';
103
+ if (/INSERT INTO bz_usage_billing_ledger\(/i.test(sql)) return 'settlement';
104
+ return undefined;
105
+ };
106
+ function packets(socket: Socket, fn: (packet: Buffer, payload: Buffer) => void) {
107
+ let buffered = Buffer.alloc(0);
108
+ socket.on('data', chunk => {
109
+ buffered = Buffer.concat([buffered, chunk]);
110
+ while (buffered.length >= 4) {
111
+ const length = buffered.readUIntLE(0, 3);
112
+ if (buffered.length < length + 4) break;
113
+ const packet = buffered.subarray(0, length + 4);
114
+ buffered = buffered.subarray(length + 4);
115
+ fn(packet, packet.subarray(4));
116
+ }
117
+ });
118
+ }
119
+ const server = createTcpServer(client => {
120
+ const upstream = connect(mysqlPort, '127.0.0.1');
121
+ sockets.add(client); sockets.add(upstream);
122
+ let stage: CrashStage | undefined, dropNext = false, blocked = false;
123
+ for (const socket of [client, upstream]) {
124
+ socket.on('error', () => { client.destroy(); upstream.destroy(); });
125
+ socket.on('close', () => { sockets.delete(socket); client.destroy(); upstream.destroy(); });
126
+ }
127
+ packets(client, (packet, payload) => {
128
+ if (payload[0] === 3) { // COM_QUERY; mysql2 query() uses the text protocol.
129
+ // mysql2/MySQL 8.4 negotiate CLIENT_QUERY_ATTRIBUTES even without
130
+ // attributes: parameter_count=0 and parameter_set_count=1 precede SQL.
131
+ const offset = payload[1] === 0 && payload[2] === 1 ? 3 : 1;
132
+ const sql = payload.subarray(offset).toString('utf8');
133
+ if (/^START TRANSACTION/i.test(sql)) stage = undefined;
134
+ stage = stageFor(sql) ?? stage;
135
+ if (/^COMMIT\s*$/i.test(sql) && stage === target && !withheld) dropNext = true;
136
+ }
137
+ upstream.write(packet);
138
+ });
139
+ packets(upstream, (packet, payload) => {
140
+ if (blocked) return;
141
+ if (dropNext) {
142
+ assert.equal(payload[0], 0, 'Target COMMIT must succeed before its acknowledgment is lost');
143
+ blocked = true; withheld = true; observed.release(); return;
144
+ }
145
+ client.write(packet);
146
+ });
147
+ });
148
+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
149
+ return { port: (server.address() as AddressInfo).port, observed: observed.promise,
150
+ close() { for (const socket of sockets) socket.destroy(); server.close(); } };
151
+ }
152
+
153
+ async function fixture() {
154
+ const database = `process_crash_${randomUUID().replaceAll('-', '')}`;
155
+ const dir = mkdtempSync(join(tmpdir(), 'bailinghub-model-process-crash-'));
156
+ const admin = createPool(mysql());
157
+ let pool: Pool | undefined;
158
+ const cleanup: Array<() => unknown | Promise<unknown>> = [() => rmSync(dir, { recursive: true, force: true }), () => admin.end()];
159
+ const providerGate = gate();
160
+ async function dispose() {
161
+ providerGate.release();
162
+ const errors: unknown[] = [];
163
+ for (const release of cleanup.reverse()) { try { await release(); } catch (error) { errors.push(error); } }
164
+ if (errors.length) throw new Error(`Synthetic process fixture cleanup failed (${errors.length})`);
165
+ }
166
+ try {
167
+ await admin.query(`CREATE DATABASE \`${database}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_bin`);
168
+ cleanup.push(() => admin.query(`DROP DATABASE \`${database}\``));
169
+ await migrateBailingHubCoreSchema({ mysql: { ...mysql(), database }, logger: { log() {}, warn() {} } });
170
+ pool = createPool({ ...mysql(), database });
171
+ const sql = pool;
172
+ cleanup.push(() => sql.end());
173
+ const repository = new UsageRepository(() => sql);
174
+ const provider = { calls: 0, responses: 0 };
175
+ const server = createServer(async (req, res) => {
176
+ for await (const _chunk of req) { /* Synthetic input only. */ }
177
+ provider.calls++;
178
+ await providerGate.promise;
179
+ if (res.destroyed) return;
180
+ res.writeHead(200, { 'content-type': 'application/json' });
181
+ res.end(JSON.stringify(req.url === '/v1/chat/completions'
182
+ ? { id: 'synthetic-execution', choices: [{ index: 0, message: { role: 'assistant', content: 'Synthetic output' }, finish_reason: 'stop' }],
183
+ usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 } }
184
+ : { id: 'synthetic-execution', data: [{ url: 'https://synthetic.invalid/image.png' }],
185
+ usage: { output_image_count: 1, output_image_type: '1k', output_width: 1024, output_height: 1024 } }));
186
+ provider.responses++;
187
+ });
188
+ cleanup.push(() => { server.close(); server.closeAllConnections(); });
189
+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
190
+ const config: AppConfig = {
191
+ root: process.cwd(), runtimeRoot: dir, env: 'development', server: { host: '127.0.0.1', port: 0, token: '' }, brand: { name: 'Synthetic process recovery' },
192
+ displayTz: 'Asia/Shanghai', displayTzLabel: '北京时间', auditRetentionDays: 0, alerts: null, metrics: { enabled: false, token: '', scrapeTimeoutMs: 1000 },
193
+ bootstrapAdmin: null, concurrency: 1, killSwitchFile: join(dir, '.paused'), claudeBin: 'synthetic-unused', defaultProfile: 'readonly', brainDir: join(dir, 'brain'),
194
+ state: { backend: 'mysql', jsonlPath: join(dir, 'jobs.jsonl'), mysql: { ...mysql(), database } }, projects: {},
195
+ llmCredentials: { synthetic: { base_url: `http://127.0.0.1:${(server.address() as AddressInfo).port}/v1`, api_key: 'REPLACE_ME' } },
196
+ executor: { hubUrl: '', token: '', executorId: 'synthetic', targets: [], waitMs: 100, concurrency: 1, labels: [] },
197
+ };
198
+ for (const kind of ['image', 'chat'] as const) {
199
+ const modelId = `synthetic/${kind}`, endpointId = 'synthetic-provider';
200
+ await sql.query('INSERT INTO bz_usage_price_snapshots VALUES(?,?,?)', [
201
+ createHash('sha256').update(`${kind}:${modelId}`).digest('hex'),
202
+ JSON.stringify({ fetchedAt: Date.now(), items: [{ id: endpointId, pricing: {
203
+ source: 'openrouter', modelId, endpointId, currency: 'USD', fetchedAt: Date.now(),
204
+ lines: kind === 'image' ? [{ billable: 'output_image', unit: 'image', costUsd: '0.2', variant: '1k' }]
205
+ : [{ billable: 'prompt', unit: 'token', costUsd: '0.01' }, { billable: 'completion', unit: 'token', costUsd: '0.01' }],
206
+ } }] }), Date.now(),
207
+ ]);
208
+ await repository.putService({ id: `synthetic-${kind}`, label: `Synthetic ${kind}`, expectedRevision: 0, config: {
209
+ credential: 'synthetic', model: `synthetic-${kind}`, providerScope: database, maxInputBytes: 16384, maxOutputTokens: 100, timeoutMs: 30000,
210
+ purpose: kind === 'image' ? 'tool' : 'chat', pricing: { source: 'openrouter', kind, modelId, endpointId },
211
+ ...(kind === 'image' ? { tool: { name: 'generate_image', capability: 'image_generation', description: 'Synthetic image', outputs: ['image'], adapter: 'aliyun-image',
212
+ parameters: [{ name: 'prompt', type: 'string', required: true, description: 'Synthetic input' }] } } : {}),
213
+ } });
214
+ }
215
+ const identity = getUsageIdentity(repository);
216
+ const issuer = await identity.createIssuer({ id: 'synthetic-product', label: 'Synthetic product', permissions: ['identity:exchange'], service_ids: ['synthetic-image', 'synthetic-chat'] });
217
+ const user = await identity.exchange(issuer.credential!, { request_key: randomUUID(), tenant: 'synthetic', subject: 'synthetic-subject', service_id: 'synthetic-image', model_access: 'token_gateway' });
218
+ const tokens = getBillingRepository(repository);
219
+ await tokens.putPlan({ id: 'synthetic-plan', label: 'Synthetic allowance', expected_revision: 0,
220
+ config: { mode: 'credits', serviceIds: ['synthetic-image', 'synthetic-chat'], priceUsd: 100, multiplier: 1, duration: { unit: 'month', count: 1 } } });
221
+ await tokens.grant(user.session.accountId, { request_key: 'synthetic-grant', plan_id: 'synthetic-plan', expected_revision: 0 });
222
+
223
+ async function start(point?: CrashPoint, ack?: CrashStage) {
224
+ const proxy = ack ? await commitAckProxy(ack) : undefined;
225
+ if (proxy) cleanup.push(() => proxy.close());
226
+ const child = spawn(process.execPath, ['--import', 'tsx', childPath], {
227
+ cwd: process.cwd(), env: { PATH: process.env.PATH }, stdio: ['ignore', 'ignore', 'pipe', 'ipc'],
228
+ });
229
+ children.add(child);
230
+ cleanup.push(() => kill(child));
231
+ let stderr = '';
232
+ child.stderr?.on('data', chunk => { stderr = (stderr + String(chunk)).slice(-4000); });
233
+ const ready = gate(), fault = gate();
234
+ let base = '', error: Error | undefined;
235
+ child.on('message', message => {
236
+ const value = message as { type: string; base?: string; message?: string; point?: string; pid: number };
237
+ assert.equal(value.pid === undefined || value.pid === child.pid, true);
238
+ if (value.type === 'ready') { base = value.base!; ready.release(); }
239
+ if (value.type === 'fault') { assert.equal(value.point, point); fault.release(); }
240
+ if (value.type === 'error') { error = new Error(value.message); ready.release(); fault.release(); }
241
+ });
242
+ child.once('exit', () => { children.delete(child); if (!base) { error = new Error(`Synthetic Kernel exited before ready: ${stderr}`); ready.release(); } });
243
+ const init: CrashChildInit = { type: 'init', config: { ...config, state: { ...config.state, mysql: { ...config.state.mysql, port: proxy?.port ?? mysqlPort } } }, instanceKey: database, ...(point ? { point } : {}) };
244
+ child.send(init);
245
+ await deadline(ready.promise, 'Synthetic Kernel did not become ready');
246
+ if (error) throw error;
247
+ async function api(path: string, method = 'GET', body?: unknown) {
248
+ const response = await fetch(base + path, { method, signal: AbortSignal.timeout(10000), headers: { authorization: `Bearer ${user.credential}`, 'content-type': 'application/json' },
249
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }) });
250
+ return { status: response.status, body: await response.json() as Record<string, any> };
251
+ }
252
+ const request = (operationId: string, kind: 'image' | 'chat' = 'image') => api(kind === 'image' ? '/usage/v1/model/tools/requests' : '/usage/v1/model/requests', 'POST',
253
+ kind === 'image' ? { operation_id: operationId, service_id: 'synthetic-image', arguments: { prompt: 'Synthetic input' } }
254
+ : { operation_id: operationId, service_id: 'synthetic-chat', messages: [{ role: 'user', content: 'Synthetic input' }] });
255
+ async function stop() {
256
+ const exit = new Promise<number | null>(resolve => child.once('exit', code => resolve(code)));
257
+ child.send({ type: 'shutdown' });
258
+ assert.equal(await deadline(exit, 'Recovery Kernel did not close'), 0);
259
+ }
260
+ return { child, api, request, stop, fault: proxy?.observed ?? fault.promise };
261
+ }
262
+ const rows = async () => (await sql.query<any[]>('SELECT id,operation_id,state,result_state,billing_state,fence,result_json,result_hash,billed_usd FROM bz_usage_billing_requests'))[0];
263
+ const ledger = async () => (await sql.query<any[]>('SELECT request_id,billed_usd FROM bz_usage_billing_ledger'))[0];
264
+ const consumed = async () => Number((await sql.query<any[]>('SELECT consumed_usd FROM bz_usage_billing_periods'))[0][0]?.consumed_usd ?? 0);
265
+ return { start, rows, ledger, consumed, provider, providerGate, close: dispose };
266
+ } catch (error) { await dispose().catch(() => {}); throw error; }
267
+ }
268
+
269
+ const windows: Array<{ point?: CrashPoint; ack?: CrashStage; label: string; stage: CrashStage; committed: boolean; kind?: 'image' | 'chat' }> = [
270
+ { point: 'admitted:before', label: 'before admission COMMIT', stage: 'admitted', committed: false },
271
+ { point: 'admitted:after', label: 'after admission COMMIT, before dispatch', stage: 'admitted', committed: true },
272
+ { point: 'dispatch:before', label: 'before dispatch COMMIT', stage: 'dispatch', committed: false },
273
+ { point: 'dispatch:after', label: 'after dispatch COMMIT, before provider send', stage: 'dispatch', committed: true },
274
+ { ack: 'dispatch', label: 'dispatch COMMIT OK packet lost', stage: 'dispatch', committed: true },
275
+ { point: 'result:before', label: 'provider response received, before result COMMIT', stage: 'result', committed: false },
276
+ { point: 'result:after', label: 'result COMMIT complete, before settlement', stage: 'result', committed: true },
277
+ { ack: 'result', label: 'result COMMIT OK packet lost', stage: 'result', committed: true },
278
+ { point: 'settlement:before', label: 'before settlement COMMIT', stage: 'settlement', committed: false },
279
+ { ack: 'settlement', label: 'settlement COMMIT OK packet lost', stage: 'settlement', committed: true },
280
+ { point: 'result:after', label: 'chat result committed, HTTP response lost', stage: 'result', committed: true, kind: 'chat' },
281
+ ];
282
+ for (const window of windows) {
283
+ test(`real SIGKILL recovery: ${window.label}`, { skip: !enabled, timeout: 45000 }, async t => {
284
+ const h = await fixture(), operationId = randomUUID(), kind = window.kind ?? 'image';
285
+ try {
286
+ const first = await h.start(window.point, window.ack);
287
+ h.providerGate.release();
288
+ const delivered = first.request(operationId, kind).catch(() => null);
289
+ await deadline(first.fault, `Crash window not reached: ${window.label}`);
290
+ const before = await h.rows();
291
+ const absent = window.stage === 'admitted' && !window.committed;
292
+ const complete = window.stage === 'settlement' || (window.stage === 'result' && window.committed);
293
+ const dispatched = !absent && (window.stage !== 'admitted' && !(window.stage === 'dispatch' && !window.committed));
294
+ assert.equal(before.length, absent ? 0 : 1);
295
+ if (!absent) {
296
+ assert.equal(before[0].operation_id, operationId);
297
+ assert.equal(Boolean(before[0].fence), dispatched);
298
+ assert.equal(before[0].state, complete ? 'completed' : dispatched ? 'dispatch_committed' : 'admitted');
299
+ assert.equal(before[0].result_state, complete ? 'complete' : 'pending');
300
+ assert.equal(before[0].billing_state, window.stage === 'settlement' && window.committed ? 'settled' : 'pending');
301
+ assert.equal(Boolean(before[0].result_hash), complete);
302
+ }
303
+ assert.equal(h.provider.calls, ['result', 'settlement'].includes(window.stage) ? 1 : 0);
304
+ const callsBefore = h.provider.calls;
305
+ assert.equal((await h.ledger()).length, window.stage === 'settlement' && window.committed ? 1 : 0);
306
+ await kill(first.child);
307
+ await delivered;
308
+
309
+ const recovery = await h.start();
310
+ assert.notEqual(recovery.child.pid, first.child.pid);
311
+ const replay = await recovery.request(operationId, kind);
312
+ assert.equal(replay.body.operation_id, operationId);
313
+ assert.equal(replay.status, absent || complete ? (kind === 'image' && absent ? 202 : 200) : 202);
314
+ if (!absent) assert.equal((await h.rows())[0].id, before[0].id);
315
+ if (complete) assert.deepEqual(replay.body.response, typeof before[0].result_json === 'string' ? JSON.parse(before[0].result_json) : before[0].result_json);
316
+ if (absent || complete) {
317
+ await until(async () => (await h.rows())[0]?.billing_state === 'settled', 'Saved evidence was not reconciled');
318
+ const after = (await h.rows())[0];
319
+ assert.equal(after.result_state, 'complete'); assert.ok(after.result_hash);
320
+ if (complete) assert.equal(after.result_hash, before[0].result_hash);
321
+ assert.equal(h.provider.calls, 1);
322
+ assert.equal((await h.ledger()).length, 1);
323
+ assert.equal(Number((await h.ledger())[0].billed_usd), kind === 'image' ? 0.2 : 0.02);
324
+ assert.equal(await h.consumed(), kind === 'image' ? 0.2 : 0.02);
325
+ for (let i = 0; i < 3; i++) {
326
+ const again = await recovery.request(operationId, kind);
327
+ assert.equal(again.status, 200); assert.equal(again.body.operation_id, operationId);
328
+ }
329
+ assert.equal((await h.ledger()).length, 1); assert.equal(h.provider.calls, 1);
330
+ } else {
331
+ assert.equal(replay.body.dispatch, dispatched ? 'unknown' : 'not_dispatched');
332
+ assert.equal(replay.body.next_action, 'inspect_original');
333
+ await delay(100);
334
+ assert.equal(h.provider.calls, callsBefore);
335
+ assert.equal((await h.ledger()).length, 0); assert.equal(await h.consumed(), 0);
336
+ if (!dispatched) {
337
+ const cancelled = await recovery.api(`/usage/v1/model/requests/${operationId}/cancel`, 'POST', {});
338
+ assert.equal(cancelled.body.result_state, 'cancelled'); assert.equal(cancelled.body.billing_state, 'settled');
339
+ assert.equal(cancelled.body.billed_usd, 0); assert.equal(h.provider.calls, 0);
340
+ }
341
+ }
342
+ t.diagnostic(JSON.stringify({ window: window.label, killedPid: first.child.pid, recoveredPid: recovery.child.pid,
343
+ signal: 'SIGKILL', providerCallsBefore: callsBefore, providerCallsAfter: h.provider.calls,
344
+ rows: (await h.rows()).length, ledgerRows: (await h.ledger()).length, consumedUsd: await h.consumed() }));
345
+ await recovery.stop();
346
+ } finally { await h.close(); }
347
+ });
348
+ }
349
+
350
+ test('real SIGKILL after provider receipt preserves original pending and never re-dispatches', { skip: !enabled, timeout: 45000 }, async t => {
351
+ const h = await fixture(), operationId = randomUUID();
352
+ try {
353
+ const first = await h.start();
354
+ const accepted = await first.request(operationId);
355
+ assert.equal(accepted.status, 202);
356
+ await until(() => h.provider.calls === 1, 'Synthetic provider did not receive the original request');
357
+ const original = (await h.rows())[0];
358
+ assert.equal(original.state, 'dispatch_committed'); assert.equal(original.result_hash, null);
359
+ await kill(first.child);
360
+ h.providerGate.release();
361
+ const recovery = await h.start();
362
+ assert.notEqual(recovery.child.pid, first.child.pid);
363
+ for (let i = 0; i < 4; i++) {
364
+ const replay = await recovery.request(operationId);
365
+ assert.equal(replay.status, 202); assert.equal(replay.body.operation_id, operationId);
366
+ assert.equal(replay.body.dispatch, 'unknown'); assert.equal(replay.body.next_action, 'inspect_original');
367
+ const read = await recovery.api(`/usage/v1/model/requests/${operationId}`);
368
+ assert.equal(read.status, 200); assert.equal(read.body.dispatch, 'unknown');
369
+ }
370
+ await delay(100);
371
+ assert.equal(h.provider.calls, 1); assert.equal((await h.rows())[0].id, original.id);
372
+ assert.equal((await h.ledger()).length, 0); assert.equal(await h.consumed(), 0);
373
+ t.diagnostic(JSON.stringify({ window: 'provider received, no saved result', killedPid: first.child.pid,
374
+ recoveredPid: recovery.child.pid, signal: 'SIGKILL', replayCount: 4, providerCalls: h.provider.calls, ledgerRows: 0, consumedUsd: 0 }));
375
+ await recovery.stop();
376
+ } finally { await h.close(); }
377
+ });
@@ -0,0 +1,49 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { mkdtemp, writeFile, readFile, rm } from 'node:fs/promises';
4
+ import { tmpdir } from 'node:os';
5
+ import { join } from 'node:path';
6
+ import { Readable } from 'node:stream';
7
+ import type { IncomingMessage, ServerResponse } from 'node:http';
8
+ import type { AppConfig } from '../core/config/config';
9
+ import { createBailingHubKernel } from './kernel';
10
+
11
+ test('Kernel close drains detached callback before resource release; timeout permits retry', async () => {
12
+ const dir = await mkdtemp(join(tmpdir(), 'kernel-notification-test-'));
13
+ const cfg: AppConfig = { root: process.cwd(), runtimeRoot: dir, env: 'development',
14
+ server: { host: '127.0.0.1', port: 0, token: 'synthetic-only' }, brand: { name: 'Synthetic' },
15
+ displayTz: 'Asia/Shanghai', displayTzLabel: '北京时间', auditRetentionDays: 0, alerts: null,
16
+ metrics: { enabled: false, token: '', scrapeTimeoutMs: 1000 }, bootstrapAdmin: null,
17
+ concurrency: 1, killSwitchFile: join(dir, '.paused'), claudeBin: 'synthetic-unused', defaultProfile: 'readonly', brainDir: join(dir, 'brain'),
18
+ state: { backend: 'jsonl', jsonlPath: join(dir, 'jobs.jsonl'), mysql: { host: '', port: 3306, database: '', user: '', password: '', connectionLimit: 2 } },
19
+ projects: {}, llmCredentials: {}, executor: { hubUrl: '', token: '', executorId: 'synthetic', targets: [], waitMs: 100, concurrency: 1, labels: [] } };
20
+ const job = { job_id: 'synthetic-notification-job', request_id: 'synthetic-notification-request', status: 'dispatched', target: 'synthetic-executor',
21
+ source: 'test', profile: 'readonly', project: '', input_preview: '', metadata: {}, callback_url: 'https://synthetic.invalid/callback',
22
+ created_at: new Date().toISOString(), updated_at: new Date().toISOString() };
23
+ await writeFile(cfg.state.jsonlPath, JSON.stringify({ kind: 'job', job }) + '\n');
24
+ const originalFetch = globalThis.fetch;
25
+ let started!: () => void, release!: () => void, completed = false;
26
+ const startedGate = new Promise<void>(resolve => { started = resolve; });
27
+ const gate = new Promise<void>(resolve => { release = resolve; });
28
+ globalThis.fetch = async () => { started(); await gate; completed = true; return new Response('', { status: 200 }); };
29
+ const kernel = createBailingHubKernel({ instanceKey: 'notification:test', config: cfg, bootstrapLocalAdmin: false });
30
+ try {
31
+ const req = Readable.from([Buffer.from(JSON.stringify({ job_id: job.job_id, ok: true, output: { text: 'synthetic result' } }))]) as IncomingMessage;
32
+ req.method = 'POST'; req.url = '/executor/result'; req.headers = { host: 'localhost', authorization: 'Bearer synthetic-only' };
33
+ let responseStatus = 0;
34
+ await kernel.handle(req, { writeHead(code: number) { responseStatus = code; }, end() {} } as unknown as ServerResponse, new URL('http://localhost/executor/result'));
35
+ await startedGate;
36
+ assert.equal(responseStatus, 200);
37
+ await assert.rejects(kernel.close(2), /notification background drain timed out/);
38
+ assert.equal(completed, false);
39
+ const pendingClose = kernel.close(1000);
40
+ release(); await pendingClose;
41
+ assert.equal(completed, true);
42
+ const records = (await readFile(cfg.state.jsonlPath, 'utf8')).trim().split('\n').map(line => JSON.parse(line));
43
+ assert.equal(records.filter(x => x.kind === 'job').at(-1).job.status, 'done');
44
+ assert.equal(records.filter(x => x.kind === 'audit' && x.entry.event === 'callback').length, 1);
45
+ await kernel.close(0);
46
+ } finally {
47
+ release(); await kernel.close(1000); globalThis.fetch = originalFetch; await rm(dir, { recursive: true, force: true });
48
+ }
49
+ });
package/src/app/kernel.ts CHANGED
@@ -5,6 +5,7 @@ import { bootstrapInitialAdmin } from './admin-bootstrap';
5
5
  import type { Principal } from './auth';
6
6
  import { channelSendFor } from './channels';
7
7
  import { createEngineRuntime } from './engine';
8
+ import { reconcileApprovalContinuationsFor } from './approval-continuations';
8
9
  import { createBailingHttpServer } from './http-server';
9
10
  import { normalizeHttpMountPath, now, send, serveConsoleFromRoot, sleep } from './http';
10
11
  import { createOperationalMetricsEndpointFor } from './operational-metrics';
@@ -62,6 +63,7 @@ import { handleSendFor, type SendApiDeps } from '../routes/send';
62
63
  import { handleWecomInboundFor, WecomRuntimeState, type WecomApiDeps } from '../routes/wecom';
63
64
  import { WecomAccessTokenCache } from '../adapters/channels/wecom-api';
64
65
  import { DemoDatasetService } from '../services/demo-dataset';
66
+ import { NotificationBackgroundWork, bindNotificationBackgroundWork } from '../core/runtime/notification-background-work';
65
67
 
66
68
  const timezoneClaims = new Map<string, number>();
67
69
  const MAX_KERNEL_CLOSE_DRAIN_MS = 10 * 60_000;
@@ -183,6 +185,11 @@ export function createBailingHubKernel(input: CreateBailingHubKernelInputV1): Ba
183
185
  composition.cfgStore?.usage?.backgroundWork.setFailureReporter(kind => {
184
186
  logger.warn?.(`[Kernel ${instanceKey}] usage background ${kind} failed; original durable evidence is retained`);
185
187
  });
188
+ const notificationWork = new NotificationBackgroundWork();
189
+ bindNotificationBackgroundWork(composition.store, notificationWork);
190
+ notificationWork.setFailureReporter(kind => {
191
+ logger.warn?.(`[Kernel ${instanceKey}] notification background ${kind} failed`);
192
+ });
186
193
  const demoDataset = composition.cfgStore ? new DemoDatasetService(composition.cfgStore, cfg.demoDataset) : null;
187
194
  const runtimeHelpers = createRuntimeContextHelpers({
188
195
  cfg,
@@ -234,6 +241,15 @@ export function createBailingHubKernel(input: CreateBailingHubKernelInputV1): Ba
234
241
  now,
235
242
  sleep,
236
243
  targetRegistry,
244
+ reconcileApprovalContinuations: async () => {
245
+ await reconcileApprovalContinuationsFor({
246
+ configStore: composition.cfgStore,
247
+ stateStore: composition.store,
248
+ engineRuntime: engine,
249
+ now,
250
+ isClosing: () => closing || closed,
251
+ });
252
+ },
237
253
  afterStoresInitialized: !localAdminManagement || input.bootstrapLocalAdmin === false
238
254
  ? undefined
239
255
  : async () => { await bootstrapInitialAdmin(cfg.bootstrapAdmin, { admins: composition.cfgStore?.admins ?? null }); },
@@ -248,6 +264,7 @@ export function createBailingHubKernel(input: CreateBailingHubKernelInputV1): Ba
248
264
  isPaused,
249
265
  auditFailures: edition.auditFailures,
250
266
  logger,
267
+ notificationWork,
251
268
  });
252
269
 
253
270
  const runDeps: RunApiDeps = {
@@ -465,6 +482,9 @@ export function createBailingHubKernel(input: CreateBailingHubKernelInputV1): Ba
465
482
  if (!initializedWithinBudget) throw new Error(`Kernel ${instanceKey} initialization drain timed out`);
466
483
  }
467
484
  schedulers?.stop();
485
+ if (schedulers?.drain && !await schedulers.drain(remainingDrainMs())) {
486
+ throw new Error(`Kernel ${instanceKey} persisted evidence maintenance drain timed out`);
487
+ }
468
488
  schedulers = null;
469
489
  if (bootRecoveryTimer) clearTimeout(bootRecoveryTimer);
470
490
  bootRecoveryTimer = null;
@@ -492,6 +512,8 @@ export function createBailingHubKernel(input: CreateBailingHubKernelInputV1): Ba
492
512
  usageWork.beginDrain();
493
513
  if (!await usageWork.drain(remainingDrainMs())) throw new Error(`Kernel ${instanceKey} usage background drain timed out`);
494
514
  }
515
+ notificationWork.beginDrain();
516
+ if (!await notificationWork.drain(remainingDrainMs())) throw new Error(`Kernel ${instanceKey} notification background drain timed out`);
495
517
  targetRegistry.bindStore(null);
496
518
  wecomRuntimeState.dispose();
497
519
  wecomAccessTokenCache.dispose();
@@ -0,0 +1,53 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import type { AppConfig } from '../core/config/config';
4
+ import type { Job } from '../core/contracts/types';
5
+ import type { RuntimeStateStore } from '../core/state/state-contracts';
6
+ import type { ConfigStoreContract } from '../infrastructure/config/configstore';
7
+ import { notificationBackgroundWorkFor } from '../core/runtime/notification-background-work';
8
+ import { finishJob } from '../core/runtime/finish-runtime';
9
+ import { approvalDepsForStores } from './tool-approvals';
10
+ import { spawnDeliveryJobFor } from './delivery';
11
+ import { outboundRuntimeDepsFor, sendAlertWithDeps } from './outbound';
12
+
13
+ const cfg = { server: { token: 'synthetic-only' }, brand: { name: 'Synthetic' }, alerts: null } as AppConfig;
14
+ const now = () => new Date().toISOString();
15
+ const job: Job = { job_id: 'fixture', request_id: 'fixture', status: 'done', source: 'test', profile: 'fixture', project: '',
16
+ input_preview: '', created_at: now(), updated_at: now(), result: { text: 'synthetic' }, metadata: {} };
17
+
18
+ for (const kind of ['delivery', 'approval', 'alert'] as const) test(`notification tracker retains innermost detached ${kind} webhook`, async () => {
19
+ const originalFetch = globalThis.fetch;
20
+ let release!: () => void, started!: () => void;
21
+ const gate = new Promise<void>(resolve => { release = resolve; });
22
+ const startedGate = new Promise<void>(resolve => { started = resolve; });
23
+ globalThis.fetch = async () => { started(); await gate; return new Response('', { status: 200 }); };
24
+ const state = { appendAudit: async () => {} } as unknown as RuntimeStateStore;
25
+ const work = notificationBackgroundWorkFor(state);
26
+ try {
27
+ if (kind === 'delivery') await spawnDeliveryJobFor({ cfg, configStore: null, stateStore: state, now, sleep: async () => {} },
28
+ { ...job, dispatch: { delivery: { type: 'webhook', url: 'https://synthetic.invalid/delivery' } } });
29
+ if (kind === 'approval') {
30
+ const approvals = approvalDepsForStores({ approvals: {} } as ConfigStoreContract, state, job, { name: 'fixture' } as any,
31
+ { approval: { type: 'business_webhook', url: 'https://synthetic.invalid/approval' } }, { provider: 'fixture', allow: ['*'] }, cfg, now, async () => {});
32
+ await approvals!.notify(1, { tool: 'fixture', scope: 'fixture', risk: 'high', policy: 'always', reason: 'fixture', method: 'POST', path: '/', args_hash: 'fixture', args_json: '{}' });
33
+ }
34
+ if (kind === 'alert') await sendAlertWithDeps(outboundRuntimeDepsFor({ cfg: { ...cfg, alerts: { type: 'webhook', url: 'https://synthetic.invalid/alert', cooldown_min: 0 } },
35
+ configStore: null, stateStore: state, now, sleep: async () => {} }), 'fixture', 'synthetic');
36
+ await startedGate;
37
+ work.beginDrain(); assert.equal(await work.drain(1), false);
38
+ release(); assert.equal(await work.drain(100), true);
39
+ } finally { release(); await work.drain(100); globalThis.fetch = originalFetch; }
40
+ });
41
+
42
+ test('finish tracks a DLQ insertion through drain and reports a failed insert', async () => {
43
+ const state = { updateJob: async (_id: string, patch: Partial<Job>) => ({ ...job, ...patch }), appendAudit: async () => {} };
44
+ const work = notificationBackgroundWorkFor(state);
45
+ const failures: string[] = []; work.setFailureReporter(kind => failures.push(kind));
46
+ let release!: () => void;
47
+ const gate = new Promise<void>(resolve => { release = resolve; });
48
+ await finishJob({ ...job, source: 'delivery', target: 'sms-notify' }, { status: 'error' }, { store: state, now,
49
+ fireCallback: async () => {}, spawnDeliveryJob: async () => {}, sendAlert: async () => {},
50
+ deliveryDlq: { async record() { await gate; throw new Error('private SQL error'); } } });
51
+ assert.equal(await work.drain(1), false); release(); assert.equal(await work.drain(100), true);
52
+ assert.ok(failures.includes('delivery-dlq'));
53
+ });
@@ -3,7 +3,8 @@ import test from 'node:test';
3
3
  import type { AppConfig } from '../core/config/config';
4
4
  import type { RuntimeStateStore } from '../core/state/state-contracts';
5
5
  import type { ConfigStoreContract } from '../infrastructure/config/configstore';
6
- import { createOperationalMetricsEndpointFor } from './operational-metrics';
6
+ import { createOperationalMetricsEndpointFor, type OperationalMetricsDeps } from './operational-metrics';
7
+ import { UsageRepository } from '../modules/usage/repository';
7
8
 
8
9
  const metrics = {
9
10
  enabled: true,
@@ -15,6 +16,7 @@ function endpoint(input: {
15
16
  store: RuntimeStateStore;
16
17
  configStore?: ConfigStoreContract | null;
17
18
  logger?: Pick<Console, 'error'>;
19
+ notificationWork?: OperationalMetricsDeps['notificationWork'];
18
20
  }) {
19
21
  return createOperationalMetricsEndpointFor({
20
22
  cfg: { root: process.cwd(), metrics } as Pick<AppConfig, 'root' | 'metrics'>,
@@ -24,6 +26,7 @@ function endpoint(input: {
24
26
  isPaused: () => false,
25
27
  auditFailures: { snapshot: () => ({ total: 3, lastFailureAt: null }) },
26
28
  logger: input.logger,
29
+ notificationWork: input.notificationWork,
27
30
  build: { version: 'test', commit: 'abc123' },
28
31
  });
29
32
  }
@@ -71,3 +74,36 @@ test('operational metrics: a stalled collector is bounded by the configured time
71
74
  assert.match(text, /bailinghub_metrics_collector_success\{collector="state"\} 0/);
72
75
  assert.match(logs[0]!, /"failure":"timeout"/);
73
76
  });
77
+
78
+ test('maintenance scrape reads in-memory usage and notification snapshots without database or provider work', async () => {
79
+ let reads = 0, snapshots = 0;
80
+ const usage = new UsageRepository(() => { reads++; throw new Error('No SQL or provider calls during maintenance scrape'); });
81
+ const configStore = { usage, observability: {} } as unknown as ConfigStoreContract;
82
+ const target = endpoint({ store: {} as RuntimeStateStore, configStore, notificationWork: { snapshot() {
83
+ snapshots++;
84
+ return { draining: false, drainTimeouts: 0, kinds: [{ kind: 'callback', inFlight: 1, completed: 2, failed: 3,
85
+ oldestPendingAgeMs: 1000, lastStartedAt: null, lastCompletedAt: null, lastFailedAt: null }] };
86
+ } } });
87
+ const text = await target.scrape();
88
+ assert.equal(reads, 0);
89
+ assert.equal(snapshots, 1);
90
+ assert.match(text, /bailinghub_metrics_collector_success\{collector="maintenance"\} 1/);
91
+ assert.match(text, /bailinghub_background_work_in_flight\{source="notification",kind="callback"\} 1/);
92
+ assert.match(text, /bailinghub_background_work_in_flight\{source="usage",kind="settlement"\} 0/);
93
+ assert.doesNotMatch(text, /bailinghub_maintenance_last_page_records/); // No billing page was initialized by the scrape.
94
+ });
95
+
96
+ test('maintenance snapshot failures leave existing metrics available and redact raw errors', async () => {
97
+ const logs: string[] = [];
98
+ const text = await endpoint({ store: {} as RuntimeStateStore,
99
+ notificationWork: { snapshot() { throw new Error('PRIVATE_TENANT_ACCOUNT_JOB_ROUTE_PROMPT_TOKEN_BODY'); } },
100
+ logger: { error(message) { logs.push(message); } },
101
+ }).scrape();
102
+ assert.match(text, /bailinghub_up 1/);
103
+ assert.match(text, /bailinghub_runtime_queue\{state="running"\} 1/);
104
+ assert.match(text, /bailinghub_metrics_collector_success\{collector="maintenance"\} 0/);
105
+ assert.doesNotMatch(text, /bailinghub_background_work_in_flight/);
106
+ assert.equal(logs.length, 1);
107
+ assert.match(logs[0]!, /"collector":"maintenance"/);
108
+ assert.doesNotMatch(logs[0]!, /PRIVATE|TENANT|ACCOUNT|JOB|ROUTE|PROMPT|TOKEN|BODY/);
109
+ });