bailinghub 0.8.0 → 0.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.dockerignore +6 -0
- package/.npmignore +6 -0
- package/CONTRIBUTING.md +4 -0
- package/GOVERNANCE.md +9 -0
- package/README.en.md +8 -6
- package/README.md +8 -6
- package/SECURITY.md +8 -2
- package/THIRD_PARTY_NOTICES.md +17 -17
- package/docker-compose.images.yml +2 -2
- package/docs/ARCHITECTURE.md +1 -1
- package/docs/CHANGELOG.en.md +22 -1
- package/docs/CHANGELOG.md +22 -1
- package/docs/COMPATIBILITY.en.md +8 -0
- package/docs/IMPLEMENTATION_STATUS.en.md +73 -0
- package/docs/IMPLEMENTATION_STATUS.md +73 -0
- package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
- package/docs/INDEPENDENT_VALIDATION.md +4 -4
- package/docs/KERNEL_HOST_API.en.md +18 -0
- package/docs/KERNEL_HOST_API.md +18 -0
- package/docs/MODEL_BILLING.en.md +123 -0
- package/docs/MODEL_BILLING.md +125 -0
- package/docs/PERIOD_ALLOWANCE_UPGRADE.en.md +31 -0
- package/docs/PERIOD_ALLOWANCE_UPGRADE.md +31 -0
- package/docs/README.en.md +8 -1
- package/docs/README.md +7 -0
- package/docs/RELEASE_NOTES_NEXT.en.md +4 -2
- package/docs/RELEASE_NOTES_NEXT.md +4 -2
- package/docs/RELEASE_NOTES_v0.9.0.en.md +45 -0
- package/docs/RELEASE_NOTES_v0.9.0.md +45 -0
- package/docs/RELEASE_NOTES_v0.9.1.en.md +38 -0
- package/docs/RELEASE_NOTES_v0.9.1.md +38 -0
- package/docs/UPGRADE_v0.9.0.en.md +54 -0
- package/docs/UPGRADE_v0.9.0.md +54 -0
- package/docs/UPGRADE_v0.9.1.en.md +39 -0
- package/docs/UPGRADE_v0.9.1.md +39 -0
- package/docs//345/205/274/345/256/271/346/200/247/344/270/216/345/215/207/347/272/247.md +8 -0
- package/package.json +5 -4
- package/scripts/check-doc-links.mjs +6 -0
- package/scripts/check-image-tags.sh +1 -1
- package/scripts/check-release-consistency.test.mjs +2 -2
- package/scripts/dependency-audit.mjs +134 -0
- package/scripts/dependency-audit.test.mjs +125 -0
- package/scripts/install.sh +1 -1
- package/scripts/osps-results.py +114 -0
- package/scripts/publish-images.sh +1 -1
- package/scripts/release-audit.mjs +2 -0
- package/scripts/sdk-runtime-test.mjs +6 -0
- package/scripts/verify-billing-install-upgrade.mjs +225 -0
- package/scripts/verify-github-repo.mjs +2 -0
- package/sdk/node/README.md +17 -0
- package/sdk/node/examples/billing.mjs +21 -0
- package/sdk/node/package.json +5 -1
- package/sdk/node/src/index.mjs +2 -0
- package/sdk/node/src/usage.d.mts +74 -0
- package/sdk/node/src/usage.mjs +62 -0
- package/sdk/node/tests/usage-types.mts +23 -0
- package/sdk/node/tests/usage.test.mjs +81 -0
- package/sdk/php7/README.md +19 -2
- package/sdk/php7/examples/billing.php +27 -0
- package/sdk/php7/examples/well-known.php +1 -1
- package/sdk/php7/src/ToolSpec.php +1 -1
- package/sdk/php7/src/UsageClient.php +95 -0
- package/sdk/php7/src/UsageClientException.php +22 -0
- package/sdk/php7/tests/billing-core-http.php +59 -0
- package/sdk/php7/tests/usage-client.php +78 -0
- package/security/dependency-audit-exceptions.json +192 -0
- package/sql/063_usage_model_billing.sql +153 -0
- package/sql/064_period_plan_allowance.sql +25 -0
- package/sql/README.en.md +12 -4
- package/sql/README.md +14 -6
- package/src/app/auth.ts +2 -0
- package/src/app/kernel-usage-lifecycle.mysql.test.ts +325 -0
- package/src/app/kernel.ts +10 -0
- package/src/app/oss-edition.ts +1 -0
- package/src/infrastructure/config/configstore.ts +6 -0
- package/src/modules/usage/allowance-reset.mysql.test.ts +122 -0
- package/src/modules/usage/background-work.test.ts +144 -0
- package/src/modules/usage/background-work.ts +50 -0
- package/src/modules/usage/billing-contracts.ts +59 -0
- package/src/modules/usage/billing-decimal.test.ts +22 -0
- package/src/modules/usage/billing-decimal.ts +36 -0
- package/src/modules/usage/billing-external.ts +39 -0
- package/src/modules/usage/billing-gateway.mysql.test.ts +24 -0
- package/src/modules/usage/billing-ledger.test.ts +51 -0
- package/src/modules/usage/billing-ledger.ts +104 -0
- package/src/modules/usage/billing-presentation.mysql.test.ts +95 -0
- package/src/modules/usage/billing-presentation.test.ts +49 -0
- package/src/modules/usage/billing-presentation.ts +34 -0
- package/src/modules/usage/billing-prices.mysql.test.ts +88 -0
- package/src/modules/usage/billing-repository.mysql.test.ts +181 -0
- package/src/modules/usage/billing-repository.ts +465 -0
- package/src/modules/usage/contracts.ts +49 -0
- package/src/modules/usage/dynamic-plan-models.mysql.test.ts +221 -0
- package/src/modules/usage/errors.ts +19 -0
- package/src/modules/usage/http.ts +85 -0
- package/src/modules/usage/identity-revocation.mysql.test.ts +286 -0
- package/src/modules/usage/identity.mysql.test.ts +120 -0
- package/src/modules/usage/identity.ts +303 -0
- package/src/modules/usage/issuer-sdk-billing.mysql.test.ts +92 -0
- package/src/modules/usage/model-gateway.mysql.test.ts +207 -0
- package/src/modules/usage/model-gateway.ts +236 -0
- package/src/modules/usage/model-tool-gateway.mysql.test.ts +137 -0
- package/src/modules/usage/model-tool-provider.test.ts +37 -0
- package/src/modules/usage/model-tool-provider.ts +110 -0
- package/src/modules/usage/model-tools.test.ts +36 -0
- package/src/modules/usage/model-tools.ts +62 -0
- package/src/modules/usage/period-allowance.mysql.test.ts +97 -0
- package/src/modules/usage/period.test.ts +26 -0
- package/src/modules/usage/period.ts +96 -0
- package/src/modules/usage/pricing.test.ts +178 -0
- package/src/modules/usage/pricing.ts +229 -0
- package/src/modules/usage/provider-failure.ts +37 -0
- package/src/modules/usage/provider-stream.test.ts +85 -0
- package/src/modules/usage/provider-stream.ts +77 -0
- package/src/modules/usage/provider.test.ts +67 -0
- package/src/modules/usage/provider.ts +142 -0
- package/src/modules/usage/repository.ts +541 -0
- package/src/modules/usage/service-availability.mysql.test.ts +68 -0
- package/src/modules/usage/service-availability.ts +13 -0
- package/src/modules/usage/service-delete.mysql.test.ts +87 -0
- package/src/modules/usage/stream-http.ts +32 -0
- package/src/modules/usage/test-harness.ts +109 -0
- package/src/modules/usage/usage-deletion.mysql.test.ts +312 -0
- package/src/modules/usage/usage-deletion.ts +119 -0
- package/src/modules/usage/validation.test.ts +18 -0
- package/src/modules/usage/validation.ts +33 -0
- package/src/routes/admin-billing-usage.ts +73 -0
- package/src/routes/admin-usage.ts +147 -0
- package/src/routes/admin.ts +4 -0
- package/src/routes/private.ts +8 -0
- package/web/connect/bailing-connect-php7.tgz +0 -0
- package/web/console/assets/Accounts-Bervi5JU.css +1 -0
- package/web/console/assets/Accounts-DKhw_QLr.js +3 -0
- package/web/console/assets/{AgentClients-Bf7sUUs_.js → AgentClients-CM4_5HaA.js} +1 -1
- package/web/console/assets/AgentTasks-BsG850Il.css +1 -0
- package/web/console/assets/AgentTasks-CkQgZTU5.js +2 -0
- package/web/console/assets/{Approvals-BIbZvInm.js → Approvals-B9O9TkbO.js} +1 -1
- package/web/console/assets/{Audit-KyPSmBdZ.js → Audit-2vDC1SPu.js} +1 -1
- package/web/console/assets/{BrandLockup-Sv5DU2G6.js → BrandLockup-BgASiRSE.js} +1 -1
- package/web/console/assets/{Channels-B9n4fbxg.js → Channels-A-GvkNBt.js} +1 -1
- package/web/console/assets/{ChatEntries-xsOCUXi_.js → ChatEntries-BLxymI67.js} +1 -1
- package/web/console/assets/{Clients-CI3DBDHf.js → Clients-DeNlmvS6.js} +1 -1
- package/web/console/assets/{Cost-JgNXQPlN.js → Cost-CBq_L4Kz.js} +1 -1
- package/web/console/assets/{Credentials-B5UUUdt0.js → Credentials-DmtbctNj.js} +1 -1
- package/web/console/assets/{Diagnostics-BMGciWQb.js → Diagnostics-BbcRDiA-.js} +1 -1
- package/web/console/assets/{Executors-CRbboOCZ.js → Executors-gGgmQrDt.js} +1 -1
- package/web/console/assets/{HelpTip-i-KJhf5s.js → HelpTip-Dtdt2tKR.js} +1 -1
- package/web/console/assets/{Kb-CgLNGjRp.js → Kb-lgY6OXUz.js} +2 -2
- package/web/console/assets/{Login-C52JmXzx.js → Login-DA6BASZd.js} +1 -1
- package/web/console/assets/{Projects-CDOvHPVS.js → Projects-DEbmB_sT.js} +1 -1
- package/web/console/assets/Routes-CyXV4Pba.css +1 -0
- package/web/console/assets/Routes-qS6LLoyS.js +124 -0
- package/web/console/assets/{Runs-DYNDXsqk.js → Runs-DG-VLRSc.js} +1 -1
- package/web/console/assets/{Setup-B91P6i1x.js → Setup-DEpVF5uw.js} +1 -1
- package/web/console/assets/Shell-DgoPgK1E.js +1 -0
- package/web/console/assets/Shell-ykb-tUfo.css +1 -0
- package/web/console/assets/{StorageBuckets-DkuDM0oX.js → StorageBuckets-DJtNN769.js} +1 -1
- package/web/console/assets/{SystemSettings-B7Mqj3k1.js → SystemSettings-0DEUgeTR.js} +1 -1
- package/web/console/assets/{SystemStatus-Db93b6dc.js → SystemStatus-CR1phiPE.js} +1 -1
- package/web/console/assets/{Targets-CuuIYeZO.js → Targets-D65l-IMB.js} +1 -1
- package/web/console/assets/{Tools-CHiqz9XZ.js → Tools-DqtrINrN.js} +1 -1
- package/web/console/assets/Usage-B5njXNjx.js +1 -0
- package/web/console/assets/Usage-CAeDGjrb.css +1 -0
- package/web/console/assets/UsageAccess-CGGaWTuj.css +1 -0
- package/web/console/assets/UsageAccess-ChnB4pjb.js +1 -0
- package/web/console/assets/UsageHelp-BBKIvbQ5.js +1 -0
- package/web/console/assets/UsageHelp-CSM4xO0K.css +1 -0
- package/web/console/assets/{index-QnmD7N7F.js → index-65JiiUr4.js} +1 -1
- package/web/console/assets/{index-Fi9gkGxV.css → index-Cxuc9OCj.css} +1 -1
- package/web/console/assets/index-sLKrJd_p.js +2 -0
- package/web/console/assets/{request-DeGya810.js → request-BpaimqEb.js} +1 -1
- package/web/console/assets/{schema-BqlqLw1R.js → schema-D0Z4kFCZ.js} +1 -1
- package/web/console/assets/{util-4bN2dv7B.js → util-DZYfJ5Zo.js} +1 -1
- package/web/console/assets/{vendor-element-CZoEjZr8.js → vendor-element-8cVcdt5T.js} +2 -2
- package/web/console/assets/{vendor-mammoth-BUEEDX6A.js → vendor-mammoth-CnDA23N0.js} +1 -1
- package/web/console/assets/vendor-vue-Co7x2FW6.js +29 -0
- package/web/console/index.html +4 -4
- package/web-admin/README.md +17 -0
- package/web-admin/package-lock.json +83 -85
- package/web-admin/src/components/UsageDeletionPreview.vue +44 -0
- package/web-admin/src/components/UsageHelp.vue +72 -0
- package/web-admin/src/components/UsageServiceReferences.vue +169 -0
- package/web-admin/src/layout/Shell.vue +22 -5
- package/web-admin/src/pages/Accounts.vue +3 -3
- package/web-admin/src/pages/AgentTasks.vue +2 -2
- package/web-admin/src/pages/Routes.vue +5 -1
- package/web-admin/src/pages/Usage.vue +2470 -0
- package/web-admin/src/pages/UsageAccess.vue +1147 -0
- package/web-admin/src/router.ts +8 -4
- package/web-admin/src/styles/base.css +57 -0
- package/web-admin/src/table-widths.ts +16 -1
- package/web-admin/src/usage-deletion.ts +40 -0
- package/web-admin/src/usage-management.ts +13 -0
- package/web-admin/src/usage-presentation.test.ts +21 -0
- package/web-admin/src/usage-presentation.ts +107 -0
- package/web-admin/src/usage-price-preview.test.ts +60 -0
- package/web-admin/src/usage-price-preview.ts +54 -0
- package/web-admin/tests/token-usage.browser.mjs +773 -0
- package/web-admin/tests/usage-access.browser.mjs +398 -0
- package/web/console/assets/Accounts-B4ePH5jp.css +0 -1
- package/web/console/assets/Accounts-BRCR3O0P.js +0 -3
- package/web/console/assets/AgentTasks--bqL_QKg.js +0 -2
- package/web/console/assets/AgentTasks-C8ox3TyS.css +0 -1
- package/web/console/assets/Routes-DkMIjMQA.css +0 -1
- package/web/console/assets/Routes-X9vHLpKW.js +0 -124
- package/web/console/assets/Shell-Bj6C8Hgo.css +0 -1
- package/web/console/assets/Shell-BsRa7bQQ.js +0 -1
- package/web/console/assets/index-UGvfF3Xr.js +0 -2
- package/web/console/assets/vendor-vue-B2uhHUfE.js +0 -29
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { usagePresentation } from './billing-presentation';
|
|
4
|
+
import type { BillingGrant } from './billing-contracts';
|
|
5
|
+
|
|
6
|
+
const grant: BillingGrant = { id: 'synthetic', accountId: 'synthetic', planId: 'synthetic', planRevision: 1, revision: 1,
|
|
7
|
+
label: 'Synthetic', state: 'active', sourceOwner: 'hub', startsAt: 1000, expiresAt: 3000,
|
|
8
|
+
config: { mode: 'credits', priceUsd: 1000, duration: { unit: 'day', count: 1 } } };
|
|
9
|
+
|
|
10
|
+
test('credits are a fixed display projection of USD and small positive balances are not zero', () => {
|
|
11
|
+
for (const [available, expected] of [[0.00029,'0.29'],[0.0011,'1.1'],[0.000001,'<0.01'],[0.000019,'0.01'],[1,'1000'],[0,'0']] as const) {
|
|
12
|
+
const view = usagePresentation('active', grant, available, 2000);
|
|
13
|
+
assert.equal(view.kind, 'credits'); assert.equal(view.displayValue, expected);
|
|
14
|
+
assert.equal(view.remaining, available * 1000); assert.equal(view.total, 1_000_000);
|
|
15
|
+
assert.equal(view.state, available ? 'active' : 'depleted');
|
|
16
|
+
}
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
test('periodic projection describes remaining percentage, clamps the range and distinguishes sub-one-percent', () => {
|
|
20
|
+
const periodic = { ...grant, config: { ...grant.config, mode: 'periodic' as const, periodAllowanceUsd: 1000, periodUnit: 'day' as const } };
|
|
21
|
+
for (const [available, expected] of [[1000,'100'],[125,'12'],[10,'1'],[1,'<1'],[0,'0'],[-25,'0'],[1500,'100']] as const) {
|
|
22
|
+
const view = usagePresentation('active', periodic, available, 2000);
|
|
23
|
+
assert.equal(view.kind, 'percentage'); assert.equal(view.total, 100); assert.equal(view.displayValue, expected);
|
|
24
|
+
assert.equal(view.remaining, Math.min(100, Math.max(0, available) / 1000 * 100));
|
|
25
|
+
}
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
test('no allowance and nonusable states never fabricate a zero remaining allowance', () => {
|
|
29
|
+
assert.deepEqual(usagePresentation('active', null, 0, 2000), {
|
|
30
|
+
schema: 'bailing.usage-presentation.v1', kind: 'none', state: 'unavailable', remaining: null, total: null, displayValue: null,
|
|
31
|
+
});
|
|
32
|
+
for (const [accountState, g, now, state] of [
|
|
33
|
+
['active', grant, 999, 'not_started'], ['active', grant, 3000, 'expired'],
|
|
34
|
+
['suspended', grant, 2000, 'suspended'], ['active', { ...grant, state: 'suspended' as const }, 2000, 'suspended'],
|
|
35
|
+
['suspended', grant, 4000, 'suspended'],
|
|
36
|
+
] as const) {
|
|
37
|
+
const view = usagePresentation(accountState, g, 1000, now);
|
|
38
|
+
assert.equal(view.state, state); assert.equal(view.remaining, null); assert.equal(view.displayValue, null); assert.equal(view.total, 1_000_000);
|
|
39
|
+
}
|
|
40
|
+
assert.equal(usagePresentation('active', grant, 1000, 1000).state, 'active');
|
|
41
|
+
assert.equal(usagePresentation('active', { ...grant, expiresAt: null }, 1000, 4000).state, 'active');
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
test('periodic percentage divides by period allowance instead of sale price', () => {
|
|
45
|
+
const periodic: BillingGrant = { ...grant, config: { ...grant.config, mode: 'periodic', periodUnit: 'week', priceUsd: 100, periodAllowanceUsd: 20 } };
|
|
46
|
+
assert.equal(usagePresentation('active', periodic, 10, 2000).remaining, 50);
|
|
47
|
+
assert.equal(usagePresentation('active', periodic, 10, 2000).displayValue, '50');
|
|
48
|
+
assert.equal(usagePresentation('active', periodic, 20, 2000).remaining, 100);
|
|
49
|
+
});
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { billingAllowanceUsd } from './billing-ledger';
|
|
2
|
+
import { USD_SCALE, usdMicros } from './billing-decimal';
|
|
3
|
+
import type { BillingGrant, UsagePresentation } from './billing-contracts';
|
|
4
|
+
|
|
5
|
+
/** Inputs are the original grant, locked account state and DB time used by summary. */
|
|
6
|
+
export function usagePresentation(accountState: string, grant: BillingGrant | null, availableUsd: number | string, now: number): UsagePresentation {
|
|
7
|
+
const empty: UsagePresentation = { schema: 'bailing.usage-presentation.v1', kind: 'none', state: 'unavailable', remaining: null, total: null, displayValue: null };
|
|
8
|
+
if (!grant) return empty;
|
|
9
|
+
const { config } = grant;
|
|
10
|
+
const kind = config.mode === 'credits' ? 'credits' : 'percentage';
|
|
11
|
+
const total = kind === 'credits' ? config.priceUsd * 1000 : 100;
|
|
12
|
+
const unavailable = (state: UsagePresentation['state']): UsagePresentation => ({ ...empty, kind, state, total });
|
|
13
|
+
if (accountState !== 'active' || grant.state !== 'active') return unavailable('suspended');
|
|
14
|
+
if (grant.expiresAt !== null && now >= grant.expiresAt) return unavailable('expired');
|
|
15
|
+
if (now < grant.startsAt) return unavailable('not_started');
|
|
16
|
+
const available = Math.max(0, Number(availableUsd));
|
|
17
|
+
const micros = available > 0 ? usdMicros(availableUsd) : 0n;
|
|
18
|
+
const state = available > 0 ? 'active' : 'depleted';
|
|
19
|
+
if (kind === 'credits') {
|
|
20
|
+
// Decimal micro-units preserve fractional charges without binary floor errors.
|
|
21
|
+
const hundredths = micros * 100_000n / USD_SCALE;
|
|
22
|
+
const fraction = String(hundredths % 100n).padStart(2, '0').replace(/0+$/, '');
|
|
23
|
+
const displayValue = available > 0 && hundredths === 0n ? '<0.01'
|
|
24
|
+
: `${hundredths / 100n}${fraction ? `.${fraction}` : ''}`;
|
|
25
|
+
return { ...empty, kind, state, total, remaining: available * 1000, displayValue };
|
|
26
|
+
}
|
|
27
|
+
const allowance = billingAllowanceUsd(config);
|
|
28
|
+
const bounded = Math.min(available, allowance);
|
|
29
|
+
const quotaMicros = usdMicros(allowance);
|
|
30
|
+
const boundedMicros = micros < quotaMicros ? micros : quotaMicros;
|
|
31
|
+
const wholePercent = boundedMicros * 100n / quotaMicros;
|
|
32
|
+
return { ...empty, kind, state, total, remaining: Math.min(100, bounded / allowance * 100),
|
|
33
|
+
displayValue: bounded > 0 && wholePercent === 0n ? '<1' : String(wholePercent) };
|
|
34
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import test from 'node:test';
|
|
4
|
+
import { usageHash } from './repository';
|
|
5
|
+
import { createUsageTestHarness } from './test-harness';
|
|
6
|
+
import type { PriceSnapshot, BillingPlanConfig, BillingRequest } from './billing-contracts';
|
|
7
|
+
|
|
8
|
+
const enabled = process.env.BAILING_USAGE_TEST_MYSQL === '1';
|
|
9
|
+
const response = { output: 'Synthetic complete result' };
|
|
10
|
+
const price: PriceSnapshot = { source: 'openrouter', currency: 'USD', modelId: 'synthetic-model', endpointId: 'synthetic-endpoint', fetchedAt: 1,
|
|
11
|
+
lines: [{ billable: 'prompt', unit: 'token', costUsd: '0.1' }, { billable: 'completion', unit: 'token', costUsd: '0.25' }] };
|
|
12
|
+
async function fixture(mode: BillingPlanConfig['mode'] = 'credits', priceUsd = 100) {
|
|
13
|
+
const h = await createUsageTestHarness(), tokens = h.tokens;
|
|
14
|
+
const user = await h.identity.exchange(h.issuerToken, { request_key: randomUUID(), tenant: 'synthetic', subject: randomUUID(), service_id: h.service.id, model_access: 'token_gateway' });
|
|
15
|
+
const config: BillingPlanConfig = { mode, serviceIds: [h.service.id], priceUsd, multiplier: 1.5, duration: { unit: 'month', count: 1 }, ...(mode === 'periodic' ? { periodUnit: 'week', periodAllowanceUsd: priceUsd } : {}) };
|
|
16
|
+
const plan = await tokens.putPlan({ id: 'synthetic-plan', label: 'Synthetic USD plan', expected_revision: 0, config });
|
|
17
|
+
const grant = await tokens.grant(user.session.accountId, { request_key: randomUUID(), plan_id: plan.id, expected_revision: 0 });
|
|
18
|
+
const edit = (next: BillingPlanConfig, expected_revision: number) => tokens.putPlan({ id: plan.id, label: plan.label, expected_revision, config: next });
|
|
19
|
+
const admit = (snapshot = price, operationId: string = randomUUID()) => tokens.admit({ actor: user.session, operationId, serviceId: h.service.id,
|
|
20
|
+
conversationId: null, turnId: null, requestHash: usageHash(operationId), expectedServiceRevision: h.service.revision, serviceConfig: h.service.config, model: h.service.config.model, priceSnapshot: snapshot });
|
|
21
|
+
const dispatch = async (snapshot = price) => tokens.commitDispatch((await admit(snapshot)).id, user.session);
|
|
22
|
+
const finish = (request: BillingRequest, inputTokens = 3, outputTokens = 2) => tokens.complete(request.id, request.fence!, { response, usage: { inputTokens, outputTokens } });
|
|
23
|
+
return { ...h, tokens, user, config, plan, grant, edit, admit, dispatch, finish };
|
|
24
|
+
}
|
|
25
|
+
for (const mode of ['credits', 'periodic'] as const) test(`USD ${mode}: immutable allowance, uniform multiplier and tiny charges`, { skip: !enabled }, async () => {
|
|
26
|
+
const h = await fixture(mode);
|
|
27
|
+
try {
|
|
28
|
+
const first = await h.finish(await h.dispatch());
|
|
29
|
+
assert.equal(first.referenceCostUsd, 0.8); assert.equal(first.billedUsd, 1.2);
|
|
30
|
+
assert.deepEqual(first.usage, { inputTokens: 3, outputTokens: 2, totalTokens: 5 });
|
|
31
|
+
assert.equal(first.billingRate.multiplier, 1.5);
|
|
32
|
+
await h.edit({ ...h.config, priceUsd: 9999, multiplier: 2 }, 1);
|
|
33
|
+
const tiny = { ...price, lines: [{ billable: 'prompt', unit: 'token' as const, costUsd: '0.000000001' }, { billable: 'completion', unit: 'token' as const, costUsd: '0.000000002' }] };
|
|
34
|
+
for (let i = 0; i < 10; i++) assert.equal((await h.finish(await h.dispatch(tiny), 1, 1)).billedUsd, 0.000000006);
|
|
35
|
+
const summary = await h.tokens.summary(h.user.session.accountId);
|
|
36
|
+
assert.equal(summary.consumedUsd, 1.20000006); assert.equal(summary.availableUsd, 98.79999994);
|
|
37
|
+
assert.deepEqual(summary.grant, h.grant); assert.equal('multiplier' in summary.grant!.config, false);
|
|
38
|
+
assert.equal(summary.plan!.multiplier, 2);
|
|
39
|
+
assert.equal(summary.presentation.displayValue, mode === 'credits' ? '98799.99' : '98');
|
|
40
|
+
const [ledger] = await h.pool.query<any[]>('SELECT SUM(billed_usd) AS charged,SUM(input_tokens+output_tokens) AS actual FROM bz_usage_billing_ledger WHERE grant_id=?', [h.grant.id]);
|
|
41
|
+
assert.equal(ledger[0].charged, '1.200000060000'); assert.equal(Number(ledger[0].actual), 25);
|
|
42
|
+
} finally { await h.close(); }
|
|
43
|
+
});
|
|
44
|
+
test('original price and multiplier survive edits, ACK loss and repeat completion exactly once', { skip: !enabled }, async () => {
|
|
45
|
+
const h = await fixture();
|
|
46
|
+
try {
|
|
47
|
+
const admitted = await h.admit();
|
|
48
|
+
await h.edit({ ...h.config, multiplier: 3 }, 1);
|
|
49
|
+
const dispatched = await h.tokens.commitDispatch(admitted.id, h.user.session);
|
|
50
|
+
const complete = await h.finish(dispatched); assert.equal(complete.billedUsd, 1.2);
|
|
51
|
+
assert.deepEqual(h.tokens.view(complete).billing_rate, admitted.billingRate);
|
|
52
|
+
assert.deepEqual((await h.admit({ ...price, lines: [{ billable: 'prompt', unit: 'token', costUsd: '999' }] }, admitted.operationId)).billingRate, admitted.billingRate);
|
|
53
|
+
await h.finish(dispatched); await h.finish(dispatched);
|
|
54
|
+
assert.equal((await h.tokens.summary(h.user.session.accountId)).consumedUsd, 1.2);
|
|
55
|
+
const [count] = await h.pool.query<any[]>('SELECT COUNT(*) AS n FROM bz_usage_billing_ledger'); assert.equal(count[0].n, 1);
|
|
56
|
+
await assert.rejects(h.tokens.complete(dispatched.id, dispatched.fence!, { response, usage: { inputTokens: 3, outputTokens: 3 } }), { code: 'USAGE_RECEIPT_CONFLICT' });
|
|
57
|
+
} finally { await h.close(); }
|
|
58
|
+
});
|
|
59
|
+
test('concurrent work may slightly overrun USD allowance; subsequent work stops and missing usage stays pending', { skip: !enabled }, async () => {
|
|
60
|
+
const h = await fixture('credits', 2);
|
|
61
|
+
try {
|
|
62
|
+
const a = await h.dispatch(), b = await h.dispatch();
|
|
63
|
+
const noUsage = await h.tokens.complete(a.id, a.fence!, { response });
|
|
64
|
+
assert.equal(noUsage.resultState, 'complete'); assert.equal(noUsage.billedUsd, null);
|
|
65
|
+
assert.equal((await h.tokens.summary(h.user.session.accountId)).consumedUsd, 0);
|
|
66
|
+
await Promise.all([h.finish(a), h.finish(b)]);
|
|
67
|
+
const summary = await h.tokens.summary(h.user.session.accountId);
|
|
68
|
+
assert.equal(summary.consumedUsd, 2.4); assert.equal(summary.overageUsd, 0.4); assert.equal(summary.availableUsd, 0);
|
|
69
|
+
await assert.rejects(h.admit(), { code: 'ALLOWANCE_INSUFFICIENT' });
|
|
70
|
+
} finally { await h.close(); }
|
|
71
|
+
});
|
|
72
|
+
test('image accounting uses server counts, leaves tokens null, rejects changed evidence and does not trust a supplied cost', { skip: !enabled }, async () => {
|
|
73
|
+
const h = await fixture();
|
|
74
|
+
try {
|
|
75
|
+
const image: PriceSnapshot = { ...price, lines: [{ billable: 'output_image', unit: 'image', costUsd: '0.03', variant: '1k' }] };
|
|
76
|
+
const r = await h.dispatch(image);
|
|
77
|
+
const missing = await h.tokens.complete(r.id, r.fence!, { response });
|
|
78
|
+
assert.equal(missing.billingState, 'pending'); assert.equal(missing.billedUsd, null);
|
|
79
|
+
const rawUsage = { outputImageCount: 2, outputVariant: '1k', cost: 99999, providerExtension: 'synthetic-private-metadata' };
|
|
80
|
+
const done = await h.tokens.complete(r.id, r.fence!, { response, rawUsage });
|
|
81
|
+
assert.deepEqual(h.tokens.view(done).raw_usage, { outputImageCount: 2, outputVariant: '1k' });
|
|
82
|
+
assert.equal(done.usage, null); assert.equal(done.referenceCostUsd, 0.06); assert.equal(done.billedUsd, 0.09);
|
|
83
|
+
const again = await h.tokens.complete(r.id, r.fence!, { response, rawUsage }); assert.equal(again.billedUsd, 0.09);
|
|
84
|
+
await assert.rejects(h.tokens.complete(r.id, r.fence!, { response, rawUsage: { ...rawUsage, outputImageCount: 3 } }), { code: 'USAGE_RECEIPT_CONFLICT' });
|
|
85
|
+
const [ledger] = await h.pool.query<any[]>('SELECT input_tokens,output_tokens,billed_usd FROM bz_usage_billing_ledger');
|
|
86
|
+
assert.equal(ledger[0].input_tokens, null); assert.equal(ledger[0].output_tokens, null);
|
|
87
|
+
} finally { await h.close(); }
|
|
88
|
+
});
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import { readFile } from 'node:fs/promises';
|
|
5
|
+
import { createPool, type RowDataPacket } from 'mysql2/promise';
|
|
6
|
+
import { UsageRepository, usageHash } from './repository';
|
|
7
|
+
import { getUsageIdentity } from './identity';
|
|
8
|
+
import { getBillingRepository } from './billing-repository';
|
|
9
|
+
import type { BillingPlanConfig } from './billing-contracts';
|
|
10
|
+
import type { UsageActor, UsageService } from './contracts';
|
|
11
|
+
const enabled = process.env.BAILING_USAGE_TEST_MYSQL === '1';
|
|
12
|
+
test('USD repository: shared allowance, soft overage, original settlement, lifetime and scope', { skip: !enabled }, async t => {
|
|
13
|
+
const db = `token_repository_${randomUUID().replaceAll('-', '')}`;
|
|
14
|
+
const settings = { host: '127.0.0.1', port: 16307, user: 'root', password: '', multipleStatements: true, connectionLimit: 12 };
|
|
15
|
+
const admin = createPool(settings); await admin.query(`CREATE DATABASE \`${db}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_bin`);
|
|
16
|
+
const pool = createPool({ ...settings, database: db }), repo = new UsageRepository(() => pool), identity = getUsageIdentity(repo), tokens = getBillingRepository(repo);
|
|
17
|
+
try {
|
|
18
|
+
assert.equal(await tokens.ready(), false);
|
|
19
|
+
const migration = await readFile(new URL('../../../sql/063_usage_model_billing.sql', import.meta.url), 'utf8');
|
|
20
|
+
await pool.query(migration); await pool.query(migration); assert.equal(await tokens.ready(), true);
|
|
21
|
+
await t.test('fresh idempotent migration installs exactly the identity and USD schema', async () => {
|
|
22
|
+
const [tables] = await pool.query<RowDataPacket[]>('SELECT TABLE_NAME AS name FROM information_schema.tables WHERE table_schema=DATABASE()');
|
|
23
|
+
const expected = ['accounts','members','changes','services','issuers','users','sessions',
|
|
24
|
+
'billing_plans','billing_grants','billing_heads','billing_periods','billing_requests','billing_ledger','price_snapshots'].map(name => `bz_usage_${name}`);
|
|
25
|
+
assert.deepEqual(tables.map(row => row.name).sort(), expected.sort());
|
|
26
|
+
const [columns] = await pool.query<RowDataPacket[]>("SELECT COLUMN_DEFAULT AS defaultValue,IS_NULLABLE AS nullable FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='bz_usage_sessions' AND column_name='model_access'");
|
|
27
|
+
assert.equal(columns.length, 1); assert.equal(columns[0]!.defaultValue, 'service'); assert.equal(columns[0]!.nullable, 'NO');
|
|
28
|
+
assert.equal(await identity.ready(), true);
|
|
29
|
+
});
|
|
30
|
+
const services: UsageService[] = [];
|
|
31
|
+
for (const id of ['alpha','beta','outside']) services.push(await repo.putService({ id, label: `Synthetic ${id}`, expectedRevision: 0,
|
|
32
|
+
config: { credential: 'synthetic', model: `model-${id}`, providerScope: `synthetic-${id}`, maxInputBytes: 100000, maxOutputTokens: 1000, timeoutMs: 3000 } }));
|
|
33
|
+
const issuer = await identity.createIssuer({ id: 'synthetic-issuer', label: 'Synthetic issuer', permissions: ['identity:exchange','identity:revoke','usage:read'], service_ids: ['alpha','beta'] });
|
|
34
|
+
const config: BillingPlanConfig = { mode: 'credits', serviceIds: ['alpha','beta'], priceUsd: 100, duration: { unit: 'day', count: 30 }, multiplier: 1 };
|
|
35
|
+
const plan = await tokens.putPlan({ id: 'synthetic-plan', label: 'Synthetic allowance', expected_revision: 0, config });
|
|
36
|
+
async function user(modelAccess: 'service' | 'token_gateway' = 'token_gateway', planId = plan.id, startsAt?: number) {
|
|
37
|
+
const out = await identity.exchange(issuer.credential!, { request_key: randomUUID(), tenant: 'synthetic', subject: randomUUID(), service_id: 'alpha', ...(modelAccess === 'token_gateway' ? { model_access: modelAccess } : {}) });
|
|
38
|
+
const grant = await tokens.grant(out.session.accountId, { request_key: randomUUID(), plan_id: planId, expected_revision: 0, ...(startsAt === undefined ? {} : { starts_at: startsAt }) });
|
|
39
|
+
return { actor: out.session, grant };
|
|
40
|
+
}
|
|
41
|
+
async function admit(actor: UsageActor, serviceId = 'alpha', operationId: string = randomUUID()) {
|
|
42
|
+
const svc = services.find(s => s.id === serviceId)!;
|
|
43
|
+
return tokens.admit({ actor, operationId, serviceId, conversationId: null, turnId: null, requestHash: usageHash([operationId, serviceId]), expectedServiceRevision: svc.revision, serviceConfig: svc.config, model: svc.config.model, priceSnapshot: { source: 'openrouter', currency: 'USD', modelId: 'synthetic', endpointId: 'synthetic', fetchedAt: Date.now(), lines: [{ billable: 'prompt', unit: 'token', costUsd: '1' }, { billable: 'completion', unit: 'token', costUsd: '1' }] } });
|
|
44
|
+
}
|
|
45
|
+
const response = { choices: [{ message: { role: 'assistant', content: 'Synthetic result' } }] };
|
|
46
|
+
await t.test('multiple models share Token pool; finish admitted response and block next; replay exact evidence', async () => {
|
|
47
|
+
const { actor } = await user();
|
|
48
|
+
const a = await admit(actor), b = await admit(actor, 'beta');
|
|
49
|
+
const [pa,pb] = await Promise.all([tokens.commitDispatch(a.id, actor), tokens.commitDispatch(b.id, actor)]);
|
|
50
|
+
await assert.rejects(tokens.commitDispatch(a.id, actor), { code: 'USAGE_PENDING' });
|
|
51
|
+
await tokens.complete(a.id, pa.fence!, { response, usage: { inputTokens: 20, outputTokens: 40 } });
|
|
52
|
+
const receipt = { response, usage: { inputTokens: 30, outputTokens: 40 }, executionId: 'synthetic-unique' };
|
|
53
|
+
const settled = await tokens.complete(b.id, pb.fence!, receipt);
|
|
54
|
+
assert.equal(settled.billedUsd, 70); assert.equal(settled.overageUsd, 30);
|
|
55
|
+
assert.equal((await tokens.complete(b.id, pb.fence!, receipt)).revision, settled.revision);
|
|
56
|
+
const summary = await tokens.summary(actor.accountId);
|
|
57
|
+
assert.equal(summary.availableUsd, 0); assert.equal(summary.consumedUsd, 130); assert.equal(summary.overageUsd, 30);
|
|
58
|
+
await assert.rejects(admit(actor), { code: 'ALLOWANCE_INSUFFICIENT' });
|
|
59
|
+
const duplicate = await admit(actor, 'beta', b.operationId); assert.equal(duplicate.created, false);
|
|
60
|
+
await assert.rejects(tokens.complete(b.id, pb.fence!, { response, usage: { inputTokens: 1, outputTokens: 1 } }), { code: 'USAGE_RECEIPT_CONFLICT' });
|
|
61
|
+
await assert.rejects(tokens.complete(b.id, pb.fence!, { ...receipt, executionId: 'different-execution' }), { code: 'USAGE_RECEIPT_CONFLICT' });
|
|
62
|
+
const view = tokens.view(settled); assert.equal('serviceConfig' in view, false); assert.equal('fence' in view, false); assert.deepEqual(view.response, response);
|
|
63
|
+
assert.equal('response' in tokens.view(settled, settled.createdAt + 8 * 86_400_000), false);
|
|
64
|
+
});
|
|
65
|
+
await t.test('result complete without usage remains usable; delayed usage settles once, unknown never redispatches', async () => {
|
|
66
|
+
const { actor } = await user(), a = await admit(actor), p = await tokens.commitDispatch(a.id, actor);
|
|
67
|
+
const completed = await tokens.complete(a.id, p.fence!, { response });
|
|
68
|
+
assert.equal(completed.resultState, 'complete'); assert.equal(completed.billingState, 'pending');
|
|
69
|
+
assert.deepEqual(tokens.view(completed).response, response); assert.equal((await tokens.summary(actor.accountId)).pendingRequests, 1);
|
|
70
|
+
const finished = await tokens.complete(a.id, p.fence!, { response, usage: { inputTokens: 12, outputTokens: 3 } });
|
|
71
|
+
assert.equal(finished.billingState, 'settled');
|
|
72
|
+
const b = await admit(actor), q = await tokens.commitDispatch(b.id, actor);
|
|
73
|
+
await tokens.markUnknown(b.id, q.fence!, 'connection_lost');
|
|
74
|
+
assert.equal((await tokens.findRequest(actor, b.operationId))!.resultState, 'unknown');
|
|
75
|
+
assert.equal((await admit(actor, 'alpha', b.operationId)).created, false);
|
|
76
|
+
await assert.rejects(tokens.commitDispatch(b.id, actor), { code: 'USAGE_PENDING' });
|
|
77
|
+
await tokens.complete(b.id, q.fence!, { response, usage: { inputTokens: 4, outputTokens: 1 } });
|
|
78
|
+
assert.equal((await tokens.summary(actor.accountId)).consumedUsd, 20);
|
|
79
|
+
});
|
|
80
|
+
await t.test('plan CAS and grant snapshots preserve old requests and late settlement across replacement', async () => {
|
|
81
|
+
const { actor, grant } = await user(), a = await admit(actor), p = await tokens.commitDispatch(a.id, actor);
|
|
82
|
+
const edited = await tokens.putPlan({ id: plan.id, label: 'Edited template', expected_revision: plan.revision, config: { ...config, priceUsd: 300 } });
|
|
83
|
+
assert.equal((await tokens.summary(actor.accountId)).grant!.config.priceUsd, 100);
|
|
84
|
+
await assert.rejects(tokens.putPlan({ id: plan.id, label: 'Stale', expected_revision: 1, config }), { code: 'USAGE_REVISION_CONFLICT' });
|
|
85
|
+
const requestKey = randomUUID(), body = { request_key: requestKey, plan_id: edited.id, expected_revision: grant.revision };
|
|
86
|
+
const replacement = await tokens.grant(actor.accountId, body);
|
|
87
|
+
assert.equal((await tokens.grant(actor.accountId, body)).id, replacement.id);
|
|
88
|
+
await assert.rejects(tokens.grant(actor.accountId, { ...body, plan_id: 'other' }), { code: 'USAGE_IDEMPOTENCY_CONFLICT' });
|
|
89
|
+
await tokens.complete(a.id, p.fence!, { response, usage: { inputTokens: 20, outputTokens: 10 } });
|
|
90
|
+
assert.equal((await tokens.summary(actor.accountId)).availableUsd, 300);
|
|
91
|
+
const [old] = await pool.query<RowDataPacket[]>('SELECT consumed_usd FROM bz_usage_billing_periods WHERE grant_id=?', [grant.id]);
|
|
92
|
+
assert.equal(Number(old[0]!.consumed_usd), 30);
|
|
93
|
+
await assert.rejects(tokens.control(actor.accountId, { request_key: randomUUID(), expected_revision: replacement.revision, state: 'suspended' }, 'external'), { code: 'USAGE_SOURCE_CONFLICT' });
|
|
94
|
+
const before = await admit(actor);
|
|
95
|
+
await tokens.control(actor.accountId, { request_key: randomUUID(), expected_revision: replacement.revision, state: 'suspended' });
|
|
96
|
+
await assert.rejects(tokens.commitDispatch(before.id, actor), { code: 'SERVICE_NOT_ENTITLED' });
|
|
97
|
+
assert.equal((await tokens.findRequest(actor, a.operationId))!.billedUsd, 30);
|
|
98
|
+
});
|
|
99
|
+
await t.test('settlement storage failure preserves usable reply and original-request reconciliation', async () => {
|
|
100
|
+
const { actor } = await user(), a = await admit(actor), p = await tokens.commitDispatch(a.id, actor);
|
|
101
|
+
const transact = repo.withTransaction.bind(repo); let calls = 0;
|
|
102
|
+
repo.withTransaction = async fn => { calls++; if (calls === 2) throw new Error('synthetic_settlement_storage_unavailable'); return transact(fn); };
|
|
103
|
+
let pending;
|
|
104
|
+
try { pending = await tokens.complete(a.id, p.fence!, { response, usage: { inputTokens: 20, outputTokens: 10 } }); }
|
|
105
|
+
finally { repo.withTransaction = transact; }
|
|
106
|
+
assert.equal(calls, 2); assert.equal(pending.billingState, 'pending'); assert.equal(pending.resultState, 'complete'); assert.deepEqual(tokens.view(pending).response, response);
|
|
107
|
+
const [before] = await pool.query<RowDataPacket[]>('SELECT COUNT(*) AS n FROM bz_usage_billing_ledger WHERE request_id=?', [a.id]); assert.equal(Number(before[0]!.n), 0);
|
|
108
|
+
await tokens.reconcilePendingUsage();
|
|
109
|
+
const [reconciled] = await pool.query<RowDataPacket[]>('SELECT billing_state FROM bz_usage_billing_requests WHERE id=?', [a.id]); assert.equal(reconciled[0]!.billing_state, 'settled');
|
|
110
|
+
const restored = await tokens.findRequest(actor, a.operationId); assert.equal(restored!.billingState, 'settled'); assert.equal(restored!.billedUsd, 30);
|
|
111
|
+
await tokens.findRequest(actor, a.operationId);
|
|
112
|
+
const [after] = await pool.query<RowDataPacket[]>('SELECT COUNT(*) AS n FROM bz_usage_billing_ledger WHERE request_id=?', [a.id]); assert.equal(Number(after[0]!.n), 1);
|
|
113
|
+
});
|
|
114
|
+
await t.test('cancel before dispatch costs zero; late canceled completion settles but cannot return executable tools', async () => {
|
|
115
|
+
const { actor } = await user(), a = await admit(actor);
|
|
116
|
+
assert.equal((await tokens.cancel(actor, a.operationId)).billedUsd, 0);
|
|
117
|
+
await assert.rejects(tokens.commitDispatch(a.id, actor), { code: 'USAGE_PENDING' });
|
|
118
|
+
const b = await admit(actor), p = await tokens.commitDispatch(b.id, actor);
|
|
119
|
+
await tokens.cancel(actor, b.operationId);
|
|
120
|
+
const late = await tokens.complete(b.id, p.fence!, { response: { tool_calls: [{ id: 'never-execute' }] }, usage: { inputTokens: 8, outputTokens: 2 } });
|
|
121
|
+
assert.equal(late.state, 'cancelled'); assert.equal(late.billingState, 'settled'); assert.equal('response' in tokens.view(late), false);
|
|
122
|
+
assert.equal((await tokens.summary(actor.accountId)).consumedUsd, 10);
|
|
123
|
+
});
|
|
124
|
+
await t.test('service/issuer scope, member revocation and template service changes are checked again at dispatch', async () => {
|
|
125
|
+
const old = await user('service'); await assert.rejects(admit(old.actor, 'beta'), { code: 'USAGE_ACCOUNT_FORBIDDEN' });
|
|
126
|
+
const { actor } = await user(); await assert.rejects(admit(actor, 'outside'), { code: 'SERVICE_NOT_ENTITLED' });
|
|
127
|
+
const a = await admit(actor);
|
|
128
|
+
await pool.query("UPDATE bz_usage_members SET state='revoked' WHERE account_id=? AND user_id=?", [actor.accountId, actor.userId]);
|
|
129
|
+
await assert.rejects(tokens.commitDispatch(a.id, actor), { code: 'USAGE_ACCOUNT_FORBIDDEN' });
|
|
130
|
+
const fresh = await user(), b = await admit(fresh.actor);
|
|
131
|
+
await pool.query("UPDATE bz_usage_services SET state='suspended',revision=revision+1 WHERE id='alpha'");
|
|
132
|
+
await assert.rejects(tokens.commitDispatch(b.id, fresh.actor), { code: 'USAGE_REVISION_CONFLICT' });
|
|
133
|
+
await pool.query("UPDATE bz_usage_services SET state='active',revision=1 WHERE id='alpha'");
|
|
134
|
+
});
|
|
135
|
+
await t.test('late usage belongs to original anchored period; current period is fresh, expiry stops admission', async () => {
|
|
136
|
+
await tokens.putPlan({ id: 'daily', label: 'Synthetic daily', expected_revision: 0, config: { ...config, mode: 'periodic', periodAllowanceUsd: 100, periodUnit: 'day', duration: { unit: 'day', count: 3 } } });
|
|
137
|
+
const dbNow = async () => Number((await pool.query<RowDataPacket[]>('SELECT CAST(UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3))*1000 AS UNSIGNED) AS ms'))[0][0]!.ms);
|
|
138
|
+
const { actor, grant } = await user('token_gateway', 'daily', await dbNow() - 86_400_000 + 1200);
|
|
139
|
+
const a = await admit(actor), p = await tokens.commitDispatch(a.id, actor);
|
|
140
|
+
await new Promise(resolve => setTimeout(resolve, 1250));
|
|
141
|
+
await tokens.complete(a.id, p.fence!, { response, usage: { inputTokens: 110, outputTokens: 20 } });
|
|
142
|
+
const summary = await tokens.summary(actor.accountId);
|
|
143
|
+
assert.equal(summary.currentPeriodConsumedUsd, 0); assert.equal(summary.availableUsd, 100); assert.equal(summary.consumedUsd, 130);
|
|
144
|
+
const b = await admit(actor); assert.notEqual(b.periodStart, a.periodStart);
|
|
145
|
+
await pool.query('UPDATE bz_usage_billing_grants SET expires_at=? WHERE id=?', [await dbNow() - 1, grant.id]);
|
|
146
|
+
const expired = await tokens.summary(actor.accountId);
|
|
147
|
+
assert.equal(expired.availableUsd, 0); assert.equal(expired.presentation.state, 'expired'); assert.equal(expired.presentation.remaining, null);
|
|
148
|
+
});
|
|
149
|
+
await t.test('same optional coordinates support more than 256 model requests without a turn record', async () => {
|
|
150
|
+
const { actor } = await user();
|
|
151
|
+
for (let index = 0; index < 260; index++) {
|
|
152
|
+
const a = await admit(actor), p = await tokens.commitDispatch(a.id, actor);
|
|
153
|
+
await tokens.complete(a.id, p.fence!, { response, usage: { inputTokens: 0, outputTokens: 0 } });
|
|
154
|
+
}
|
|
155
|
+
assert.equal((await tokens.summary(actor.accountId)).consumedUsd, 0);
|
|
156
|
+
const page = await tokens.listRequests(actor.accountId, { limit: 25 }); assert.equal(page.items.length, 25); assert.ok(page.next_cursor);
|
|
157
|
+
const next = await tokens.listRequests(actor.accountId, { limit: 25, cursor: page.next_cursor });
|
|
158
|
+
assert.equal(new Set([...page.items,...next.items].map(x => x.operation_id)).size, 50);
|
|
159
|
+
const [tables] = await pool.query<RowDataPacket[]>('SELECT table_name FROM information_schema.tables WHERE table_schema=DATABASE()');
|
|
160
|
+
assert.equal(tables.length, 14, 'Only identity/account/model and USD accounting tables are installed.');
|
|
161
|
+
});
|
|
162
|
+
await t.test('supplier execution cannot settle two requests; expired reply body is purged without losing audit identity', async () => {
|
|
163
|
+
const { actor } = await user(), a = await admit(actor), b = await admit(actor);
|
|
164
|
+
const pa = await tokens.commitDispatch(a.id, actor), pb = await tokens.commitDispatch(b.id, actor);
|
|
165
|
+
const receipt = { response, usage: { inputTokens: 5, outputTokens: 5 }, executionId: 'unique-supplier-receipt' };
|
|
166
|
+
await tokens.complete(a.id, pa.fence!, receipt);
|
|
167
|
+
await assert.rejects(tokens.complete(b.id, pb.fence!, receipt), { code: 'USAGE_RECEIPT_CONFLICT' });
|
|
168
|
+
const oldTime = Date.now() - 8 * 86_400_000;
|
|
169
|
+
await pool.query('UPDATE bz_usage_billing_requests SET created_at=? WHERE id=?', [oldTime, a.id]);
|
|
170
|
+
await tokens.cleanupExpiredResponses();
|
|
171
|
+
const restored = (await tokens.findRequest(actor, a.operationId))!;
|
|
172
|
+
assert.equal(restored.response, null); assert.equal(restored.billedUsd, 10); assert.ok(restored.resultHash);
|
|
173
|
+
const publicView = tokens.view(restored); assert.equal(publicView.response_expired, true); assert.equal(publicView.dispatch, 'completed');
|
|
174
|
+
assert.equal('response' in publicView, false); assert.equal('resultHash' in publicView, false);
|
|
175
|
+
const other = await user(); assert.equal(await tokens.findRequest(other.actor, a.operationId), null);
|
|
176
|
+
await assert.rejects(tokens.listRequests(other.actor.accountId, { cursor: a.id }), { code: 'USAGE_INVALID_INPUT' });
|
|
177
|
+
});
|
|
178
|
+
} finally {
|
|
179
|
+
await pool.end(); await admin.query(`DROP DATABASE \`${db}\``); await admin.end();
|
|
180
|
+
}
|
|
181
|
+
});
|