bailinghub 0.9.0 → 0.9.1
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.
- package/.dockerignore +6 -0
- package/.npmignore +6 -0
- package/CONTRIBUTING.md +4 -0
- package/GOVERNANCE.md +9 -0
- package/README.en.md +7 -6
- package/README.md +7 -6
- package/SECURITY.md +8 -2
- package/THIRD_PARTY_NOTICES.md +17 -17
- package/docker-compose.images.yml +2 -2
- package/docs/CHANGELOG.en.md +11 -1
- package/docs/CHANGELOG.md +11 -1
- package/docs/COMPATIBILITY.en.md +4 -0
- package/docs/IMPLEMENTATION_STATUS.en.md +73 -0
- package/docs/IMPLEMENTATION_STATUS.md +73 -0
- package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
- package/docs/INDEPENDENT_VALIDATION.md +4 -4
- package/docs/KERNEL_HOST_API.en.md +18 -0
- package/docs/KERNEL_HOST_API.md +18 -0
- package/docs/README.en.md +3 -0
- package/docs/README.md +3 -0
- package/docs/RELEASE_NOTES_NEXT.en.md +3 -3
- package/docs/RELEASE_NOTES_NEXT.md +3 -3
- package/docs/RELEASE_NOTES_v0.9.1.en.md +38 -0
- package/docs/RELEASE_NOTES_v0.9.1.md +38 -0
- package/docs/UPGRADE_v0.9.1.en.md +39 -0
- package/docs/UPGRADE_v0.9.1.md +39 -0
- package/docs//345/205/274/345/256/271/346/200/247/344/270/216/345/215/207/347/272/247.md +4 -0
- package/package.json +5 -4
- package/scripts/check-doc-links.mjs +2 -0
- package/scripts/check-image-tags.sh +1 -1
- package/scripts/check-release-consistency.test.mjs +2 -2
- package/scripts/dependency-audit.mjs +134 -0
- package/scripts/dependency-audit.test.mjs +125 -0
- package/scripts/install.sh +1 -1
- package/scripts/osps-results.py +114 -0
- package/scripts/publish-images.sh +1 -1
- package/scripts/release-audit.mjs +1 -0
- package/scripts/verify-github-repo.mjs +1 -0
- package/security/dependency-audit-exceptions.json +192 -0
- package/src/app/kernel-usage-lifecycle.mysql.test.ts +325 -0
- package/src/app/kernel.ts +10 -0
- package/src/modules/usage/background-work.test.ts +144 -0
- package/src/modules/usage/background-work.ts +50 -0
- package/src/modules/usage/billing-repository.ts +6 -4
- package/src/modules/usage/model-gateway.ts +10 -3
- package/src/modules/usage/model-tool-gateway.mysql.test.ts +1 -1
- package/src/modules/usage/pricing.ts +3 -2
- package/src/modules/usage/repository.ts +2 -0
- package/src/modules/usage/test-harness.ts +2 -1
- package/web/console/assets/{Accounts-DnddhY6t.js → Accounts-DKhw_QLr.js} +1 -1
- package/web/console/assets/{AgentClients-VInbD7JS.js → AgentClients-CM4_5HaA.js} +1 -1
- package/web/console/assets/{AgentTasks-B-1XklBg.js → AgentTasks-CkQgZTU5.js} +1 -1
- package/web/console/assets/{Approvals-34qUPHf0.js → Approvals-B9O9TkbO.js} +1 -1
- package/web/console/assets/{Audit-BbVgkSm2.js → Audit-2vDC1SPu.js} +1 -1
- package/web/console/assets/{BrandLockup-DgscF28e.js → BrandLockup-BgASiRSE.js} +1 -1
- package/web/console/assets/{Channels-Bp-yuk8d.js → Channels-A-GvkNBt.js} +1 -1
- package/web/console/assets/{ChatEntries-C9Ft60TS.js → ChatEntries-BLxymI67.js} +1 -1
- package/web/console/assets/{Clients-NPldD-DD.js → Clients-DeNlmvS6.js} +1 -1
- package/web/console/assets/{Cost-DZcuB-EB.js → Cost-CBq_L4Kz.js} +1 -1
- package/web/console/assets/{Credentials-RTT7N6zl.js → Credentials-DmtbctNj.js} +1 -1
- package/web/console/assets/{Diagnostics-_LeK8cce.js → Diagnostics-BbcRDiA-.js} +1 -1
- package/web/console/assets/{Executors-Bi7H8rIm.js → Executors-gGgmQrDt.js} +1 -1
- package/web/console/assets/{HelpTip-BfyWrxCE.js → HelpTip-Dtdt2tKR.js} +1 -1
- package/web/console/assets/{Kb-BHamz8NP.js → Kb-lgY6OXUz.js} +2 -2
- package/web/console/assets/{Login-C1rJR-6w.js → Login-DA6BASZd.js} +1 -1
- package/web/console/assets/{Projects-BRA4a48v.js → Projects-DEbmB_sT.js} +1 -1
- package/web/console/assets/{Routes-CTC7U-fQ.js → Routes-qS6LLoyS.js} +1 -1
- package/web/console/assets/{Runs-B_fa_BlD.js → Runs-DG-VLRSc.js} +1 -1
- package/web/console/assets/{Setup-C1_d0mFy.js → Setup-DEpVF5uw.js} +1 -1
- package/web/console/assets/{Shell-CHEV6RGC.js → Shell-DgoPgK1E.js} +1 -1
- package/web/console/assets/{StorageBuckets-DlG3ojhA.js → StorageBuckets-DJtNN769.js} +1 -1
- package/web/console/assets/{SystemSettings-DYo2gg6d.js → SystemSettings-0DEUgeTR.js} +1 -1
- package/web/console/assets/{SystemStatus-DKCoUZlq.js → SystemStatus-CR1phiPE.js} +1 -1
- package/web/console/assets/{Targets-CdkG6BPR.js → Targets-D65l-IMB.js} +1 -1
- package/web/console/assets/{Tools-DVpCt0ox.js → Tools-DqtrINrN.js} +1 -1
- package/web/console/assets/{Usage-DWCpLugC.js → Usage-B5njXNjx.js} +1 -1
- package/web/console/assets/{UsageAccess-B_Xq7ARW.js → UsageAccess-ChnB4pjb.js} +1 -1
- package/web/console/assets/{UsageHelp-t5ZG_f-e.js → UsageHelp-BBKIvbQ5.js} +1 -1
- package/web/console/assets/{index-C6W4LWVV.js → index-65JiiUr4.js} +1 -1
- package/web/console/assets/{index-H1kfa0Mj.js → index-sLKrJd_p.js} +2 -2
- package/web/console/assets/{request-DLsP1_ot.js → request-BpaimqEb.js} +1 -1
- package/web/console/assets/{schema-BLOHvAJQ.js → schema-D0Z4kFCZ.js} +1 -1
- package/web/console/assets/{util-CGVh2Jvr.js → util-DZYfJ5Zo.js} +1 -1
- package/web/console/assets/{vendor-element-BD089KxE.js → vendor-element-8cVcdt5T.js} +1 -1
- package/web/console/assets/{vendor-mammoth-Bv-CZhmH.js → vendor-mammoth-CnDA23N0.js} +1 -1
- package/web/console/assets/vendor-vue-Co7x2FW6.js +29 -0
- package/web/console/index.html +3 -3
- package/web-admin/package-lock.json +83 -85
- package/web/console/assets/vendor-vue-B2uhHUfE.js +0 -29
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import test from 'node:test';
|
|
3
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
4
|
+
import { mkdtempSync, rmSync } from 'node:fs';
|
|
5
|
+
import { tmpdir } from 'node:os';
|
|
6
|
+
import { join } from 'node:path';
|
|
7
|
+
import { createServer } from 'node:http';
|
|
8
|
+
import type { AddressInfo } from 'node:net';
|
|
9
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
10
|
+
import { createPool } from 'mysql2/promise';
|
|
11
|
+
import type { AppConfig } from '../core/config/config';
|
|
12
|
+
import { migrateBailingHubCoreSchema } from '../infrastructure/schema/core-schema-migrator';
|
|
13
|
+
import { UsageRepository } from '../modules/usage/repository';
|
|
14
|
+
import { getUsageIdentity } from '../modules/usage/identity';
|
|
15
|
+
import { BillingRepository, getBillingRepository } from '../modules/usage/billing-repository';
|
|
16
|
+
import { ReferencePricing } from '../modules/usage/pricing';
|
|
17
|
+
import type { BillingRequest } from '../modules/usage/billing-contracts';
|
|
18
|
+
import { createBailingHubKernel } from './kernel';
|
|
19
|
+
|
|
20
|
+
const enabled = process.env.BAILING_USAGE_TEST_MYSQL === '1';
|
|
21
|
+
function gate() {
|
|
22
|
+
let release!: () => void;
|
|
23
|
+
const promise = new Promise<void>(resolve => { release = resolve; });
|
|
24
|
+
return { promise, release };
|
|
25
|
+
}
|
|
26
|
+
async function until(predicate: () => boolean, message: string) {
|
|
27
|
+
for (let i = 0; i < 300; i++) { if (predicate()) return; await delay(10); }
|
|
28
|
+
throw new Error(message);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Fresh loopback schema and synthetic provider; never loads deployment configuration. */
|
|
32
|
+
async function fixture(schedulerMode: 'managed' | 'standalone' = 'managed') {
|
|
33
|
+
const database = `kernel_usage_${randomUUID().replaceAll('-', '')}`;
|
|
34
|
+
const dir = mkdtempSync(join(tmpdir(), 'bailinghub-usage-lifecycle-'));
|
|
35
|
+
const mysql = { host: '127.0.0.1', port: 16307, user: 'root', password: '', connectionLimit: 8 };
|
|
36
|
+
const admin = createPool(mysql);
|
|
37
|
+
const providerGate = gate();
|
|
38
|
+
const cleanup: Array<() => void | Promise<unknown>> = [() => rmSync(dir, { recursive: true, force: true }), () => admin.end()];
|
|
39
|
+
async function dispose() {
|
|
40
|
+
providerGate.release();
|
|
41
|
+
let failed = false;
|
|
42
|
+
for (const release of cleanup.reverse()) { try { await release(); } catch { failed = true; } }
|
|
43
|
+
if (failed) throw new Error('Synthetic Kernel fixture cleanup failed');
|
|
44
|
+
}
|
|
45
|
+
try {
|
|
46
|
+
await admin.query(`CREATE DATABASE \`${database}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_bin`);
|
|
47
|
+
cleanup.push(() => admin.query(`DROP DATABASE \`${database}\``));
|
|
48
|
+
await migrateBailingHubCoreSchema({ mysql: { ...mysql, database }, logger: { log() {}, warn() {} } });
|
|
49
|
+
const pool = createPool({ ...mysql, database });
|
|
50
|
+
cleanup.push(() => pool.end());
|
|
51
|
+
const repository = new UsageRepository(() => pool);
|
|
52
|
+
const state = { calls: 0 };
|
|
53
|
+
const provider = createServer(async (req, res) => {
|
|
54
|
+
for await (const _chunk of req) { /* synthetic input only */ }
|
|
55
|
+
state.calls++;
|
|
56
|
+
await providerGate.promise;
|
|
57
|
+
res.writeHead(200, { 'content-type': 'application/json' });
|
|
58
|
+
res.end(JSON.stringify(req.url === '/v1/chat/completions'
|
|
59
|
+
? { id: 'synthetic-original', choices: [{ index: 0, message: { role: 'assistant', content: 'Synthetic output' }, finish_reason: 'stop' }], usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 } }
|
|
60
|
+
: { id: 'synthetic-original', data: [{ url: 'https://synthetic.invalid/image.png' }], usage: { input_image_count: 0, output_image_count: 1, output_image_type: '1k', output_width: 1024, output_height: 1024 } }));
|
|
61
|
+
});
|
|
62
|
+
cleanup.push(() => { provider.close(); provider.closeAllConnections(); });
|
|
63
|
+
await new Promise<void>(resolve => provider.listen(0, '127.0.0.1', resolve));
|
|
64
|
+
const modelId = 'synthetic/image', endpointId = 'synthetic-provider';
|
|
65
|
+
const price = { source: 'openrouter', modelId, endpointId, currency: 'USD', fetchedAt: Date.now(),
|
|
66
|
+
lines: [{ billable: 'output_image', unit: 'image', costUsd: '0.2', variant: '1k' }] };
|
|
67
|
+
await pool.query('INSERT INTO bz_usage_price_snapshots VALUES(?,?,?)', [
|
|
68
|
+
createHash('sha256').update(`image:${modelId}`).digest('hex'), JSON.stringify({ fetchedAt: Date.now(), items: [{ id: endpointId, pricing: price }] }), Date.now(),
|
|
69
|
+
]);
|
|
70
|
+
const service = await repository.putService({ id: 'synthetic-image', label: 'Synthetic image', expectedRevision: 0, config: {
|
|
71
|
+
credential: 'synthetic', model: 'synthetic-image', providerScope: database, maxInputBytes: 16384, maxOutputTokens: 100, timeoutMs: 10000,
|
|
72
|
+
purpose: 'tool', pricing: { source: 'openrouter', kind: 'image', modelId, endpointId },
|
|
73
|
+
tool: { name: 'generate_image', capability: 'image_generation', description: 'Synthetic image', outputs: ['image'], adapter: 'aliyun-image',
|
|
74
|
+
parameters: [{ name: 'prompt', type: 'string', required: true, description: 'Synthetic input' }] },
|
|
75
|
+
} });
|
|
76
|
+
const identity = getUsageIdentity(repository);
|
|
77
|
+
const chatModelId = 'synthetic/chat';
|
|
78
|
+
const chat = await repository.putService({ id: 'synthetic-chat', label: 'Synthetic chat', expectedRevision: 0, config: {
|
|
79
|
+
...service.config, purpose: 'chat', tool: undefined, pricing: { source: 'openrouter', kind: 'chat', modelId: chatModelId, endpointId },
|
|
80
|
+
} });
|
|
81
|
+
await pool.query('INSERT INTO bz_usage_price_snapshots VALUES(?,?,?)', [createHash('sha256').update(`chat:${chatModelId}`).digest('hex'),
|
|
82
|
+
JSON.stringify({ fetchedAt: Date.now(), items: [{ id: endpointId, pricing: { source: 'openrouter', modelId: chatModelId, endpointId, currency: 'USD', fetchedAt: Date.now(),
|
|
83
|
+
lines: [{ billable: 'prompt', unit: 'token', costUsd: '0.01' }, { billable: 'completion', unit: 'token', costUsd: '0.01' }] } }] }), Date.now()]);
|
|
84
|
+
const issuer = await identity.createIssuer({ id: 'synthetic-product', label: 'Synthetic product', permissions: ['identity:exchange'], service_ids: [service.id, chat.id] });
|
|
85
|
+
const user = await identity.exchange(issuer.credential!, { request_key: randomUUID(), tenant: 'synthetic', subject: 'same-subject', service_id: service.id, model_access: 'token_gateway' });
|
|
86
|
+
const tokens = getBillingRepository(repository);
|
|
87
|
+
await tokens.putPlan({ id: 'synthetic-plan', label: 'Synthetic allowance', expected_revision: 0, config: {
|
|
88
|
+
mode: 'credits', serviceIds: [service.id, chat.id], priceUsd: 100, multiplier: 1, duration: { unit: 'month', count: 1 },
|
|
89
|
+
} });
|
|
90
|
+
await tokens.grant(user.session.accountId, { request_key: 'synthetic-grant', plan_id: 'synthetic-plan', expected_revision: 0 });
|
|
91
|
+
const config: AppConfig = {
|
|
92
|
+
root: process.cwd(), runtimeRoot: dir, env: 'development', server: { host: '127.0.0.1', port: 0, token: '' }, brand: { name: 'Synthetic lifecycle test' },
|
|
93
|
+
displayTz: 'Asia/Shanghai', displayTzLabel: '北京时间', auditRetentionDays: 0, alerts: null, metrics: { enabled: false, token: '', scrapeTimeoutMs: 1000 },
|
|
94
|
+
bootstrapAdmin: null, concurrency: 1, killSwitchFile: join(dir, '.paused'), claudeBin: 'synthetic-unused', defaultProfile: 'readonly', brainDir: join(dir, 'brain'),
|
|
95
|
+
state: { backend: 'mysql', jsonlPath: join(dir, 'jobs.jsonl'), mysql: { ...mysql, database } }, projects: {},
|
|
96
|
+
llmCredentials: { synthetic: { base_url: `http://127.0.0.1:${(provider.address() as AddressInfo).port}/v1`, api_key: 'REPLACE_ME' } },
|
|
97
|
+
executor: { hubUrl: '', token: '', executorId: 'synthetic', targets: [], waitMs: 100, concurrency: 1, labels: [] },
|
|
98
|
+
};
|
|
99
|
+
const warnings: string[] = [];
|
|
100
|
+
const kernel = createBailingHubKernel({ instanceKey: database, config, schedulerMode, bootstrapLocalAdmin: false,
|
|
101
|
+
logger: { log() {}, warn(message) { warnings.push(message); }, error() {} } });
|
|
102
|
+
cleanup.push(() => kernel.close(5000));
|
|
103
|
+
await kernel.initialize();
|
|
104
|
+
const server = createServer((req, res) => { void kernel.handle(req, res).catch(error => res.destroy(error)); });
|
|
105
|
+
cleanup.push(() => { server.close(); server.closeAllConnections(); });
|
|
106
|
+
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
|
|
107
|
+
const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
|
|
108
|
+
async function api(path: string, method = 'GET', body?: unknown) {
|
|
109
|
+
const response = await fetch(base + path, { method, headers: { authorization: `Bearer ${user.credential}`, 'content-type': 'application/json' },
|
|
110
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) }) });
|
|
111
|
+
return { status: response.status, body: await response.json() as Record<string, any> };
|
|
112
|
+
}
|
|
113
|
+
const request = (operationId: string) => api('/usage/v1/model/tools/requests', 'POST', { operation_id: operationId, service_id: service.id, arguments: { prompt: 'Synthetic input' } });
|
|
114
|
+
const chatRequest = (operationId: string) => api('/usage/v1/model/requests', 'POST', { operation_id: operationId, service_id: chat.id, messages: [{ role: 'user', content: 'Synthetic input' }] });
|
|
115
|
+
return { kernel, repository, pool, providerGate, state, request, chatRequest, api, warnings, close: dispose };
|
|
116
|
+
} catch (error) { await dispose().catch(() => {}); throw error; }
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
test('Kernel drains detached model completion and late SQL settlement; timeout retains pool for same-instance retry', { skip: !enabled }, async () => {
|
|
120
|
+
const h = await fixture(), operationId = randomUUID(), settlementGate = gate();
|
|
121
|
+
const prototype = BillingRepository.prototype as unknown as { settleRecorded(r: BillingRequest): Promise<BillingRequest> };
|
|
122
|
+
const original = prototype.settleRecorded;
|
|
123
|
+
let entered = false, kernelRepository: UsageRepository | undefined;
|
|
124
|
+
prototype.settleRecorded = async function (this: BillingRepository, r) {
|
|
125
|
+
if (r.operationId === operationId) { entered = true; kernelRepository = this.repository; await settlementGate.promise; }
|
|
126
|
+
return original.call(this, r);
|
|
127
|
+
};
|
|
128
|
+
try {
|
|
129
|
+
const first = await h.request(operationId);
|
|
130
|
+
assert.equal(first.status, 202); assert.equal(first.body.result_state, 'pending');
|
|
131
|
+
await until(() => h.state.calls === 1, 'Synthetic provider did not start');
|
|
132
|
+
await assert.rejects(h.kernel.close(10), /usage background drain timed out/);
|
|
133
|
+
assert.equal((await h.request(operationId)).status, 503);
|
|
134
|
+
h.providerGate.release();
|
|
135
|
+
await until(() => entered, 'Late settlement did not start');
|
|
136
|
+
await assert.rejects(h.kernel.close(0), /usage background drain timed out/);
|
|
137
|
+
assert.ok(kernelRepository); await kernelRepository.getPool().query('SELECT 1');
|
|
138
|
+
const [before] = await h.pool.query<any[]>('SELECT result_state,billing_state FROM bz_usage_billing_requests');
|
|
139
|
+
assert.equal(before[0].result_state, 'complete'); assert.equal(before[0].billing_state, 'pending');
|
|
140
|
+
settlementGate.release();
|
|
141
|
+
await h.kernel.close(2000);
|
|
142
|
+
const [after] = await h.pool.query<any[]>('SELECT result_state,billing_state FROM bz_usage_billing_requests');
|
|
143
|
+
assert.equal(after[0].result_state, 'complete'); assert.equal(after[0].billing_state, 'settled');
|
|
144
|
+
const [ledger] = await h.pool.query<any[]>('SELECT COUNT(*) n FROM bz_usage_billing_ledger');
|
|
145
|
+
assert.equal(Number(ledger[0].n), 1); assert.equal(h.state.calls, 1);
|
|
146
|
+
} finally { settlementGate.release(); prototype.settleRecorded = original; await h.close(); }
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
test('normal model HTTP delivery does not wait for SQL settlement, but Kernel close does', { skip: !enabled }, async () => {
|
|
150
|
+
const h = await fixture(), operationId = randomUUID(), settlementGate = gate();
|
|
151
|
+
const prototype = BillingRepository.prototype as unknown as { settleRecorded(r: BillingRequest): Promise<BillingRequest> };
|
|
152
|
+
const original = prototype.settleRecorded;
|
|
153
|
+
let entered = false;
|
|
154
|
+
prototype.settleRecorded = async function (this: BillingRepository, r) {
|
|
155
|
+
if (r.operationId === operationId) { entered = true; await settlementGate.promise; }
|
|
156
|
+
return original.call(this, r);
|
|
157
|
+
};
|
|
158
|
+
try {
|
|
159
|
+
h.providerGate.release();
|
|
160
|
+
const response = await h.chatRequest(operationId);
|
|
161
|
+
assert.equal(response.status, 200); assert.equal(response.body.result_state, 'complete'); assert.equal(response.body.billing_state, 'pending');
|
|
162
|
+
await until(() => entered, 'Normal model settlement did not start');
|
|
163
|
+
await assert.rejects(h.kernel.close(10), /usage background drain timed out/);
|
|
164
|
+
settlementGate.release(); await h.kernel.close(2000);
|
|
165
|
+
const [rows] = await h.pool.query<any[]>('SELECT billing_state FROM bz_usage_billing_requests');
|
|
166
|
+
assert.equal(rows[0].billing_state, 'settled'); assert.equal(h.state.calls, 1);
|
|
167
|
+
} finally { settlementGate.release(); prototype.settleRecorded = original; await h.close(); }
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
test('failed background settlement retains original result and durable pending without replaying the provider', { skip: !enabled }, async () => {
|
|
171
|
+
const h = await fixture(), operationId = randomUUID();
|
|
172
|
+
const prototype = BillingRepository.prototype as unknown as { settleRecorded(r: BillingRequest): Promise<BillingRequest> };
|
|
173
|
+
const original = prototype.settleRecorded;
|
|
174
|
+
let fail = true;
|
|
175
|
+
prototype.settleRecorded = async function (this: BillingRepository, r) {
|
|
176
|
+
if (r.operationId === operationId && fail) throw new Error('SYNTHETIC_PRIVATE_ERROR_MUST_NOT_BE_LOGGED');
|
|
177
|
+
return original.call(this, r);
|
|
178
|
+
};
|
|
179
|
+
try {
|
|
180
|
+
assert.equal((await h.request(operationId)).status, 202); h.providerGate.release();
|
|
181
|
+
await until(() => h.warnings.some(x => x.includes('usage background settlement failed')), 'Settlement failure was not observed');
|
|
182
|
+
const recovered = await h.request(operationId);
|
|
183
|
+
assert.equal(recovered.status, 200); assert.equal(recovered.body.result_state, 'complete'); assert.equal(recovered.body.billing_state, 'pending');
|
|
184
|
+
assert.equal(h.warnings.join('\n').includes('SYNTHETIC_PRIVATE_ERROR'), false);
|
|
185
|
+
await h.kernel.close(2000); // pending is persisted work for maintenance, not an active provider or retry permit
|
|
186
|
+
const [before] = await h.pool.query<any[]>('SELECT result_hash,billing_state FROM bz_usage_billing_requests');
|
|
187
|
+
assert.ok(before[0].result_hash); assert.equal(before[0].billing_state, 'pending');
|
|
188
|
+
fail = false;
|
|
189
|
+
await getBillingRepository(h.repository).reconcilePendingUsage();
|
|
190
|
+
const [after] = await h.pool.query<any[]>('SELECT billing_state FROM bz_usage_billing_requests');
|
|
191
|
+
const [ledger] = await h.pool.query<any[]>('SELECT COUNT(*) n FROM bz_usage_billing_ledger');
|
|
192
|
+
assert.equal(after[0].billing_state, 'settled'); assert.equal(Number(ledger[0].n), 1); assert.equal(h.state.calls, 1);
|
|
193
|
+
} finally { prototype.settleRecorded = original; await h.close(); }
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
test('standalone shutdown uses the same Kernel background barrier before exit', { skip: !enabled }, async () => {
|
|
197
|
+
const h = await fixture('standalone');
|
|
198
|
+
let exitCode: number | undefined;
|
|
199
|
+
let standalone: ReturnType<typeof h.kernel.createStandaloneServer> | undefined;
|
|
200
|
+
try {
|
|
201
|
+
standalone = h.kernel.createStandaloneServer({ exit(code) { exitCode = code; } });
|
|
202
|
+
await standalone.start();
|
|
203
|
+
assert.equal((await h.request(randomUUID())).status, 202);
|
|
204
|
+
await until(() => h.state.calls === 1, 'Synthetic provider did not start');
|
|
205
|
+
let finished = false;
|
|
206
|
+
const closing = standalone.shutdown('test').then(() => { finished = true; });
|
|
207
|
+
await delay(20);
|
|
208
|
+
assert.equal(finished, false); assert.equal(exitCode, undefined);
|
|
209
|
+
h.providerGate.release(); await closing;
|
|
210
|
+
assert.equal(exitCode, 0);
|
|
211
|
+
const [rows] = await h.pool.query<any[]>('SELECT billing_state FROM bz_usage_billing_requests');
|
|
212
|
+
assert.equal(rows[0].billing_state, 'settled'); assert.equal(h.state.calls, 1);
|
|
213
|
+
} finally { h.providerGate.release(); await standalone?.shutdown('test'); await h.close(); }
|
|
214
|
+
});
|
|
215
|
+
|
|
216
|
+
test('Kernel waits for a real locked completion transaction before pool close', { skip: !enabled }, async () => {
|
|
217
|
+
const h = await fixture(), operationId = randomUUID();
|
|
218
|
+
const lock = await h.pool.getConnection();
|
|
219
|
+
try {
|
|
220
|
+
assert.equal((await h.request(operationId)).status, 202);
|
|
221
|
+
await until(() => h.state.calls === 1, 'Synthetic provider did not start');
|
|
222
|
+
await lock.beginTransaction();
|
|
223
|
+
await lock.query('SELECT id FROM bz_usage_billing_requests WHERE operation_id=? FOR UPDATE', [operationId]);
|
|
224
|
+
h.providerGate.release();
|
|
225
|
+
await assert.rejects(h.kernel.close(20), /usage background drain timed out/);
|
|
226
|
+
const [pending] = await h.pool.query<any[]>('SELECT result_state FROM bz_usage_billing_requests');
|
|
227
|
+
assert.equal(pending[0].result_state, 'pending');
|
|
228
|
+
await lock.rollback();
|
|
229
|
+
await h.kernel.close(2000);
|
|
230
|
+
const [done] = await h.pool.query<any[]>('SELECT result_state,billing_state FROM bz_usage_billing_requests');
|
|
231
|
+
assert.equal(done[0].result_state, 'complete'); assert.equal(done[0].billing_state, 'settled'); assert.equal(h.state.calls, 1);
|
|
232
|
+
} finally { await lock.rollback(); lock.release(); await h.close(); }
|
|
233
|
+
});
|
|
234
|
+
|
|
235
|
+
test('two Kernels with the same original operation ID own separate background work and pools', { skip: !enabled }, async () => {
|
|
236
|
+
const one = await fixture(), operationId = randomUUID();
|
|
237
|
+
let closeTwo: (() => Promise<void>) | undefined;
|
|
238
|
+
try {
|
|
239
|
+
const two = await fixture(); closeTwo = two.close;
|
|
240
|
+
assert.equal((await one.request(operationId)).status, 202); assert.equal((await two.request(operationId)).status, 202);
|
|
241
|
+
await until(() => one.state.calls === 1 && two.state.calls === 1, 'Synthetic providers did not start');
|
|
242
|
+
await assert.rejects(one.kernel.close(10), /usage background drain timed out/);
|
|
243
|
+
one.providerGate.release();
|
|
244
|
+
await one.kernel.close(2000);
|
|
245
|
+
assert.equal(two.kernel.isClosing(), false);
|
|
246
|
+
assert.equal((await two.request(operationId)).status, 202); assert.equal(two.state.calls, 1);
|
|
247
|
+
const [pending] = await two.pool.query<any[]>('SELECT result_state FROM bz_usage_billing_requests');
|
|
248
|
+
assert.equal(pending[0].result_state, 'pending');
|
|
249
|
+
await assert.rejects(two.kernel.close(10), /usage background drain timed out/);
|
|
250
|
+
two.providerGate.release(); await two.kernel.close(2000);
|
|
251
|
+
for (const h of [one, two]) {
|
|
252
|
+
const [rows] = await h.pool.query<any[]>('SELECT COUNT(*) n FROM bz_usage_billing_ledger');
|
|
253
|
+
assert.equal(Number(rows[0].n), 1); assert.equal(h.state.calls, 1);
|
|
254
|
+
}
|
|
255
|
+
} finally { await one.close(); await closeTwo?.(); }
|
|
256
|
+
});
|
|
257
|
+
|
|
258
|
+
test('Kernel tracks response cleanup, reconciliation and reference-price SQL refresh, and stops new maintenance', { skip: !enabled }, async () => {
|
|
259
|
+
const h = await fixture(), cleanupGate = gate(), reconciliationGate = gate(), priceGate = gate();
|
|
260
|
+
const cleanup = BillingRepository.prototype.cleanupExpiredResponses, reconcile = BillingRepository.prototype.reconcilePendingUsage;
|
|
261
|
+
let kernelRepository: UsageRepository | undefined, cleanupEntered = false, reconcileEntered = false, priceCalls = 0;
|
|
262
|
+
BillingRepository.prototype.cleanupExpiredResponses = async function (now) {
|
|
263
|
+
kernelRepository = this.repository; cleanupEntered = true; await cleanupGate.promise; return cleanup.call(this, now);
|
|
264
|
+
};
|
|
265
|
+
BillingRepository.prototype.reconcilePendingUsage = async function () {
|
|
266
|
+
reconcileEntered = true; await reconciliationGate.promise; return reconcile.call(this);
|
|
267
|
+
};
|
|
268
|
+
let refresh: Promise<unknown> | undefined;
|
|
269
|
+
try {
|
|
270
|
+
assert.equal((await h.api('/usage/v1/model/tools')).status, 200);
|
|
271
|
+
await until(() => cleanupEntered && reconcileEntered, 'Gateway maintenance was not registered');
|
|
272
|
+
assert.ok(kernelRepository);
|
|
273
|
+
const pricing = new ReferencePricing(kernelRepository, async () => {
|
|
274
|
+
priceCalls++; await priceGate.promise;
|
|
275
|
+
return new Response(JSON.stringify({ data: { endpoints: [{ tag: 'synthetic', pricing: { prompt: '1', completion: '1' } }] } }), { status: 200 });
|
|
276
|
+
});
|
|
277
|
+
await h.pool.query('INSERT INTO bz_usage_price_snapshots VALUES(?,?,?)', [createHash('sha256').update('chat:synthetic/refresh').digest('hex'),
|
|
278
|
+
JSON.stringify({ fetchedAt: 1, items: [{ id: 'synthetic', pricing: { source: 'openrouter', modelId: 'synthetic/refresh', endpointId: 'synthetic', currency: 'USD', fetchedAt: 1,
|
|
279
|
+
lines: [{ billable: 'prompt', unit: 'token', costUsd: '1' }, { billable: 'completion', unit: 'token', costUsd: '1' }] } }] }), 1]);
|
|
280
|
+
const cached = await pricing.inspect({ source: 'openrouter', kind: 'chat', modelId: 'synthetic/refresh', endpointId: 'synthetic' });
|
|
281
|
+
assert.equal(cached.availability.state, 'ready', 'Stale cached quote returns without waiting for refresh');
|
|
282
|
+
await until(() => priceCalls === 1, 'Reference refresh did not start');
|
|
283
|
+
refresh = pricing.catalog('chat', 'synthetic/refresh', true); // joins the already detached refresh
|
|
284
|
+
await assert.rejects(h.kernel.close(10), /usage background drain timed out/);
|
|
285
|
+
await kernelRepository.getPool().query('SELECT 1');
|
|
286
|
+
await assert.rejects(pricing.catalog('chat', 'synthetic/new-refresh', true), /同步已停止/);
|
|
287
|
+
assert.equal(kernelRepository.backgroundWork.startMaintenance('response-cleanup', async () => { throw new Error('must not run'); }), null);
|
|
288
|
+
cleanupGate.release(); reconciliationGate.release();
|
|
289
|
+
await assert.rejects(h.kernel.close(10), /usage background drain timed out/);
|
|
290
|
+
priceGate.release(); await refresh;
|
|
291
|
+
await h.kernel.close(2000);
|
|
292
|
+
const [saved] = await h.pool.query<any[]>('SELECT snapshot_json FROM bz_usage_price_snapshots WHERE cache_key=?', [createHash('sha256').update('chat:synthetic/refresh').digest('hex')]);
|
|
293
|
+
const snapshot = typeof saved[0].snapshot_json === 'string' ? JSON.parse(saved[0].snapshot_json) : saved[0].snapshot_json;
|
|
294
|
+
assert.equal(saved.length, 1); assert.ok(Number(snapshot.fetchedAt) > 1); assert.equal(priceCalls, 1); assert.equal(h.state.calls, 0);
|
|
295
|
+
} finally {
|
|
296
|
+
cleanupGate.release(); reconciliationGate.release(); priceGate.release(); await refresh?.catch(() => {});
|
|
297
|
+
BillingRepository.prototype.cleanupExpiredResponses = cleanup; BillingRepository.prototype.reconcilePendingUsage = reconcile;
|
|
298
|
+
await h.close();
|
|
299
|
+
}
|
|
300
|
+
});
|
|
301
|
+
|
|
302
|
+
for (const kind of ['response-cleanup', 'usage-reconciliation'] as const) {
|
|
303
|
+
test(`Kernel individually drains gateway ${kind} before closing its pool`, { skip: !enabled }, async () => {
|
|
304
|
+
const h = await fixture(), workGate = gate();
|
|
305
|
+
const cleanup = BillingRepository.prototype.cleanupExpiredResponses, reconcile = BillingRepository.prototype.reconcilePendingUsage;
|
|
306
|
+
let entered = false, kernelRepository: UsageRepository | undefined;
|
|
307
|
+
if (kind === 'response-cleanup') BillingRepository.prototype.cleanupExpiredResponses = async function (now) {
|
|
308
|
+
entered = true; kernelRepository = this.repository; await workGate.promise; return cleanup.call(this, now);
|
|
309
|
+
};
|
|
310
|
+
else BillingRepository.prototype.reconcilePendingUsage = async function () {
|
|
311
|
+
entered = true; kernelRepository = this.repository; await workGate.promise; return reconcile.call(this);
|
|
312
|
+
};
|
|
313
|
+
try {
|
|
314
|
+
assert.equal((await h.api('/usage/v1/model/tools')).status, 200);
|
|
315
|
+
await until(() => entered, 'Gateway background SQL did not start');
|
|
316
|
+
await assert.rejects(h.kernel.close(10), /usage background drain timed out/);
|
|
317
|
+
assert.ok(kernelRepository); await kernelRepository.getPool().query('SELECT 1');
|
|
318
|
+
workGate.release(); await h.kernel.close(2000);
|
|
319
|
+
assert.equal(h.state.calls, 0);
|
|
320
|
+
} finally {
|
|
321
|
+
workGate.release(); BillingRepository.prototype.cleanupExpiredResponses = cleanup; BillingRepository.prototype.reconcilePendingUsage = reconcile;
|
|
322
|
+
await h.close();
|
|
323
|
+
}
|
|
324
|
+
});
|
|
325
|
+
}
|
package/src/app/kernel.ts
CHANGED
|
@@ -180,6 +180,9 @@ export function createBailingHubKernel(input: CreateBailingHubKernelInputV1): Ba
|
|
|
180
180
|
queue: new Queue(cfg.concurrency, input.executionQueue),
|
|
181
181
|
serialScope: instanceKey,
|
|
182
182
|
});
|
|
183
|
+
composition.cfgStore?.usage?.backgroundWork.setFailureReporter(kind => {
|
|
184
|
+
logger.warn?.(`[Kernel ${instanceKey}] usage background ${kind} failed; original durable evidence is retained`);
|
|
185
|
+
});
|
|
183
186
|
const demoDataset = composition.cfgStore ? new DemoDatasetService(composition.cfgStore, cfg.demoDataset) : null;
|
|
184
187
|
const runtimeHelpers = createRuntimeContextHelpers({
|
|
185
188
|
cfg,
|
|
@@ -482,6 +485,13 @@ export function createBailingHubKernel(input: CreateBailingHubKernelInputV1): Ba
|
|
|
482
485
|
composition.queue.closeAdmission();
|
|
483
486
|
const queueDrained = await composition.queue.drain(remainingDrainMs());
|
|
484
487
|
if (!queueDrained) throw new Error(`Kernel ${instanceKey} execution queue drain timed out`);
|
|
488
|
+
const usageWork = composition.cfgStore?.usage?.backgroundWork;
|
|
489
|
+
if (usageWork) {
|
|
490
|
+
// Foreground handlers have finished registering their continuations.
|
|
491
|
+
// Stop new maintenance, but let already accepted completions settle.
|
|
492
|
+
usageWork.beginDrain();
|
|
493
|
+
if (!await usageWork.drain(remainingDrainMs())) throw new Error(`Kernel ${instanceKey} usage background drain timed out`);
|
|
494
|
+
}
|
|
485
495
|
targetRegistry.bindStore(null);
|
|
486
496
|
wecomRuntimeState.dispose();
|
|
487
497
|
wecomAccessTokenCache.dispose();
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import test from 'node:test';
|
|
3
|
+
import { UsageBackgroundWork } from './background-work';
|
|
4
|
+
|
|
5
|
+
function deferred<T>() {
|
|
6
|
+
let resolve!: (value: T) => void;
|
|
7
|
+
const promise = new Promise<T>(done => { resolve = done; });
|
|
8
|
+
return { promise, resolve };
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function gate() {
|
|
12
|
+
const value = deferred<void>();
|
|
13
|
+
return { promise: value.promise, release: () => value.resolve(undefined) };
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const turn = () => new Promise<void>(resolve => setImmediate(resolve));
|
|
17
|
+
|
|
18
|
+
test('usage work is already in flight when its factory first runs', async (t) => {
|
|
19
|
+
const owner = new UsageBackgroundWork(), held = gate(), observed = deferred<boolean>();
|
|
20
|
+
t.after(() => held.release());
|
|
21
|
+
const task = owner.track('model-completion', async () => {
|
|
22
|
+
// This is observed from inside the factory, not from private tracker state.
|
|
23
|
+
observed.resolve(await owner.drain(0));
|
|
24
|
+
await held.promise;
|
|
25
|
+
});
|
|
26
|
+
assert.equal(await observed.promise, false);
|
|
27
|
+
held.release();
|
|
28
|
+
await task;
|
|
29
|
+
assert.equal(await owner.drain(100), true);
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
test('drain waits for a late child even when the original snapshot parent does not await it', async (t) => {
|
|
33
|
+
const owner = new UsageBackgroundWork(), parentGate = gate(), childGate = gate();
|
|
34
|
+
const childEntered = deferred<void>();
|
|
35
|
+
t.after(() => { parentGate.release(); childGate.release(); });
|
|
36
|
+
let child: Promise<void> | undefined;
|
|
37
|
+
const parent = owner.track('model-completion', async () => {
|
|
38
|
+
await parentGate.promise;
|
|
39
|
+
child = owner.track('settlement', async () => {
|
|
40
|
+
childEntered.resolve(undefined);
|
|
41
|
+
await childGate.promise;
|
|
42
|
+
});
|
|
43
|
+
// Intentionally finish this parent: a one-snapshot drain would return early.
|
|
44
|
+
});
|
|
45
|
+
owner.beginDrain();
|
|
46
|
+
let drainReturned = false;
|
|
47
|
+
const drained = owner.drain(2000).then(result => { drainReturned = true; return result; });
|
|
48
|
+
parentGate.release();
|
|
49
|
+
await parent;
|
|
50
|
+
await childEntered.promise;
|
|
51
|
+
await turn();
|
|
52
|
+
assert.equal(drainReturned, false);
|
|
53
|
+
assert.equal(await owner.drain(0), false);
|
|
54
|
+
childGate.release();
|
|
55
|
+
assert.ok(child);
|
|
56
|
+
await child;
|
|
57
|
+
assert.equal(await drained, true);
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
test('beginDrain rejects future maintenance before its factory can perform side effects', async () => {
|
|
61
|
+
const owner = new UsageBackgroundWork();
|
|
62
|
+
let acceptedEffects = 0, rejectedEffects = 0;
|
|
63
|
+
const accepted = owner.startMaintenance('response-cleanup', async () => { acceptedEffects++; });
|
|
64
|
+
assert.ok(accepted);
|
|
65
|
+
owner.beginDrain();
|
|
66
|
+
assert.equal(owner.acceptingRequests, false);
|
|
67
|
+
for (const kind of ['response-cleanup', 'usage-reconciliation', 'reference-price-refresh'] as const) {
|
|
68
|
+
assert.equal(owner.startMaintenance(kind, async () => { rejectedEffects++; }), null);
|
|
69
|
+
}
|
|
70
|
+
await accepted;
|
|
71
|
+
await turn();
|
|
72
|
+
assert.equal(acceptedEffects, 1); // Previously accepted maintenance is not cancelled.
|
|
73
|
+
assert.equal(rejectedEffects, 0);
|
|
74
|
+
assert.equal(await owner.drain(0), true);
|
|
75
|
+
assert.equal(owner.acceptingRequests, false);
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
test('zero budget and a timed-out drain retain accepted work for a same-owner retry', async (t) => {
|
|
79
|
+
const owner = new UsageBackgroundWork(), held = gate(), entered = deferred<void>();
|
|
80
|
+
t.after(() => held.release());
|
|
81
|
+
let starts = 0, completed = 0;
|
|
82
|
+
const task = owner.track('model-completion', async () => {
|
|
83
|
+
starts++;
|
|
84
|
+
entered.resolve(undefined);
|
|
85
|
+
await held.promise;
|
|
86
|
+
completed++;
|
|
87
|
+
});
|
|
88
|
+
await entered.promise;
|
|
89
|
+
owner.beginDrain();
|
|
90
|
+
assert.equal(await owner.drain(0), false);
|
|
91
|
+
assert.equal(await owner.drain(10), false);
|
|
92
|
+
assert.equal(starts, 1);
|
|
93
|
+
assert.equal(completed, 0);
|
|
94
|
+
assert.equal(owner.acceptingRequests, false);
|
|
95
|
+
assert.equal(owner.startMaintenance('usage-reconciliation', async () => { completed += 100; }), null);
|
|
96
|
+
held.release();
|
|
97
|
+
await task;
|
|
98
|
+
assert.equal(await owner.drain(100), true);
|
|
99
|
+
assert.equal(starts, 1);
|
|
100
|
+
assert.equal(completed, 1);
|
|
101
|
+
assert.equal(owner.acceptingRequests, false);
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
test('two owners isolate admission and drain; one pending completion cannot hold the other', async (t) => {
|
|
105
|
+
const one = new UsageBackgroundWork(), two = new UsageBackgroundWork(), held = gate();
|
|
106
|
+
t.after(() => held.release());
|
|
107
|
+
let oneCompleted = false, twoCompleted = false;
|
|
108
|
+
const pending = one.track('model-completion', async () => { await held.promise; oneCompleted = true; });
|
|
109
|
+
one.beginDrain();
|
|
110
|
+
assert.equal(two.acceptingRequests, true);
|
|
111
|
+
const independent = two.startMaintenance('usage-reconciliation', async () => { twoCompleted = true; });
|
|
112
|
+
assert.ok(independent);
|
|
113
|
+
two.beginDrain();
|
|
114
|
+
assert.equal(await two.drain(100), true);
|
|
115
|
+
assert.equal(twoCompleted, true);
|
|
116
|
+
assert.equal(oneCompleted, false);
|
|
117
|
+
assert.equal(await one.drain(0), false);
|
|
118
|
+
held.release();
|
|
119
|
+
await pending;
|
|
120
|
+
assert.equal(await one.drain(100), true);
|
|
121
|
+
assert.equal(oneCompleted, true);
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
test('rejected work is drained and reported using only its fixed kind', async () => {
|
|
125
|
+
const owner = new UsageBackgroundWork(), reported: unknown[][] = [];
|
|
126
|
+
owner.setFailureReporter((...args: unknown[]) => { reported.push(args); });
|
|
127
|
+
const failed = owner.track('settlement', async () => {
|
|
128
|
+
throw new Error('Synthetic provider body must not enter lifecycle diagnostics');
|
|
129
|
+
});
|
|
130
|
+
owner.beginDrain();
|
|
131
|
+
await assert.rejects(failed, { message: 'Synthetic provider body must not enter lifecycle diagnostics' });
|
|
132
|
+
assert.equal(await owner.drain(100), true);
|
|
133
|
+
assert.deepEqual(reported, [['settlement']]);
|
|
134
|
+
assert.equal(await owner.drain(0), true);
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
test('a throwing failure reporter cannot keep rejected work live or replace its failure', async () => {
|
|
138
|
+
const owner = new UsageBackgroundWork();
|
|
139
|
+
owner.setFailureReporter(() => { throw new Error('Synthetic diagnostic sink failure'); });
|
|
140
|
+
const failed = owner.track('usage-reconciliation', async () => { throw new Error('Synthetic original work failure'); });
|
|
141
|
+
await assert.rejects(failed, { message: 'Synthetic original work failure' });
|
|
142
|
+
owner.beginDrain();
|
|
143
|
+
assert.equal(await owner.drain(100), true);
|
|
144
|
+
});
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
export type UsageBackgroundKind = 'model-completion' | 'settlement' | 'response-cleanup' | 'usage-reconciliation' | 'reference-price-refresh';
|
|
2
|
+
type MaintenanceKind = Exclude<UsageBackgroundKind, 'model-completion' | 'settlement'>;
|
|
3
|
+
|
|
4
|
+
/** One UsageRepository owns its accepted work, including children created during drain. */
|
|
5
|
+
export class UsageBackgroundWork {
|
|
6
|
+
private readonly pending = new Set<Promise<unknown>>();
|
|
7
|
+
private draining = false;
|
|
8
|
+
private failureReporter: ((kind: UsageBackgroundKind) => void) | undefined;
|
|
9
|
+
|
|
10
|
+
get acceptingRequests(): boolean { return !this.draining; }
|
|
11
|
+
setFailureReporter(reporter: (kind: UsageBackgroundKind) => void): void { this.failureReporter = reporter; }
|
|
12
|
+
beginDrain(): void { this.draining = true; }
|
|
13
|
+
|
|
14
|
+
track<T>(kind: UsageBackgroundKind, run: () => Promise<T>): Promise<T> {
|
|
15
|
+
// Register before invoking run: even an immediately resolving parent must not
|
|
16
|
+
// leave a gap before its SQL/settlement continuation has been registered.
|
|
17
|
+
const work = Promise.resolve().then(run);
|
|
18
|
+
this.pending.add(work);
|
|
19
|
+
void work.then(() => { this.pending.delete(work); }, () => {
|
|
20
|
+
this.pending.delete(work);
|
|
21
|
+
// Report only the fixed work kind; provider bodies, SQL and credentials
|
|
22
|
+
// are never included in lifecycle diagnostics.
|
|
23
|
+
try { this.failureReporter?.(kind); } catch { /* diagnostics cannot own lifecycle */ }
|
|
24
|
+
});
|
|
25
|
+
return work;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
startMaintenance<T>(kind: MaintenanceKind, run: () => Promise<T>): Promise<T> | null {
|
|
29
|
+
return this.draining ? null : this.track(kind, run);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
async drain(drainMs: number): Promise<boolean> {
|
|
33
|
+
const deadline = Date.now() + Math.max(0, drainMs);
|
|
34
|
+
while (this.pending.size) {
|
|
35
|
+
const remaining = deadline - Date.now();
|
|
36
|
+
if (remaining <= 0) return false;
|
|
37
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
38
|
+
try {
|
|
39
|
+
const drained = await Promise.race([
|
|
40
|
+
Promise.allSettled([...this.pending]).then(() => true),
|
|
41
|
+
new Promise<boolean>(resolve => { timer = setTimeout(() => resolve(false), remaining); }),
|
|
42
|
+
]);
|
|
43
|
+
if (!drained) return false;
|
|
44
|
+
} finally { if (timer) clearTimeout(timer); }
|
|
45
|
+
// A tracked completion can register settlement after drain started. Do
|
|
46
|
+
// not mistake a finished snapshot for a quiescent repository.
|
|
47
|
+
}
|
|
48
|
+
return true;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
@@ -355,17 +355,19 @@ export class BillingRepository {
|
|
|
355
355
|
return recorded.billingState === 'pending' && (recorded.usage || recorded.rawUsage) ? this.settleRecorded(recorded) : recorded;
|
|
356
356
|
}
|
|
357
357
|
private readonly settlements = new Map<string, Promise<void>>();
|
|
358
|
-
scheduleSettlement(operationId: string, actor: UsageActor): void {
|
|
358
|
+
scheduleSettlement(operationId: string, actor: UsageActor): Promise<void> {
|
|
359
359
|
const key = operationIdKey(actor, operationId);
|
|
360
|
-
|
|
361
|
-
|
|
360
|
+
const existing = this.settlements.get(key);
|
|
361
|
+
if (existing) return existing;
|
|
362
|
+
const work = this.repository.backgroundWork.track('settlement', async () => {
|
|
362
363
|
const r = await this.findRequest(actor, operationId);
|
|
363
364
|
if (r?.billingState === 'pending' && (r.usage || r.rawUsage) && r.resultHash) await this.settleRecorded(r);
|
|
364
365
|
}).catch(() => { /* Durable pending evidence is retried by maintenance. */ })
|
|
365
366
|
.finally(() => { this.settlements.delete(key); });
|
|
366
367
|
this.settlements.set(key, work);
|
|
368
|
+
return work;
|
|
367
369
|
}
|
|
368
|
-
async drainSettlements(): Promise<void> { await Promise.allSettled([...this.settlements.values()]); }
|
|
370
|
+
async drainSettlements(): Promise<void> { while (this.settlements.size) await Promise.allSettled([...this.settlements.values()]); }
|
|
369
371
|
private async settleRecorded(recorded: BillingRequest): Promise<BillingRequest> {
|
|
370
372
|
try {
|
|
371
373
|
return await this.repository.withTransaction(async c => {
|
|
@@ -28,13 +28,15 @@ export interface UsageGatewayDeps {
|
|
|
28
28
|
|
|
29
29
|
const responseCleanup = new WeakMap<UsageRepository, number>();
|
|
30
30
|
function scheduleResponseCleanup(repository: UsageRepository): void {
|
|
31
|
+
if (!repository.backgroundWork.acceptingRequests) return;
|
|
31
32
|
const now = Date.now();
|
|
32
33
|
if (now - (responseCleanup.get(repository) ?? 0) < 60_000) return;
|
|
33
34
|
responseCleanup.set(repository, now);
|
|
34
35
|
// Bounded maintenance is independent of admission and model delivery. A failed
|
|
35
36
|
// cleanup is retried on later traffic; expired bodies are never returned meanwhile.
|
|
36
37
|
const tokens = getBillingRepository(repository);
|
|
37
|
-
void
|
|
38
|
+
void repository.backgroundWork.startMaintenance('response-cleanup', () => tokens.cleanupExpiredResponses(now))?.catch(() => {});
|
|
39
|
+
void repository.backgroundWork.startMaintenance('usage-reconciliation', () => tokens.reconcilePendingUsage())?.catch(() => {});
|
|
38
40
|
}
|
|
39
41
|
|
|
40
42
|
export const MODEL_GATEWAY_CAPABILITIES = {
|
|
@@ -95,7 +97,7 @@ export async function runModelRequest(deps: UsageGatewayDeps, actor: UsageSessio
|
|
|
95
97
|
usageAssert(previous.requestHash === requestHash, 'USAGE_IDEMPOTENCY_CONFLICT', '原请求标识已关联其他内容。');
|
|
96
98
|
return tokens.view(previous);
|
|
97
99
|
}
|
|
98
|
-
usageAssert(!deps.isPaused?.(), 'USAGE_SERVICE_PAUSED', '模型服务维护中;原请求结果仍可查询。', 503);
|
|
100
|
+
usageAssert(repository.backgroundWork.acceptingRequests && !deps.isPaused?.(), 'USAGE_SERVICE_PAUSED', '模型服务维护中;原请求结果仍可查询。', 503);
|
|
99
101
|
const current = await tokens.summary(actor.accountId);
|
|
100
102
|
usageAssert(current.grant, 'SERVICE_NOT_ENTITLED', '尚未开通套餐。', 403);
|
|
101
103
|
if (!modelAllowedServices(actor, current.plan?.serviceIds ?? []).includes(serviceId))
|
|
@@ -144,7 +146,12 @@ export async function runModelRequest(deps: UsageGatewayDeps, actor: UsageSessio
|
|
|
144
146
|
};
|
|
145
147
|
if (toolRequest) {
|
|
146
148
|
// Return the durable dispatch record promptly. Disconnecting never regenerates an image.
|
|
147
|
-
void
|
|
149
|
+
void repository.backgroundWork.track('model-completion', async () => {
|
|
150
|
+
const result = await complete();
|
|
151
|
+
// The accepted parent remains live through the late-created settlement.
|
|
152
|
+
// Delivery still returns 202 immediately; close must drain both stages.
|
|
153
|
+
await tokens.scheduleSettlement(result.operation_id, actor);
|
|
154
|
+
}).catch(()=>{});
|
|
148
155
|
return tokens.view(request);
|
|
149
156
|
}
|
|
150
157
|
return complete();
|
|
@@ -61,7 +61,7 @@ async function fixture(options: {response?: () => Response | Promise<Response>}
|
|
|
61
61
|
throw new Error('Synthetic image operation did not settle');
|
|
62
62
|
}
|
|
63
63
|
return {...h,image,excluded,pending,user,calls,input,request,release,settled,
|
|
64
|
-
async close(){release();
|
|
64
|
+
async close(){release();server.close();server.closeAllConnections();h.repository.backgroundWork.beginDrain();assert.equal(await h.repository.backgroundWork.drain(5000),true,'Synthetic model-tool background drain timed out');await h.close();},
|
|
65
65
|
};
|
|
66
66
|
}
|
|
67
67
|
|
|
@@ -167,7 +167,7 @@ export class ReferencePricing {
|
|
|
167
167
|
}
|
|
168
168
|
private async refresh(kind: 'chat'|'image', modelId?: string): Promise<Catalog> {
|
|
169
169
|
const key = this.key(kind,modelId), pending = this.flights.get(key); if (pending) return pending;
|
|
170
|
-
const job = (async () => {
|
|
170
|
+
const job = this.repository.backgroundWork.startMaintenance('reference-price-refresh', async () => {
|
|
171
171
|
const prefix = kind === 'image' ? 'images/models' : 'models';
|
|
172
172
|
const encoded = modelId?.split('/').map(encodeURIComponent).join('/');
|
|
173
173
|
const value = await this.fetchJson(modelId ? `${prefix}/${encoded}/endpoints` : prefix);
|
|
@@ -189,7 +189,8 @@ export class ReferencePricing {
|
|
|
189
189
|
items = items.filter((x:any) => items.filter((y:any)=>y.id===x.id).length===1);
|
|
190
190
|
}
|
|
191
191
|
const result = {items,fetchedAt}; await this.save(key,result); return result;
|
|
192
|
-
})
|
|
192
|
+
});
|
|
193
|
+
usageAssert(job, 'USAGE_PRICE_UNAVAILABLE', '参考价格同步已停止,请稍后重试。', 503);
|
|
193
194
|
this.flights.set(key,job); try {return await job;} finally {this.flights.delete(key);}
|
|
194
195
|
}
|
|
195
196
|
async catalog(kind:'chat'|'image', modelId?: string, force=false): Promise<Catalog> {
|