bailinghub 0.9.0 → 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.
- 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 +22 -1
- package/docs/CHANGELOG.md +22 -1
- package/docs/COMPATIBILITY.en.md +4 -0
- package/docs/CORE_RELIABILITY.en.md +59 -0
- package/docs/CORE_RELIABILITY.md +59 -0
- package/docs/DEPLOYMENT_DIAGNOSTICS.en.md +78 -0
- package/docs/DEPLOYMENT_DIAGNOSTICS.md +78 -0
- package/docs/IMPLEMENTATION_STATUS.en.md +81 -0
- package/docs/IMPLEMENTATION_STATUS.md +81 -0
- package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
- package/docs/INDEPENDENT_VALIDATION.md +4 -4
- package/docs/KERNEL_HOST_API.en.md +20 -0
- package/docs/KERNEL_HOST_API.md +20 -0
- package/docs/MODEL_BILLING.en.md +4 -0
- package/docs/MODEL_BILLING.md +4 -0
- package/docs/MODEL_PROCESS_RECOVERY.en.md +32 -0
- package/docs/MODEL_PROCESS_RECOVERY.md +37 -0
- package/docs/README.en.md +8 -0
- package/docs/README.md +8 -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/RELEASE_NOTES_v0.9.2.en.md +45 -0
- package/docs/RELEASE_NOTES_v0.9.2.md +45 -0
- package/docs/UPGRADE_v0.9.1.en.md +39 -0
- package/docs/UPGRADE_v0.9.1.md +39 -0
- package/docs/UPGRADE_v0.9.2.en.md +62 -0
- package/docs/UPGRADE_v0.9.2.md +62 -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 +10 -5
- package/scripts/check-doc-links.mjs +4 -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/doctor-deployment.test.ts +419 -0
- package/scripts/doctor-deployment.ts +357 -0
- package/scripts/doctor.ts +8 -1
- package/scripts/install-secrets.test.mjs +185 -0
- package/scripts/install.sh +10 -6
- package/scripts/osps-results.py +114 -0
- package/scripts/publish-images.sh +1 -1
- package/scripts/release-audit.mjs +5 -0
- package/scripts/verify-github-repo.mjs +5 -0
- package/security/dependency-audit-exceptions.json +192 -0
- package/sql/065_usage_reconciliation_scan.sql +4 -0
- package/sql/066_approval_continuations.sql +15 -0
- package/sql/README.md +9 -0
- package/src/app/approval-continuations.mysql.test.ts +138 -0
- package/src/app/approval-continuations.test.ts +325 -0
- package/src/app/approval-continuations.ts +107 -0
- package/src/app/http-server.ts +3 -0
- package/src/app/kernel-model-process-crash.mysql.test.ts +377 -0
- package/src/app/kernel-usage-lifecycle.mysql.test.ts +325 -0
- package/src/app/kernel.ts +23 -0
- package/src/app/runtime-evidence-maintenance.test.ts +55 -0
- package/src/app/runtime-lifecycle-default.ts +7 -0
- package/src/app/runtime-lifecycle.ts +39 -0
- package/src/core/contracts/approval-continuation.ts +43 -0
- package/src/core/contracts/types.ts +2 -0
- package/src/core/state/approval-continuation.ts +22 -0
- package/src/core/state/state-codec.ts +1 -0
- package/src/core/state/state-contracts.ts +3 -0
- package/src/infrastructure/config/config-approval-ledger.ts +75 -0
- package/src/infrastructure/config/configstore.ts +2 -2
- package/src/infrastructure/state/state-jsonl.ts +41 -11
- package/src/infrastructure/state/state-mysql.ts +27 -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-reconciliation.mysql.test.ts +163 -0
- package/src/modules/usage/billing-reconciliation.test.ts +71 -0
- package/src/modules/usage/billing-repository.ts +60 -15
- package/src/modules/usage/maintenance.test.ts +62 -0
- package/src/modules/usage/maintenance.ts +31 -0
- package/src/modules/usage/model-gateway.ts +11 -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/src/routes/admin-default.ts +2 -2
- package/src/routes/admin-runtime-default.ts +2 -2
- package/src/routes/admin-runtime.test.ts +1 -1
- package/src/routes/admin-runtime.ts +25 -18
- package/src/routes/admin.ts +1 -1
- package/src/routes/approvals-default.ts +2 -2
- package/src/routes/approvals.ts +30 -33
- package/src/routes/critical-routes.test.ts +16 -3
- package/src/test-support/approval-continuation-crash-child.ts +24 -0
- package/src/test-support/model-process-crash-child.ts +78 -0
- 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
|
@@ -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';
|
|
@@ -180,6 +181,9 @@ export function createBailingHubKernel(input: CreateBailingHubKernelInputV1): Ba
|
|
|
180
181
|
queue: new Queue(cfg.concurrency, input.executionQueue),
|
|
181
182
|
serialScope: instanceKey,
|
|
182
183
|
});
|
|
184
|
+
composition.cfgStore?.usage?.backgroundWork.setFailureReporter(kind => {
|
|
185
|
+
logger.warn?.(`[Kernel ${instanceKey}] usage background ${kind} failed; original durable evidence is retained`);
|
|
186
|
+
});
|
|
183
187
|
const demoDataset = composition.cfgStore ? new DemoDatasetService(composition.cfgStore, cfg.demoDataset) : null;
|
|
184
188
|
const runtimeHelpers = createRuntimeContextHelpers({
|
|
185
189
|
cfg,
|
|
@@ -231,6 +235,15 @@ export function createBailingHubKernel(input: CreateBailingHubKernelInputV1): Ba
|
|
|
231
235
|
now,
|
|
232
236
|
sleep,
|
|
233
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
|
+
},
|
|
234
247
|
afterStoresInitialized: !localAdminManagement || input.bootstrapLocalAdmin === false
|
|
235
248
|
? undefined
|
|
236
249
|
: async () => { await bootstrapInitialAdmin(cfg.bootstrapAdmin, { admins: composition.cfgStore?.admins ?? null }); },
|
|
@@ -462,6 +475,9 @@ export function createBailingHubKernel(input: CreateBailingHubKernelInputV1): Ba
|
|
|
462
475
|
if (!initializedWithinBudget) throw new Error(`Kernel ${instanceKey} initialization drain timed out`);
|
|
463
476
|
}
|
|
464
477
|
schedulers?.stop();
|
|
478
|
+
if (schedulers?.drain && !await schedulers.drain(remainingDrainMs())) {
|
|
479
|
+
throw new Error(`Kernel ${instanceKey} persisted evidence maintenance drain timed out`);
|
|
480
|
+
}
|
|
465
481
|
schedulers = null;
|
|
466
482
|
if (bootRecoveryTimer) clearTimeout(bootRecoveryTimer);
|
|
467
483
|
bootRecoveryTimer = null;
|
|
@@ -482,6 +498,13 @@ export function createBailingHubKernel(input: CreateBailingHubKernelInputV1): Ba
|
|
|
482
498
|
composition.queue.closeAdmission();
|
|
483
499
|
const queueDrained = await composition.queue.drain(remainingDrainMs());
|
|
484
500
|
if (!queueDrained) throw new Error(`Kernel ${instanceKey} execution queue drain timed out`);
|
|
501
|
+
const usageWork = composition.cfgStore?.usage?.backgroundWork;
|
|
502
|
+
if (usageWork) {
|
|
503
|
+
// Foreground handlers have finished registering their continuations.
|
|
504
|
+
// Stop new maintenance, but let already accepted completions settle.
|
|
505
|
+
usageWork.beginDrain();
|
|
506
|
+
if (!await usageWork.drain(remainingDrainMs())) throw new Error(`Kernel ${instanceKey} usage background drain timed out`);
|
|
507
|
+
}
|
|
485
508
|
targetRegistry.bindStore(null);
|
|
486
509
|
wecomRuntimeState.dispose();
|
|
487
510
|
wecomAccessTokenCache.dispose();
|
|
@@ -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 也能复现
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { ApprovalRequeueInput, ApprovalRequeueOutcome } from '../contracts/approval-continuation';
|
|
2
|
+
import type { Job } from '../contracts/types';
|
|
3
|
+
|
|
4
|
+
/** Only the state adapter may commit this patch, atomically with its queue transition. */
|
|
5
|
+
export function approvalRequeuePlan(job: Job | null, input: ApprovalRequeueInput): { outcome: ApprovalRequeueOutcome; patch?: Partial<Job> } {
|
|
6
|
+
if (!job) return { outcome: 'missing' };
|
|
7
|
+
if (!Number.isSafeInteger(input.approval_id) || input.approval_id <= 0 || !input.decision_key
|
|
8
|
+
|| input.decision_key.length > 160 || job.job_id !== input.job_id || job.request_id !== input.request_id
|
|
9
|
+
|| job.target === 'agent-tool-v1') return { outcome: 'conflict' };
|
|
10
|
+
const key = String(input.approval_id);
|
|
11
|
+
const previous = job.approval_continuation_keys?.[key];
|
|
12
|
+
if (previous !== undefined) return { outcome: previous === input.decision_key ? 'already_queued' : 'conflict' };
|
|
13
|
+
if (!['done', 'error', 'rejected'].includes(job.status)) return { outcome: 'in_flight' };
|
|
14
|
+
const metadata = { ...job.metadata };
|
|
15
|
+
delete metadata.no_delivery;
|
|
16
|
+
return { outcome: 'queued', patch: {
|
|
17
|
+
status: 'queued', attempts: 0, run_after: undefined, error: undefined,
|
|
18
|
+
executor_id: undefined, claimed_at: undefined, lease_until: undefined,
|
|
19
|
+
dispatched_at: undefined, claim_token: undefined, metadata,
|
|
20
|
+
approval_continuation_keys: { ...job.approval_continuation_keys, [key]: input.decision_key },
|
|
21
|
+
} };
|
|
22
|
+
}
|