bailinghub 0.9.1 → 0.9.2

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 (74) 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 +12 -1
  5. package/docs/CHANGELOG.md +12 -1
  6. package/docs/CORE_RELIABILITY.en.md +59 -0
  7. package/docs/CORE_RELIABILITY.md +59 -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 +22 -14
  11. package/docs/IMPLEMENTATION_STATUS.md +23 -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/README.en.md +5 -0
  21. package/docs/README.md +5 -0
  22. package/docs/RELEASE_NOTES_v0.9.2.en.md +45 -0
  23. package/docs/RELEASE_NOTES_v0.9.2.md +45 -0
  24. package/docs/UPGRADE_v0.9.2.en.md +62 -0
  25. package/docs/UPGRADE_v0.9.2.md +62 -0
  26. package/package.json +7 -3
  27. package/scripts/check-doc-links.mjs +2 -0
  28. package/scripts/check-image-tags.sh +1 -1
  29. package/scripts/check-release-consistency.test.mjs +2 -2
  30. package/scripts/doctor-deployment.test.ts +419 -0
  31. package/scripts/doctor-deployment.ts +357 -0
  32. package/scripts/doctor.ts +8 -1
  33. package/scripts/install-secrets.test.mjs +185 -0
  34. package/scripts/install.sh +10 -6
  35. package/scripts/publish-images.sh +1 -1
  36. package/scripts/release-audit.mjs +4 -0
  37. package/scripts/verify-github-repo.mjs +4 -0
  38. package/sql/065_usage_reconciliation_scan.sql +4 -0
  39. package/sql/066_approval_continuations.sql +15 -0
  40. package/sql/README.md +9 -0
  41. package/src/app/approval-continuations.mysql.test.ts +138 -0
  42. package/src/app/approval-continuations.test.ts +325 -0
  43. package/src/app/approval-continuations.ts +107 -0
  44. package/src/app/http-server.ts +3 -0
  45. package/src/app/kernel-model-process-crash.mysql.test.ts +377 -0
  46. package/src/app/kernel.ts +13 -0
  47. package/src/app/runtime-evidence-maintenance.test.ts +55 -0
  48. package/src/app/runtime-lifecycle-default.ts +7 -0
  49. package/src/app/runtime-lifecycle.ts +39 -0
  50. package/src/core/contracts/approval-continuation.ts +43 -0
  51. package/src/core/contracts/types.ts +2 -0
  52. package/src/core/state/approval-continuation.ts +22 -0
  53. package/src/core/state/state-codec.ts +1 -0
  54. package/src/core/state/state-contracts.ts +3 -0
  55. package/src/infrastructure/config/config-approval-ledger.ts +75 -0
  56. package/src/infrastructure/config/configstore.ts +2 -2
  57. package/src/infrastructure/state/state-jsonl.ts +41 -11
  58. package/src/infrastructure/state/state-mysql.ts +27 -0
  59. package/src/modules/usage/billing-reconciliation.mysql.test.ts +163 -0
  60. package/src/modules/usage/billing-reconciliation.test.ts +71 -0
  61. package/src/modules/usage/billing-repository.ts +54 -11
  62. package/src/modules/usage/maintenance.test.ts +62 -0
  63. package/src/modules/usage/maintenance.ts +31 -0
  64. package/src/modules/usage/model-gateway.ts +2 -1
  65. package/src/routes/admin-default.ts +2 -2
  66. package/src/routes/admin-runtime-default.ts +2 -2
  67. package/src/routes/admin-runtime.test.ts +1 -1
  68. package/src/routes/admin-runtime.ts +25 -18
  69. package/src/routes/admin.ts +1 -1
  70. package/src/routes/approvals-default.ts +2 -2
  71. package/src/routes/approvals.ts +30 -33
  72. package/src/routes/critical-routes.test.ts +16 -3
  73. package/src/test-support/approval-continuation-crash-child.ts +24 -0
  74. 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
