bailinghub 0.9.1 → 0.9.3
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 +23 -1
- package/docs/CHANGELOG.md +23 -1
- package/docs/CORE_RELIABILITY.en.md +79 -0
- package/docs/CORE_RELIABILITY.md +79 -0
- package/docs/DEPLOYMENT_DIAGNOSTICS.en.md +78 -0
- package/docs/DEPLOYMENT_DIAGNOSTICS.md +78 -0
- package/docs/IMPLEMENTATION_STATUS.en.md +27 -15
- package/docs/IMPLEMENTATION_STATUS.md +27 -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/OPERATIONS.en.md +13 -0
- package/docs/OPERATIONS.md +12 -0
- package/docs/README.en.md +7 -0
- package/docs/README.md +7 -0
- package/docs/RELEASE_NOTES_v0.9.2.en.md +45 -0
- package/docs/RELEASE_NOTES_v0.9.2.md +45 -0
- package/docs/RELEASE_NOTES_v0.9.3.en.md +51 -0
- package/docs/RELEASE_NOTES_v0.9.3.md +51 -0
- package/docs/TOOLS_DESIGN.md +1 -0
- package/docs/UPGRADE_v0.9.2.en.md +62 -0
- package/docs/UPGRADE_v0.9.2.md +62 -0
- package/docs/UPGRADE_v0.9.3.en.md +63 -0
- package/docs/UPGRADE_v0.9.3.md +63 -0
- package/package.json +7 -3
- 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/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 +8 -0
- package/scripts/verify-github-repo.mjs +8 -0
- package/security/dependency-audit-exceptions.json +1 -1
- package/sql/065_usage_reconciliation_scan.sql +4 -0
- package/sql/066_approval_continuations.sql +15 -0
- package/sql/067_delivery_dlq_replay.sql +10 -0
- package/sql/README.en.md +6 -0
- package/sql/README.md +15 -0
- package/src/adapters/llm/file.test.ts +59 -0
- package/src/adapters/llm/file.ts +11 -4
- package/src/app/agent-tool-invocations.test.ts +3 -1
- package/src/app/approval-continuations.mysql.test.ts +138 -0
- package/src/app/approval-continuations.test.ts +351 -0
- package/src/app/approval-continuations.ts +148 -0
- package/src/app/channels-attachments.test.ts +63 -0
- package/src/app/channels.ts +7 -4
- package/src/app/delivery-dlq-replay.mysql.test.ts +139 -0
- package/src/app/delivery-dlq-replay.test.ts +75 -0
- package/src/app/delivery-dlq-replay.ts +41 -0
- package/src/app/delivery.ts +3 -2
- package/src/app/http-server.ts +3 -0
- package/src/app/kernel-model-process-crash.mysql.test.ts +377 -0
- package/src/app/kernel-notification-lifecycle.test.ts +49 -0
- package/src/app/kernel.ts +22 -0
- package/src/app/notification-outbound.test.ts +53 -0
- package/src/app/operational-metrics.test.ts +37 -1
- package/src/app/operational-metrics.ts +25 -2
- package/src/app/outbound.ts +13 -2
- package/src/app/runtime-evidence-maintenance.test.ts +55 -0
- package/src/app/runtime-lifecycle-default.ts +7 -0
- package/src/app/runtime-lifecycle.test.ts +89 -0
- package/src/app/runtime-lifecycle.ts +52 -11
- package/src/app/tool-approvals.ts +2 -1
- package/src/core/contracts/approval-continuation.ts +43 -0
- package/src/core/contracts/delivery-replay.ts +41 -0
- package/src/core/contracts/tools-idempotency.test.ts +121 -5
- package/src/core/contracts/tools.ts +21 -11
- package/src/core/contracts/types.ts +4 -0
- package/src/core/observability/openmetrics.test.ts +28 -0
- package/src/core/observability/openmetrics.ts +91 -0
- package/src/core/platform/http-body.test.ts +185 -0
- package/src/core/platform/http-body.ts +58 -0
- package/src/core/runtime/finish-runtime.test.ts +2 -0
- package/src/core/runtime/finish-runtime.ts +10 -7
- package/src/core/runtime/notification-background-work.test.ts +50 -0
- package/src/core/runtime/notification-background-work.ts +101 -0
- package/src/core/state/approval-continuation.ts +22 -0
- package/src/core/state/delivery-replay.ts +19 -0
- package/src/core/state/state-codec.ts +2 -0
- package/src/core/state/state-contracts.ts +6 -0
- package/src/infrastructure/config/config-approval-ledger.ts +75 -0
- package/src/infrastructure/config/config-delivery-dlq-ledger.ts +36 -10
- package/src/infrastructure/config/configstore.ts +4 -3
- package/src/infrastructure/state/state-jsonl.ts +56 -11
- package/src/infrastructure/state/state-mysql.ts +54 -0
- package/src/modules/usage/background-work.test.ts +28 -0
- package/src/modules/usage/background-work.ts +43 -7
- package/src/modules/usage/billing-reconciliation.mysql.test.ts +163 -0
- package/src/modules/usage/billing-reconciliation.test.ts +85 -0
- package/src/modules/usage/billing-repository.ts +63 -11
- package/src/modules/usage/maintenance.test.ts +78 -0
- package/src/modules/usage/maintenance.ts +39 -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 +39 -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
|
@@ -5,12 +5,23 @@ 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';
|
|
10
|
+
import { deliveryRequeuePlan } from '../../core/state/delivery-replay';
|
|
11
|
+
import type { DeliveryRequeueInput, DeliveryRequeueOutcome } from '../../core/contracts/delivery-replay';
|
|
8
12
|
|
|
9
13
|
/** jsonl 后端:本地烟测与最小私有部署。状态仍是中枢自己的,不进业务库。 */
|
|
10
14
|
export class JsonlStore implements RuntimeStateStore {
|
|
11
15
|
private readonly jobs = new Map<string, Job>();
|
|
12
16
|
private readonly byRequest = new Map<string, string>();
|
|
13
17
|
private readonly locks = new Map<string, { owner: string; expiresAt: number }>();
|
|
18
|
+
private jobWrite: Promise<void> = Promise.resolve();
|
|
19
|
+
|
|
20
|
+
private async serialJobWrite<T>(write: () => Promise<T>): Promise<T> {
|
|
21
|
+
const work = this.jobWrite.then(write);
|
|
22
|
+
this.jobWrite = work.then(() => undefined, () => undefined);
|
|
23
|
+
return await work;
|
|
24
|
+
}
|
|
14
25
|
|
|
15
26
|
constructor(private readonly path: string) {}
|
|
16
27
|
|
|
@@ -39,37 +50,71 @@ export class JsonlStore implements RuntimeStateStore {
|
|
|
39
50
|
}
|
|
40
51
|
|
|
41
52
|
async createJob(job: Job): Promise<void> {
|
|
42
|
-
this.
|
|
43
|
-
|
|
44
|
-
|
|
53
|
+
await this.serialJobWrite(async () => {
|
|
54
|
+
await this.persist(job);
|
|
55
|
+
this.jobs.set(job.job_id, job);
|
|
56
|
+
this.byRequest.set(job.request_id, job.job_id);
|
|
57
|
+
});
|
|
45
58
|
}
|
|
46
59
|
|
|
47
60
|
async updateJob(jobId: string, patch: Partial<Job>): Promise<Job | null> {
|
|
61
|
+
return await this.serialJobWrite(async () => this.writeJob(jobId, patch));
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
private async writeJob(jobId: string, patch: Partial<Job>, expectedStatuses?: Array<Job['status']>): Promise<Job | null> {
|
|
48
65
|
const cur = this.jobs.get(jobId);
|
|
49
|
-
if (!cur) return null;
|
|
50
|
-
const
|
|
51
|
-
|
|
66
|
+
if (!cur || (expectedStatuses && !expectedStatuses.includes(cur.status))) return null;
|
|
67
|
+
const { approval_continuation_keys: _ignored, delivery_replay_keys: _ignoredDelivery, ...ordinaryPatch } = patch;
|
|
68
|
+
const next: Job = { ...cur, ...ordinaryPatch, updated_at: new Date().toISOString() };
|
|
52
69
|
await this.persist(next);
|
|
70
|
+
this.jobs.set(jobId, next);
|
|
53
71
|
return next;
|
|
54
72
|
}
|
|
55
73
|
|
|
56
74
|
async updateJobIfStatus(jobId: string, expectedStatuses: Array<Job['status']>, patch: Partial<Job>): Promise<Job | null> {
|
|
57
75
|
if (!expectedStatuses.length) return null;
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
76
|
+
return await this.serialJobWrite(async () => this.writeJob(jobId, patch, expectedStatuses));
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async requeueApprovedJobOnce(input: ApprovalRequeueInput): Promise<ApprovalRequeueOutcome> {
|
|
80
|
+
return await this.serialJobWrite(async () => {
|
|
81
|
+
const plan = approvalRequeuePlan(this.jobs.get(input.job_id) ?? null, input);
|
|
82
|
+
if (plan.patch) {
|
|
83
|
+
if (!input.isApprovedUnused) return 'conflict';
|
|
84
|
+
if (!await input.isApprovedUnused()) return 'consumed';
|
|
85
|
+
const current = this.jobs.get(input.job_id)!;
|
|
86
|
+
const next = { ...current, ...plan.patch, updated_at: new Date().toISOString() };
|
|
87
|
+
// Publish only after durable append succeeds; failed writes remain retryable.
|
|
88
|
+
await this.persist(next);
|
|
89
|
+
this.jobs.set(input.job_id, next);
|
|
90
|
+
}
|
|
91
|
+
return plan.outcome;
|
|
92
|
+
});
|
|
61
93
|
}
|
|
62
94
|
|
|
63
95
|
async getJob(jobId: string): Promise<Job | null> {
|
|
64
96
|
return this.jobs.get(jobId) ?? null;
|
|
65
97
|
}
|
|
66
98
|
|
|
99
|
+
async requeueDeliveryJobOnce(input: DeliveryRequeueInput): Promise<DeliveryRequeueOutcome> {
|
|
100
|
+
return await this.serialJobWrite(async () => {
|
|
101
|
+
const plan = deliveryRequeuePlan(this.jobs.get(input.job_id) ?? null, input);
|
|
102
|
+
if (plan.patch) {
|
|
103
|
+
if (!input.isOriginalDelivery || !await input.isOriginalDelivery()) return 'conflict';
|
|
104
|
+
const next = { ...this.jobs.get(input.job_id)!, ...plan.patch, updated_at: new Date().toISOString() };
|
|
105
|
+
await this.persist(next);
|
|
106
|
+
this.jobs.set(input.job_id, next);
|
|
107
|
+
}
|
|
108
|
+
return plan.outcome;
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
|
|
67
112
|
async claimNextJob(targets: string[], executorId: string, leaseMs: number): Promise<Job | null> {
|
|
68
113
|
if (!targets.length) return null;
|
|
69
114
|
const nowMs = Date.now();
|
|
70
115
|
for (const job of this.jobs.values()) {
|
|
71
116
|
if (this.isClaimable(job, targets, nowMs)) {
|
|
72
|
-
return await this.
|
|
117
|
+
return await this.updateJobIfStatus(job.job_id, ['queued'], {
|
|
73
118
|
status: 'dispatched',
|
|
74
119
|
executor_id: executorId,
|
|
75
120
|
claimed_at: new Date(nowMs).toISOString(),
|
|
@@ -88,7 +133,7 @@ export class JsonlStore implements RuntimeStateStore {
|
|
|
88
133
|
const nowMs = Date.now();
|
|
89
134
|
for (const job of this.jobs.values()) {
|
|
90
135
|
if (this.isClaimable(job, targets, nowMs)) {
|
|
91
|
-
return await this.
|
|
136
|
+
return await this.updateJobIfStatus(job.job_id, ['queued'], {
|
|
92
137
|
status: 'running',
|
|
93
138
|
executor_id: workerId,
|
|
94
139
|
claimed_at: new Date(nowMs).toISOString(),
|
|
@@ -7,6 +7,10 @@ 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';
|
|
12
|
+
import { deliveryRequeuePlan } from '../../core/state/delivery-replay';
|
|
13
|
+
import { isOriginalExecutorDelivery, type DeliveryRequeueInput, type DeliveryRequeueOutcome } from '../../core/contracts/delivery-replay';
|
|
10
14
|
|
|
11
15
|
/** mysql 后端:生产状态库。对应 sql/001_init_state.sql 的 bz_ 表。 */
|
|
12
16
|
export class MysqlStore implements RuntimeStateStore {
|
|
@@ -50,11 +54,61 @@ export class MysqlStore implements RuntimeStateStore {
|
|
|
50
54
|
return this.writeJob(jobId, patch);
|
|
51
55
|
}
|
|
52
56
|
|
|
57
|
+
async requeueApprovedJobOnce(input: ApprovalRequeueInput): Promise<ApprovalRequeueOutcome> {
|
|
58
|
+
const conn = await this.pool.getConnection();
|
|
59
|
+
try {
|
|
60
|
+
await conn.beginTransaction();
|
|
61
|
+
const [rows] = await conn.query('SELECT * FROM bz_jobs WHERE job_id=? FOR UPDATE', [input.job_id]);
|
|
62
|
+
const row = (rows as any[])[0];
|
|
63
|
+
const plan = approvalRequeuePlan(row ? rowToJob(row) : null, input);
|
|
64
|
+
if (plan.patch) {
|
|
65
|
+
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]);
|
|
66
|
+
const approval = (approvals as any[])[0];
|
|
67
|
+
if (!approval || approval.status !== 'approved' || approval.job_id !== input.job_id || approval.request_id !== input.request_id
|
|
68
|
+
|| (approval.decision_id ?? null) !== (input.decision_id ?? null)) { await conn.commit(); return 'conflict'; }
|
|
69
|
+
if (approval.used_at != null) { await conn.commit(); return 'consumed'; }
|
|
70
|
+
const update = mysqlJobUpdatePlan(plan.patch, new Date().toISOString());
|
|
71
|
+
await conn.query(`UPDATE bz_jobs SET ${update.assignments.join(',')},approval_continuation_keys=? WHERE job_id=?`,
|
|
72
|
+
[...update.values, json(plan.patch.approval_continuation_keys), input.job_id]);
|
|
73
|
+
}
|
|
74
|
+
await conn.commit();
|
|
75
|
+
return plan.outcome;
|
|
76
|
+
} catch (error) {
|
|
77
|
+
await conn.rollback().catch(() => undefined);
|
|
78
|
+
throw error;
|
|
79
|
+
} finally { conn.release(); }
|
|
80
|
+
}
|
|
81
|
+
|
|
53
82
|
async updateJobIfStatus(jobId: string, expectedStatuses: Array<Job['status']>, patch: Partial<Job>): Promise<Job | null> {
|
|
54
83
|
if (!expectedStatuses.length) return null;
|
|
55
84
|
return this.writeJob(jobId, patch, expectedStatuses);
|
|
56
85
|
}
|
|
57
86
|
|
|
87
|
+
async requeueDeliveryJobOnce(input: DeliveryRequeueInput): Promise<DeliveryRequeueOutcome> {
|
|
88
|
+
const conn = await this.pool.getConnection();
|
|
89
|
+
try {
|
|
90
|
+
await conn.beginTransaction();
|
|
91
|
+
const [rows] = await conn.query('SELECT * FROM bz_jobs WHERE job_id=? FOR UPDATE', [input.job_id]);
|
|
92
|
+
const row = (rows as any[])[0];
|
|
93
|
+
const job = row ? rowToJob(row) : null;
|
|
94
|
+
const plan = deliveryRequeuePlan(job, input);
|
|
95
|
+
if (plan.patch) {
|
|
96
|
+
const [dlqs] = await conn.query('SELECT * FROM bz_delivery_dlq WHERE id=? FOR UPDATE', [input.dlq_id]);
|
|
97
|
+
const dlq = (dlqs as any[])[0];
|
|
98
|
+
if (!dlq || dlq.resolved || dlq.executor_replay_key !== input.replay_key || !isOriginalExecutorDelivery(dlq, job)) {
|
|
99
|
+
await conn.commit(); return 'conflict';
|
|
100
|
+
}
|
|
101
|
+
const update = mysqlJobUpdatePlan(plan.patch, new Date().toISOString());
|
|
102
|
+
await conn.query(`UPDATE bz_jobs SET ${update.assignments.join(',')},delivery_replay_keys=? WHERE job_id=?`,
|
|
103
|
+
[...update.values, json(plan.patch.delivery_replay_keys), input.job_id]);
|
|
104
|
+
}
|
|
105
|
+
await conn.commit();
|
|
106
|
+
return plan.outcome;
|
|
107
|
+
} catch (error) {
|
|
108
|
+
await conn.rollback().catch(() => undefined); throw error;
|
|
109
|
+
} finally { conn.release(); }
|
|
110
|
+
}
|
|
111
|
+
|
|
58
112
|
private async writeJob(jobId: string, patch: Partial<Job>, expectedStatuses?: Array<Job['status']>): Promise<Job | null> {
|
|
59
113
|
const plan = mysqlJobUpdatePlan(patch, new Date().toISOString());
|
|
60
114
|
const whereStatus = expectedStatuses?.length ? ` AND status IN (${expectedStatuses.map(() => '?').join(',')})` : '';
|
|
@@ -142,3 +142,31 @@ test('a throwing failure reporter cannot keep rejected work live or replace its
|
|
|
142
142
|
owner.beginDrain();
|
|
143
143
|
assert.equal(await owner.drain(100), true);
|
|
144
144
|
});
|
|
145
|
+
|
|
146
|
+
test('fixed-kind snapshots expose accepted work age and outcomes without error bodies or mutable state', async () => {
|
|
147
|
+
let now = 1000;
|
|
148
|
+
const owner = new UsageBackgroundWork(() => now), held = gate();
|
|
149
|
+
const pending = owner.track('model-completion', () => held.promise);
|
|
150
|
+
const failed = owner.track('settlement', async () => { throw new Error('PRIVATE_PROVIDER_BODY_TOKEN'); });
|
|
151
|
+
await assert.rejects(failed);
|
|
152
|
+
now = 5000;
|
|
153
|
+
const snapshot = owner.snapshot();
|
|
154
|
+
assert.equal(snapshot.kinds.find(value => value.kind === 'model-completion')!.inFlight, 1);
|
|
155
|
+
assert.equal(snapshot.kinds.find(value => value.kind === 'model-completion')!.oldestPendingAgeMs, 4000);
|
|
156
|
+
assert.equal(snapshot.kinds.find(value => value.kind === 'settlement')!.failed, 1);
|
|
157
|
+
assert.equal(snapshot.kinds.find(value => value.kind === 'settlement')!.lastFailedAt, new Date(1000).toISOString());
|
|
158
|
+
assert.doesNotMatch(JSON.stringify(snapshot), /PRIVATE_PROVIDER|TOKEN/);
|
|
159
|
+
snapshot.kinds[0]!.completed = 1000;
|
|
160
|
+
assert.equal(owner.snapshot().kinds[0]!.completed, 0);
|
|
161
|
+
owner.beginDrain();
|
|
162
|
+
assert.equal(await owner.drain(0), false);
|
|
163
|
+
assert.equal(owner.snapshot().drainTimeouts, 1);
|
|
164
|
+
held.release(); await pending;
|
|
165
|
+
assert.equal(await owner.drain(100), true);
|
|
166
|
+
const done = owner.snapshot();
|
|
167
|
+
assert.equal(done.draining, true);
|
|
168
|
+
assert.equal(done.kinds[0]!.inFlight, 0);
|
|
169
|
+
assert.equal(done.kinds[0]!.oldestPendingAgeMs, 0);
|
|
170
|
+
assert.equal(done.kinds[0]!.completed, 1);
|
|
171
|
+
assert.equal(done.kinds[0]!.lastCompletedAt, new Date(5000).toISOString());
|
|
172
|
+
});
|
|
@@ -1,23 +1,59 @@
|
|
|
1
|
-
|
|
1
|
+
import type { BackgroundWorkMetricsSnapshot } from '../../core/observability/openmetrics';
|
|
2
|
+
|
|
3
|
+
export const USAGE_BACKGROUND_KINDS = ['model-completion', 'settlement', 'response-cleanup', 'usage-reconciliation', 'reference-price-refresh'] as const;
|
|
4
|
+
export type UsageBackgroundKind = typeof USAGE_BACKGROUND_KINDS[number];
|
|
2
5
|
type MaintenanceKind = Exclude<UsageBackgroundKind, 'model-completion' | 'settlement'>;
|
|
3
6
|
|
|
4
7
|
/** One UsageRepository owns its accepted work, including children created during drain. */
|
|
5
8
|
export class UsageBackgroundWork {
|
|
6
|
-
private readonly pending = new
|
|
9
|
+
private readonly pending = new Map<Promise<unknown>, { kind: UsageBackgroundKind; startedAt: number }>();
|
|
10
|
+
private readonly counts = new Map(USAGE_BACKGROUND_KINDS.map(kind => [kind, {
|
|
11
|
+
completed: 0, failed: 0,
|
|
12
|
+
lastStartedAt: null as string | null, lastCompletedAt: null as string | null, lastFailedAt: null as string | null,
|
|
13
|
+
}]));
|
|
7
14
|
private draining = false;
|
|
15
|
+
private drainTimeouts = 0;
|
|
8
16
|
private failureReporter: ((kind: UsageBackgroundKind) => void) | undefined;
|
|
9
17
|
|
|
18
|
+
constructor(private readonly clock: () => number = Date.now) {}
|
|
19
|
+
|
|
10
20
|
get acceptingRequests(): boolean { return !this.draining; }
|
|
11
21
|
setFailureReporter(reporter: (kind: UsageBackgroundKind) => void): void { this.failureReporter = reporter; }
|
|
12
22
|
beginDrain(): void { this.draining = true; }
|
|
13
23
|
|
|
24
|
+
/** Process-local fixed-kind values only; snapshots never start work or access SQL. */
|
|
25
|
+
snapshot(nowMs = this.clock()): BackgroundWorkMetricsSnapshot {
|
|
26
|
+
const live = new Map(USAGE_BACKGROUND_KINDS.map(kind => [kind, { count: 0, oldest: Infinity }]));
|
|
27
|
+
for (const work of this.pending.values()) {
|
|
28
|
+
const value = live.get(work.kind)!;
|
|
29
|
+
value.count++; value.oldest = Math.min(value.oldest, work.startedAt);
|
|
30
|
+
}
|
|
31
|
+
return {
|
|
32
|
+
draining: this.draining,
|
|
33
|
+
drainTimeouts: this.drainTimeouts,
|
|
34
|
+
kinds: USAGE_BACKGROUND_KINDS.map(kind => {
|
|
35
|
+
const value = live.get(kind)!;
|
|
36
|
+
return { kind, ...this.counts.get(kind)!, inFlight: value.count,
|
|
37
|
+
oldestPendingAgeMs: value.count ? Math.max(0, nowMs - value.oldest) : 0 };
|
|
38
|
+
}),
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
|
|
14
42
|
track<T>(kind: UsageBackgroundKind, run: () => Promise<T>): Promise<T> {
|
|
15
43
|
// Register before invoking run: even an immediately resolving parent must not
|
|
16
44
|
// leave a gap before its SQL/settlement continuation has been registered.
|
|
17
45
|
const work = Promise.resolve().then(run);
|
|
18
|
-
this.
|
|
19
|
-
|
|
46
|
+
const startedAt = this.clock(), counts = this.counts.get(kind)!;
|
|
47
|
+
this.pending.set(work, { kind, startedAt });
|
|
48
|
+
counts.lastStartedAt = new Date(startedAt).toISOString();
|
|
49
|
+
void work.then(() => {
|
|
50
|
+
this.pending.delete(work);
|
|
51
|
+
counts.completed++;
|
|
52
|
+
counts.lastCompletedAt = new Date(this.clock()).toISOString();
|
|
53
|
+
}, () => {
|
|
20
54
|
this.pending.delete(work);
|
|
55
|
+
counts.failed++;
|
|
56
|
+
counts.lastFailedAt = new Date(this.clock()).toISOString();
|
|
21
57
|
// Report only the fixed work kind; provider bodies, SQL and credentials
|
|
22
58
|
// are never included in lifecycle diagnostics.
|
|
23
59
|
try { this.failureReporter?.(kind); } catch { /* diagnostics cannot own lifecycle */ }
|
|
@@ -33,14 +69,14 @@ export class UsageBackgroundWork {
|
|
|
33
69
|
const deadline = Date.now() + Math.max(0, drainMs);
|
|
34
70
|
while (this.pending.size) {
|
|
35
71
|
const remaining = deadline - Date.now();
|
|
36
|
-
if (remaining <= 0) return false;
|
|
72
|
+
if (remaining <= 0) { this.drainTimeouts++; return false; }
|
|
37
73
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
38
74
|
try {
|
|
39
75
|
const drained = await Promise.race([
|
|
40
|
-
Promise.allSettled([...this.pending]).then(() => true),
|
|
76
|
+
Promise.allSettled([...this.pending.keys()]).then(() => true),
|
|
41
77
|
new Promise<boolean>(resolve => { timer = setTimeout(() => resolve(false), remaining); }),
|
|
42
78
|
]);
|
|
43
|
-
if (!drained) return false;
|
|
79
|
+
if (!drained) { this.drainTimeouts++; return false; }
|
|
44
80
|
} finally { if (timer) clearTimeout(timer); }
|
|
45
81
|
// A tracked completion can register settlement after drain started. Do
|
|
46
82
|
// not mistake a finished snapshot for a quiescent repository.
|
|
@@ -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,85 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import type { UsageRepository } from './repository';
|
|
4
|
+
import { getBillingRepository, usageReconciliationSnapshotFor } 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: getBillingRepository(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
|
+
});
|
|
72
|
+
|
|
73
|
+
test('readonly reconciliation snapshot is absent before the first page and returns detached aggregate values afterward', async () => {
|
|
74
|
+
const h = fixture(2);
|
|
75
|
+
assert.equal(usageReconciliationSnapshotFor(h.tokens.repository), undefined);
|
|
76
|
+
const before = h.statements.length;
|
|
77
|
+
assert.equal(usageReconciliationSnapshotFor(h.tokens.repository), undefined);
|
|
78
|
+
assert.equal(h.statements.length, before);
|
|
79
|
+
await h.tokens.reconcilePendingUsage();
|
|
80
|
+
const snapshot = usageReconciliationSnapshotFor(h.tokens.repository)!;
|
|
81
|
+
assert.equal(snapshot.scanned, 2);
|
|
82
|
+
snapshot.scanned = 999;
|
|
83
|
+
assert.equal(usageReconciliationSnapshotFor(h.tokens.repository)!.scanned, 2);
|
|
84
|
+
assert.doesNotMatch(JSON.stringify(snapshot), /account|request|SYNTHETIC|result_json/);
|
|
85
|
+
});
|