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
|
@@ -31,6 +31,7 @@ export function rowToJob(r: any): Job {
|
|
|
31
31
|
usage: parse(r.usage),
|
|
32
32
|
error: r.error ?? undefined,
|
|
33
33
|
metadata: parse(r.metadata) ?? {},
|
|
34
|
+
approval_continuation_keys: parse(r.approval_continuation_keys),
|
|
34
35
|
callback_url: r.callback_url ?? undefined,
|
|
35
36
|
dispatch: parse(r.dispatch),
|
|
36
37
|
attempts: r.attempts != null ? Number(r.attempts) : 0,
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { AuditEntry, Job, JobStatus } from '../contracts/types';
|
|
2
|
+
import type { ApprovalRequeueInput, ApprovalRequeueOutcome } from '../contracts/approval-continuation';
|
|
2
3
|
|
|
3
4
|
export interface JobOperationalMetricsSnapshot {
|
|
4
5
|
byStatus: Record<JobStatus, number>;
|
|
@@ -48,6 +49,8 @@ export interface RuntimeLockRepository {
|
|
|
48
49
|
}
|
|
49
50
|
|
|
50
51
|
export interface RuntimeStateStore extends JobRepository, AuditLedger, RuntimeLockRepository {
|
|
52
|
+
/** Atomic original-job queue transition + permanent decision marker; no substitute operation. */
|
|
53
|
+
requeueApprovedJobOnce?(input: ApprovalRequeueInput): Promise<ApprovalRequeueOutcome>;
|
|
51
54
|
init(): Promise<void>;
|
|
52
55
|
/** Kernel 释放时关闭自己拥有的资源;外部实现可不提供。 */
|
|
53
56
|
close?(): Promise<void>;
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { dt, rowToolApproval } from '../../core/config/config-codec';
|
|
2
2
|
import type { ToolApproval } from '../../core/contracts/types';
|
|
3
|
+
import type { ApprovalContinuation, ApprovalContinuationDecisionOptions } from '../../core/contracts/approval-continuation';
|
|
3
4
|
|
|
4
5
|
export class ApprovalLedger {
|
|
6
|
+
private continuationCursor = 0;
|
|
5
7
|
constructor(private readonly poolOf: () => any) {}
|
|
6
8
|
|
|
7
9
|
private get pool(): any { return this.poolOf(); }
|
|
@@ -43,6 +45,72 @@ export class ApprovalLedger {
|
|
|
43
45
|
return r?.affectedRows === 1;
|
|
44
46
|
}
|
|
45
47
|
|
|
48
|
+
/** Decision and immutable follow-up coordinates are a single database transaction. */
|
|
49
|
+
async decideWithContinuation(id: number, status: 'approved' | 'denied', decidedBy: string,
|
|
50
|
+
opts: ApprovalContinuationDecisionOptions): Promise<'decided' | 'same' | 'conflict'> {
|
|
51
|
+
const conn = await this.pool.getConnection();
|
|
52
|
+
try {
|
|
53
|
+
await conn.beginTransaction();
|
|
54
|
+
const [rows]: any = await conn.query('SELECT * FROM bz_tool_approvals WHERE id=? FOR UPDATE', [id]);
|
|
55
|
+
if (!rows[0]) { await conn.commit(); return 'conflict'; }
|
|
56
|
+
const approval = rowToolApproval(rows[0]);
|
|
57
|
+
if (approval.status !== 'pending') {
|
|
58
|
+
const same = approval.status === status && (approval.decision_id ?? null) === (opts.decision_id ?? null);
|
|
59
|
+
await conn.commit();
|
|
60
|
+
return same ? 'same' : 'conflict';
|
|
61
|
+
}
|
|
62
|
+
const intent: ApprovalContinuation = {
|
|
63
|
+
schema_version: 'bailing.approval-continuation.v1', approval_id: id,
|
|
64
|
+
decision_key: opts.decision_id ?? `console:${id}`, decision: status,
|
|
65
|
+
...(opts.decision_id ? { decision_id: opts.decision_id } : {}),
|
|
66
|
+
job_id: approval.job_id, request_id: approval.request_id, args_hash: approval.args_hash,
|
|
67
|
+
tool: approval.tool, scope: approval.scope, by: decidedBy,
|
|
68
|
+
source: opts.source, auth: opts.auth, mode: opts.mode,
|
|
69
|
+
...(approval.policy ? { policy: approval.policy } : {}),
|
|
70
|
+
...(approval.reason ? { reason: approval.reason } : {}),
|
|
71
|
+
...(approval.summary ? { summary: approval.summary } : {}),
|
|
72
|
+
...(opts.comment ? { comment: opts.comment } : {}),
|
|
73
|
+
audit_recorded: false, completed: false,
|
|
74
|
+
};
|
|
75
|
+
await conn.query("UPDATE bz_tool_approvals SET status=?,decided_by=?,decision_id=?,decision_comment=?,decided_at=? WHERE id=? AND status='pending'",
|
|
76
|
+
[status, decidedBy, opts.decision_id ?? null, opts.comment ?? null, dt(), id]);
|
|
77
|
+
await conn.query('INSERT INTO bz_approval_continuations (approval_id,intent_json,created_at) VALUES (?,?,?)',
|
|
78
|
+
[id, JSON.stringify(intent), dt()]);
|
|
79
|
+
await conn.commit();
|
|
80
|
+
return 'decided';
|
|
81
|
+
} catch (error) {
|
|
82
|
+
await conn.rollback().catch(() => undefined);
|
|
83
|
+
if ((error as { code?: string }).code === 'ER_DUP_ENTRY') return 'conflict';
|
|
84
|
+
throw error;
|
|
85
|
+
} finally { conn.release(); }
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
async getContinuation(id: number): Promise<ApprovalContinuation | null> {
|
|
89
|
+
const [rows]: any = await this.pool.query('SELECT * FROM bz_approval_continuations WHERE approval_id=?', [id]);
|
|
90
|
+
return rows[0] ? continuationRow(rows[0]) : null;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
async pendingContinuations(limit = 25): Promise<ApprovalContinuation[]> {
|
|
94
|
+
const n = Math.min(Math.max(Math.trunc(limit) || 25, 1), 100);
|
|
95
|
+
let [rows]: any = await this.pool.query(`SELECT * FROM bz_approval_continuations WHERE completed_at IS NULL AND approval_id>? ORDER BY approval_id LIMIT ${n}`, [this.continuationCursor]);
|
|
96
|
+
if (!rows.length && this.continuationCursor > 0) {
|
|
97
|
+
this.continuationCursor = 0;
|
|
98
|
+
[rows] = await this.pool.query(`SELECT * FROM bz_approval_continuations WHERE completed_at IS NULL AND approval_id>? ORDER BY approval_id LIMIT ${n}`, [0]);
|
|
99
|
+
}
|
|
100
|
+
if (rows.length) this.continuationCursor = Number(rows[rows.length - 1].approval_id);
|
|
101
|
+
return rows.map(continuationRow);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
async markContinuationAuditRecorded(id: number, decisionKey: string): Promise<void> {
|
|
105
|
+
await this.pool.query("UPDATE bz_approval_continuations SET audit_recorded_at=COALESCE(audit_recorded_at,?) WHERE approval_id=? AND JSON_UNQUOTE(JSON_EXTRACT(intent_json,'$.decision_key'))=?",
|
|
106
|
+
[dt(), id, decisionKey]);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
async completeContinuation(id: number, decisionKey: string): Promise<void> {
|
|
110
|
+
await this.pool.query("UPDATE bz_approval_continuations SET completed_at=COALESCE(completed_at,?) WHERE approval_id=? AND audit_recorded_at IS NOT NULL AND JSON_UNQUOTE(JSON_EXTRACT(intent_json,'$.decision_key'))=?",
|
|
111
|
+
[dt(), id, decisionKey]);
|
|
112
|
+
}
|
|
113
|
+
|
|
46
114
|
async use(id: number): Promise<boolean> {
|
|
47
115
|
const [r]: any = await this.pool.query(
|
|
48
116
|
"UPDATE bz_tool_approvals SET used_at=? WHERE id=? AND status='approved' AND used_at IS NULL",
|
|
@@ -88,3 +156,10 @@ export class ApprovalLedger {
|
|
|
88
156
|
return grouped;
|
|
89
157
|
}
|
|
90
158
|
}
|
|
159
|
+
|
|
160
|
+
function continuationRow(row: any): ApprovalContinuation {
|
|
161
|
+
const intent = typeof row.intent_json === 'string' ? JSON.parse(row.intent_json) : row.intent_json;
|
|
162
|
+
if (!intent || intent.schema_version !== 'bailing.approval-continuation.v1'
|
|
163
|
+
|| intent.approval_id !== Number(row.approval_id)) throw new Error('approval_continuation_invalid');
|
|
164
|
+
return { ...intent, audit_recorded: row.audit_recorded_at != null, completed: row.completed_at != null };
|
|
165
|
+
}
|
|
@@ -53,8 +53,8 @@ export type ChatConfigRepositoryContract = Pick<ChatConfigRepository, keyof Chat
|
|
|
53
53
|
export type RateLimitLedgerContract = Omit<Pick<RateLimitLedger, keyof RateLimitLedger>, 'consumeAll'>
|
|
54
54
|
& Partial<Pick<RateLimitLedger, 'consumeAll'>>;
|
|
55
55
|
export type ApprovalLedgerContract =
|
|
56
|
-
Omit<Pick<ApprovalLedger, keyof ApprovalLedger>, 'forJobs'>
|
|
57
|
-
& Partial<Pick<ApprovalLedger, 'forJobs'>>;
|
|
56
|
+
Omit<Pick<ApprovalLedger, keyof ApprovalLedger>, 'forJobs' | 'decideWithContinuation' | 'getContinuation' | 'pendingContinuations' | 'markContinuationAuditRecorded' | 'completeContinuation'>
|
|
57
|
+
& Partial<Pick<ApprovalLedger, 'forJobs' | 'decideWithContinuation' | 'getContinuation' | 'pendingContinuations' | 'markContinuationAuditRecorded' | 'completeContinuation'>>;
|
|
58
58
|
export type ConversationLedgerContract = Pick<ConversationLedger, keyof ConversationLedger>;
|
|
59
59
|
export type ExecutorLedgerContract = Pick<ExecutorLedger, keyof ExecutorLedger>;
|
|
60
60
|
export type ToolCallLedgerContract = Pick<ToolCallLedger, keyof ToolCallLedger>;
|
|
@@ -5,12 +5,21 @@ import { dirname } from 'node:path';
|
|
|
5
5
|
import { completeTraceEntry } from '../../core/runtime/trace-runtime';
|
|
6
6
|
import { JOB_STATUSES, TERMINAL_JOB_STATUSES, type AuditEntry, type Job } from '../../core/contracts/types';
|
|
7
7
|
import type { JobOperationalMetricsSnapshot, RuntimeStateStore } from '../../core/state/state-contracts';
|
|
8
|
+
import type { ApprovalRequeueInput, ApprovalRequeueOutcome } from '../../core/contracts/approval-continuation';
|
|
9
|
+
import { approvalRequeuePlan } from '../../core/state/approval-continuation';
|
|
8
10
|
|
|
9
11
|
/** jsonl 后端:本地烟测与最小私有部署。状态仍是中枢自己的,不进业务库。 */
|
|
10
12
|
export class JsonlStore implements RuntimeStateStore {
|
|
11
13
|
private readonly jobs = new Map<string, Job>();
|
|
12
14
|
private readonly byRequest = new Map<string, string>();
|
|
13
15
|
private readonly locks = new Map<string, { owner: string; expiresAt: number }>();
|
|
16
|
+
private jobWrite: Promise<void> = Promise.resolve();
|
|
17
|
+
|
|
18
|
+
private async serialJobWrite<T>(write: () => Promise<T>): Promise<T> {
|
|
19
|
+
const work = this.jobWrite.then(write);
|
|
20
|
+
this.jobWrite = work.then(() => undefined, () => undefined);
|
|
21
|
+
return await work;
|
|
22
|
+
}
|
|
14
23
|
|
|
15
24
|
constructor(private readonly path: string) {}
|
|
16
25
|
|
|
@@ -39,25 +48,46 @@ export class JsonlStore implements RuntimeStateStore {
|
|
|
39
48
|
}
|
|
40
49
|
|
|
41
50
|
async createJob(job: Job): Promise<void> {
|
|
42
|
-
this.
|
|
43
|
-
|
|
44
|
-
|
|
51
|
+
await this.serialJobWrite(async () => {
|
|
52
|
+
await this.persist(job);
|
|
53
|
+
this.jobs.set(job.job_id, job);
|
|
54
|
+
this.byRequest.set(job.request_id, job.job_id);
|
|
55
|
+
});
|
|
45
56
|
}
|
|
46
57
|
|
|
47
58
|
async updateJob(jobId: string, patch: Partial<Job>): Promise<Job | null> {
|
|
59
|
+
return await this.serialJobWrite(async () => this.writeJob(jobId, patch));
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
private async writeJob(jobId: string, patch: Partial<Job>, expectedStatuses?: Array<Job['status']>): Promise<Job | null> {
|
|
48
63
|
const cur = this.jobs.get(jobId);
|
|
49
|
-
if (!cur) return null;
|
|
50
|
-
const
|
|
51
|
-
|
|
64
|
+
if (!cur || (expectedStatuses && !expectedStatuses.includes(cur.status))) return null;
|
|
65
|
+
const { approval_continuation_keys: _ignored, ...ordinaryPatch } = patch;
|
|
66
|
+
const next: Job = { ...cur, ...ordinaryPatch, updated_at: new Date().toISOString() };
|
|
52
67
|
await this.persist(next);
|
|
68
|
+
this.jobs.set(jobId, next);
|
|
53
69
|
return next;
|
|
54
70
|
}
|
|
55
71
|
|
|
56
72
|
async updateJobIfStatus(jobId: string, expectedStatuses: Array<Job['status']>, patch: Partial<Job>): Promise<Job | null> {
|
|
57
73
|
if (!expectedStatuses.length) return null;
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
74
|
+
return await this.serialJobWrite(async () => this.writeJob(jobId, patch, expectedStatuses));
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
async requeueApprovedJobOnce(input: ApprovalRequeueInput): Promise<ApprovalRequeueOutcome> {
|
|
78
|
+
return await this.serialJobWrite(async () => {
|
|
79
|
+
const plan = approvalRequeuePlan(this.jobs.get(input.job_id) ?? null, input);
|
|
80
|
+
if (plan.patch) {
|
|
81
|
+
if (!input.isApprovedUnused) return 'conflict';
|
|
82
|
+
if (!await input.isApprovedUnused()) return 'consumed';
|
|
83
|
+
const current = this.jobs.get(input.job_id)!;
|
|
84
|
+
const next = { ...current, ...plan.patch, updated_at: new Date().toISOString() };
|
|
85
|
+
// Publish only after durable append succeeds; failed writes remain retryable.
|
|
86
|
+
await this.persist(next);
|
|
87
|
+
this.jobs.set(input.job_id, next);
|
|
88
|
+
}
|
|
89
|
+
return plan.outcome;
|
|
90
|
+
});
|
|
61
91
|
}
|
|
62
92
|
|
|
63
93
|
async getJob(jobId: string): Promise<Job | null> {
|
|
@@ -69,7 +99,7 @@ export class JsonlStore implements RuntimeStateStore {
|
|
|
69
99
|
const nowMs = Date.now();
|
|
70
100
|
for (const job of this.jobs.values()) {
|
|
71
101
|
if (this.isClaimable(job, targets, nowMs)) {
|
|
72
|
-
return await this.
|
|
102
|
+
return await this.updateJobIfStatus(job.job_id, ['queued'], {
|
|
73
103
|
status: 'dispatched',
|
|
74
104
|
executor_id: executorId,
|
|
75
105
|
claimed_at: new Date(nowMs).toISOString(),
|
|
@@ -88,7 +118,7 @@ export class JsonlStore implements RuntimeStateStore {
|
|
|
88
118
|
const nowMs = Date.now();
|
|
89
119
|
for (const job of this.jobs.values()) {
|
|
90
120
|
if (this.isClaimable(job, targets, nowMs)) {
|
|
91
|
-
return await this.
|
|
121
|
+
return await this.updateJobIfStatus(job.job_id, ['queued'], {
|
|
92
122
|
status: 'running',
|
|
93
123
|
executor_id: workerId,
|
|
94
124
|
claimed_at: new Date(nowMs).toISOString(),
|
|
@@ -7,6 +7,8 @@ import type { JobOperationalMetricsSnapshot, RuntimeStateStore } from '../../cor
|
|
|
7
7
|
import { dt, json, rowToJob } from '../../core/state/state-codec';
|
|
8
8
|
import { mysqlJobUpdatePlan } from './state-mysql-update-plan';
|
|
9
9
|
import { MysqlPoolOwner, type MysqlPoolResource } from '../mysql/pool-owner';
|
|
10
|
+
import type { ApprovalRequeueInput, ApprovalRequeueOutcome } from '../../core/contracts/approval-continuation';
|
|
11
|
+
import { approvalRequeuePlan } from '../../core/state/approval-continuation';
|
|
10
12
|
|
|
11
13
|
/** mysql 后端:生产状态库。对应 sql/001_init_state.sql 的 bz_ 表。 */
|
|
12
14
|
export class MysqlStore implements RuntimeStateStore {
|
|
@@ -50,6 +52,31 @@ export class MysqlStore implements RuntimeStateStore {
|
|
|
50
52
|
return this.writeJob(jobId, patch);
|
|
51
53
|
}
|
|
52
54
|
|
|
55
|
+
async requeueApprovedJobOnce(input: ApprovalRequeueInput): Promise<ApprovalRequeueOutcome> {
|
|
56
|
+
const conn = await this.pool.getConnection();
|
|
57
|
+
try {
|
|
58
|
+
await conn.beginTransaction();
|
|
59
|
+
const [rows] = await conn.query('SELECT * FROM bz_jobs WHERE job_id=? FOR UPDATE', [input.job_id]);
|
|
60
|
+
const row = (rows as any[])[0];
|
|
61
|
+
const plan = approvalRequeuePlan(row ? rowToJob(row) : null, input);
|
|
62
|
+
if (plan.patch) {
|
|
63
|
+
const [approvals] = await conn.query('SELECT status,used_at,job_id,request_id,decision_id FROM bz_tool_approvals WHERE id=? FOR UPDATE', [input.approval_id]);
|
|
64
|
+
const approval = (approvals as any[])[0];
|
|
65
|
+
if (!approval || approval.status !== 'approved' || approval.job_id !== input.job_id || approval.request_id !== input.request_id
|
|
66
|
+
|| (approval.decision_id ?? null) !== (input.decision_id ?? null)) { await conn.commit(); return 'conflict'; }
|
|
67
|
+
if (approval.used_at != null) { await conn.commit(); return 'consumed'; }
|
|
68
|
+
const update = mysqlJobUpdatePlan(plan.patch, new Date().toISOString());
|
|
69
|
+
await conn.query(`UPDATE bz_jobs SET ${update.assignments.join(',')},approval_continuation_keys=? WHERE job_id=?`,
|
|
70
|
+
[...update.values, json(plan.patch.approval_continuation_keys), input.job_id]);
|
|
71
|
+
}
|
|
72
|
+
await conn.commit();
|
|
73
|
+
return plan.outcome;
|
|
74
|
+
} catch (error) {
|
|
75
|
+
await conn.rollback().catch(() => undefined);
|
|
76
|
+
throw error;
|
|
77
|
+
} finally { conn.release(); }
|
|
78
|
+
}
|
|
79
|
+
|
|
53
80
|
async updateJobIfStatus(jobId: string, expectedStatuses: Array<Job['status']>, patch: Partial<Job>): Promise<Job | null> {
|
|
54
81
|
if (!expectedStatuses.length) return null;
|
|
55
82
|
return this.writeJob(jobId, patch, expectedStatuses);
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import { mkdtemp, rm } from 'node:fs/promises';
|
|
5
|
+
import { tmpdir } from 'node:os';
|
|
6
|
+
import { join } from 'node:path';
|
|
7
|
+
import { createPool, type RowDataPacket } from 'mysql2/promise';
|
|
8
|
+
import { UsageRepository, usageHash } from './repository';
|
|
9
|
+
import { BillingRepository, getBillingRepository } from './billing-repository';
|
|
10
|
+
import { getUsageIdentity } from './identity';
|
|
11
|
+
import { runUsageMaintenanceFor } from './maintenance';
|
|
12
|
+
import { createBailingHubKernel } from '../../app/kernel';
|
|
13
|
+
import { migrateBailingHubCoreSchema } from '../../infrastructure/schema/core-schema-migrator';
|
|
14
|
+
import type { AppConfig } from '../../core/config/config';
|
|
15
|
+
|
|
16
|
+
const enabled = process.env.BAILING_USAGE_TEST_MYSQL === '1';
|
|
17
|
+
const mysql = { host: '127.0.0.1', port: 16307, user: 'root', password: '', connectionLimit: 8 };
|
|
18
|
+
async function fixture() {
|
|
19
|
+
const database = `usage_reconcile_${randomUUID().replaceAll('-', '')}`;
|
|
20
|
+
const runtimeRoot = await mkdtemp(join(tmpdir(), 'bailing-usage-reconcile-'));
|
|
21
|
+
const admin = createPool(mysql);
|
|
22
|
+
await admin.query(`CREATE DATABASE \`${database}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_bin`);
|
|
23
|
+
let pool: ReturnType<typeof createPool> | undefined;
|
|
24
|
+
const kernels: Array<ReturnType<typeof createBailingHubKernel>> = [];
|
|
25
|
+
const close = async () => {
|
|
26
|
+
for (const kernel of kernels) await kernel.close(5000);
|
|
27
|
+
await pool?.end();
|
|
28
|
+
await admin.query(`DROP DATABASE \`${database}\``); await admin.end();
|
|
29
|
+
await rm(runtimeRoot, { recursive: true, force: true });
|
|
30
|
+
};
|
|
31
|
+
try {
|
|
32
|
+
await migrateBailingHubCoreSchema({ mysql: { ...mysql, database }, logger: { log() {}, warn() {} } });
|
|
33
|
+
await migrateBailingHubCoreSchema({ mysql: { ...mysql, database }, logger: { log() {}, warn() {} } });
|
|
34
|
+
pool = createPool({ ...mysql, database });
|
|
35
|
+
const repository = new UsageRepository(() => pool!), tokens = getBillingRepository(repository), identity = getUsageIdentity(repository);
|
|
36
|
+
const service = await repository.putService({ id: 'synthetic-image', label: 'Synthetic image', expectedRevision: 0,
|
|
37
|
+
config: { credential: 'synthetic-unused', model: 'synthetic', providerScope: database, maxInputBytes: 4096, maxOutputTokens: 100, timeoutMs: 1000 } });
|
|
38
|
+
const issuer = await identity.createIssuer({ id: 'synthetic-issuer', label: 'Synthetic issuer', permissions: ['identity:exchange','identity:revoke'], service_ids: [service.id] });
|
|
39
|
+
const user = await identity.exchange(issuer.credential!, { request_key: randomUUID(), tenant: 'synthetic', subject: 'synthetic-subject', service_id: service.id });
|
|
40
|
+
await tokens.putPlan({ id: 'synthetic-plan', label: 'Synthetic allowance', expected_revision: 0,
|
|
41
|
+
config: { mode: 'credits', serviceIds: [service.id], priceUsd: 100, multiplier: 2, duration: { unit: 'forever', count: 0 } } });
|
|
42
|
+
await tokens.grant(user.session.accountId, { request_key: 'synthetic-grant', plan_id: 'synthetic-plan', expected_revision: 0 });
|
|
43
|
+
const price = { source: 'openrouter' as const, currency: 'USD' as const, modelId: 'synthetic', endpointId: 'synthetic', fetchedAt: Date.now(),
|
|
44
|
+
lines: [{ billable: 'output_image', unit: 'image' as const, costUsd: '0.1' }] };
|
|
45
|
+
async function saved(rawUsage?: Record<string, unknown>, unknown = false, response = { schema: 'synthetic-image', outputs: [{ base64: 'AAAA' }] }) {
|
|
46
|
+
const operationId = randomUUID();
|
|
47
|
+
const admitted = await tokens.admit({ actor: user.session, operationId, serviceId: service.id, conversationId: null, turnId: null,
|
|
48
|
+
requestHash: usageHash([operationId]), expectedServiceRevision: service.revision, serviceConfig: service.config, model: service.config.model, priceSnapshot: price });
|
|
49
|
+
const dispatched = await tokens.commitDispatch(admitted.id, user.session);
|
|
50
|
+
if (unknown) return tokens.markUnknown(admitted.id, dispatched.fence!, 'synthetic_transport_lost');
|
|
51
|
+
return tokens.recordCompletion(admitted.id, dispatched.fence!, { response, ...(rawUsage ? { rawUsage } : {}) });
|
|
52
|
+
}
|
|
53
|
+
async function kernel(schedulerMode: 'managed' | 'standalone' = 'managed') {
|
|
54
|
+
const config: AppConfig = {
|
|
55
|
+
root: process.cwd(), runtimeRoot, env: 'development', server: { host: '127.0.0.1', port: 0, token: '' }, brand: { name: 'Synthetic reconciliation' },
|
|
56
|
+
displayTz: 'Asia/Shanghai', displayTzLabel: '北京时间', auditRetentionDays: 0, alerts: null,
|
|
57
|
+
metrics: { enabled: false, token: '', scrapeTimeoutMs: 1000 }, bootstrapAdmin: null, concurrency: 1,
|
|
58
|
+
killSwitchFile: join(runtimeRoot, '.paused'), claudeBin: 'synthetic-unused', defaultProfile: 'readonly', brainDir: join(runtimeRoot, 'brain'),
|
|
59
|
+
state: { backend: 'mysql', jsonlPath: join(runtimeRoot, 'jobs.jsonl'), mysql: { ...mysql, database } }, projects: {}, llmCredentials: {},
|
|
60
|
+
executor: { hubUrl: '', token: '', executorId: 'synthetic-unused', targets: [], waitMs: 100, concurrency: 1, labels: [] },
|
|
61
|
+
};
|
|
62
|
+
const instance = createBailingHubKernel({ instanceKey: database, config, schedulerMode, bootstrapLocalAdmin: false, logger: { log() {}, warn() {}, error() {} } });
|
|
63
|
+
kernels.push(instance); await instance.initialize(); return instance;
|
|
64
|
+
}
|
|
65
|
+
async function status(id: string) { return (await pool!.query<RowDataPacket[]>('SELECT billing_state,result_state,reference_cost_usd,billed_usd FROM bz_usage_billing_requests WHERE id=?', [id]))[0][0]!; }
|
|
66
|
+
async function ledger() { return Number((await pool!.query<RowDataPacket[]>('SELECT COUNT(*) AS n FROM bz_usage_billing_ledger'))[0][0]!.n); }
|
|
67
|
+
return { pool, database, repository, tokens, identity, user, saved, kernel, status, ledger, close };
|
|
68
|
+
} catch (error) { await close().catch(() => {}); throw error; }
|
|
69
|
+
}
|
|
70
|
+
async function eventually(predicate: () => Promise<boolean>) {
|
|
71
|
+
for (let n = 0; n < 300; n++) { if (await predicate()) return; await new Promise(resolve => setTimeout(resolve, 10)); }
|
|
72
|
+
throw new Error('Synthetic reconciliation did not progress');
|
|
73
|
+
}
|
|
74
|
+
test('MySQL fair pages settle the fifty-first original without reading stored result bodies', { skip: !enabled }, async () => {
|
|
75
|
+
const h = await fixture();
|
|
76
|
+
try {
|
|
77
|
+
const missing = [];
|
|
78
|
+
for (let n = 0; n < 50; n++) missing.push(await h.saved({ requestCount: 1 }));
|
|
79
|
+
const valid = await h.saved({ requestCount: 1, outputImageCount: 1 }, false, { schema: 'synthetic-image', outputs: [{ base64: 'A'.repeat(4 * 1024 * 1024) }] });
|
|
80
|
+
await h.pool.query('UPDATE bz_usage_billing_requests SET updated_at=? WHERE id<>?', [1, valid.id]);
|
|
81
|
+
await h.pool.query('UPDATE bz_usage_billing_requests SET updated_at=? WHERE id=?', [2, valid.id]);
|
|
82
|
+
await h.tokens.reconcilePendingUsage(); assert.equal(await h.ledger(), 0);
|
|
83
|
+
await h.tokens.reconcilePendingUsage(); assert.equal(await h.ledger(), 1);
|
|
84
|
+
assert.equal((await h.status(valid.id)).billing_state, 'settled');
|
|
85
|
+
assert.equal(Number((await h.status(valid.id)).reference_cost_usd), 0.1);
|
|
86
|
+
assert.equal(Number((await h.status(valid.id)).billed_usd), 0.2); // Original shared multiplier remains 2.
|
|
87
|
+
assert.equal((await h.status(missing[0]!.id)).billing_state, 'pending');
|
|
88
|
+
const [bodies] = await h.pool.query<RowDataPacket[]>("SELECT CHAR_LENGTH(JSON_UNQUOTE(JSON_EXTRACT(result_json,'$.outputs[0].base64'))) AS bytes FROM bz_usage_billing_requests WHERE id=?", [valid.id]);
|
|
89
|
+
assert.equal(Number(bodies[0]!.bytes), 4 * 1024 * 1024); // Settlement preserved the body without loading it into its scan.
|
|
90
|
+
await h.tokens.reconcilePendingUsage(); assert.equal(await h.ledger(), 1);
|
|
91
|
+
const [indexes] = await h.pool.query<RowDataPacket[]>("SHOW INDEX FROM bz_usage_billing_requests WHERE Key_name='idx_usage_reconciliation_scan'");
|
|
92
|
+
assert.deepEqual(indexes.sort((a,b) => Number(a.Seq_in_index)-Number(b.Seq_in_index)).map(row => row.Column_name), ['billing_state','updated_at','id']);
|
|
93
|
+
const [plan] = await h.pool.query<RowDataPacket[]>("EXPLAIN SELECT id,updated_at FROM bz_usage_billing_requests WHERE billing_state='pending' AND (usage_json IS NOT NULL OR raw_usage_json IS NOT NULL) AND result_hash IS NOT NULL AND fence IS NOT NULL ORDER BY updated_at,id LIMIT 50");
|
|
94
|
+
assert(String(plan[0]!.possible_keys).includes('idx_usage_reconciliation_scan'));
|
|
95
|
+
} finally { await h.close(); }
|
|
96
|
+
});
|
|
97
|
+
test('revoked identity does not prevent trusted original-evidence settlement; unknown usage remains pending', { skip: !enabled }, async () => {
|
|
98
|
+
const h = await fixture();
|
|
99
|
+
try {
|
|
100
|
+
const valid = await h.saved({ requestCount: 1, outputImageCount: 1 }), unknown = await h.saved(undefined, true);
|
|
101
|
+
await h.identity.revokeSession(h.user.session);
|
|
102
|
+
await h.tokens.scheduleSettlement(valid.operationId, h.user.session);
|
|
103
|
+
assert.equal((await h.status(valid.id)).billing_state, 'pending');
|
|
104
|
+
await runUsageMaintenanceFor(h.repository);
|
|
105
|
+
assert.equal((await h.status(valid.id)).billing_state, 'settled'); assert.equal(await h.ledger(), 1);
|
|
106
|
+
assert.equal((await h.status(unknown.id)).result_state, 'unknown'); assert.equal((await h.status(unknown.id)).billing_state, 'pending');
|
|
107
|
+
} finally { await h.close(); }
|
|
108
|
+
});
|
|
109
|
+
test('a temporary scan SQL outage backs off and recovers from persisted evidence without HTTP', { skip: !enabled }, async () => {
|
|
110
|
+
const h = await fixture();
|
|
111
|
+
try {
|
|
112
|
+
const valid = await h.saved({ requestCount: 1, outputImageCount: 1 });
|
|
113
|
+
const scan = h.tokens.reconcilePendingUsage.bind(h.tokens); let fail = true, attempts = 0;
|
|
114
|
+
h.tokens.reconcilePendingUsage = async () => { attempts++; if (fail) await h.pool.query('SELECT * FROM synthetic_missing_table'); return scan(); };
|
|
115
|
+
await runUsageMaintenanceFor(h.repository, 1); assert.equal((await h.status(valid.id)).billing_state, 'pending');
|
|
116
|
+
fail = false; await runUsageMaintenanceFor(h.repository, 60000); assert.equal(attempts, 1);
|
|
117
|
+
await runUsageMaintenanceFor(h.repository, 60001); assert.equal((await h.status(valid.id)).billing_state, 'settled');
|
|
118
|
+
assert.equal(await h.ledger(), 1);
|
|
119
|
+
} finally { await h.close(); }
|
|
120
|
+
});
|
|
121
|
+
test('a recreated managed Kernel settles durable evidence using initialize/tick without new HTTP', { skip: !enabled }, async () => {
|
|
122
|
+
const h = await fixture();
|
|
123
|
+
try {
|
|
124
|
+
const first = await h.kernel(); await first.close(5000);
|
|
125
|
+
const valid = await h.saved({ requestCount: 1, outputImageCount: 1 });
|
|
126
|
+
const restarted = await h.kernel(); await restarted.tick();
|
|
127
|
+
await eventually(async () => (await h.status(valid.id)).billing_state === 'settled');
|
|
128
|
+
assert.equal(await h.ledger(), 1);
|
|
129
|
+
} finally { await h.close(); }
|
|
130
|
+
});
|
|
131
|
+
test('standalone startup independently reconciles previously saved evidence without HTTP', { skip: !enabled }, async () => {
|
|
132
|
+
const h = await fixture();
|
|
133
|
+
let server: ReturnType<ReturnType<typeof createBailingHubKernel>['createStandaloneServer']> | undefined;
|
|
134
|
+
try {
|
|
135
|
+
const valid = await h.saved({ requestCount: 1, outputImageCount: 1 });
|
|
136
|
+
const kernel = await h.kernel('standalone');
|
|
137
|
+
server = kernel.createStandaloneServer({ exit() {} });
|
|
138
|
+
await server.start(); // The public standalone entry owns timer startup; initialize alone does not.
|
|
139
|
+
await eventually(async () => (await h.status(valid.id)).billing_state === 'settled');
|
|
140
|
+
assert.equal(await h.ledger(), 1);
|
|
141
|
+
} finally { await server?.shutdown('test'); await h.close(); }
|
|
142
|
+
});
|
|
143
|
+
test('two real Kernels isolate SQL/close blockage and preserve pending evidence for same-owner retry', { skip: !enabled }, async () => {
|
|
144
|
+
const one = await fixture(), two = await fixture();
|
|
145
|
+
const original = BillingRepository.prototype.reconcilePendingUsage;
|
|
146
|
+
let blocked = false, release!: () => void;
|
|
147
|
+
const gate = new Promise<void>(resolve => { release = resolve; });
|
|
148
|
+
BillingRepository.prototype.reconcilePendingUsage = async function () {
|
|
149
|
+
const [database] = await this.repository.getPool().query<RowDataPacket[]>('SELECT DATABASE() AS name');
|
|
150
|
+
if (database[0]!.name === one.database) { blocked = true; await gate; }
|
|
151
|
+
return original.call(this);
|
|
152
|
+
};
|
|
153
|
+
try {
|
|
154
|
+
const a = await one.saved({ requestCount: 1, outputImageCount: 1 }), b = await two.saved({ requestCount: 1, outputImageCount: 1 });
|
|
155
|
+
const first = await one.kernel(), second = await two.kernel();
|
|
156
|
+
await first.tick(); await second.tick();
|
|
157
|
+
await eventually(async () => blocked);
|
|
158
|
+
await eventually(async () => (await two.status(b.id)).billing_state === 'settled');
|
|
159
|
+
await assert.rejects(first.close(1), /drain timed out/);
|
|
160
|
+
await second.close(5000); assert.equal(await two.ledger(), 1); assert.equal((await one.status(a.id)).billing_state, 'pending');
|
|
161
|
+
release(); await first.close(5000); assert.equal((await one.status(a.id)).billing_state, 'settled'); assert.equal(await one.ledger(), 1);
|
|
162
|
+
} finally { release(); BillingRepository.prototype.reconcilePendingUsage = original; await one.close(); await two.close(); }
|
|
163
|
+
});
|