bailinghub 0.9.1 â 0.9.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +6 -6
- package/README.md +6 -6
- package/docker-compose.images.yml +2 -2
- package/docs/CHANGELOG.en.md +23 -1
- package/docs/CHANGELOG.md +23 -1
- package/docs/CORE_RELIABILITY.en.md +79 -0
- package/docs/CORE_RELIABILITY.md +79 -0
- package/docs/DEPLOYMENT_DIAGNOSTICS.en.md +78 -0
- package/docs/DEPLOYMENT_DIAGNOSTICS.md +78 -0
- package/docs/IMPLEMENTATION_STATUS.en.md +27 -15
- package/docs/IMPLEMENTATION_STATUS.md +27 -15
- package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
- package/docs/INDEPENDENT_VALIDATION.md +4 -4
- package/docs/KERNEL_HOST_API.en.md +2 -0
- package/docs/KERNEL_HOST_API.md +2 -0
- package/docs/MODEL_BILLING.en.md +4 -0
- package/docs/MODEL_BILLING.md +4 -0
- package/docs/MODEL_PROCESS_RECOVERY.en.md +32 -0
- package/docs/MODEL_PROCESS_RECOVERY.md +37 -0
- package/docs/OPERATIONS.en.md +13 -0
- package/docs/OPERATIONS.md +12 -0
- package/docs/README.en.md +7 -0
- package/docs/README.md +7 -0
- package/docs/RELEASE_NOTES_v0.9.2.en.md +45 -0
- package/docs/RELEASE_NOTES_v0.9.2.md +45 -0
- package/docs/RELEASE_NOTES_v0.9.3.en.md +51 -0
- package/docs/RELEASE_NOTES_v0.9.3.md +51 -0
- package/docs/TOOLS_DESIGN.md +1 -0
- package/docs/UPGRADE_v0.9.2.en.md +62 -0
- package/docs/UPGRADE_v0.9.2.md +62 -0
- package/docs/UPGRADE_v0.9.3.en.md +63 -0
- package/docs/UPGRADE_v0.9.3.md +63 -0
- package/package.json +7 -3
- package/scripts/check-doc-links.mjs +4 -0
- package/scripts/check-image-tags.sh +1 -1
- package/scripts/check-release-consistency.test.mjs +2 -2
- package/scripts/doctor-deployment.test.ts +419 -0
- package/scripts/doctor-deployment.ts +357 -0
- package/scripts/doctor.ts +8 -1
- package/scripts/install-secrets.test.mjs +185 -0
- package/scripts/install.sh +10 -6
- package/scripts/publish-images.sh +1 -1
- package/scripts/release-audit.mjs +8 -0
- package/scripts/verify-github-repo.mjs +8 -0
- package/security/dependency-audit-exceptions.json +1 -1
- package/sql/065_usage_reconciliation_scan.sql +4 -0
- package/sql/066_approval_continuations.sql +15 -0
- package/sql/067_delivery_dlq_replay.sql +10 -0
- package/sql/README.en.md +6 -0
- package/sql/README.md +15 -0
- package/src/adapters/llm/file.test.ts +59 -0
- package/src/adapters/llm/file.ts +11 -4
- package/src/app/agent-tool-invocations.test.ts +3 -1
- package/src/app/approval-continuations.mysql.test.ts +138 -0
- package/src/app/approval-continuations.test.ts +351 -0
- package/src/app/approval-continuations.ts +148 -0
- package/src/app/channels-attachments.test.ts +63 -0
- package/src/app/channels.ts +7 -4
- package/src/app/delivery-dlq-replay.mysql.test.ts +139 -0
- package/src/app/delivery-dlq-replay.test.ts +75 -0
- package/src/app/delivery-dlq-replay.ts +41 -0
- package/src/app/delivery.ts +3 -2
- package/src/app/http-server.ts +3 -0
- package/src/app/kernel-model-process-crash.mysql.test.ts +377 -0
- package/src/app/kernel-notification-lifecycle.test.ts +49 -0
- package/src/app/kernel.ts +22 -0
- package/src/app/notification-outbound.test.ts +53 -0
- package/src/app/operational-metrics.test.ts +37 -1
- package/src/app/operational-metrics.ts +25 -2
- package/src/app/outbound.ts +13 -2
- package/src/app/runtime-evidence-maintenance.test.ts +55 -0
- package/src/app/runtime-lifecycle-default.ts +7 -0
- package/src/app/runtime-lifecycle.test.ts +89 -0
- package/src/app/runtime-lifecycle.ts +52 -11
- package/src/app/tool-approvals.ts +2 -1
- package/src/core/contracts/approval-continuation.ts +43 -0
- package/src/core/contracts/delivery-replay.ts +41 -0
- package/src/core/contracts/tools-idempotency.test.ts +121 -5
- package/src/core/contracts/tools.ts +21 -11
- package/src/core/contracts/types.ts +4 -0
- package/src/core/observability/openmetrics.test.ts +28 -0
- package/src/core/observability/openmetrics.ts +91 -0
- package/src/core/platform/http-body.test.ts +185 -0
- package/src/core/platform/http-body.ts +58 -0
- package/src/core/runtime/finish-runtime.test.ts +2 -0
- package/src/core/runtime/finish-runtime.ts +10 -7
- package/src/core/runtime/notification-background-work.test.ts +50 -0
- package/src/core/runtime/notification-background-work.ts +101 -0
- package/src/core/state/approval-continuation.ts +22 -0
- package/src/core/state/delivery-replay.ts +19 -0
- package/src/core/state/state-codec.ts +2 -0
- package/src/core/state/state-contracts.ts +6 -0
- package/src/infrastructure/config/config-approval-ledger.ts +75 -0
- package/src/infrastructure/config/config-delivery-dlq-ledger.ts +36 -10
- package/src/infrastructure/config/configstore.ts +4 -3
- package/src/infrastructure/state/state-jsonl.ts +56 -11
- package/src/infrastructure/state/state-mysql.ts +54 -0
- package/src/modules/usage/background-work.test.ts +28 -0
- package/src/modules/usage/background-work.ts +43 -7
- package/src/modules/usage/billing-reconciliation.mysql.test.ts +163 -0
- package/src/modules/usage/billing-reconciliation.test.ts +85 -0
- package/src/modules/usage/billing-repository.ts +63 -11
- package/src/modules/usage/maintenance.test.ts +78 -0
- package/src/modules/usage/maintenance.ts +39 -0
- package/src/modules/usage/model-gateway.ts +2 -1
- package/src/routes/admin-default.ts +2 -2
- package/src/routes/admin-runtime-default.ts +2 -2
- package/src/routes/admin-runtime.test.ts +1 -1
- package/src/routes/admin-runtime.ts +39 -18
- package/src/routes/admin.ts +1 -1
- package/src/routes/approvals-default.ts +2 -2
- package/src/routes/approvals.ts +30 -33
- package/src/routes/critical-routes.test.ts +16 -3
- package/src/test-support/approval-continuation-crash-child.ts +24 -0
- package/src/test-support/model-process-crash-child.ts +78 -0
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
import { test } from 'node:test';
|
|
4
4
|
import assert from 'node:assert/strict';
|
|
5
5
|
import { TOOL_DEFINITION_SCHEMA_VERSION, type ToolDefinition } from './tool-definition';
|
|
6
|
-
import { argsHash, buildToolRuntime, toolCallIdempotencyKey, type ToolExecutionJournalEntry, type ToolRuntimeDeps } from './tools';
|
|
6
|
+
import { argsHash, AUDIT_MAX_BYTES, buildToolRuntime, toolCallIdempotencyKey, type ToolExecutionJournalEntry, type ToolRuntimeDeps } from './tools';
|
|
7
7
|
|
|
8
8
|
function mkTool(over: Partial<ToolDefinition>): ToolDefinition {
|
|
9
9
|
return {
|
|
@@ -21,6 +21,7 @@ function mkRuntime(
|
|
|
21
21
|
tool: ToolDefinition,
|
|
22
22
|
audit: ToolRuntimeDeps['audit'] = async () => { /* noop */ },
|
|
23
23
|
ledger = new Map<string, ToolExecutionJournalEntry>(),
|
|
24
|
+
overrides: Partial<ToolRuntimeDeps> = {},
|
|
24
25
|
) {
|
|
25
26
|
const deps: ToolRuntimeDeps = {
|
|
26
27
|
provider: { name: 'p', base_url: 'http://x.invalid', secret: 's', timeout_ms: 5000, rate_limit_per_min: 0, log_payload: false } as any,
|
|
@@ -60,7 +61,7 @@ function mkRuntime(
|
|
|
60
61
|
},
|
|
61
62
|
},
|
|
62
63
|
};
|
|
63
|
-
return buildToolRuntime(deps);
|
|
64
|
+
return buildToolRuntime({ ...deps, ...overrides });
|
|
64
65
|
}
|
|
65
66
|
|
|
66
67
|
function mkRuntimeWithApprovals(tool: ToolDefinition) {
|
|
@@ -115,7 +116,7 @@ function mkRuntimeWithApprovals(tool: ToolDefinition) {
|
|
|
115
116
|
async function withFetchCounter(fn: (count: () => number) => Promise<void>): Promise<void> {
|
|
116
117
|
let n = 0;
|
|
117
118
|
const orig = globalThis.fetch;
|
|
118
|
-
globalThis.fetch = (async () => { n++; return
|
|
119
|
+
globalThis.fetch = (async () => { n++; return new Response('{"ok":true}', { status: 200 }); }) as typeof fetch;
|
|
119
120
|
try { await fn(() => n); } finally { globalThis.fetch = orig; }
|
|
120
121
|
}
|
|
121
122
|
|
|
@@ -222,6 +223,121 @@ test('ĺŻä˝ç¨ĺˇĽĺ
ˇďźä¸ć¸¸čś
ćśĺĺťçťć§čĄďźć˘ĺ¤ćéčˇä¸ĺžĺ
|
|
|
222
223
|
}
|
|
223
224
|
});
|
|
224
225
|
|
|
226
|
+
test('塼ĺ
ˇĺĺşäź čžďź200/302/500 ćŁćčś
éé˝ĺćśĺšśĺťçťďźć˘ĺ¤ä¸ĺžéćĺĺ
Ľ', async (t) => {
|
|
227
|
+
for (const status of [200, 302, 500]) {
|
|
228
|
+
for (const declared of [false, true]) {
|
|
229
|
+
await t.test(`status=${status}, declared=${declared}`, async (t) => {
|
|
230
|
+
let calls = 0;
|
|
231
|
+
let pulls = 0;
|
|
232
|
+
let cancels = 0;
|
|
233
|
+
const audits: Array<{ event: string; detail: Record<string, unknown> }> = [];
|
|
234
|
+
t.mock.method(globalThis, 'fetch', async () => {
|
|
235
|
+
calls++;
|
|
236
|
+
return new Response(new ReadableStream<Uint8Array>({
|
|
237
|
+
pull(controller) {
|
|
238
|
+
pulls++;
|
|
239
|
+
controller.enqueue(new Uint8Array(pulls === 1 ? 32 : 1));
|
|
240
|
+
},
|
|
241
|
+
cancel() { cancels++; },
|
|
242
|
+
}, { highWaterMark: 0 }), { status, headers: declared ? { 'content-length': '33' } : {} });
|
|
243
|
+
});
|
|
244
|
+
const ledger = new Map<string, ToolExecutionJournalEntry>();
|
|
245
|
+
const runtime = mkRuntime(mkTool({}), async (event, detail) => { audits.push({ event, detail }); }, ledger, { maxResponseBodyBytes: 32 });
|
|
246
|
+
const first = await runtime.invoke('create_thing', { x: 1 });
|
|
247
|
+
assert.equal(first.ok, false);
|
|
248
|
+
assert.equal(first.status, 0, 'headers alone cannot confirm a write after body loss');
|
|
249
|
+
assert.equal(first.governance_state, 'reconciliation_required');
|
|
250
|
+
assert.equal(first.auto_retry_allowed, false);
|
|
251
|
+
assert.equal(runtime.executionUncertainty()?.state, 'uncertain');
|
|
252
|
+
assert.equal(cancels, 1);
|
|
253
|
+
assert.equal(pulls, declared ? 0 : 2);
|
|
254
|
+
assert.equal(audits.some((audit) => audit.event === 'tool_result'), false);
|
|
255
|
+
const recovered = mkRuntime(mkTool({}), undefined, ledger, { maxResponseBodyBytes: 32 });
|
|
256
|
+
assert.equal((await recovered.invoke('create_thing', { x: 1 })).ok, false);
|
|
257
|
+
assert.equal(calls, 1);
|
|
258
|
+
});
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
});
|
|
262
|
+
|
|
263
|
+
test('塼ĺ
ˇéťčŽ¤äź čžé˘çŽďźčś
čżĺşĺŽ5 MiBç声ćäšä¸č˝çĄŽčޤĺ°ćŁćĺĺ
Ľ', async (t) => {
|
|
264
|
+
t.mock.method(globalThis, 'fetch', async () => new Response('synthetic', {
|
|
265
|
+
status: 200, headers: { 'content-length': String(5 * 1024 * 1024 + 1) },
|
|
266
|
+
}));
|
|
267
|
+
const runtime = mkRuntime(mkTool({}));
|
|
268
|
+
const result = await runtime.invoke('create_thing', {});
|
|
269
|
+
assert.equal(result.ok, false);
|
|
270
|
+
assert.equal(result.governance_state, 'reconciliation_required');
|
|
271
|
+
assert.equal(result.auto_retry_allowed, false);
|
|
272
|
+
assert.equal(runtime.executionUncertainty()?.state, 'uncertain');
|
|
273
|
+
});
|
|
274
|
+
|
|
275
|
+
test('塼ĺ
ˇĺĺşäź čžďźbody timeout äżçĺ俥ĺˇĺ unknown çťćďźä¸čްĺ˝ĺćŞćĺ', async (t) => {
|
|
276
|
+
let calls = 0;
|
|
277
|
+
const audits: Array<{ event: string; detail: Record<string, unknown> }> = [];
|
|
278
|
+
t.mock.method(globalThis, 'fetch', async (_url: unknown, init: RequestInit) => {
|
|
279
|
+
calls++;
|
|
280
|
+
return new Response(new ReadableStream<Uint8Array>({
|
|
281
|
+
start(controller) {
|
|
282
|
+
controller.enqueue(new TextEncoder().encode('{"ok":'));
|
|
283
|
+
init.signal!.addEventListener('abort', () => controller.error(init.signal!.reason), { once: true });
|
|
284
|
+
},
|
|
285
|
+
}), { status: 200 });
|
|
286
|
+
});
|
|
287
|
+
const runtime = mkRuntime(mkTool({ timeoutMs: 20 }), async (event, detail) => { audits.push({ event, detail }); });
|
|
288
|
+
const watchdog = setTimeout(() => undefined, 1000);
|
|
289
|
+
try {
|
|
290
|
+
const result = await runtime.invoke('create_thing', { x: 1 });
|
|
291
|
+
assert.equal(result.ok, false);
|
|
292
|
+
assert.equal(result.governance_state, 'reconciliation_required');
|
|
293
|
+
assert.match(runtime.executionUncertainty()?.reason ?? '', /čś
ćś/);
|
|
294
|
+
assert.equal(audits.some((audit) => audit.event === 'tool_result'), false);
|
|
295
|
+
await runtime.invoke('create_thing', { x: 1 });
|
|
296
|
+
assert.equal(calls, 1);
|
|
297
|
+
} finally { clearTimeout(watchdog); }
|
|
298
|
+
});
|
|
299
|
+
|
|
300
|
+
test('塼ĺ
ˇĺĺşč§ĺžďźä¸ćç樥ĺĺ厥莥 UTF-8 ĺčé˘çŽçĺŽćç', async (t) => {
|
|
301
|
+
const audits: Array<{ event: string; detail: Record<string, unknown> }> = [];
|
|
302
|
+
const value = 'ćą'.repeat(AUDIT_MAX_BYTES);
|
|
303
|
+
t.mock.method(globalThis, 'fetch', async () => new Response(value));
|
|
304
|
+
const def = mkTool({ inputSchema: { type: 'object', properties: { x: { type: 'string' } } } });
|
|
305
|
+
const runtime = mkRuntime(def, async (event, detail) => { audits.push({ event, detail }); }, undefined,
|
|
306
|
+
{ provider: { name: 'p', base_url: 'https://synthetic.invalid', secret: 'synthetic', timeout_ms: 5000, rate_limit_per_min: 0, log_payload: true } as any });
|
|
307
|
+
const result = await runtime.invoke('create_thing', { x: value });
|
|
308
|
+
assert.equal(result.ok, true);
|
|
309
|
+
assert.equal(Buffer.byteLength(result.text), 8190);
|
|
310
|
+
assert.equal(result.text.includes('\ufffd'), false);
|
|
311
|
+
const call = audits.find((entry) => entry.event === 'tool_call')!.detail;
|
|
312
|
+
assert.equal(call.args_bytes, Buffer.byteLength(JSON.stringify({ x: value })));
|
|
313
|
+
assert.ok(Buffer.byteLength(String(call.args)) <= AUDIT_MAX_BYTES);
|
|
314
|
+
assert.equal(call.args_truncated, true);
|
|
315
|
+
const response = audits.find((entry) => entry.event === 'tool_result')!.detail;
|
|
316
|
+
assert.equal(response.resp_bytes, Buffer.byteLength(value));
|
|
317
|
+
assert.ok(Buffer.byteLength(String(response.resp)) <= AUDIT_MAX_BYTES);
|
|
318
|
+
assert.equal(response.resp_truncated, true);
|
|
319
|
+
});
|
|
320
|
+
|
|
321
|
+
test('塼ĺ
ˇĺĺşč§ĺžďźćć塼ĺ
ˇäťčąćďźĺĺşĺčć°äżćĺŽé
čžĺ
ĽčŽĄć°', async (t) => {
|
|
322
|
+
const audits: Array<{ event: string; detail: Record<string, unknown> }> = [];
|
|
323
|
+
t.mock.method(globalThis, 'fetch', async () => new Response(new Uint8Array([255])));
|
|
324
|
+
const runtime = mkRuntime(mkTool({ sensitive: true }), async (event, detail) => { audits.push({ event, detail }); }, undefined,
|
|
325
|
+
{ provider: { name: 'p', base_url: 'https://synthetic.invalid', secret: 'synthetic', timeout_ms: 5000, rate_limit_per_min: 0, log_payload: true } as any });
|
|
326
|
+
await runtime.invoke('create_thing', { x: 42 });
|
|
327
|
+
const response = audits.find((entry) => entry.event === 'tool_result')!.detail;
|
|
328
|
+
assert.equal(response.resp_bytes, 1, 'replacement decoding must not alter consumed byte count');
|
|
329
|
+
assert.equal(response.resp, '<1 bytes>');
|
|
330
|
+
assert.equal(audits.find((entry) => entry.event === 'tool_call')!.detail.args, '["x"]');
|
|
331
|
+
});
|
|
332
|
+
|
|
333
|
+
test('塼ĺ
ˇĺĺşč§ĺžďźçŠşĺĺş fallback äšéľĺŽćĺ°ĺčé˘çŽ', async (t) => {
|
|
334
|
+
t.mock.method(globalThis, 'fetch', async () => new Response(null, { status: 204 }));
|
|
335
|
+
const runtime = mkRuntime(mkTool({}), undefined, undefined, { truncateBytes: 1 });
|
|
336
|
+
const result = await runtime.invoke('create_thing', {});
|
|
337
|
+
assert.equal(result.ok, true);
|
|
338
|
+
assert.ok(Buffer.byteLength(result.text) <= 1);
|
|
339
|
+
});
|
|
340
|
+
|
|
225
341
|
test('ĺŻä˝ç¨ĺˇĽĺ
ˇďźĺ´Šćşéç dispatching ĺ ä˝ćśďźć°čżčĄćś fail-closed ä¸ä¸ĺ¤ĺ', async () => {
|
|
226
342
|
const callArgs = { x: 10 };
|
|
227
343
|
const hash = argsHash(callArgs);
|
|
@@ -268,7 +384,7 @@ test('ĺŻä˝ç¨ĺˇĽĺ
ˇďźĺé稳ĺŽçä¸ć¸¸ĺšçéŽďźä¸čŻĽéŽä¸äťťĺĄă
|
|
|
268
384
|
let seen = '';
|
|
269
385
|
globalThis.fetch = (async (_url, init) => {
|
|
270
386
|
seen = String((init?.headers as Record<string, string>)['x-bailing-idempotency-key'] ?? '');
|
|
271
|
-
return
|
|
387
|
+
return new Response('{"ok":true}', { status: 200 });
|
|
272
388
|
}) as typeof fetch;
|
|
273
389
|
try {
|
|
274
390
|
await rt.invoke('create_thing', { x: 9 });
|
|
@@ -347,7 +463,7 @@ test('塼ĺ
ˇč°ç¨ďźpath/header/query/body ĺć°ć ToolDefinition.paramIn çť
|
|
|
347
463
|
seenUrl = String(url);
|
|
348
464
|
seenHeaders = init?.headers;
|
|
349
465
|
seenBody = init?.body;
|
|
350
|
-
return
|
|
466
|
+
return new Response('{"ok":true}', { status: 200 });
|
|
351
467
|
}) as typeof fetch;
|
|
352
468
|
try {
|
|
353
469
|
await rt.invoke('update_staff', { store_id: 's 1', staff_id: 'u/2', tenant: 't1', dry_run: true, name: 'Alice' });
|
|
@@ -4,6 +4,7 @@ import { effectiveToolRateLimit, type RateLimitRequest, type RateLimitDecision }
|
|
|
4
4
|
// ä¸ć˘ĺŞĺ reachďźç˝ĺĺ/éŁéŠé¸/éćľ/çžĺ/厥莥ďźďźauthorityďźčżä¸Şäşşč˝ä¸č˝ĺďźć°¸čżçąä¸ĺĄäž§éŞçžĺčŁĺłă
|
|
5
5
|
import { createHash, createHmac } from 'node:crypto';
|
|
6
6
|
import { AgentTaskControlError } from '../runtime/agent-task-control';
|
|
7
|
+
import { readResponseBody, truncateUtf8 } from '../platform/http-body';
|
|
7
8
|
import type { ToolProvider } from './types';
|
|
8
9
|
import { schemaAtPath, schemaTypes, valueMatchesSchemaType, type ToolConfirmCondition, type ToolDefinition } from './tool-definition';
|
|
9
10
|
import { toolSummary } from './tool-definition';
|
|
@@ -219,18 +220,17 @@ function escapeRegExp(s: string): string {
|
|
|
219
220
|
*/
|
|
220
221
|
function modelFacingToolResponse(fullText: string, status: number, truncateBytes: number, contentType: string): string {
|
|
221
222
|
const limit = Math.max(0, truncateBytes);
|
|
222
|
-
if (status >= 200 && status < 300) return fullText
|
|
223
|
-
if (status === 0) return fullText
|
|
223
|
+
if (status >= 200 && status < 300) return truncateUtf8(fullText, limit);
|
|
224
|
+
if (status === 0) return truncateUtf8(fullText, limit);
|
|
224
225
|
|
|
225
226
|
const looksLikeHtml = /text\/html/i.test(contentType)
|
|
226
227
|
|| /^\s*(?:<!doctype\s+html|<html\b)/i.test(fullText);
|
|
227
228
|
if (looksLikeHtml) {
|
|
228
|
-
return `HTTP ${status}ďźä¸ĺĄĺˇĽĺ
ˇčżĺ HTML é误饾ďź${fullText.length}
|
|
229
|
-
.slice(0, limit);
|
|
229
|
+
return truncateUtf8(`HTTP ${status}ďźä¸ĺĄĺˇĽĺ
ˇčżĺ HTML é误饾ďź${fullText.length} ĺ珌ďźăĺĺşćçŹçŤé˘çŽäżçĺ¨ĺŽĄčŽĄčŽ°ĺ˝ä¸ă`, limit);
|
|
230
230
|
}
|
|
231
231
|
|
|
232
|
-
const errorText = fullText.trim()
|
|
233
|
-
return (errorText ? `HTTP ${status}ďź${errorText}` : `HTTP ${status}
|
|
232
|
+
const errorText = truncateUtf8(fullText.trim(), Math.min(limit, 2048));
|
|
233
|
+
return truncateUtf8(errorText ? `HTTP ${status}ďź${errorText}` : `HTTP ${status} 犺ĺĺş`, limit);
|
|
234
234
|
}
|
|
235
235
|
|
|
236
236
|
// ---- éćľďźčżç¨ĺ
ćťçŞďźä¸ĺąďźćŻäťťĺĄ max_calls çąč°ç¨ćščŽĄć° / ćŻĺˇĽĺ
ˇ ACC execution.rate_limit / 塼ĺ
ˇćşćťé¸ďź----
|
|
@@ -278,6 +278,8 @@ export const TOOL_INLINE_MAX = 12;
|
|
|
278
278
|
* çĺŽĺčć°ĺ§çťĺŚčް resp_bytes/args_bytesďźčś
ĺ°éĄśčް *_truncated=trueďźçťä¸ééťä¸˘ă64KB čŚççťĺ¤§ĺ¤ć°ä¸ĺĄĺĺşă
|
|
279
279
|
*/
|
|
280
280
|
export const AUDIT_MAX_BYTES = 65536;
|
|
281
|
+
/** Independent HTTP body budget; the application uses this fixed default, not an ACC field. */
|
|
282
|
+
export const TOOL_RESPONSE_MAX_BYTES = 5 * 1024 * 1024;
|
|
281
283
|
|
|
282
284
|
/** 大čĺŻç¨ç塼ĺ
ˇčżčĄćśďźć¸
ĺďźĺ LLMďź+ ĺ沝ççč°ç¨ĺĽćăçą server ĺ¨ć´žĺćśčŁ
é
嚜注ĺ
Ľ AdapterContextă */
|
|
283
285
|
export interface ToolRuntime {
|
|
@@ -427,6 +429,8 @@ export interface ToolRuntimeDeps {
|
|
|
427
429
|
jobId: string;
|
|
428
430
|
clientAppId: string;
|
|
429
431
|
truncateBytes: number; // 塼ĺ
ˇçťćĺćľćŞćďźéťčޤ 8192ďź
|
|
432
|
+
/** Trusted runtime assembly only; independent from model/audit view budgets. */
|
|
433
|
+
maxResponseBodyBytes?: number;
|
|
430
434
|
approvedNote?: string; // éčˇćśĺˇ˛ćšĺč°ç¨ć¸
ĺć示
|
|
431
435
|
approvals?: ApprovalDeps; // ä¸ćł¨ĺ
Ľ = high/confirm ä¸ĺžćŚ
|
|
432
436
|
/** A trusted assembly supplies these hooks; model parameters cannot create a task or permit. */
|
|
@@ -458,6 +462,8 @@ export interface ToolRuntimeDeps {
|
|
|
458
462
|
}
|
|
459
463
|
|
|
460
464
|
export function buildToolRuntime(d: ToolRuntimeDeps): ToolRuntime {
|
|
465
|
+
const responseMaxBytes = d.maxResponseBodyBytes ?? TOOL_RESPONSE_MAX_BYTES;
|
|
466
|
+
if (!Number.isSafeInteger(responseMaxBytes) || responseMaxBytes <= 0) throw new RangeError('Invalid tool response byte limit');
|
|
461
467
|
const byName = new Map(d.allowedTools.map((t) => [t.name, t]));
|
|
462
468
|
const llmTools = d.allowedTools.map((t) => ({
|
|
463
469
|
type: 'function' as const,
|
|
@@ -682,8 +688,9 @@ export function buildToolRuntime(d: ToolRuntimeDeps): ToolRuntime {
|
|
|
682
688
|
// logFull ćśĺ
Ľĺĺ
¨éĺ
ĽĺŽĄčŽĄďźĺ°éĄś AUDIT_MAX_BYTESďźčś
ĺşčް args_truncatedďźçĺŽĺčć° args_bytes ĺ§çťčްďźă
|
|
683
689
|
const logFull = d.provider.log_payload && !t.sensitive;
|
|
684
690
|
const argsStr = JSON.stringify(callArgs);
|
|
691
|
+
const argsBytes = Buffer.byteLength(argsStr, 'utf8');
|
|
685
692
|
const argsLog = logFull
|
|
686
|
-
? { args: argsStr
|
|
693
|
+
? { args: truncateUtf8(argsStr, AUDIT_MAX_BYTES), args_bytes: argsBytes, ...(argsBytes > AUDIT_MAX_BYTES ? { args_truncated: true } : {}) }
|
|
687
694
|
: { args: JSON.stringify(Object.keys(callArgs)) };
|
|
688
695
|
await d.audit('tool_call', {
|
|
689
696
|
provider: d.provider.name, tool: name, scope: t.scope, method: t.method, path: t.path,
|
|
@@ -740,6 +747,7 @@ export function buildToolRuntime(d: ToolRuntimeDeps): ToolRuntime {
|
|
|
740
747
|
const started = Date.now();
|
|
741
748
|
const timeoutMs = t.timeoutMs || d.provider.timeout_ms || 10000; // ACC execution.timeout_ms ĺ塼ĺ
ˇčŚçďźć
˘ćĽĺŁćžĺŽ˝ďźďźçźşç塼ĺ
ˇćşčś
ćś
|
|
742
749
|
let status = 0; let fullText = '';
|
|
750
|
+
let responseBytes = 0;
|
|
743
751
|
let responseContentType = '';
|
|
744
752
|
try {
|
|
745
753
|
const r = await fetch(d.provider.base_url.replace(/\/+$/, '') + pathWithQuery, {
|
|
@@ -764,7 +772,9 @@ export function buildToolRuntime(d: ToolRuntimeDeps): ToolRuntime {
|
|
|
764
772
|
});
|
|
765
773
|
status = r.status;
|
|
766
774
|
responseContentType = r.headers?.get?.('content-type') ?? '';
|
|
767
|
-
|
|
775
|
+
const responseBody = await readResponseBody(r, responseMaxBytes);
|
|
776
|
+
responseBytes = responseBody.byteLength;
|
|
777
|
+
fullText = new TextDecoder().decode(responseBody);
|
|
768
778
|
} catch (e) {
|
|
769
779
|
const error = e instanceof Error && e.name === 'TimeoutError' ? `čś
ćśďź${timeoutMs}msďź` : String(e);
|
|
770
780
|
fullText = `č°ç¨çťćä¸çĄŽĺŽďź${error}`;
|
|
@@ -809,7 +819,7 @@ export function buildToolRuntime(d: ToolRuntimeDeps): ToolRuntime {
|
|
|
809
819
|
// ĺćľçťć¨Ąĺçďźĺä¸ä¸ćé˘çŽ truncateBytes ćŞćďźä¸ĺŽĄčŽĄçĺč§ŁčŚďź
|
|
810
820
|
const text = modelFacingToolResponse(fullText, status, d.truncateBytes, responseContentType);
|
|
811
821
|
const ok = status >= 200 && status < 300;
|
|
812
|
-
const retText = text || `ďźHTTP ${status}
|
|
822
|
+
const retText = text || truncateUtf8(`ďźHTTP ${status} 犺ĺĺşďź`, d.truncateBytes);
|
|
813
823
|
if (idemHash && !d.taskControl) {
|
|
814
824
|
try {
|
|
815
825
|
await d.idempotency!.recordResponse(name, idemHash, { ok, status, text: retText });
|
|
@@ -834,8 +844,8 @@ export function buildToolRuntime(d: ToolRuntimeDeps): ToolRuntime {
|
|
|
834
844
|
}
|
|
835
845
|
// 厥莥çĺďźlogFull 莰ĺ
¨éĺĺşďźĺ°éĄś AUDIT_MAX_BYTESďźčś
ĺşčް resp_truncatedďźďźresp_bytes ĺ§çťčްçĺŽĺčć°ă
|
|
836
846
|
const respLog = logFull
|
|
837
|
-
? { resp: fullText
|
|
838
|
-
: { resp: `<${
|
|
847
|
+
? { resp: truncateUtf8(fullText, AUDIT_MAX_BYTES), resp_bytes: responseBytes, ...(Buffer.byteLength(fullText, 'utf8') > AUDIT_MAX_BYTES ? { resp_truncated: true } : {}) }
|
|
848
|
+
: { resp: `<${responseBytes} bytes>`, resp_bytes: responseBytes };
|
|
839
849
|
try {
|
|
840
850
|
await d.audit('tool_result', {
|
|
841
851
|
tool: name,
|
|
@@ -32,6 +32,10 @@ export interface Job {
|
|
|
32
32
|
usage?: { duration_ms?: number; num_turns?: number; cost_usd?: number; tokens?: number };
|
|
33
33
|
error?: string;
|
|
34
34
|
metadata: Record<string, unknown>;
|
|
35
|
+
/** Core-owned durable queue admissions; ordinary updates must preserve these keys. */
|
|
36
|
+
approval_continuation_keys?: Record<string, string>;
|
|
37
|
+
/** Permanent DLQ replay admission keys; ordinary updates cannot clear them. */
|
|
38
|
+
delivery_replay_keys?: Record<string, string>;
|
|
35
39
|
callback_url?: string;
|
|
36
40
|
// čżçŤŻć§čĄĺ¨ć´žć´ťç¸ĺ
łďźĺŤ route 忍ç
§ďźroute äšĺĺŻč˝ćš/ĺ ďźć
č˝ĺ° job ä¸ďźďźkb_refs=çĽčŻćŁç´˘ĺ˝ä¸ĺżŤç
§ďźĺźç¨ćĽćşĺćľďź
|
|
37
41
|
// user_images/user_audio/user_files=ç¨ćˇĺĺ§čžĺ
ĽéçĺŞä˝ URL 忍ç
§ďźĺŞĺç¨ćˇĺçďźä¸ĺŤçĽčŻĺşćł¨ĺ
Ľčľäş§ďźďźĺ¤ć¨Ąćéé
ĺ¨ćŽć¤é樥ĺďźrerun äšč˝ĺ¤ç°
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import assert from 'node:assert/strict';
|
|
2
2
|
import test from 'node:test';
|
|
3
3
|
import { renderOperationalMetrics } from './openmetrics';
|
|
4
|
+
import type { RuntimeMaintenanceMetricsSnapshot } from './openmetrics';
|
|
4
5
|
|
|
5
6
|
test('OpenMetrics renderer: emits fixed low-cardinality families and escapes build labels', () => {
|
|
6
7
|
const text = renderOperationalMetrics({
|
|
@@ -55,3 +56,30 @@ test('OpenMetrics renderer: unavailable optional collectors are explicit and do
|
|
|
55
56
|
assert.doesNotMatch(text, /bailinghub_job_records/);
|
|
56
57
|
assert.doesNotMatch(text, /bailinghub_approvals_pending/);
|
|
57
58
|
});
|
|
59
|
+
|
|
60
|
+
test('maintenance renderer allows only fixed sources, kinds, phases and page outcomes', () => {
|
|
61
|
+
const known = { kind: 'model-completion', inFlight: 2, completed: 4, failed: 1, oldestPendingAgeMs: 3000,
|
|
62
|
+
lastStartedAt: new Date(1000).toISOString(), lastCompletedAt: null, lastFailedAt: new Date(2000).toISOString() };
|
|
63
|
+
const snapshot: RuntimeMaintenanceMetricsSnapshot = {
|
|
64
|
+
capturedAtMs: 5000,
|
|
65
|
+
usage: { draining: true, drainTimeouts: 2, kinds: [known,
|
|
66
|
+
{ ...known, kind: 'PRIVATE_ACCOUNT_PROMPT_TOKEN_ROUTE' }] },
|
|
67
|
+
usageReconciliation: { scanned: 50, settled: 1, deferred: 48, failed: 1, hasMore: true },
|
|
68
|
+
approvalReconciliation: { scanned: 3, completed: 1, pending: 1, failed: 1 },
|
|
69
|
+
usageRetry: { running: false, consecutiveFailures: 1, retryAfterMs: 2500 },
|
|
70
|
+
};
|
|
71
|
+
const text = renderOperationalMetrics({ version: 'test', commit: 'abc', paused: false, queue: { running: 0, waiting: 0 },
|
|
72
|
+
state: { available: false, success: false }, controlPlane: { available: false, success: false },
|
|
73
|
+
maintenance: { available: true, success: true, value: snapshot }, auditWriteFailuresTotal: 0, scrapeDurationSeconds: 0 });
|
|
74
|
+
assert.match(text, /bailinghub_background_work_in_flight\{source="usage",kind="model-completion"\} 2/);
|
|
75
|
+
assert.match(text, /bailinghub_background_work_oldest_pending_age_seconds\{source="usage",kind="model-completion"\} 3/);
|
|
76
|
+
assert.match(text, /bailinghub_background_work_finished_total\{source="usage",kind="model-completion",outcome="failed"\} 1/);
|
|
77
|
+
assert.match(text, /bailinghub_background_work_last_run_age_seconds\{source="usage",kind="model-completion",phase="started"\} 4/);
|
|
78
|
+
assert.match(text, /bailinghub_background_work_last_run_timestamp_seconds\{source="usage",kind="model-completion",phase="completed"\} 0/);
|
|
79
|
+
assert.doesNotMatch(text, /bailinghub_background_work_last_run_age_seconds[^\n]*phase="completed"/);
|
|
80
|
+
assert.match(text, /bailinghub_background_drain_timeouts_total\{source="usage"\} 2/);
|
|
81
|
+
assert.match(text, /bailinghub_maintenance_last_page_records\{kind="usage-reconciliation",outcome="failed"\} 1/);
|
|
82
|
+
assert.match(text, /bailinghub_maintenance_last_page_records\{kind="approval-continuation",outcome="pending"\} 1/);
|
|
83
|
+
assert.match(text, /bailinghub_usage_maintenance_retry_after_seconds 2\.5/);
|
|
84
|
+
assert.doesNotMatch(text, /PRIVATE_ACCOUNT|PROMPT|TOKEN|ROUTE/);
|
|
85
|
+
});
|
|
@@ -13,6 +13,23 @@ export interface CollectorResult<T> {
|
|
|
13
13
|
value?: T;
|
|
14
14
|
}
|
|
15
15
|
|
|
16
|
+
export interface BackgroundWorkMetricsSnapshot {
|
|
17
|
+
draining?: boolean;
|
|
18
|
+
drainTimeouts?: number;
|
|
19
|
+
kinds: Array<{ kind: string; inFlight: number; completed: number; failed: number; oldestPendingAgeMs: number;
|
|
20
|
+
lastStartedAt: string | null; lastCompletedAt: string | null; lastFailedAt: string | null }>;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface RuntimeMaintenanceMetricsSnapshot {
|
|
24
|
+
capturedAtMs: number;
|
|
25
|
+
usage?: BackgroundWorkMetricsSnapshot;
|
|
26
|
+
notification?: BackgroundWorkMetricsSnapshot;
|
|
27
|
+
approval?: BackgroundWorkMetricsSnapshot;
|
|
28
|
+
usageReconciliation?: { scanned: number; settled: number; deferred: number; failed: number; hasMore: boolean };
|
|
29
|
+
approvalReconciliation?: { scanned: number; completed: number; pending: number; failed: number };
|
|
30
|
+
usageRetry?: { running: boolean; consecutiveFailures: number; retryAfterMs: number };
|
|
31
|
+
}
|
|
32
|
+
|
|
16
33
|
export interface OperationalMetricsDocument {
|
|
17
34
|
version: string;
|
|
18
35
|
commit: string;
|
|
@@ -20,6 +37,7 @@ export interface OperationalMetricsDocument {
|
|
|
20
37
|
queue: { running: number; waiting: number };
|
|
21
38
|
state: CollectorResult<JobOperationalMetricsSnapshot>;
|
|
22
39
|
controlPlane: CollectorResult<ControlPlaneOperationalMetricsSnapshot>;
|
|
40
|
+
maintenance?: CollectorResult<RuntimeMaintenanceMetricsSnapshot>;
|
|
23
41
|
auditWriteFailuresTotal: number;
|
|
24
42
|
scrapeDurationSeconds: number;
|
|
25
43
|
}
|
|
@@ -38,6 +56,75 @@ function family(lines: string[], name: string, help: string, type: 'counter' | '
|
|
|
38
56
|
lines.push(...samples);
|
|
39
57
|
}
|
|
40
58
|
|
|
59
|
+
// Never render a caller-supplied kind, phase, status or source as a label.
|
|
60
|
+
const BACKGROUND_KINDS = {
|
|
61
|
+
usage: ['model-completion', 'settlement', 'response-cleanup', 'usage-reconciliation', 'reference-price-refresh'],
|
|
62
|
+
notification: ['callback', 'delivery', 'approval-notification', 'alert', 'delivery-dlq'],
|
|
63
|
+
approval: ['approval-continuation'],
|
|
64
|
+
} as const;
|
|
65
|
+
|
|
66
|
+
function renderMaintenance(lines: string[], snapshot: RuntimeMaintenanceMetricsSnapshot): void {
|
|
67
|
+
const flight: string[] = [], oldest: string[] = [], finished: string[] = [], timestamps: string[] = [], ages: string[] = [];
|
|
68
|
+
const draining: string[] = [], timeouts: string[] = [];
|
|
69
|
+
for (const source of ['usage', 'notification', 'approval'] as const) {
|
|
70
|
+
const value = snapshot[source];
|
|
71
|
+
if (!value) continue;
|
|
72
|
+
if (value.draining !== undefined) draining.push(`bailinghub_background_draining{source="${source}"} ${value.draining ? 1 : 0}`);
|
|
73
|
+
if (value.drainTimeouts !== undefined) timeouts.push(`bailinghub_background_drain_timeouts_total{source="${source}"} ${finite(value.drainTimeouts)}`);
|
|
74
|
+
for (const kind of BACKGROUND_KINDS[source]) {
|
|
75
|
+
const work = value.kinds.find(row => row.kind === kind);
|
|
76
|
+
if (!work) continue;
|
|
77
|
+
const labels = `source="${source}",kind="${kind}"`;
|
|
78
|
+
flight.push(`bailinghub_background_work_in_flight{${labels}} ${finite(work.inFlight)}`);
|
|
79
|
+
oldest.push(`bailinghub_background_work_oldest_pending_age_seconds{${labels}} ${finite(work.oldestPendingAgeMs) / 1000}`);
|
|
80
|
+
for (const outcome of ['completed', 'failed'] as const) {
|
|
81
|
+
finished.push(`bailinghub_background_work_finished_total{${labels},outcome="${outcome}"} ${finite(work[outcome])}`);
|
|
82
|
+
}
|
|
83
|
+
for (const phase of ['started', 'completed', 'failed'] as const) {
|
|
84
|
+
const at = work[phase === 'started' ? 'lastStartedAt' : phase === 'completed' ? 'lastCompletedAt' : 'lastFailedAt'];
|
|
85
|
+
const epoch = at === null ? NaN : Date.parse(at);
|
|
86
|
+
timestamps.push(`bailinghub_background_work_last_run_timestamp_seconds{${labels},phase="${phase}"} ${Number.isFinite(epoch) ? epoch / 1000 : 0}`);
|
|
87
|
+
// Missing history is explicit as timestamp=0; do not invent an age of zero.
|
|
88
|
+
if (Number.isFinite(epoch)) ages.push(`bailinghub_background_work_last_run_age_seconds{${labels},phase="${phase}"} ${Math.max(0, finite(snapshot.capturedAtMs - epoch)) / 1000}`);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
const groups: Array<[string, string, 'counter' | 'gauge', string[]]> = [
|
|
93
|
+
['bailinghub_background_work_in_flight', 'Accepted process-local continuations currently in flight.', 'gauge', flight],
|
|
94
|
+
['bailinghub_background_work_oldest_pending_age_seconds', 'Age of the oldest accepted process-local continuation.', 'gauge', oldest],
|
|
95
|
+
['bailinghub_background_work_finished_total', 'Process-local continuation outcomes, not recipient delivery acknowledgements.', 'counter', finished],
|
|
96
|
+
['bailinghub_background_work_last_run_timestamp_seconds', 'Last observed start or completion time; zero means never observed.', 'gauge', timestamps],
|
|
97
|
+
['bailinghub_background_work_last_run_age_seconds', 'Age since the last observed start or completion, omitted when never observed.', 'gauge', ages],
|
|
98
|
+
['bailinghub_background_draining', 'Whether an owning background tracker has stopped new maintenance admission.', 'gauge', draining],
|
|
99
|
+
['bailinghub_background_drain_timeouts_total', 'Process-local background drain calls that exhausted their budget.', 'counter', timeouts],
|
|
100
|
+
];
|
|
101
|
+
for (const [name, help, type, samples] of groups) if (samples.length) family(lines, name, help, type, samples);
|
|
102
|
+
|
|
103
|
+
const progress: string[] = [];
|
|
104
|
+
if (snapshot.usageReconciliation) {
|
|
105
|
+
for (const outcome of ['scanned', 'settled', 'deferred', 'failed'] as const) {
|
|
106
|
+
progress.push(`bailinghub_maintenance_last_page_records{kind="usage-reconciliation",outcome="${outcome}"} ${finite(snapshot.usageReconciliation[outcome])}`);
|
|
107
|
+
}
|
|
108
|
+
family(lines, 'bailinghub_maintenance_last_page_has_more', 'Whether the last usage reconciliation page reached its bounded scan size.', 'gauge', [
|
|
109
|
+
`bailinghub_maintenance_last_page_has_more{kind="usage-reconciliation"} ${snapshot.usageReconciliation.hasMore ? 1 : 0}`,
|
|
110
|
+
]);
|
|
111
|
+
}
|
|
112
|
+
if (snapshot.approvalReconciliation) {
|
|
113
|
+
for (const outcome of ['scanned', 'completed', 'pending', 'failed'] as const) {
|
|
114
|
+
progress.push(`bailinghub_maintenance_last_page_records{kind="approval-continuation",outcome="${outcome}"} ${finite(snapshot.approvalReconciliation[outcome])}`);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
if (progress.length) family(lines, 'bailinghub_maintenance_last_page_records', 'Aggregate records processed in the latest/current bounded maintenance page, not total persisted backlog.', 'gauge', progress);
|
|
118
|
+
if (snapshot.usageRetry) {
|
|
119
|
+
family(lines, 'bailinghub_usage_maintenance_consecutive_failures', 'Current bounded usage maintenance failure backoff count.', 'gauge', [
|
|
120
|
+
`bailinghub_usage_maintenance_consecutive_failures ${finite(snapshot.usageRetry.consecutiveFailures)}`,
|
|
121
|
+
]);
|
|
122
|
+
family(lines, 'bailinghub_usage_maintenance_retry_after_seconds', 'Seconds until the current usage maintenance retry backoff expires.', 'gauge', [
|
|
123
|
+
`bailinghub_usage_maintenance_retry_after_seconds ${finite(snapshot.usageRetry.retryAfterMs) / 1000}`,
|
|
124
|
+
]);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
41
128
|
/** Render only fixed, low-cardinality labels. Job, tenant, principal and argument data never enter this document. */
|
|
42
129
|
export function renderOperationalMetrics(document: OperationalMetricsDocument): string {
|
|
43
130
|
const lines: string[] = [];
|
|
@@ -55,10 +142,12 @@ export function renderOperationalMetrics(document: OperationalMetricsDocument):
|
|
|
55
142
|
family(lines, 'bailinghub_metrics_collector_available', 'Whether an optional metrics collector is implemented.', 'gauge', [
|
|
56
143
|
`bailinghub_metrics_collector_available{collector="state"} ${document.state.available ? 1 : 0}`,
|
|
57
144
|
`bailinghub_metrics_collector_available{collector="control_plane"} ${document.controlPlane.available ? 1 : 0}`,
|
|
145
|
+
`bailinghub_metrics_collector_available{collector="maintenance"} ${document.maintenance?.available ? 1 : 0}`,
|
|
58
146
|
]);
|
|
59
147
|
family(lines, 'bailinghub_metrics_collector_success', 'Whether an optional collector succeeded during this scrape.', 'gauge', [
|
|
60
148
|
`bailinghub_metrics_collector_success{collector="state"} ${document.state.success ? 1 : 0}`,
|
|
61
149
|
`bailinghub_metrics_collector_success{collector="control_plane"} ${document.controlPlane.success ? 1 : 0}`,
|
|
150
|
+
`bailinghub_metrics_collector_success{collector="maintenance"} ${document.maintenance?.success ? 1 : 0}`,
|
|
62
151
|
]);
|
|
63
152
|
|
|
64
153
|
if (document.state.value) {
|
|
@@ -92,6 +181,8 @@ export function renderOperationalMetrics(document: OperationalMetricsDocument):
|
|
|
92
181
|
]);
|
|
93
182
|
}
|
|
94
183
|
|
|
184
|
+
if (document.maintenance?.value) renderMaintenance(lines, document.maintenance.value);
|
|
185
|
+
|
|
95
186
|
family(lines, 'bailinghub_audit_write_failures_total', 'Audit ledger write failures observed by this process.', 'counter', [
|
|
96
187
|
`bailinghub_audit_write_failures_total ${finite(document.auditWriteFailuresTotal)}`,
|
|
97
188
|
]);
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { createServer, type ServerResponse } from 'node:http';
|
|
4
|
+
import { gzipSync } from 'node:zlib';
|
|
5
|
+
import { readResponseBody, ResponseBodyLimitError, truncateUtf8 } from './http-body';
|
|
6
|
+
|
|
7
|
+
function response(chunks: Uint8Array[], headers: Record<string, string> = {}) {
|
|
8
|
+
let pulls = 0;
|
|
9
|
+
let cancels = 0;
|
|
10
|
+
const body = new ReadableStream<Uint8Array>({
|
|
11
|
+
pull(controller) {
|
|
12
|
+
const chunk = chunks[pulls++];
|
|
13
|
+
if (chunk) controller.enqueue(chunk);
|
|
14
|
+
else controller.close();
|
|
15
|
+
},
|
|
16
|
+
cancel() { cancels++; },
|
|
17
|
+
}, { highWaterMark: 0 });
|
|
18
|
+
return { response: new Response(body, { headers }), body, counts: () => ({ pulls, cancels }) };
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
async function withLoopbackServer(handler: (response: ServerResponse) => void, check: (url: string) => Promise<void>) {
|
|
22
|
+
const server = createServer((_req, res) => handler(res));
|
|
23
|
+
await new Promise<void>((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve); });
|
|
24
|
+
try {
|
|
25
|
+
const address = server.address();
|
|
26
|
+
assert.ok(address && typeof address !== 'string');
|
|
27
|
+
await check(`http://127.0.0.1:${address.port}/synthetic`);
|
|
28
|
+
} finally {
|
|
29
|
+
server.closeAllConnections();
|
|
30
|
+
await new Promise<void>((resolve) => server.close(() => resolve()));
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
test('bounded response: exact limit preserves bytes and releases the reader', async () => {
|
|
35
|
+
const fx = response([new Uint8Array([1, 2]), new Uint8Array([3, 4])]);
|
|
36
|
+
assert.deepEqual(new Uint8Array(await readResponseBody(fx.response, 4)), new Uint8Array([1, 2, 3, 4]));
|
|
37
|
+
assert.equal(fx.body.locked, false);
|
|
38
|
+
assert.equal(fx.counts().cancels, 0);
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
test('bounded response: stream over limit cancels before consuming later chunks', async () => {
|
|
42
|
+
const fx = response([new Uint8Array(4), new Uint8Array(1), new Uint8Array(100)]);
|
|
43
|
+
await assert.rejects(readResponseBody(fx.response, 4), (error: unknown) => {
|
|
44
|
+
assert.ok(error instanceof ResponseBodyLimitError);
|
|
45
|
+
assert.equal(error.source, 'stream');
|
|
46
|
+
assert.equal(error.observedBytes, 5);
|
|
47
|
+
return true;
|
|
48
|
+
});
|
|
49
|
+
assert.deepEqual(fx.counts(), { pulls: 2, cancels: 1 });
|
|
50
|
+
assert.equal(fx.body.locked, false);
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
test('bounded response: excessive declared length cancels without reading', async () => {
|
|
54
|
+
const fx = response([new Uint8Array(4)], { 'content-length': '5' });
|
|
55
|
+
await assert.rejects(readResponseBody(fx.response, 4), (error: unknown) => {
|
|
56
|
+
assert.ok(error instanceof ResponseBodyLimitError);
|
|
57
|
+
assert.equal(error.source, 'content-length');
|
|
58
|
+
return true;
|
|
59
|
+
});
|
|
60
|
+
assert.deepEqual(fx.counts(), { pulls: 0, cancels: 1 });
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
test('bounded response: low encoded length cannot bypass decoded stream budget', async () => {
|
|
64
|
+
const fx = response([new Uint8Array(5)], { 'content-length': '1', 'content-encoding': 'gzip' });
|
|
65
|
+
await assert.rejects(readResponseBody(fx.response, 4), ResponseBodyLimitError);
|
|
66
|
+
assert.equal(fx.counts().cancels, 1);
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
test('bounded response: native fetch gzip decoding cannot bypass the byte budget', async () => {
|
|
70
|
+
const encoded = gzipSync('a'.repeat(2048));
|
|
71
|
+
assert.ok(encoded.byteLength < 1024);
|
|
72
|
+
await withLoopbackServer((r) => {
|
|
73
|
+
r.writeHead(200, { 'content-encoding': 'gzip', 'content-length': encoded.byteLength });
|
|
74
|
+
r.end(encoded);
|
|
75
|
+
}, async (url) => {
|
|
76
|
+
const r = await fetch(url);
|
|
77
|
+
await assert.rejects(readResponseBody(r, 1024), (error: unknown) => {
|
|
78
|
+
assert.ok(error instanceof ResponseBodyLimitError);
|
|
79
|
+
assert.equal(error.source, 'stream');
|
|
80
|
+
assert.ok(error.observedBytes > 1024);
|
|
81
|
+
return true;
|
|
82
|
+
});
|
|
83
|
+
assert.equal(r.body!.locked, false);
|
|
84
|
+
});
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
test('bounded response: native fetch abort after headers rejects partial body', async () => {
|
|
88
|
+
await withLoopbackServer((r) => { r.writeHead(200); r.write('a'); }, async (url) => {
|
|
89
|
+
const abort = new AbortController();
|
|
90
|
+
const r = await fetch(url, { signal: abort.signal });
|
|
91
|
+
const pending = readResponseBody(r, 1024);
|
|
92
|
+
abort.abort();
|
|
93
|
+
await assert.rejects(pending, (error: unknown) => error instanceof Error && error.name === 'AbortError');
|
|
94
|
+
assert.equal(r.body!.locked, false);
|
|
95
|
+
});
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
test('bounded response: invalid length is ignored while the stream remains limited', async () => {
|
|
99
|
+
for (const length of ['garbage', '-1', '2.5']) {
|
|
100
|
+
const fx = response([new Uint8Array(5)], { 'content-length': length });
|
|
101
|
+
await assert.rejects(readResponseBody(fx.response, 4), ResponseBodyLimitError);
|
|
102
|
+
assert.equal(fx.counts().cancels, 1);
|
|
103
|
+
}
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
test('bounded response: enormous declared lengths also fail closed', async () => {
|
|
107
|
+
const fx = response([], { 'content-length': '9'.repeat(400) });
|
|
108
|
+
await assert.rejects(readResponseBody(fx.response, 4), ResponseBodyLimitError);
|
|
109
|
+
assert.equal(fx.counts().pulls, 0);
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
test('bounded response: empty body and zero budget are supported', async () => {
|
|
113
|
+
assert.equal((await readResponseBody(new Response(null), 0)).byteLength, 0);
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
test('bounded response: invalid budget rejects before response consumption', async () => {
|
|
117
|
+
const fx = response([new Uint8Array(5)]);
|
|
118
|
+
await assert.rejects(readResponseBody(fx.response, Infinity), RangeError);
|
|
119
|
+
assert.equal(fx.counts().pulls, 0);
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
test('bounded response: original error survives rejected/pending cancellation and releases reader', { timeout: 1000 }, async () => {
|
|
123
|
+
for (const pending of [false, true]) {
|
|
124
|
+
const original = new DOMException('synthetic body timeout', 'TimeoutError');
|
|
125
|
+
let cancels = 0;
|
|
126
|
+
let releases = 0;
|
|
127
|
+
const fake = { headers: new Headers(), body: { getReader: () => ({
|
|
128
|
+
read: async () => { throw original; },
|
|
129
|
+
cancel: async () => {
|
|
130
|
+
cancels++;
|
|
131
|
+
if (pending) await new Promise<void>(() => undefined);
|
|
132
|
+
else throw new Error('synthetic cancellation failure');
|
|
133
|
+
},
|
|
134
|
+
releaseLock: () => { releases++; },
|
|
135
|
+
}) } } as unknown as Response;
|
|
136
|
+
await assert.rejects(readResponseBody(fake, 4), (error: unknown) => error === original);
|
|
137
|
+
assert.equal(cancels, 1);
|
|
138
|
+
assert.equal(releases, 1);
|
|
139
|
+
}
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
test('bounded response: pending cancel cannot hold a limit error or reader lock open', { timeout: 1000 }, async () => {
|
|
143
|
+
for (const declared of [false, true]) {
|
|
144
|
+
let cancels = 0;
|
|
145
|
+
const body = new ReadableStream<Uint8Array>({
|
|
146
|
+
pull(controller) { controller.enqueue(new Uint8Array(5)); },
|
|
147
|
+
cancel() { cancels++; return new Promise<void>(() => undefined); },
|
|
148
|
+
}, { highWaterMark: 0 });
|
|
149
|
+
const r = new Response(body, { headers: declared ? { 'content-length': '5' } : {} });
|
|
150
|
+
await assert.rejects(readResponseBody(r, 4), ResponseBodyLimitError);
|
|
151
|
+
assert.equal(cancels, 1);
|
|
152
|
+
assert.equal(body.locked, false);
|
|
153
|
+
}
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
test('bounded response: fetch body abort is propagated without partial success', async () => {
|
|
157
|
+
const controller = new AbortController();
|
|
158
|
+
const failure = new DOMException('synthetic timeout', 'TimeoutError');
|
|
159
|
+
const body = new ReadableStream<Uint8Array>({
|
|
160
|
+
start(stream) {
|
|
161
|
+
stream.enqueue(new Uint8Array([1]));
|
|
162
|
+
controller.signal.addEventListener('abort', () => stream.error(controller.signal.reason), { once: true });
|
|
163
|
+
},
|
|
164
|
+
});
|
|
165
|
+
const pending = readResponseBody(new Response(body), 4);
|
|
166
|
+
controller.abort(failure);
|
|
167
|
+
await assert.rejects(pending, (error: unknown) => error === failure);
|
|
168
|
+
assert.equal(body.locked, false);
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
test('bounded response: Unicode split between chunks remains intact', async () => {
|
|
172
|
+
const bytes = new TextEncoder().encode('ćąđ');
|
|
173
|
+
const fx = response([bytes.subarray(0, 1), bytes.subarray(1, 4), bytes.subarray(4)]);
|
|
174
|
+
assert.equal(new TextDecoder().decode(await readResponseBody(fx.response, 7)), 'ćąđ');
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
test('UTF-8 view budget: no split characters, replacement suffix, or excess bytes', () => {
|
|
178
|
+
for (let limit = 0; limit <= 9; limit++) {
|
|
179
|
+
const got = truncateUtf8('aćąđz', limit);
|
|
180
|
+
assert.ok(Buffer.byteLength(got) <= limit);
|
|
181
|
+
assert.equal(got.includes('\ufffd'), false);
|
|
182
|
+
}
|
|
183
|
+
assert.equal(truncateUtf8('ćąđ', 6), 'ćą');
|
|
184
|
+
assert.equal(truncateUtf8('ćąđ', 7), 'ćąđ');
|
|
185
|
+
});
|