bailinghub 0.9.1 → 0.9.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +6 -6
- package/README.md +6 -6
- package/docker-compose.images.yml +2 -2
- package/docs/CHANGELOG.en.md +12 -1
- package/docs/CHANGELOG.md +12 -1
- 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 +22 -14
- package/docs/IMPLEMENTATION_STATUS.md +23 -15
- package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
- package/docs/INDEPENDENT_VALIDATION.md +4 -4
- package/docs/KERNEL_HOST_API.en.md +2 -0
- package/docs/KERNEL_HOST_API.md +2 -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 +5 -0
- package/docs/README.md +5 -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.2.en.md +62 -0
- package/docs/UPGRADE_v0.9.2.md +62 -0
- package/package.json +7 -3
- package/scripts/check-doc-links.mjs +2 -0
- package/scripts/check-image-tags.sh +1 -1
- package/scripts/check-release-consistency.test.mjs +2 -2
- package/scripts/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/publish-images.sh +1 -1
- package/scripts/release-audit.mjs +4 -0
- package/scripts/verify-github-repo.mjs +4 -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.ts +13 -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/billing-reconciliation.mysql.test.ts +163 -0
- package/src/modules/usage/billing-reconciliation.test.ts +71 -0
- package/src/modules/usage/billing-repository.ts +54 -11
- package/src/modules/usage/maintenance.test.ts +62 -0
- package/src/modules/usage/maintenance.ts +31 -0
- package/src/modules/usage/model-gateway.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
|
@@ -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
|
+
}
|
|
@@ -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,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
|
+
});
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import type { UsageRepository } from './repository';
|
|
4
|
+
import { BillingRepository } from './billing-repository';
|
|
5
|
+
|
|
6
|
+
const price = { source: 'openrouter', currency: 'USD', modelId: 'synthetic', endpointId: 'synthetic', fetchedAt: 1,
|
|
7
|
+
lines: [{ billable: 'output_image', unit: 'image', costUsd: '0.1' }] };
|
|
8
|
+
function fixture(count = 51) {
|
|
9
|
+
const records: Record<string, any>[] = Array.from({ length: count }, (_, n) => ({
|
|
10
|
+
id: `request-${String(n).padStart(2, '0')}`, operation_id: `op-${n}`, account_id: 'account', user_id: 'user', session_id: 'session',
|
|
11
|
+
service_id: 'model', conversation_id: null, turn_id: null, request_hash: 'a'.repeat(64), revision: 1, state: 'completed',
|
|
12
|
+
result_state: 'complete', billing_state: 'pending', service_json: {}, service_revision: 1, model: 'synthetic', fence: 'same-fence',
|
|
13
|
+
billing_rate_json: { planId: 'plan', planRevision: 1, multiplier: 1, price }, grant_id: 'grant', grant_revision: 1,
|
|
14
|
+
grant_json: { mode: 'credits', priceUsd: 100, duration: { unit: 'forever', count: 0 } }, period_start: 1, period_end: null,
|
|
15
|
+
result_json: 'INVALID_RESULT_JSON_MUST_NEVER_BE_READ', result_hash: 'b'.repeat(64), usage_json: null,
|
|
16
|
+
raw_usage_json: n === count - 1 ? { requestCount: 1, outputImageCount: 1 } : { requestCount: 1 },
|
|
17
|
+
reference_cost_usd: null, billed_usd: null, overage_usd: null, cancelled_at: null, created_at: n, updated_at: 1,
|
|
18
|
+
}));
|
|
19
|
+
const ledger: string[] = [], attempts: string[] = [], statements: string[] = [];
|
|
20
|
+
const period = { allowance_usd: '100', consumed_usd: '0' };
|
|
21
|
+
const executor = { async query(sql: string, args: any[] = []): Promise<any> {
|
|
22
|
+
statements.push(sql);
|
|
23
|
+
if (sql.includes('ORDER BY updated_at,id LIMIT 50')) {
|
|
24
|
+
let selected = records.filter(r => r.billing_state === 'pending');
|
|
25
|
+
if (args.length) selected = selected.filter(r => r.updated_at > args[0] || (r.updated_at === args[1] && r.id > args[2]));
|
|
26
|
+
return [selected.sort((a, b) => a.updated_at - b.updated_at || a.id.localeCompare(b.id)).slice(0, 50).map(r => ({ id: r.id, updated_at: r.updated_at }))];
|
|
27
|
+
}
|
|
28
|
+
if (sql.startsWith('SELECT account_id FROM bz_usage_billing_requests')) return [[records.find(r => r.id === args[0])]];
|
|
29
|
+
if (sql.startsWith('SELECT * FROM bz_usage_accounts')) return [[{ id: 'account', state: 'active' }]];
|
|
30
|
+
if (sql.includes('NULL AS result_json') && sql.includes('FROM bz_usage_billing_requests WHERE id=?')) {
|
|
31
|
+
if (sql.includes('FOR UPDATE')) attempts.push(args[0]);
|
|
32
|
+
const record = records.find(r => r.id === args[0]);
|
|
33
|
+
return [record ? [{ ...record, result_json: null }] : []];
|
|
34
|
+
}
|
|
35
|
+
if (sql.startsWith('SELECT * FROM bz_usage_billing_periods')) return [[period]];
|
|
36
|
+
if (sql.startsWith('SELECT CAST(UNIX_TIMESTAMP')) return [[{ ms: 1000 }]];
|
|
37
|
+
if (sql.startsWith('UPDATE bz_usage_billing_periods')) { period.consumed_usd = args[0]; return [{}]; }
|
|
38
|
+
if (sql.startsWith('INSERT INTO bz_usage_billing_ledger')) { ledger.push(args[0]); return [{}]; }
|
|
39
|
+
if (sql.startsWith("UPDATE bz_usage_billing_requests SET billing_state='settled'")) {
|
|
40
|
+
Object.assign(records.find(r => r.id === args[4])!, { billing_state: 'settled', reference_cost_usd: args[0], billed_usd: args[1], overage_usd: args[2], updated_at: args[3] });
|
|
41
|
+
return [{}];
|
|
42
|
+
}
|
|
43
|
+
throw new Error('Unexpected synthetic statement');
|
|
44
|
+
} };
|
|
45
|
+
const repository = { getPool: () => executor, withTransaction: async (fn: (c: any) => Promise<any>) => fn(executor) } as unknown as UsageRepository;
|
|
46
|
+
return { tokens: new BillingRepository(repository), records, ledger, attempts, statements, period };
|
|
47
|
+
}
|
|
48
|
+
test('fifty unpriceable originals cannot starve the fifty-first payable result, including equal timestamps', async () => {
|
|
49
|
+
const h = fixture();
|
|
50
|
+
await h.tokens.reconcilePendingUsage();
|
|
51
|
+
assert.equal(h.ledger.length, 0); assert.equal(h.tokens.getReconciliationProgress().scanned, 50);
|
|
52
|
+
await h.tokens.reconcilePendingUsage();
|
|
53
|
+
assert.deepEqual(h.ledger, ['request-50']); assert.equal(h.records[50]!.billed_usd, '0.1');
|
|
54
|
+
await h.tokens.reconcilePendingUsage();
|
|
55
|
+
assert.equal(h.ledger.length, 1); assert.equal(h.period.consumed_usd, '0.1');
|
|
56
|
+
assert.equal(h.records.filter(r => r.billing_state === 'pending').length, 50);
|
|
57
|
+
assert(h.statements.every(sql => !sql.startsWith('SELECT * FROM bz_usage_billing_requests')));
|
|
58
|
+
});
|
|
59
|
+
test('one malformed record does not stop a later valid receipt and progress contains no evidence bodies', async () => {
|
|
60
|
+
const h = fixture(2); h.records[0]!.billing_rate_json = 'SYNTHETIC_MALFORMED_JSON';
|
|
61
|
+
await h.tokens.reconcilePendingUsage();
|
|
62
|
+
assert.deepEqual(h.ledger, ['request-01']);
|
|
63
|
+
assert.deepEqual(h.tokens.getReconciliationProgress(), { scanned: 2, settled: 1, deferred: 0, failed: 1, hasMore: false });
|
|
64
|
+
});
|
|
65
|
+
test('concurrent reconciliation shares one page rather than skipping its cursor', async () => {
|
|
66
|
+
const h = fixture();
|
|
67
|
+
const first = h.tokens.reconcilePendingUsage();
|
|
68
|
+
assert.equal(h.tokens.reconcilePendingUsage(), first);
|
|
69
|
+
await first;
|
|
70
|
+
assert.equal(h.attempts.length, 50);
|
|
71
|
+
});
|