+ });
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';
@@ -234,6 +235,15 @@ export function createBailingHubKernel(input: CreateBailingHubKernelInputV1): Ba
234
235
  now,
235
236
  sleep,
236
237
  targetRegistry,
238
+ reconcileApprovalContinuations: async () => {
239
+ await reconcileApprovalContinuationsFor({
240
+ configStore: composition.cfgStore,
241
+ stateStore: composition.store,
242
+ engineRuntime: engine,
243
+ now,
244
+ isClosing: () => closing || closed,
245
+ });
246
+ },
237
247
  afterStoresInitialized: !localAdminManagement || input.bootstrapLocalAdmin === false
238
248
  ? undefined
239
249
  : async () => { await bootstrapInitialAdmin(cfg.bootstrapAdmin, { admins: composition.cfgStore?.admins ?? null }); },
@@ -465,6 +475,9 @@ export function createBailingHubKernel(input: CreateBailingHubKernelInputV1): Ba
465
475
  if (!initializedWithinBudget) throw new Error(`Kernel ${instanceKey} initialization drain timed out`);
466
476
  }
467
477
  schedulers?.stop();
478
+ if (schedulers?.drain && !await schedulers.drain(remainingDrainMs())) {
479
+ throw new Error(`Kernel ${instanceKey} persisted evidence maintenance drain timed out`);
480
+ }
468
481
  schedulers = null;
469
482
  if (bootRecoveryTimer) clearTimeout(bootRecoveryTimer);
470
483
  bootRecoveryTimer = null;
@@ -0,0 +1,55 @@
1
+ import assert from 'node:assert/strict';
2
+ import test from 'node:test';
3
+ import type { AppConfig } from '../core/config/config';
4
+ import type { RuntimeStateStore } from '../core/state/state-contracts';
5
+ import { startRuntimeSchedulersFor, type RuntimeLifecycleDeps } from './runtime-lifecycle';
6
+
7
+ function deps(reconcileApprovalContinuations: () => Promise<void>): RuntimeLifecycleDeps {
8
+ return {
9
+ cfg: { auditRetentionDays: 0 } as AppConfig,
10
+ configStore: null, stateStore: {} as RuntimeStateStore,
11
+ kbService: null, kbSync: null, toolIndex: null,
12
+ isPaused: () => false, refreshTargets: async () => {},
13
+ kickInhubScheduler() {}, drainInhubScheduler: async () => 0,
14
+ recoverInhubJobs: async () => 0,
15
+ now: () => new Date(0).toISOString(), sleep: async () => {},
16
+ reconcileApprovalContinuations,
17
+ };
18
+ }
19
+
20
+ test('standalone stop preserves unfinished evidence writes across drain timeout and retry', async (t) => {
21
+ let release!: () => void;
22
+ const gate = new Promise<void>(resolve => { release = resolve; });
23
+ let started!: () => void;
24
+ const firstPass = new Promise<void>(resolve => { started = resolve; });
25
+ let calls = 0;
26
+ let completed = false;
27
+ const schedulers = startRuntimeSchedulersFor(deps(async () => {
28
+ calls++; started(); await gate; completed = true;
29
+ }));
30
+ t.after(() => { schedulers.stop(); release(); });
31
+ // The scheduler's timer is unref'ed; a bounded guard keeps this test alive.
32
+ let guard: ReturnType<typeof setTimeout> | undefined;
33
+ try {
34
+ await Promise.race([firstPass, new Promise<never>((_, reject) => {
35
+ guard = setTimeout(() => reject(new Error('first evidence pass did not start')), 1_000);
36
+ })]);
37
+ } finally { if (guard) clearTimeout(guard); }
38
+ schedulers.stop();
39
+ assert.equal(await schedulers.drain!(1), false);
40
+ assert.equal(completed, false, 'a timeout must not treat a pending write as drained');
41
+ assert.equal(await schedulers.drain!(1), false, 'a retry still observes the original pending write');
42
+ release();
43
+ assert.equal(await schedulers.drain!(1_000), true);
44
+ assert.equal(completed, true);
45
+ assert.equal(calls, 1);
46
+ });
47
+
48
+ test('standalone stop before the first timer admits no persisted evidence work', async () => {
49
+ let calls = 0;
50
+ const schedulers = startRuntimeSchedulersFor(deps(async () => { calls++; }));
51
+ schedulers.stop();
52
+ await new Promise<void>(resolve => setTimeout(resolve, 5));
53
+ assert.equal(calls, 0);
54
+ assert.equal(await schedulers.drain!(1), true);
55
+ });
@@ -12,6 +12,7 @@ import {
12
12
  type RuntimeSchedulers,
13
13
  } from './runtime-lifecycle';
