bailinghub 0.8.0 → 0.9.0

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.
Files changed (184) hide show
  1. package/README.en.md +6 -5
  2. package/README.md +6 -5
  3. package/docker-compose.images.yml +2 -2
  4. package/docs/ARCHITECTURE.md +1 -1
  5. package/docs/CHANGELOG.en.md +12 -1
  6. package/docs/CHANGELOG.md +12 -1
  7. package/docs/COMPATIBILITY.en.md +4 -0
  8. package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
  9. package/docs/INDEPENDENT_VALIDATION.md +4 -4
  10. package/docs/MODEL_BILLING.en.md +123 -0
  11. package/docs/MODEL_BILLING.md +125 -0
  12. package/docs/PERIOD_ALLOWANCE_UPGRADE.en.md +31 -0
  13. package/docs/PERIOD_ALLOWANCE_UPGRADE.md +31 -0
  14. package/docs/README.en.md +5 -1
  15. package/docs/README.md +4 -0
  16. package/docs/RELEASE_NOTES_NEXT.en.md +4 -2
  17. package/docs/RELEASE_NOTES_NEXT.md +4 -2
  18. package/docs/RELEASE_NOTES_v0.9.0.en.md +45 -0
  19. package/docs/RELEASE_NOTES_v0.9.0.md +45 -0
  20. package/docs/UPGRADE_v0.9.0.en.md +54 -0
  21. package/docs/UPGRADE_v0.9.0.md +54 -0
  22. package/docs//345/205/274/345/256/271/346/200/247/344/270/216/345/215/207/347/272/247.md +4 -0
  23. package/package.json +1 -1
  24. package/scripts/check-doc-links.mjs +4 -0
  25. package/scripts/check-image-tags.sh +1 -1
  26. package/scripts/check-release-consistency.test.mjs +2 -2
  27. package/scripts/install.sh +1 -1
  28. package/scripts/publish-images.sh +1 -1
  29. package/scripts/release-audit.mjs +1 -0
  30. package/scripts/sdk-runtime-test.mjs +6 -0
  31. package/scripts/verify-billing-install-upgrade.mjs +225 -0
  32. package/scripts/verify-github-repo.mjs +1 -0
  33. package/sdk/node/README.md +17 -0
  34. package/sdk/node/examples/billing.mjs +21 -0
  35. package/sdk/node/package.json +5 -1
  36. package/sdk/node/src/index.mjs +2 -0
  37. package/sdk/node/src/usage.d.mts +74 -0
  38. package/sdk/node/src/usage.mjs +62 -0
  39. package/sdk/node/tests/usage-types.mts +23 -0
  40. package/sdk/node/tests/usage.test.mjs +81 -0
  41. package/sdk/php7/README.md +19 -2
  42. package/sdk/php7/examples/billing.php +27 -0
  43. package/sdk/php7/examples/well-known.php +1 -1
  44. package/sdk/php7/src/ToolSpec.php +1 -1
  45. package/sdk/php7/src/UsageClient.php +95 -0
  46. package/sdk/php7/src/UsageClientException.php +22 -0
  47. package/sdk/php7/tests/billing-core-http.php +59 -0
  48. package/sdk/php7/tests/usage-client.php +78 -0
  49. package/sql/063_usage_model_billing.sql +153 -0
  50. package/sql/064_period_plan_allowance.sql +25 -0
  51. package/sql/README.en.md +12 -4
  52. package/sql/README.md +14 -6
  53. package/src/app/auth.ts +2 -0
  54. package/src/app/oss-edition.ts +1 -0
  55. package/src/infrastructure/config/configstore.ts +6 -0
  56. package/src/modules/usage/allowance-reset.mysql.test.ts +122 -0
  57. package/src/modules/usage/billing-contracts.ts +59 -0
  58. package/src/modules/usage/billing-decimal.test.ts +22 -0
  59. package/src/modules/usage/billing-decimal.ts +36 -0
  60. package/src/modules/usage/billing-external.ts +39 -0
  61. package/src/modules/usage/billing-gateway.mysql.test.ts +24 -0
  62. package/src/modules/usage/billing-ledger.test.ts +51 -0
  63. package/src/modules/usage/billing-ledger.ts +104 -0
  64. package/src/modules/usage/billing-presentation.mysql.test.ts +95 -0
  65. package/src/modules/usage/billing-presentation.test.ts +49 -0
  66. package/src/modules/usage/billing-presentation.ts +34 -0
  67. package/src/modules/usage/billing-prices.mysql.test.ts +88 -0
  68. package/src/modules/usage/billing-repository.mysql.test.ts +181 -0
  69. package/src/modules/usage/billing-repository.ts +463 -0
  70. package/src/modules/usage/contracts.ts +49 -0
  71. package/src/modules/usage/dynamic-plan-models.mysql.test.ts +221 -0
  72. package/src/modules/usage/errors.ts +19 -0
  73. package/src/modules/usage/http.ts +85 -0
  74. package/src/modules/usage/identity-revocation.mysql.test.ts +286 -0
  75. package/src/modules/usage/identity.mysql.test.ts +120 -0
  76. package/src/modules/usage/identity.ts +303 -0
  77. package/src/modules/usage/issuer-sdk-billing.mysql.test.ts +92 -0
  78. package/src/modules/usage/model-gateway.mysql.test.ts +207 -0
  79. package/src/modules/usage/model-gateway.ts +229 -0
  80. package/src/modules/usage/model-tool-gateway.mysql.test.ts +137 -0
  81. package/src/modules/usage/model-tool-provider.test.ts +37 -0
  82. package/src/modules/usage/model-tool-provider.ts +110 -0
  83. package/src/modules/usage/model-tools.test.ts +36 -0
  84. package/src/modules/usage/model-tools.ts +62 -0
  85. package/src/modules/usage/period-allowance.mysql.test.ts +97 -0
  86. package/src/modules/usage/period.test.ts +26 -0
  87. package/src/modules/usage/period.ts +96 -0
  88. package/src/modules/usage/pricing.test.ts +178 -0
  89. package/src/modules/usage/pricing.ts +228 -0
  90. package/src/modules/usage/provider-failure.ts +37 -0
  91. package/src/modules/usage/provider-stream.test.ts +85 -0
  92. package/src/modules/usage/provider-stream.ts +77 -0
  93. package/src/modules/usage/provider.test.ts +67 -0
  94. package/src/modules/usage/provider.ts +142 -0
  95. package/src/modules/usage/repository.ts +539 -0
  96. package/src/modules/usage/service-availability.mysql.test.ts +68 -0
  97. package/src/modules/usage/service-availability.ts +13 -0
  98. package/src/modules/usage/service-delete.mysql.test.ts +87 -0
  99. package/src/modules/usage/stream-http.ts +32 -0
  100. package/src/modules/usage/test-harness.ts +108 -0
  101. package/src/modules/usage/usage-deletion.mysql.test.ts +312 -0
  102. package/src/modules/usage/usage-deletion.ts +119 -0
  103. package/src/modules/usage/validation.test.ts +18 -0
  104. package/src/modules/usage/validation.ts +33 -0
  105. package/src/routes/admin-billing-usage.ts +73 -0
  106. package/src/routes/admin-usage.ts +147 -0
  107. package/src/routes/admin.ts +4 -0
  108. package/src/routes/private.ts +8 -0
  109. package/web/connect/bailing-connect-php7.tgz +0 -0
  110. package/web/console/assets/Accounts-Bervi5JU.css +1 -0
  111. package/web/console/assets/Accounts-DnddhY6t.js +3 -0
  112. package/web/console/assets/{AgentClients-Bf7sUUs_.js → AgentClients-VInbD7JS.js} +1 -1
  113. package/web/console/assets/AgentTasks-B-1XklBg.js +2 -0
  114. package/web/console/assets/AgentTasks-BsG850Il.css +1 -0
  115. package/web/console/assets/{Approvals-BIbZvInm.js → Approvals-34qUPHf0.js} +1 -1
  116. package/web/console/assets/{Audit-KyPSmBdZ.js → Audit-BbVgkSm2.js} +1 -1
  117. package/web/console/assets/{BrandLockup-Sv5DU2G6.js → BrandLockup-DgscF28e.js} +1 -1
  118. package/web/console/assets/{Channels-B9n4fbxg.js → Channels-Bp-yuk8d.js} +1 -1
  119. package/web/console/assets/{ChatEntries-xsOCUXi_.js → ChatEntries-C9Ft60TS.js} +1 -1
  120. package/web/console/assets/{Clients-CI3DBDHf.js → Clients-NPldD-DD.js} +1 -1
  121. package/web/console/assets/{Cost-JgNXQPlN.js → Cost-DZcuB-EB.js} +1 -1
  122. package/web/console/assets/{Credentials-B5UUUdt0.js → Credentials-RTT7N6zl.js} +1 -1
  123. package/web/console/assets/{Diagnostics-BMGciWQb.js → Diagnostics-_LeK8cce.js} +1 -1
  124. package/web/console/assets/{Executors-CRbboOCZ.js → Executors-Bi7H8rIm.js} +1 -1
  125. package/web/console/assets/{HelpTip-i-KJhf5s.js → HelpTip-BfyWrxCE.js} +1 -1
  126. package/web/console/assets/{Kb-CgLNGjRp.js → Kb-BHamz8NP.js} +2 -2
  127. package/web/console/assets/{Login-C52JmXzx.js → Login-C1rJR-6w.js} +1 -1
  128. package/web/console/assets/{Projects-CDOvHPVS.js → Projects-BRA4a48v.js} +1 -1
  129. package/web/console/assets/Routes-CTC7U-fQ.js +124 -0
  130. package/web/console/assets/Routes-CyXV4Pba.css +1 -0
  131. package/web/console/assets/{Runs-DYNDXsqk.js → Runs-B_fa_BlD.js} +1 -1
  132. package/web/console/assets/{Setup-B91P6i1x.js → Setup-C1_d0mFy.js} +1 -1
  133. package/web/console/assets/Shell-CHEV6RGC.js +1 -0
  134. package/web/console/assets/Shell-ykb-tUfo.css +1 -0
  135. package/web/console/assets/{StorageBuckets-DkuDM0oX.js → StorageBuckets-DlG3ojhA.js} +1 -1
  136. package/web/console/assets/{SystemSettings-B7Mqj3k1.js → SystemSettings-DYo2gg6d.js} +1 -1
  137. package/web/console/assets/{SystemStatus-Db93b6dc.js → SystemStatus-DKCoUZlq.js} +1 -1
  138. package/web/console/assets/{Targets-CuuIYeZO.js → Targets-CdkG6BPR.js} +1 -1
  139. package/web/console/assets/{Tools-CHiqz9XZ.js → Tools-DVpCt0ox.js} +1 -1
  140. package/web/console/assets/Usage-CAeDGjrb.css +1 -0
  141. package/web/console/assets/Usage-DWCpLugC.js +1 -0
  142. package/web/console/assets/UsageAccess-B_Xq7ARW.js +1 -0
  143. package/web/console/assets/UsageAccess-CGGaWTuj.css +1 -0
  144. package/web/console/assets/UsageHelp-CSM4xO0K.css +1 -0
  145. package/web/console/assets/UsageHelp-t5ZG_f-e.js +1 -0
  146. package/web/console/assets/{index-QnmD7N7F.js → index-C6W4LWVV.js} +1 -1
  147. package/web/console/assets/{index-Fi9gkGxV.css → index-Cxuc9OCj.css} +1 -1
  148. package/web/console/assets/index-H1kfa0Mj.js +2 -0
  149. package/web/console/assets/{request-DeGya810.js → request-DLsP1_ot.js} +1 -1
  150. package/web/console/assets/{schema-BqlqLw1R.js → schema-BLOHvAJQ.js} +1 -1
  151. package/web/console/assets/{util-4bN2dv7B.js → util-CGVh2Jvr.js} +1 -1
  152. package/web/console/assets/{vendor-element-CZoEjZr8.js → vendor-element-BD089KxE.js} +1 -1
  153. package/web/console/assets/{vendor-mammoth-BUEEDX6A.js → vendor-mammoth-Bv-CZhmH.js} +1 -1
  154. package/web/console/index.html +3 -3
  155. package/web-admin/README.md +17 -0
  156. package/web-admin/src/components/UsageDeletionPreview.vue +44 -0
  157. package/web-admin/src/components/UsageHelp.vue +72 -0
  158. package/web-admin/src/components/UsageServiceReferences.vue +169 -0
  159. package/web-admin/src/layout/Shell.vue +22 -5
  160. package/web-admin/src/pages/Accounts.vue +3 -3
  161. package/web-admin/src/pages/AgentTasks.vue +2 -2
  162. package/web-admin/src/pages/Routes.vue +5 -1
  163. package/web-admin/src/pages/Usage.vue +2470 -0
  164. package/web-admin/src/pages/UsageAccess.vue +1147 -0
  165. package/web-admin/src/router.ts +8 -4
  166. package/web-admin/src/styles/base.css +57 -0
  167. package/web-admin/src/table-widths.ts +16 -1
  168. package/web-admin/src/usage-deletion.ts +40 -0
  169. package/web-admin/src/usage-management.ts +13 -0
  170. package/web-admin/src/usage-presentation.test.ts +21 -0
  171. package/web-admin/src/usage-presentation.ts +107 -0
  172. package/web-admin/src/usage-price-preview.test.ts +60 -0
  173. package/web-admin/src/usage-price-preview.ts +54 -0
  174. package/web-admin/tests/token-usage.browser.mjs +773 -0
  175. package/web-admin/tests/usage-access.browser.mjs +398 -0
  176. package/web/console/assets/Accounts-B4ePH5jp.css +0 -1
  177. package/web/console/assets/Accounts-BRCR3O0P.js +0 -3
  178. package/web/console/assets/AgentTasks--bqL_QKg.js +0 -2
  179. package/web/console/assets/AgentTasks-C8ox3TyS.css +0 -1
  180. package/web/console/assets/Routes-DkMIjMQA.css +0 -1
  181. package/web/console/assets/Routes-X9vHLpKW.js +0 -124
  182. package/web/console/assets/Shell-Bj6C8Hgo.css +0 -1
  183. package/web/console/assets/Shell-BsRa7bQQ.js +0 -1
  184. package/web/console/assets/index-UGvfF3Xr.js +0 -2