14
14
  import { bootstrapInitialAdmin } from './admin-bootstrap';
15
+ import { reconcileApprovalContinuationsFor } from './approval-continuations';
15
16
 
16
17
  export function defaultRuntimeLifecycleDeps(): RuntimeLifecycleDeps {
17
18
  return {
@@ -29,6 +30,12 @@ export function defaultRuntimeLifecycleDeps(): RuntimeLifecycleDeps {
29
30
  now,
30
31
  sleep,
31
32
  targetRegistry,
33
+ reconcileApprovalContinuations: async () => {
34
+ await reconcileApprovalContinuationsFor({
35
+ configStore: cfgStore, stateStore: store,
36
+ engineRuntime: { kickInhubScheduler }, now,
37
+ });
38
+ },
32
39
  afterStoresInitialized: async () => {
33
40
  await bootstrapInitialAdmin(cfg.bootstrapAdmin, { admins: cfgStore?.admins ?? null });
34
41
  },
@@ -12,6 +12,7 @@ import type { KbService } from '../services/kb';
12
12
  import type { KbSyncService } from '../services/kbsync';
13
13
  import type { ToolIndexService } from '../services/tools-index';
14
14
  import { embedConfigOf } from './tool-context';
15
+ import { runUsageMaintenanceFor } from '../modules/usage/maintenance';
15
16
 
16
17
  const TARGET_REFRESH_MS = 60_000;
17
18
  const INHUB_DRAIN_MS = 500;
@@ -23,6 +24,8 @@ const REAPER_INTERVAL_MS = 60_000;
23
24
  const TOOL_CALL_CLEANUP_MS = 60 * 60 * 1000;
24
25
  const AUDIT_RETENTION_CLEANUP_MS = 6 * 60 * 60 * 1000;
25
26
  const TOOL_INDEX_PREWARM_DELAY_MS = 0;
27
+ const USAGE_MAINTENANCE_MS = 60_000;
28
+ const APPROVAL_CONTINUATION_MS = 60_000;
26
29
 
27
30
  // 兜底:定期把派发后长时间未回报的 dispatched 任务重排回队列(执行器/网络异常时不至于卡死)。
28
31
  // 阈值需大于最长任务耗时(出厂能力档上限 6min),这里取 20min。
@@ -36,6 +39,8 @@ const TOOL_CALL_RETENTION_MS = 3 * 24 * 60 * 60 * 1000;
36
39
 
37
40
  export interface RuntimeSchedulers {
38
41
  stop(): void;
42
+ /** New persisted-evidence maintenance must finish before its stores close. */
43
+ drain?(drainMs?: number): Promise<boolean>;
39
44
  }
40
45
 
41
46
  export interface RuntimeLifecycleDeps {
@@ -53,6 +58,8 @@ export interface RuntimeLifecycleDeps {
53
58
  now: () => string;
54
59
  sleep: (ms: number) => Promise<void>;
55
60
  afterStoresInitialized?: () => Promise<void>;
61
+ /** Reconcile already-decided approvals; never creates a new user decision. */
62
+ reconcileApprovalContinuations?: () => Promise<void>;
56
63
  /** 可嵌入宿主必须注入 Kernel 自己的 registry;默认实例仅服务旧 OSS 包装。 */
57
64
  targetRegistry?: TargetRegistry;
58
65
  }
@@ -117,6 +124,8 @@ async function runToolIndexPrewarmFor(deps: RuntimeLifecycleDeps): Promise<void>
117
124
  }
118
125
 
119
126
  interface RuntimeMaintenanceActions {
127
+ reconcileUsage(): Promise<void>;
128
+ reconcileApprovals(): Promise<void>;
120
129
  prewarmToolIndexes(): Promise<void>;
121
130
  refreshTargets(): Promise<void>;
122
131
  drainInhub(maxClaims?: number): Promise<number>;
@@ -135,6 +144,8 @@ interface RuntimeMaintenanceActions {
135
144
  */
136
145
  function runtimeMaintenanceActionsFor(deps: RuntimeLifecycleDeps): RuntimeMaintenanceActions {
137
146
  return {
147
+ reconcileUsage: () => runUsageMaintenanceFor(deps.configStore?.usage ?? null),
148
+ reconcileApprovals: () => deps.reconcileApprovalContinuations?.() ?? Promise.resolve(),
138
149
  prewarmToolIndexes: () => runToolIndexPrewarmFor(deps),
139
150
  async refreshTargets() {
140
151
  await deps.refreshTargets();
@@ -298,6 +309,10 @@ export function createManagedRuntimeMaintenanceFor(
298
309
  const tasks: ManagedMaintenanceTask[] = [
299
310
  // Prewarm is per Kernel cache, so it must run again after an eviction.
300
311
  scheduled('tool-index-prewarm', 0, null, actions.prewarmToolIndexes, false),
312
+ // New Kernel owners reconcile saved evidence on their first existing tick.
313
+ // Neither task sends provider requests or restores client orchestration.
314
+ scheduled('usage-maintenance', 0, USAGE_MAINTENANCE_MS, actions.reconcileUsage, false),
315
+ scheduled('approval-continuations', 0, APPROVAL_CONTINUATION_MS, actions.reconcileApprovals, false),
301
316
  scheduled('boot-recovery', 2_000, null, actions.recoverBoot),
302
317
  scheduled('target-refresh', TARGET_REFRESH_MS, TARGET_REFRESH_MS, actions.refreshTargets),
303
318
  scheduled('monitor', MONITOR_DELAY_MS, MONITOR_INTERVAL_MS, actions.monitor),
@@ -378,6 +393,14 @@ export function createManagedRuntimeMaintenanceFor(
378
393
  export function startRuntimeSchedulersFor(deps: RuntimeLifecycleDeps): RuntimeSchedulers {
379
394
  const actions = runtimeMaintenanceActionsFor(deps);
380
395
  const timers: Array<ReturnType<typeof setInterval> | ReturnType<typeof setTimeout>> = [];
396
+ const evidenceWork = new Set<Promise<void>>();
397
+ let stopped = false;
398
+ function reconcile(action: () => Promise<void>): void {
399
+ if (stopped) return;
400
+ const work = Promise.resolve().then(action);
401
+ evidenceWork.add(work);
402
+ void work.finally(() => evidenceWork.delete(work)).catch(() => undefined);
403
+ }
381
404
  const every = (fn: () => void, ms: number): void => {
382
405
  const timer = setInterval(fn, ms);
383
406
  timer.unref();
@@ -391,6 +414,10 @@ export function startRuntimeSchedulersFor(deps: RuntimeLifecycleDeps): RuntimeSc
391
414
 
392
415
  // 服务先启动,索引随后在后台预热;任何数据库/索引异常都不阻塞 HTTP 就绪。
393
416
  later(() => void actions.prewarmToolIndexes(), TOOL_INDEX_PREWARM_DELAY_MS);
417
+ later(() => reconcile(actions.reconcileUsage), 0);
418
+ later(() => reconcile(actions.reconcileApprovals), 0);
419
+ every(() => reconcile(actions.reconcileUsage), USAGE_MAINTENANCE_MS);
420
+ every(() => reconcile(actions.reconcileApprovals), APPROVAL_CONTINUATION_MS);
394
421
 
395
422
  every(() => void actions.refreshTargets().catch(() => undefined), TARGET_REFRESH_MS);
396
423
 
@@ -424,8 +451,20 @@ export function startRuntimeSchedulersFor(deps: RuntimeLifecycleDeps): RuntimeSc
424
451
 
425
452
  return {
426
453
  stop() {
454
+ stopped = true;
427
455
  for (const timer of timers.splice(0)) clearTimeout(timer);
428
456
  },
457
+ async drain(drainMs = 30_000) {
458
+ if (evidenceWork.size === 0) return true;
459
+ const bounded = Number.isFinite(drainMs) ? Math.max(0, Math.floor(drainMs)) : 0;
460
+ let timer: ReturnType<typeof setTimeout> | undefined;
461
+ try {
462
+ return await Promise.race([
463
+ Promise.allSettled([...evidenceWork]).then(() => true),
464
+ new Promise<boolean>(resolve => { timer = setTimeout(() => resolve(false), bounded); }),
465
+ ]);
466
+ } finally { if (timer) clearTimeout(timer); }
467
+ },
429
468
  };
430
469
  }
431
470
 
@@ -0,0 +1,43 @@
1
+ /** Trusted decision coordinates, independent of business metadata and model input. */
2
+ export interface ApprovalContinuation {
3
+ schema_version: 'bailing.approval-continuation.v1';
4
+ approval_id: number;
5
+ decision_key: string;
6
+ decision_id?: string;
7
+ decision: 'approved' | 'denied';
8
+ job_id: string;
9
+ request_id: string;
10
+ args_hash: string;
11
+ tool: string;
12
+ scope: string;
13
+ by: string;
14
+ source: 'external' | 'console';
15
+ auth: string;
16
+ mode: 'rerun' | 'manual';
17
+ policy?: string;
18
+ reason?: string;
19
+ summary?: string;
20
+ comment?: string;
21
+ audit_recorded: boolean;
22
+ completed: boolean;
23
+ }
24
+
25
+ export interface ApprovalContinuationDecisionOptions {
26
+ decision_id?: string;
27
+ comment?: string;
28
+ source: 'external' | 'console';
29
+ auth: string;
30
+ mode: 'rerun' | 'manual';
31
+ }
32
+
33
+ export interface ApprovalRequeueInput {
34
+ job_id: string;
35
+ request_id: string;
36
+ approval_id: number;
37
+ decision_key: string;
38
+ decision_id?: string;
39
+ /** JSONL adapter rechecks this after seeing a terminal job under its single-writer lock. */
40
+ isApprovedUnused?: () => Promise<boolean>;
41
+ }
42
+
43
+ export type ApprovalRequeueOutcome = 'queued' | 'already_queued' | 'in_flight' | 'consumed' | 'missing' | 'conflict';
@@ -32,6 +32,8 @@ export interface Job {
32
32
  usage?: { duration_ms?: number; num_turns?: number; cost_usd?: number; tokens?: number };
33
33
  error?: string;
34
34
  metadata: Record<string, unknown>;
35
+ /** Core-owned durable queue admissions; ordinary updates must preserve these keys. */
36
+ approval_continuation_keys?: Record<string, string>;
35
37
  callback_url?: string;
36
38
  // 远端执行器派活相关(含 route 快照:route 之后可能改/删,故落到 job 上);kb_refs=知识检索命中快照(引用来源回流)
37
39
  // user_images/user_audio/user_files=用户原始输入里的媒体 URL 快照(只取用户发的,不含知识库注入资产);多模态适配器据此送模型,rerun 也能复现