@@ -0,0 +1,87 @@
1
+ import assert from 'node:assert/strict';
2
+ import { randomUUID } from 'node:crypto';
3
+ import test from 'node:test';
4
+ import { getBillingRepository } from './billing-repository';
5
+ import { createUsageTestHarness } from './test-harness';
6
+
7
+ const enabled = process.env.BAILING_USAGE_TEST_MYSQL === '1';
8
+ const admin = 'synthetic-admin';
9
+ const config = (serviceId: string) => ({ mode: 'credits', serviceIds: [serviceId], priceUsd: 1000, multiplier: 1,
10
+ duration: { unit: 'month', count: 1 } });
11
+ async function fixture() {
12
+ const h = await createUsageTestHarness(), tokens = getBillingRepository(h.repository);
13
+ const deletion = (request_key = randomUUID(), expected_revision = h.service.revision) =>
14
+ h.request(`/admin/api/usage/services/${h.service.id}`, admin, 'DELETE', { request_key, expected_revision });
15
+ const plan = () => tokens.putPlan({ id: 'synthetic-plan', label: 'Synthetic allowance', expected_revision: 0, config: config(h.service.id) });
16
+ return { ...h, tokens, deletion, plan };
17
+ }
18
+
19
+ test('service deletion: encoded identity is decoded once; malformed and encoded separators are rejected', { skip: !enabled }, async () => {
20
+ const h = await fixture();
21
+ try {
22
+ const service = await h.repository.putService({ id: 'synthetic:model', label: 'Synthetic encoded', expectedRevision: 0, config: h.service.config });
23
+ const body = { request_key: randomUUID(), expected_revision: 1 };
24
+ for (const segment of ['bad%ZZ', 'bad%2Fname', 'bad%253Aname']) {
25
+ const invalid = await h.request(`/admin/api/usage/services/${segment}`, admin, 'DELETE', body);
26
+ assert.equal(invalid.status, 400, JSON.stringify(invalid));
27
+ assert.equal(invalid.body.error, 'USAGE_INVALID_INPUT');
28
+ }
29
+ const deleted = await h.request(`/admin/api/usage/services/${encodeURIComponent(service.id)}`, admin, 'DELETE', body);
30
+ assert.equal(deleted.status, 200, JSON.stringify(deleted.body));
31
+ assert.equal(deleted.body.id, service.id);
32
+ assert(await h.repository.getService(h.service.id));
33
+ } finally { await h.close(); }
34
+ });
35
+
36
+ test('service deletion: explicit authority, CAS, durable retry receipt and reserved old ID', { skip: !enabled }, async () => {
37
+ const h = await fixture();
38
+ try {
39
+ const user = await h.seedUser({ grant: false });
40
+ const path = `/admin/api/usage/services/${h.service.id}`, body = { request_key: randomUUID(), expected_revision: 1 };
41
+ assert.equal((await h.request(path, 'synthetic-auditor', 'DELETE', body)).status, 403);
42
+ assert.equal((await h.request(path, admin, 'DELETE', { ...body, unexpected: true })).status, 400);
43
+ assert.equal((await h.deletion(randomUUID(), 9)).body.error, 'USAGE_REVISION_CONFLICT');
44
+ const deleted = await h.request(path, admin, 'DELETE', body);
45
+ assert.equal(deleted.status, 200, JSON.stringify(deleted.body));
46
+ assert.equal(deleted.body.deleted, true); assert.equal(deleted.body.revision, 2);
47
+ assert.equal(deleted.body.id, h.service.id); assert(deleted.body.deletedAt > 0);
48
+ assert.deepEqual((await h.request(path, admin, 'DELETE', body)).body, deleted.body);
49
+ assert.equal((await h.request(path, admin, 'DELETE', { ...body, expected_revision: 2 })).body.error, 'USAGE_IDEMPOTENCY_CONFLICT');
50
+ assert.equal((await h.deletion()).body.error, 'USAGE_SERVICE_NOT_FOUND');
51
+ assert.equal(await h.repository.getService(h.service.id), null);
52
+ assert.deepEqual((await h.request('/admin/api/usage/services', admin)).body.items, []);
53
+ await assert.rejects(h.repository.putService({ ...h.service, expectedRevision: 0 }), { code: 'USAGE_SERVICE_DELETED' });
54
+ await assert.rejects(h.repository.putService({ ...h.service, expectedRevision: 2 }), { code: 'USAGE_SERVICE_DELETED' });
55
+ const [rows] = await h.pool.query<any[]>('SELECT state,config_json FROM bz_usage_services WHERE id=?', [h.service.id]);
56
+ assert.equal(rows[0].state, 'deleted'); assert.deepEqual(rows[0].config_json, h.service.config);
57
+ const [sessions] = await h.pool.query<any[]>('SELECT state FROM bz_usage_sessions WHERE id=?', [user.actor.sessionId]);
58
+ assert.equal(sessions[0].state, 'active'); assert.equal(h.state.calls, 0);
59
+ } finally { await h.close(); }
60
+ });
61
+
62
+ for (const mode of ['ok', 'missing_usage'] as const) {
63
+ test(`service deletion: ${mode} complete history survives exact GET and POST retry without redispatch`, { skip: !enabled }, async () => {
64
+ const h = await fixture();
65
+ try {
66
+ const p = await h.plan(), user = await h.seedUser({ grant: false });
67
+ await h.tokens.grant(user.accountId, { request_key: randomUUID(), plan_id: p.id, expected_revision: 0 });
68
+ h.state.mode = mode;
69
+ const input = { operation_id: randomUUID(), messages: [{ role: 'user', content: 'Synthetic' }] };
70
+ let original = await h.request('/usage/v1/model/requests', user.token, 'POST', input);
71
+ assert.equal(original.status, 200); assert.equal(original.body.result_state, 'complete');
72
+ await h.tokens.drainSettlements();
73
+ original = await h.request(`/usage/v1/model/requests/${input.operation_id}`, user.token);
74
+ await h.tokens.putPlan({ id: p.id, label: p.label, config: p.config, expected_revision: 1, state: 'suspended' });
75
+ await h.tokens.control(user.accountId, { request_key: randomUUID(), expected_revision: 1, state: 'suspended' });
76
+ const [before] = await h.pool.query<any[]>('SELECT * FROM bz_usage_billing_ledger ORDER BY id');
77
+ assert.equal((await h.deletion()).status, 200);
78
+ const recovered = await h.request(`/usage/v1/model/requests/${input.operation_id}`, user.token);
79
+ assert.equal(recovered.status, 200); assert.deepEqual(recovered.body, original.body);
80
+ assert.deepEqual((await h.request('/usage/v1/model/requests', user.token, 'POST', input)).body, original.body);
81
+ assert.equal(h.state.calls, 1);
82
+ const [after] = await h.pool.query<any[]>('SELECT * FROM bz_usage_billing_ledger ORDER BY id');
83
+ assert.deepEqual(after, before);
84
+ assert.deepEqual((await h.request('/usage/v1/model/models', user.token)).body.items, []);
85
+ } finally { await h.close(); }
86
+ });
87
+ }
@@ -0,0 +1,32 @@
1
+ import type { ServerResponse } from 'node:http';
2
+
3
+ /** A disconnected viewer never cancels/replays the separately recorded provider operation. */
4
+ export class UsageStreamWriter {
5
+ private sequence = 0;
6
+ private heartbeat?: ReturnType<typeof setInterval>;
7
+ constructor(private readonly res: ServerResponse, private readonly operationId: string) {}
8
+ get open() { return this.res.headersSent; }
9
+ async emit(type: 'started' | 'provider' | 'operation', payload: Record<string, unknown> = {}) {
10
+ const res = this.res;
11
+ if (res.destroyed || res.writableEnded) return;
12
+ if (!res.headersSent) {
13
+ res.writeHead(200, { 'content-type': 'text/event-stream; charset=utf-8', 'cache-control': 'no-cache, no-transform', 'x-accel-buffering': 'no' });
14
+ res.flushHeaders();
15
+ this.heartbeat = setInterval(() => {
16
+ if (!res.destroyed && !res.writableEnded && res.writableLength < 65536) res.write(': keep-alive\n\n');
17
+ }, 15000);
18
+ this.heartbeat.unref();
19
+ res.once('close', () => this.stop());
20
+ }
21
+ const data = JSON.stringify({ schema: 'bailing.model-stream.v1', operation_id: this.operationId,
22
+ seq: ++this.sequence, type, ...payload });
23
+ if (res.write(`data: ${data}\n\n`)) return;
24
+ await new Promise<void>(resolve => {
25
+ const finish = () => { clearTimeout(timer); res.off('drain', finish); res.off('close', finish); resolve(); };
26
+ const timer = setTimeout(() => { res.destroy(); finish(); }, 5000); timer.unref();
27
+ res.once('drain', finish); res.once('close', finish);
28
+ });
29
+ }
30
+ stop() { if (this.heartbeat) clearInterval(this.heartbeat); }
31
+ end() { this.stop(); if (!this.res.destroyed && !this.res.writableEnded) this.res.end(); }
32
+ }
@@ -0,0 +1,108 @@
1
+ // Synthetic local-only acceptance fixture. Never reads deployment configuration or real credentials.
2
+ import { createHash, randomUUID } from 'node:crypto';
3
+ import { readFile } from 'node:fs/promises';
4
+ import { createServer } from 'node:http';
5
+ import { once } from 'node:events';
6
+ import type { AddressInfo } from 'node:net';
7
+ import { createPool } from 'mysql2/promise';
8
+ import { send } from '../../app/http';
9
+ import { handleAdminUsageApiFor } from '../../routes/admin-usage';
10
+ import { UsageRepository } from './repository';
11
+ import { getUsageIdentity } from './identity';
12
+ import { handleUsageApiFor } from './http';
13
+ import { handleModelGatewayApiFor } from './model-gateway';
14
+ import { getBillingRepository } from './billing-repository';
15
+
16
+ export async function createUsageTestHarness() {
17
+ const dbName = `usage_acceptance_${randomUUID().replaceAll('-', '')}`;
18
+ const mysql = { host: '127.0.0.1', port: 16307, user: 'root', password: '', connectionLimit: 8, multipleStatements: true };
19
+ const adminPool = createPool(mysql);
20
+ await adminPool.query(`CREATE DATABASE \`${dbName}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_bin`);
21
+ const pool = createPool({ ...mysql, database: dbName });
22
+ for (const file of ['063_usage_model_billing.sql'])
23
+ await pool.query(await readFile(new URL(`../../../sql/${file}`, import.meta.url), 'utf8'));
24
+ const repository = new UsageRepository(() => pool);
25
+ const identity = getUsageIdentity(repository);
26
+ const fixturePrice = {source:'openrouter' as const,modelId:'synthetic/model',endpointId:'synthetic',currency:'USD' as const,fetchedAt:Date.now(),lines:[{billable:'prompt',unit:'token' as const,costUsd:'1'},{billable:'completion',unit:'token' as const,costUsd:'1'}]};
27
+ await pool.query('INSERT INTO bz_usage_price_snapshots VALUES(?,?,?)',[createHash('sha256').update('chat:synthetic/model').digest('hex'),JSON.stringify({fetchedAt:Date.now(),items:[{id:'synthetic',pricing:fixturePrice}]}),Date.now()]);
28
+ const state = { calls: 0, counts: 0, mode: 'ok' as 'ok' | 'missing_usage' | 'error' | 'incomplete' | 'delay' | 'stream' | 'stream_drop' | 'stream_tools_nullable', release: null as (() => void) | null };
29
+ const provider = createServer(async (req, res) => {
30
+ for await (const _chunk of req) { /* consume synthetic input */ }
31
+ if (req.url === '/v1/count-input') { state.counts++; send(res, 200, { input_tokens: 20 }); return; }
32
+ state.calls++;
33
+ if (state.mode === 'error') { send(res, 503, { error: 'synthetic_failure' }); return; }
34
+ if (state.mode === 'incomplete') {
35
+ res.writeHead(200, { 'content-type': 'text/event-stream' });
36
+ res.end('data: {"id":"synthetic-incomplete","choices":[{"delta":{"content":"Partial"},"finish_reason":null}]}\n\n'); return;
37
+ }
38
+ if (state.mode === 'stream_tools_nullable') {
39
+ const id = `synthetic-stream-${state.calls}`;
40
+ const frame = (delta: unknown, finish_reason: string | null = null) =>
41
+ `data: ${JSON.stringify({ id, choices: [{ index: 0, delta, finish_reason }] })}\n\n`;
42
+ res.writeHead(200, { 'content-type': 'text/event-stream' });
43
+ res.write(frame({ role: 'assistant', reasoning_content: 'Synthetic preview', tool_calls: null }));
44
+ res.write(frame({ content: null, tool_calls: [{ index: 0, id: 'call-original', type: 'function', function: { name: 'inspect_product', arguments: null } }] }));
45
+ res.write(frame({ role: null, tool_calls: [{ index: 0, id: null, type: null, function: { name: null, arguments: '{"id":7}' } }] }));
46
+ res.write(frame({ content: null, tool_calls: null }, 'tool_calls'));
47
+ res.end(`data: ${JSON.stringify({ id, choices: [], usage: { prompt_tokens: 20, completion_tokens: 5, total_tokens: 25 } })}\n\ndata: [DONE]\n\n`);
48
+ return;
49
+ }
50
+ if (state.mode === 'stream' || state.mode === 'stream_drop') {
51
+ const id = `synthetic-stream-${state.calls}`;
52
+ res.writeHead(200, { 'content-type': 'text/event-stream' });
53
+ res.write(`data: ${JSON.stringify({ id, choices: [{ index: 0, delta: { role: 'assistant', content: 'Synthetic preview' }, finish_reason: null }] })}\n\n`);
54
+ if (state.mode === 'stream_drop') { res.end(); return; }
55
+ await new Promise<void>(resolve => { state.release = resolve; });
56
+ res.end(`data: ${JSON.stringify({ id, choices: [{ index: 0, delta: {}, finish_reason: 'stop' }], usage: { prompt_tokens: 20, completion_tokens: 5, total_tokens: 25 } })}\n\ndata: [DONE]\n\n`);
57
+ return;
58
+ }
59
+ if (state.mode === 'delay') await new Promise<void>(resolve => { state.release = resolve; });
60
+ send(res, 200, { id: `synthetic-result-${state.calls}`, choices: [{ index: 0, message: { role: 'assistant', content: 'Synthetic product is available.' }, finish_reason: 'stop' }],
61
+ ...(state.mode === 'missing_usage' ? {} : { usage: { prompt_tokens: 20, completion_tokens: 5, total_tokens: 25 } }) });
62
+ }).listen(0, '127.0.0.1'); await once(provider, 'listening');
63
+ const service = await repository.putService({ id: 'synthetic-text', label: 'Synthetic text', expectedRevision: 0,
64
+ config: { pricing: {source:'openrouter',kind:'chat',modelId:'synthetic/model',endpointId:'synthetic'}, credential: 'synthetic', model: 'synthetic-model', providerScope: dbName, maxInputBytes: 16384,
65
+ maxOutputTokens: 100, timeoutMs: 5000 } });
66
+ const issuer = await identity.createIssuer({ id: 'synthetic-product', label: 'Synthetic product', permissions: ['identity:exchange', 'identity:revoke', 'entitlements:write', 'allowance:grant', 'usage:read'], service_ids: [service.id] });
67
+ const cfg = { llmCredentials: { synthetic: { base_url: `http://127.0.0.1:${(provider.address() as AddressInfo).port}/v1`, api_key: 'REPLACE_ME' } } };
68
+ let paused = false;
69
+ const hub = createServer(async (req, res) => {
70
+ try {
71
+ const url = new URL(req.url ?? '/', 'http://localhost');
72
+ if (await handleUsageApiFor({ usage: repository }, req, res, url)) return;
73
+ if (await handleModelGatewayApiFor({ usage: repository, cfg, isPaused: () => paused }, req, res, url)) return;
74
+ if (url.pathname.startsWith('/admin/api/usage')) {
75
+ const role = req.headers.authorization === 'Bearer synthetic-admin' ? 'admin' : 'usage_auditor';
76
+ await handleAdminUsageApiFor(repository, req.method ?? 'GET', url.pathname, req, res, { kind: 'admin', via: 'session', role }); return;
77
+ }
78
+ send(res, 404, { error: 'not_found' });
79
+ } catch { send(res, 500, { error: 'synthetic_harness_error' }); }
80
+ }).listen(0, '127.0.0.1'); await once(hub, 'listening');
81
+ const baseUrl = `http://127.0.0.1:${(hub.address() as AddressInfo).port}`;
82
+ async function request(path: string, token: string, method = 'GET', body?: unknown) {
83
+ const response = await fetch(`${baseUrl}${path}`, { method, headers: { authorization: `Bearer ${token}`, ...(body !== undefined ? { 'content-type': 'application/json' } : {}) }, ...(body !== undefined ? { body: JSON.stringify(body) } : {}) });
84
+ return { status: response.status, body: await response.json() as Record<string, any> };
85
+ }
86
+ async function seedUser(options: { grant?: boolean } = {}) {
87
+ const subject = randomUUID();
88
+ const exchange = await request('/usage/v1/sessions/exchange', issuer.credential!, 'POST', { request_key: subject, tenant: 'synthetic', subject, service_id: service.id });
89
+ if (exchange.status !== 200) throw new Error(`Synthetic exchange failed: ${exchange.body.error}`);
90
+ const accountId = exchange.body.session.accountId;
91
+ if (options.grant !== false) {
92
+ const tokens = getBillingRepository(repository);
93
+ await tokens.putPlan({ id: subject, label: 'Synthetic allowance', expected_revision: 0, config: {
94
+ mode: 'credits', serviceIds: [service.id], priceUsd: 1_000_000, multiplier: 1, duration: { unit: 'month', count: 1 } } });
95
+ await tokens.grant(accountId, { request_key: subject, plan_id: subject, expected_revision: 0 });
96
+ }
97
+ return { token: exchange.body.credential as string, actor: exchange.body.session, accountId, subject, sourceId: subject };
98
+ }
99
+ return { repository, identity, pool, state, service, tokens: getBillingRepository(repository), issuerToken: issuer.credential!, baseUrl, request, seedUser,
100
+ setPaused(value: boolean) { paused = value; },
101
+ async close() {
102
+ state.release?.(); hub.close(); hub.closeAllConnections(); provider.close(); provider.closeAllConnections();
103
+ await getBillingRepository(repository).drainSettlements();
104
+ await pool.end();
105
+ // Only the random database created by this fixture is removed; no shared or configured DB is touched.
106
+ await adminPool.query(`DROP DATABASE \`${dbName}\``); await adminPool.end();
107
+ } };
108
+ }
@@ -0,0 +1,312 @@
1
+ import assert from 'node:assert/strict';
2
+ import { randomUUID } from 'node:crypto';
3
+ import test from 'node:test';
4
+ import { createUsageTestHarness } from './test-harness';
5
+ import { getBillingRepository } from './billing-repository';
6
+ import { getUsageDeletionRepository } from './usage-deletion';
7
+
8
+ const enabled = process.env.BAILING_USAGE_TEST_MYSQL === '1';
9
+ const admin = 'synthetic-admin';
10
+ type Harness = Awaited<ReturnType<typeof createUsageTestHarness>>;
11
+ function gate(h: Harness, matches: (sql: string, args: any[]) => boolean, after = false) {
12
+ let entered!: () => void, release!: () => void, armed = true;
13
+ const reached = new Promise<void>(r => { entered = r; }), held = new Promise<void>(r => { release = r; });
14
+ const original = h.pool.getConnection.bind(h.pool);
15
+ h.pool.getConnection = (async () => {
16
+ const connection = await original();
17
+ return new Proxy(connection, { get(target, key) {
18
+ const value = Reflect.get(target, key);
19
+ if (key !== 'query' && key !== 'execute') return typeof value === 'function' ? value.bind(target) : value;
20
+ return async (...args: any[]) => {
21
+ if (armed && matches(String(args[0]), args[1] ?? [])) {
22
+ armed = false;
23
+ if (after) { const result = await value.apply(target, args); entered(); await held; return result; }
24
+ entered(); await held;
25
+ }
26
+ return value.apply(target, args);
27
+ };
28
+ } });
29
+ }) as typeof h.pool.getConnection;
30
+ return { reached, release: () => release(), restore() { release(); h.pool.getConnection = original; } };
31
+ }
32
+ async function fixture() {
33
+ const h = await createUsageTestHarness(), tokens = getBillingRepository(h.repository), deletion = getUsageDeletionRepository(h.repository);
34
+ const config = { mode: 'credits', serviceIds: [h.service.id], priceUsd: 100, duration: { unit: 'month', count: 1 }, multiplier: 1 };
35
+ const plan = (id: string = randomUUID()) => tokens.putPlan({ id, label: 'Synthetic unused plan', expected_revision: 0, config });
36
+ const issuerInput = (id: string, accountIds: string[] = []) => ({ id, label: 'Synthetic unused issuer', permissions: ['identity:exchange'], service_ids: [h.service.id], account_ids: accountIds });
37
+ async function organization() {
38
+ const user = await h.seedUser({ grant: false });
39
+ const input = { requestId: randomUUID(), sourceOwner: 'hub', sourceId: randomUUID(), kind: 'organization' as const, label: 'Synthetic organization', userId: user.actor.userId };
40
+ const account = await h.repository.createAccount(input);
41
+ return { user, input, account };
42
+ }
43
+ const suspend = (id: string) => h.repository.setAccountState({accountId:id,expectedRevision:1,requestId:randomUUID(),actor:admin,state:'suspended'});
44
+ const remove = (kind: 'plan' | 'issuer' | 'account', id: string, expectedRevision = 1, requestKey = randomUUID()) => deletion.remove({ kind, id, expectedRevision, requestKey, actor: admin });
45
+ return { ...h, tokens, deletion, config, plan, issuerInput, organization, remove, suspend };
46
+ }
47
+
48
+ test('idle plan deletion: preview, authority, CAS, exact replay, immutable tombstone and encoded IDs', { skip: !enabled }, async () => {
49
+ const h = await fixture();
50
+ try {
51
+ const p = await h.plan('synthetic:plan'), path = `/admin/api/usage/billing/plans/${encodeURIComponent(p.id)}`;
52
+ const preview = await h.request(`${path}/deletion-preview`, admin);
53
+ assert.equal(preview.status, 200); assert.equal(preview.body.kind, 'plan'); assert.equal(preview.body.can_delete, true);
54
+ assert.deepEqual(preview.body.blockers, []); assert.equal(preview.body.revision, 1); assert.match(preview.body.effect, /原标识/);
55
+ const body = { request_key: randomUUID(), expected_revision: 1 };
56
+ assert.equal((await h.request(`${path}/deletion-preview`, 'synthetic-auditor')).status, 200);
57
+ assert.equal((await h.request(path, 'synthetic-auditor', 'DELETE', body)).status, 403);
58
+ assert.equal((await h.request(path, admin, 'DELETE', { ...body, expected_revision: 9 })).body.error, 'USAGE_REVISION_CONFLICT');
59
+ assert.equal((await h.request(path, admin, 'DELETE', { ...body, extra: true })).status, 400);
60
+ const removed = await h.request(path, admin, 'DELETE', body); assert.equal(removed.status, 200); assert.equal(removed.body.revision, 2);
61
+ assert.deepEqual((await h.request(path, admin, 'DELETE', body)).body, removed.body);
62
+ assert.equal((await h.request(path, admin, 'DELETE', { ...body, expected_revision: 2 })).body.error, 'USAGE_IDEMPOTENCY_CONFLICT');
63
+ assert.equal((await h.request(path, admin, 'DELETE', { request_key: randomUUID(), expected_revision: 2 })).body.error, 'USAGE_RESOURCE_DELETED');
64
+ assert.equal((await h.request(`${path}/deletion-preview`, admin)).status, 404);
65
+ assert.deepEqual(await h.tokens.listPlans(), []);
66
+ await assert.rejects(h.tokens.putPlan({ id: p.id, label: p.label, config: p.config, expected_revision: 2 }), { code: 'USAGE_RESOURCE_DELETED' });
67
+ for (const segment of ['bad%ZZ','bad%2Fname','bad%253Aname']) assert.equal((await h.request(`/admin/api/usage/billing/plans/${segment}/deletion-preview`, admin)).status, 400);
68
+ const [saved] = await h.pool.query<any[]>('SELECT state,revision FROM bz_usage_billing_plans WHERE id=?', [p.id]); assert.equal(saved[0].state, 'deleted');
69
+ await h.repository.deleteService({ id: h.service.id, expectedRevision: 1, requestId: randomUUID(), actor: admin });
70
+ const [unchanged] = await h.pool.query<any[]>('SELECT revision FROM bz_usage_billing_plans WHERE id=?', [p.id]); assert.equal(Number(unchanged[0].revision), 2);
71
+ } finally { await h.close(); }
72
+ });
73
+
74
+ test('suspended current grants allow plan deletion while source history stays protected', { skip: !enabled }, async () => {
75
+ const h = await fixture();
76
+ try {
77
+ const p = await h.plan(), user = await h.seedUser({ grant: false });
78
+ await h.tokens.grant(user.accountId, { request_key: randomUUID(), plan_id: p.id, expected_revision: 0 }, 'issuer:synthetic-product');
79
+ await h.tokens.control(user.accountId, { request_key: randomUUID(), expected_revision: 1, state: 'suspended' }, 'issuer:synthetic-product');
80
+ const plan = await h.deletion.preview('plan', p.id); assert.equal(plan.can_delete, true); assert.deepEqual(plan.blockers, []);
81
+ const failed = await h.request(`/admin/api/usage/billing/plans/${p.id}`, admin, 'DELETE', { request_key: randomUUID(), expected_revision: 1 });
82
+ assert.equal(failed.status, 200);
83
+ await assert.rejects(h.tokens.control(user.accountId,{request_key:randomUUID(),expected_revision:2,state:'active'},'issuer:synthetic-product'),{code:'SERVICE_NOT_ENTITLED'});
84
+ const source = await h.deletion.preview('issuer', 'synthetic-product');
85
+ assert.deepEqual(source.blockers.map(x => x.code).sort(), ['ISSUER_GRANT_HISTORY','ISSUER_SESSION_HISTORY','ISSUER_USER_HISTORY']);
86
+ await assert.rejects(h.remove('issuer', 'synthetic-product'), { code: 'USAGE_RESOURCE_IN_USE' });
87
+ assert.equal((await h.repository.getAccount(user.accountId))!.state, 'active');
88
+ } finally { await h.close(); }
89
+ });
90
+
91
+ test('unused issuer deletion hides the source, invalidates its credential and cannot be recreated or reactivated', { skip: !enabled }, async () => {
92
+ const h = await fixture();
93
+ try {
94
+ const input = h.issuerInput('unused:source'), created = await h.identity.createIssuer(input);
95
+ const path = `/admin/api/usage/issuers/${encodeURIComponent(input.id)}`, body = { request_key: randomUUID(), expected_revision: 1 };
96
+ assert.equal((await h.request(`${path}/deletion-preview`, 'synthetic-auditor')).status, 403);
97
+ assert.equal((await h.request(path, 'synthetic-auditor', 'DELETE', body)).status, 403);
98
+ const preview = await h.request(`${path}/deletion-preview`, admin); assert.equal(preview.body.can_delete, true); assert.deepEqual(preview.body.blockers, []);
99
+ const removed = await h.request(path, admin, 'DELETE', body); assert.equal(removed.status, 200);
100
+ assert.deepEqual((await h.request(path, admin, 'DELETE', body)).body, removed.body);
101
+ assert(!(await h.identity.listIssuers()).some(item => item.id === input.id));
102
+ await assert.rejects(h.identity.createIssuer(input), { code: 'USAGE_RESOURCE_DELETED' });
103
+ await assert.rejects(h.identity.controlIssuer(input.id, 2, 'active', true), { code: 'USAGE_RESOURCE_DELETED' });
104
+ await assert.rejects(h.identity.exchange(created.credential!, { request_key: randomUUID(), tenant: 'synthetic', subject: 'later', service_id: h.service.id }), { code: 'USAGE_ISSUER_REQUIRED' });
105
+ const [counts] = await h.pool.query<any[]>('SELECT COUNT(*) AS n FROM bz_usage_users WHERE issuer_id=?', [input.id]); assert.equal(counts[0].n, 0);
106
+ } finally { await h.close(); }
107
+ });
108
+
109
+ test('archived organization preserves members and history; admin-only restoration is CAS protected and idempotent', { skip: !enabled }, async () => {
110
+ const h = await fixture();
111
+ try {
112
+ const { user, input, account } = await h.organization(), path = `/admin/api/usage/accounts/${account.id}`;
113
+ assert.deepEqual((await h.deletion.preview('account',account.id)).blockers.map(b=>b.code),['ACCOUNT_ACTIVE']);
114
+ await assert.rejects(h.remove('account',account.id),{code:'USAGE_RESOURCE_IN_USE'});
115
+ await h.repository.setMembership({accountId:account.id,userId:user.actor.userId,expectedRevision:1,state:'revoked',requestId:randomUUID(),actor:admin});
116
+ await h.suspend(account.id);
117
+ assert.equal((await h.deletion.preview('account',account.id)).can_delete,true);
118
+ const body = {request_key:randomUUID(),expected_revision:2};
119
+ assert.equal((await h.request(path,'synthetic-auditor','DELETE',body)).status,403);
120
+ const receipt = await h.request(path,admin,'DELETE',body); assert.equal(receipt.status,200);
121
+ assert.equal(await h.repository.getAccount(account.id),null);
122
+ assert(!(await h.repository.listAccounts()).items.some(a=>a.id===account.id));
123
+ assert(!(await h.repository.listAccounts({userId:user.actor.userId,archived:true})).items.some(a=>a.id===account.id));
124
+ const archivedList=await h.request('/admin/api/usage/accounts?view=archived',admin); assert.equal(archivedList.status,200);
125
+ assert(archivedList.body.items.some((a:any)=>a.id===account.id));
126
+ const detail = await h.request(path,admin); assert.equal(detail.body.account.state,'archived');
127
+ assert.equal(detail.body.members[0].state,'revoked'); assert.equal(detail.body.members[0].revision,2);
128
+ await assert.rejects(h.repository.createAccount(input),{code:'USAGE_ACCOUNT_SUSPENDED'});
129
+ await assert.rejects(h.repository.setAccountState({accountId:account.id,expectedRevision:3,requestId:randomUUID(),actor:admin,state:'active'}),{code:'USAGE_ACCOUNT_SUSPENDED'});
130
+ await assert.rejects(h.repository.setMembership({accountId:account.id,userId:user.actor.userId,expectedRevision:2,requestId:randomUUID(),actor:admin,state:'active'}),{code:'USAGE_ACCOUNT_SUSPENDED'});
131
+ await assert.rejects(h.identity.createIssuer(h.issuerInput('bad-reference',[account.id])),{code:'USAGE_ACCOUNT_FORBIDDEN'});
132
+ const restore = {request_key:randomUUID(),expected_revision:3};
133
+ assert.equal((await h.request(`${path}/restore`,'synthetic-auditor','POST',restore)).status,403);
134
+ assert.equal((await h.request(`${path}/restore`,admin,'POST',{...restore,expected_revision:2})).body.error,'USAGE_REVISION_CONFLICT');
135
+ const restored = await h.request(`${path}/restore`,admin,'POST',restore); assert.equal(restored.status,200); assert.equal(restored.body.state,'suspended');
136
+ assert.deepEqual((await h.request(`${path}/restore`,admin,'POST',restore)).body,restored.body);
137
+ assert.equal((await h.request(`${path}/restore`,admin,'POST',{...restore,expected_revision:4})).body.error,'USAGE_IDEMPOTENCY_CONFLICT');
138
+ assert.deepEqual((await h.request(path,admin,'DELETE',body)).body,receipt.body);
139
+ assert.equal((await h.repository.getAccount(account.id))!.state,'suspended'); // Lost delete ACK must not remove it again.
140
+ const [members] = await h.pool.query<any[]>('SELECT state,revision FROM bz_usage_members WHERE account_id=?',[account.id]);
141
+ assert.equal(members[0].state,'revoked'); assert.equal(Number(members[0].revision),2);
142
+ await h.remove('account',account.id,4);
143
+ assert.deepEqual((await h.request(`${path}/restore`,admin,'POST',restore)).body,restored.body);
144
+ assert.equal((await h.repository.getAccount(account.id,true))!.state,'archived'); // Old restore ACK cannot revive a new removal.
145
+ } finally {await h.close();}
146
+ });
147
+
148
+ test('personal archive retains grant and results, settles in-flight once, and never recreates identity or revives credentials', { skip: !enabled }, async () => {
149
+ const h = await fixture();
150
+ try {
151
+ const p=await h.plan(),user=await h.seedUser({grant:false});
152
+ const originalGrant=await h.tokens.grant(user.accountId,{request_key:randomUUID(),plan_id:p.id,expected_revision:0});
153
+ const original=await h.tokens.admit({actor:user.actor,operationId:randomUUID(),serviceId:h.service.id,conversationId:null,turnId:null,
154
+ requestHash:'b'.repeat(64),expectedServiceRevision:h.service.revision,serviceConfig:h.service.config,model:h.service.config.model,
155
+ priceSnapshot:{source:'openrouter',modelId:'synthetic/model',endpointId:'synthetic',currency:'USD',fetchedAt:1,
156
+ lines:[{billable:'prompt',unit:'token',costUsd:'1'},{billable:'completion',unit:'token',costUsd:'1'}]}});
157
+ const dispatched=await h.tokens.commitDispatch(original.id,user.actor);
158
+ await h.suspend(user.accountId);
159
+ assert.equal((await h.deletion.preview('account',user.accountId)).can_delete,true);
160
+ await h.remove('account',user.accountId,2);
161
+ const login=()=>h.identity.exchange(h.issuerToken,{request_key:randomUUID(),tenant:'synthetic',subject:user.subject,service_id:h.service.id});
162
+ await assert.rejects(login(),{code:'USAGE_ACCOUNT_SUSPENDED'});
163
+ const result={response:{output:'synthetic'},usage:{inputTokens:3,outputTokens:2}};
164
+ const done=await h.tokens.complete(original.id,dispatched.fence!,result); assert.equal(done.billedUsd,5);
165
+ await h.tokens.complete(original.id,dispatched.fence!,result);
166
+ let summary=await h.tokens.summary(user.accountId); assert.equal(summary.availableUsd,0); assert.equal(summary.consumedUsd,5);assert.equal(summary.grant!.id,originalGrant.id);
167
+ const [ledger]=await h.pool.query<any[]>('SELECT COUNT(*) AS n FROM bz_usage_billing_ledger WHERE request_id=?',[original.id]);assert.equal(Number(ledger[0].n),1);
168
+ await assert.rejects(h.tokens.control(user.accountId,{request_key:randomUUID(),expected_revision:1,state:'active'}),{code:'USAGE_ACCOUNT_SUSPENDED'});
169
+ await assert.rejects(h.tokens.grant(user.accountId,{request_key:randomUUID(),plan_id:p.id,expected_revision:1}),{code:'USAGE_ACCOUNT_SUSPENDED'});
170
+ await h.deletion.restoreAccount({id:user.accountId,expectedRevision:3,requestKey:randomUUID(),actor:admin});
171
+ assert.equal((await h.tokens.summary(user.accountId)).availableUsd,0);
172
+ await h.repository.setAccountState({accountId:user.accountId,expectedRevision:4,state:'active',requestId:randomUUID(),actor:admin});
173
+ summary=await h.tokens.summary(user.accountId); assert.equal(summary.availableUsd,95); assert.equal(summary.grant!.id,originalGrant.id);
174
+ await assert.rejects(h.repository.withTransaction(c=>h.identity.validateActor(c,user.actor)));
175
+ const reopened=await login();assert.equal(reopened.session.accountId,user.accountId);
176
+ const [grants]=await h.pool.query<any[]>('SELECT COUNT(*) AS n FROM bz_usage_billing_grants WHERE account_id=?',[user.accountId]); assert.equal(Number(grants[0].n),1);
177
+ const [members]=await h.pool.query<any[]>('SELECT state,revision FROM bz_usage_members WHERE account_id=?',[user.accountId]);assert.equal(members[0].state,'active');assert.equal(Number(members[0].revision),1);
178
+ } finally {await h.close();}
179
+ });
180
+
181
+ test('existing source references do not prevent archive or grant access to archived accounts', { skip: !enabled }, async () => {
182
+ const h=await fixture();
183
+ try {
184
+ const {account}=await h.organization();
185
+ const source=await h.identity.createIssuer(h.issuerInput('configured-only',[account.id]));
186
+ await h.suspend(account.id);await h.remove('account',account.id,2);
187
+ await assert.rejects(h.identity.requireIssuerAccount(source.issuer,account.id),{code:'USAGE_ACCOUNT_FORBIDDEN'});
188
+ } finally {await h.close();}
189
+ });
190
+
191
+ test('deletion checks remain authoritative against delayed grant and first identity exchange', { skip: !enabled, timeout: 30000 }, async () => {
192
+ const h = await fixture();
193
+ try {
194
+ const p = await h.plan(), user = await h.seedUser({ grant: false });
195
+ const planGate = gate(h, (sql, args) => sql === 'SELECT * FROM bz_usage_accounts WHERE id=? FOR UPDATE' && args[0] === user.accountId);
196
+ try {
197
+ const pending = h.tokens.grant(user.accountId, { request_key: randomUUID(), plan_id: p.id, expected_revision: 0 });
198
+ const rejection = assert.rejects(pending, { code: 'SERVICE_NOT_ENTITLED' }); await planGate.reached;
199
+ await h.remove('plan', p.id); planGate.release(); await rejection;
200
+ } finally { planGate.restore(); }
201
+ const source = await h.identity.createIssuer(h.issuerInput('race-source'));
202
+ const sourceGate = gate(h, (sql, args) => sql === 'SELECT state,revision FROM bz_usage_issuers WHERE id=? FOR SHARE' && args[0] === source.issuer.id);
203
+ try {
204
+ const pending = h.identity.exchange(source.credential!, { request_key: randomUUID(), tenant: 'synthetic', subject: 'late', service_id: h.service.id });
205
+ const rejection = assert.rejects(pending, { code: 'USAGE_ISSUER_REQUIRED' }); await sourceGate.reached;
206
+ await h.remove('issuer', source.issuer.id); sourceGate.release(); await rejection;
207
+ const [rows] = await h.pool.query<any[]>('SELECT COUNT(*) AS n FROM bz_usage_users WHERE issuer_id=?', [source.issuer.id]); assert.equal(rows[0].n, 0);
208
+ } finally { sourceGate.restore(); }
209
+ } finally { await h.close(); }
210
+ });
211
+
212
+ test('grant winning its shared lock makes a stale successful deletion preview non-authoritative', { skip: !enabled, timeout: 30000 }, async () => {
213
+ const h = await fixture();
214
+ try {
215
+ const p = await h.plan(), user = await h.seedUser({ grant: false });
216
+ assert.equal((await h.deletion.preview('plan', p.id)).can_delete, true);
217
+ const hold = gate(h, (sql, args) => sql === 'SELECT * FROM bz_usage_billing_plans WHERE id=? FOR SHARE' && args[0] === p.id, true);
218
+ try {
219
+ const grant = h.tokens.grant(user.accountId, { request_key: randomUUID(), plan_id: p.id, expected_revision: 0 });
220
+ await hold.reached;
221
+ const deletion = assert.rejects(h.remove('plan', p.id), { code: 'USAGE_RESOURCE_IN_USE' });
222
+ hold.release(); await grant; await deletion;
223
+ } finally { hold.restore(); }
224
+ } finally { await h.close(); }
225
+ });
226
+
227
+ test('account deletion serializes with an issuer configuration that tries to add the removed account', { skip: !enabled, timeout: 30000 }, async () => {
228
+ const h = await fixture();
229
+ try {
230
+ const { account } = await h.organization();
231
+ await h.suspend(account.id);
232
+ const hold = gate(h, (sql, args) => sql === 'SELECT state FROM bz_usage_accounts WHERE id=? FOR SHARE' && args[0] === account.id);
233
+ try {
234
+ const source = assert.rejects(h.identity.createIssuer(h.issuerInput('late-reference', [account.id])), { code: 'USAGE_ACCOUNT_FORBIDDEN' });
235
+ await hold.reached; await h.remove('account', account.id,2); hold.release(); await source;
236
+ assert(!(await h.identity.listIssuers()).some(x => x.id === 'late-reference'));
237
+ } finally { hold.restore(); }
238
+ } finally { await h.close(); }
239
+ });
240
+
241
+ test('incomplete USD schema fails closed without legacy configuration bypass', { skip: !enabled }, async () => {
242
+ const h = await fixture();
243
+ try {
244
+ const p = await h.plan();
245
+ await h.pool.query('ALTER TABLE bz_usage_billing_requests DROP COLUMN billing_rate_json');
246
+ assert.equal(await h.tokens.configurationReady(), false); assert.equal(await h.tokens.ready(), false);
247
+ const result = await h.request(`/admin/api/usage/billing/plans/${p.id}/deletion-preview`, admin);
248
+ assert.equal(result.status, 503); assert.equal(result.body.error, 'USAGE_UNSUPPORTED');
249
+ } finally { await h.close(); }
250
+ });
251
+
252
+
253
+ test('replacing a plan releases its catalog entry while preserving old dispatch, settlement and replay', { skip: !enabled }, async () => {
254
+ const h = await fixture();
255
+ try {
256
+ const oldPlan = await h.plan(), nextPlan = await h.plan(), user = await h.seedUser({ grant: false });
257
+ const originalGrant = await h.tokens.grant(user.accountId, {request_key:randomUUID(),plan_id:oldPlan.id,expected_revision:0});
258
+ const operationId = randomUUID();
259
+ const original = await h.tokens.admit({actor:user.actor,operationId,serviceId:h.service.id,conversationId:null,turnId:null,
260
+ requestHash:'a'.repeat(64),expectedServiceRevision:h.service.revision,serviceConfig:h.service.config,model:h.service.config.model,
261
+ priceSnapshot:{source:'openrouter',modelId:'synthetic/model',endpointId:'synthetic',currency:'USD',fetchedAt:1,
262
+ lines:[{billable:'prompt',unit:'token',costUsd:'1'},{billable:'completion',unit:'token',costUsd:'1'}]}});
263
+ const dispatched = await h.tokens.commitDispatch(original.id,user.actor);
264
+ await h.tokens.grant(user.accountId,{request_key:randomUUID(),plan_id:nextPlan.id,expected_revision:1});
265
+ assert.equal((await h.deletion.preview('plan',oldPlan.id)).can_delete,true);
266
+ assert.equal((await h.deletion.preview('plan',nextPlan.id)).can_delete,false);
267
+ const receipt = await h.remove('plan',oldPlan.id);
268
+ assert.equal(receipt.deleted,true);
269
+ const done = await h.tokens.complete(original.id,dispatched.fence!,{response:{output:'synthetic'},usage:{inputTokens:3,outputTokens:2}});
270
+ assert.equal(done.billedUsd,5); assert.equal(done.grantId,originalGrant.id);
271
+ assert.equal((await h.tokens.findRequest(user.actor,operationId))!.id,original.id);
272
+ await h.tokens.complete(original.id,dispatched.fence!,{response:{output:'synthetic'},usage:{inputTokens:3,outputTokens:2}});
273
+ const [ledger] = await h.pool.query<any[]>('SELECT COUNT(*) AS n FROM bz_usage_billing_ledger WHERE request_id=?',[original.id]);
274
+ assert.equal(Number(ledger[0].n),1);
275
+ const summary = await h.tokens.summary(user.accountId);
276
+ assert.equal(summary.plan!.id,nextPlan.id);assert.equal(summary.availableUsd,100);
277
+ const [grants] = await h.pool.query<any[]>('SELECT COUNT(*) AS n FROM bz_usage_billing_grants WHERE plan_id=?',[oldPlan.id]);
278
+ assert.equal(Number(grants[0].n),1);
279
+ assert(!(await h.tokens.listPlans()).some(p=>p.id===oldPlan.id));
280
+ } finally {await h.close();}
281
+ });
282
+
283
+ test('expired current plans can be removed but future grants remain protected', { skip: !enabled }, async () => {
284
+ const h = await fixture();
285
+ try {
286
+ const expired = await h.plan(), future = await h.plan(), user = await h.seedUser({grant:false});
287
+ await h.tokens.grant(user.accountId,{request_key:randomUUID(),plan_id:expired.id,expected_revision:0,starts_at:Date.now()-40*86400000});
288
+ assert.equal((await h.deletion.preview('plan',expired.id)).can_delete,true);
289
+ await h.remove('plan',expired.id);
290
+ assert.equal((await h.tokens.summary(user.accountId)).presentation.state,'expired');
291
+ await h.tokens.grant(user.accountId,{request_key:randomUUID(),plan_id:future.id,expected_revision:1,starts_at:Date.now()+86400000});
292
+ assert.deepEqual((await h.deletion.preview('plan',future.id)).blockers.map(b=>[b.code,b.count]),[['PLAN_CURRENT_ACCOUNTS',1]]);
293
+ await assert.rejects(h.remove('plan',future.id),{code:'USAGE_RESOURCE_IN_USE'});
294
+ } finally {await h.close();}
295
+ });
296
+
297
+
298
+ test('disabled test accounts do not pin a plan and reactivation cannot restore deleted model access', { skip: !enabled }, async () => {
299
+ const h = await fixture();
300
+ try {
301
+ const p = await h.plan(), user = await h.seedUser({grant:false});
302
+ await h.tokens.grant(user.accountId,{request_key:randomUUID(),plan_id:p.id,expected_revision:0});
303
+ assert.equal((await h.deletion.preview('plan',p.id)).can_delete,false);
304
+ await h.repository.setAccountState({accountId:user.accountId,expectedRevision:1,requestId:randomUUID(),actor:admin,state:'suspended'});
305
+ assert.equal((await h.deletion.preview('plan',p.id)).can_delete,true);
306
+ await h.remove('plan',p.id);
307
+ await h.repository.setAccountState({accountId:user.accountId,expectedRevision:2,requestId:randomUUID(),actor:admin,state:'active'});
308
+ const summary = await h.tokens.summary(user.accountId);
309
+ assert.equal(summary.plan,null); assert.equal(summary.availableUsd,0);
310
+ await assert.rejects(h.tokens.control(user.accountId,{request_key:randomUUID(),expected_revision:1,state:'active'}),{code:'SERVICE_NOT_ENTITLED'});
311
+ } finally {await h.close();}
312
+ });