bailinghub 0.9.2 → 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 +12 -1
- package/docs/CHANGELOG.md +12 -1
- package/docs/CORE_RELIABILITY.en.md +22 -2
- package/docs/CORE_RELIABILITY.md +22 -2
- package/docs/IMPLEMENTATION_STATUS.en.md +19 -15
- package/docs/IMPLEMENTATION_STATUS.md +19 -15
- package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
- package/docs/INDEPENDENT_VALIDATION.md +4 -4
- package/docs/OPERATIONS.en.md +13 -0
- package/docs/OPERATIONS.md +12 -0
- package/docs/README.en.md +3 -1
- package/docs/README.md +3 -1
- 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.3.en.md +63 -0
- package/docs/UPGRADE_v0.9.3.md +63 -0
- package/package.json +1 -1
- package/scripts/check-doc-links.mjs +2 -0
- package/scripts/check-image-tags.sh +1 -1
- package/scripts/check-release-consistency.test.mjs +2 -2
- package/scripts/install.sh +1 -1
- package/scripts/publish-images.sh +1 -1
- package/scripts/release-audit.mjs +4 -0
- package/scripts/verify-github-repo.mjs +4 -0
- package/security/dependency-audit-exceptions.json +1 -1
- package/sql/067_delivery_dlq_replay.sql +10 -0
- package/sql/README.en.md +6 -0
- package/sql/README.md +6 -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.test.ts +27 -1
- package/src/app/approval-continuations.ts +44 -3
- 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/kernel-notification-lifecycle.test.ts +49 -0
- package/src/app/kernel.ts +9 -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-lifecycle.test.ts +89 -0
- package/src/app/runtime-lifecycle.ts +20 -18
- package/src/app/tool-approvals.ts +2 -1
- 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 +2 -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/delivery-replay.ts +19 -0
- package/src/core/state/state-codec.ts +1 -0
- package/src/core/state/state-contracts.ts +3 -0
- package/src/infrastructure/config/config-delivery-dlq-ledger.ts +36 -10
- package/src/infrastructure/config/configstore.ts +2 -1
- package/src/infrastructure/state/state-jsonl.ts +16 -1
- package/src/infrastructure/state/state-mysql.ts +27 -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.test.ts +16 -2
- package/src/modules/usage/billing-repository.ts +9 -0
- package/src/modules/usage/maintenance.test.ts +18 -2
- package/src/modules/usage/maintenance.ts +8 -0
- package/src/routes/admin-runtime.ts +14 -0
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
export const NOTIFICATION_BACKGROUND_KINDS = ['callback', 'delivery', 'approval-notification', 'alert', 'delivery-dlq'] as const;
|
|
2
|
+
export type NotificationBackgroundKind = typeof NOTIFICATION_BACKGROUND_KINDS[number];
|
|
3
|
+
|
|
4
|
+
export interface NotificationBackgroundKindSnapshot {
|
|
5
|
+
kind: NotificationBackgroundKind;
|
|
6
|
+
inFlight: number;
|
|
7
|
+
completed: number;
|
|
8
|
+
failed: number;
|
|
9
|
+
oldestPendingAgeMs: number;
|
|
10
|
+
lastStartedAt: string | null;
|
|
11
|
+
lastCompletedAt: string | null;
|
|
12
|
+
lastFailedAt: string | null;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface NotificationBackgroundSnapshot {
|
|
16
|
+
draining: boolean;
|
|
17
|
+
drainTimeouts: number;
|
|
18
|
+
kinds: NotificationBackgroundKindSnapshot[];
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** One Kernel owns its accepted notifications, including children registered during drain. */
|
|
22
|
+
export class NotificationBackgroundWork {
|
|
23
|
+
private readonly pending = new Map<Promise<unknown>, { kind: NotificationBackgroundKind; startedAt: number }>();
|
|
24
|
+
private readonly counters = new Map(NOTIFICATION_BACKGROUND_KINDS.map(kind => [kind, {
|
|
25
|
+
completed: 0, failed: 0, lastStartedAt: null as string | null,
|
|
26
|
+
lastCompletedAt: null as string | null, lastFailedAt: null as string | null,
|
|
27
|
+
}]));
|
|
28
|
+
private draining = false;
|
|
29
|
+
private drainTimeouts = 0;
|
|
30
|
+
private failureReporter: ((kind: NotificationBackgroundKind) => void) | undefined;
|
|
31
|
+
|
|
32
|
+
setFailureReporter(reporter: (kind: NotificationBackgroundKind) => void): void { this.failureReporter = reporter; }
|
|
33
|
+
beginDrain(): void { this.draining = true; }
|
|
34
|
+
|
|
35
|
+
track<T>(kind: NotificationBackgroundKind, run: () => Promise<T>, failed?: (value: T) => boolean): Promise<T> {
|
|
36
|
+
// Register before run, and allow accepted continuations to register children
|
|
37
|
+
// after beginDrain. Kernel admission, not this tracker, stops new producers.
|
|
38
|
+
const startedAt = Date.now();
|
|
39
|
+
const counters = this.counters.get(kind)!;
|
|
40
|
+
counters.lastStartedAt = new Date(startedAt).toISOString();
|
|
41
|
+
const work = Promise.resolve().then(run);
|
|
42
|
+
this.pending.set(work, { kind, startedAt });
|
|
43
|
+
const finish = (isFailure: boolean) => {
|
|
44
|
+
this.pending.delete(work);
|
|
45
|
+
if (isFailure) {
|
|
46
|
+
counters.failed++;
|
|
47
|
+
counters.lastFailedAt = new Date().toISOString();
|
|
48
|
+
try { this.failureReporter?.(kind); } catch { /* diagnostic only */ }
|
|
49
|
+
} else {
|
|
50
|
+
counters.completed++;
|
|
51
|
+
counters.lastCompletedAt = new Date().toISOString();
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
// Attach a rejection handler immediately so detached callers cannot leak an
|
|
55
|
+
// unhandled rejection; awaited callers still receive the original rejection.
|
|
56
|
+
void work.then(value => {
|
|
57
|
+
let isFailure = false;
|
|
58
|
+
try { isFailure = failed?.(value) ?? false; } catch { isFailure = true; }
|
|
59
|
+
finish(isFailure);
|
|
60
|
+
}, () => finish(true));
|
|
61
|
+
return work;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
snapshot(now = Date.now()): NotificationBackgroundSnapshot {
|
|
65
|
+
return { draining: this.draining, drainTimeouts: this.drainTimeouts,
|
|
66
|
+
kinds: NOTIFICATION_BACKGROUND_KINDS.map(kind => {
|
|
67
|
+
let inFlight = 0, oldestStartedAt = now;
|
|
68
|
+
for (const work of this.pending.values()) if (work.kind === kind) {
|
|
69
|
+
inFlight++; oldestStartedAt = Math.min(oldestStartedAt, work.startedAt);
|
|
70
|
+
}
|
|
71
|
+
return { kind, ...this.counters.get(kind)!, inFlight,
|
|
72
|
+
oldestPendingAgeMs: inFlight ? Math.max(0, now - oldestStartedAt) : 0 };
|
|
73
|
+
}) };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async drain(drainMs: number): Promise<boolean> {
|
|
77
|
+
const deadline = Date.now() + Math.max(0, drainMs);
|
|
78
|
+
while (this.pending.size) {
|
|
79
|
+
const remaining = deadline - Date.now();
|
|
80
|
+
if (remaining <= 0) { this.drainTimeouts++; return false; }
|
|
81
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
82
|
+
try {
|
|
83
|
+
const drained = await Promise.race([
|
|
84
|
+
Promise.allSettled([...this.pending.keys()]).then(() => true),
|
|
85
|
+
new Promise<boolean>(resolve => { timer = setTimeout(() => resolve(false), remaining); }),
|
|
86
|
+
]);
|
|
87
|
+
if (!drained) { this.drainTimeouts++; return false; }
|
|
88
|
+
} finally { if (timer) clearTimeout(timer); }
|
|
89
|
+
// Recheck the live set: finishing work can register later SQL or webhook work.
|
|
90
|
+
}
|
|
91
|
+
return true;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const workByStore = new WeakMap<object, NotificationBackgroundWork>();
|
|
96
|
+
export function bindNotificationBackgroundWork(store: object, work: NotificationBackgroundWork): void { workByStore.set(store, work); }
|
|
97
|
+
export function notificationBackgroundWorkFor(store: object): NotificationBackgroundWork {
|
|
98
|
+
let work = workByStore.get(store);
|
|
99
|
+
if (!work) { work = new NotificationBackgroundWork(); workByStore.set(store, work); }
|
|
100
|
+
return work;
|
|
101
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { Job } from '../contracts/types';
|
|
2
|
+
import { deliveryReplayKey, type DeliveryRequeueInput, type DeliveryRequeueOutcome } from '../contracts/delivery-replay';
|
|
3
|
+
|
|
4
|
+
export function deliveryRequeuePlan(job: Job | null, input: DeliveryRequeueInput): { outcome: DeliveryRequeueOutcome; patch?: Partial<Job> } {
|
|
5
|
+
if (!job) return { outcome: 'missing' };
|
|
6
|
+
if (!Number.isSafeInteger(input.dlq_id) || input.dlq_id <= 0 || input.replay_key !== deliveryReplayKey(input.dlq_id)
|
|
7
|
+
|| job.job_id !== input.job_id || job.request_id !== input.request_id || job.source !== 'delivery'
|
|
8
|
+
|| job.target !== input.target || !job.target.endsWith('-notify')) return { outcome: 'conflict' };
|
|
9
|
+
const previous = job.delivery_replay_keys?.[String(input.dlq_id)];
|
|
10
|
+
if (previous !== undefined) return { outcome: previous === input.replay_key ? 'already_queued' : 'conflict' };
|
|
11
|
+
if (['queued', 'running', 'dispatched'].includes(job.status)) return { outcome: 'in_flight' };
|
|
12
|
+
if (job.status !== 'error') return { outcome: 'conflict' };
|
|
13
|
+
return { outcome: 'queued', patch: {
|
|
14
|
+
status: 'queued', attempts: 0, run_after: undefined, error: undefined,
|
|
15
|
+
executor_id: undefined, claimed_at: undefined, lease_until: undefined,
|
|
16
|
+
dispatched_at: undefined, claim_token: undefined,
|
|
17
|
+
delivery_replay_keys: { ...job.delivery_replay_keys, [String(input.dlq_id)]: input.replay_key },
|
|
18
|
+
} };
|
|
19
|
+
}
|
|
@@ -32,6 +32,7 @@ export function rowToJob(r: any): Job {
|
|
|
32
32
|
error: r.error ?? undefined,
|
|
33
33
|
metadata: parse(r.metadata) ?? {},
|
|
34
34
|
approval_continuation_keys: parse(r.approval_continuation_keys),
|
|
35
|
+
delivery_replay_keys: parse(r.delivery_replay_keys),
|
|
35
36
|
callback_url: r.callback_url ?? undefined,
|
|
36
37
|
dispatch: parse(r.dispatch),
|
|
37
38
|
attempts: r.attempts != null ? Number(r.attempts) : 0,
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { AuditEntry, Job, JobStatus } from '../contracts/types';
|
|
2
2
|
import type { ApprovalRequeueInput, ApprovalRequeueOutcome } from '../contracts/approval-continuation';
|
|
3
|
+
import type { DeliveryRequeueInput, DeliveryRequeueOutcome } from '../contracts/delivery-replay';
|
|
3
4
|
|
|
4
5
|
export interface JobOperationalMetricsSnapshot {
|
|
5
6
|
byStatus: Record<JobStatus, number>;
|
|
@@ -51,6 +52,8 @@ export interface RuntimeLockRepository {
|
|
|
51
52
|
export interface RuntimeStateStore extends JobRepository, AuditLedger, RuntimeLockRepository {
|
|
52
53
|
/** Atomic original-job queue transition + permanent decision marker; no substitute operation. */
|
|
53
54
|
requeueApprovedJobOnce?(input: ApprovalRequeueInput): Promise<ApprovalRequeueOutcome>;
|
|
55
|
+
/** Original failed notification child + permanent DLQ key in one state transaction. */
|
|
56
|
+
requeueDeliveryJobOnce?(input: DeliveryRequeueInput): Promise<DeliveryRequeueOutcome>;
|
|
54
57
|
init(): Promise<void>;
|
|
55
58
|
/** Kernel 释放时关闭自己拥有的资源;外部实现可不提供。 */
|
|
56
59
|
close?(): Promise<void>;
|
|
@@ -1,46 +1,72 @@
|
|
|
1
1
|
import { dt } from '../../core/config/config-codec';
|
|
2
|
+
import { deliveryReplayKey, type DeliveryKind, type DeliveryDlqRecord } from '../../core/contracts/delivery-replay';
|
|
3
|
+
import { truncateUtf8 } from '../../core/platform/http-body';
|
|
2
4
|
|
|
3
5
|
export class DeliveryDlqLedger {
|
|
4
6
|
constructor(private readonly poolOf: () => any) {}
|
|
5
7
|
|
|
6
8
|
private get pool(): any { return this.poolOf(); }
|
|
7
9
|
|
|
8
|
-
async record(d: { parentJobId: string; channel: string; recipient: string; content: string; error: string }): Promise<void> {
|
|
10
|
+
async record(d: { parentJobId: string; channel: string; recipient: string; content: string; error: string; deliveryKind?: DeliveryKind; notificationJobId?: string }): Promise<void> {
|
|
9
11
|
await this.pool.query(
|
|
10
|
-
'INSERT INTO bz_delivery_dlq (parent_job_id,channel,recipient,content,error,resolved,created_at) VALUES (
|
|
11
|
-
[d.parentJobId.slice(0, 191), d.channel.slice(0, 191), d.recipient.slice(0, 512), String(d.content ?? '')
|
|
12
|
+
'INSERT INTO bz_delivery_dlq (parent_job_id,channel,recipient,content,error,delivery_kind,notification_job_id,resolved,created_at) VALUES (?,?,?,?,?,?,?,0,?)',
|
|
13
|
+
[d.parentJobId.slice(0, 191), d.channel.slice(0, 191), d.recipient.slice(0, 512), truncateUtf8(String(d.content ?? ''), 60000), String(d.error ?? '').slice(0, 2000), d.deliveryKind ?? null, d.notificationJobId?.slice(0, 191) ?? null, dt()],
|
|
12
14
|
);
|
|
13
15
|
}
|
|
14
16
|
|
|
15
|
-
async list(includeResolved = false, limit = 100): Promise<Array<{ id: number; parent_job_id: string; channel: string; recipient: string; content_preview: string; error: string; resolved: boolean; created_at: string; resolved_at: string | null }>> {
|
|
17
|
+
async list(includeResolved = false, limit = 100): Promise<Array<{ id: number; parent_job_id: string; channel: string; recipient: string; content_preview: string; error: string; resolved: boolean; created_at: string; resolved_at: string | null; delivery_kind?: DeliveryKind | null; notification_job_id?: string | null; executor_replay_key?: string | null }>> {
|
|
16
18
|
const n = Math.min(Math.max(Number(limit) || 100, 1), 500);
|
|
17
19
|
const [rows] = await this.pool.query(
|
|
18
|
-
`SELECT id,parent_job_id,channel,recipient,LEFT(content,500) AS content_preview,error,resolved,created_at,resolved_at FROM bz_delivery_dlq ${includeResolved ? '' : 'WHERE resolved=0'} ORDER BY id DESC LIMIT ${n}`,
|
|
20
|
+
`SELECT id,parent_job_id,channel,recipient,LEFT(content,500) AS content_preview,error,resolved,created_at,resolved_at,delivery_kind,notification_job_id,executor_replay_key FROM bz_delivery_dlq ${includeResolved ? '' : 'WHERE resolved=0'} ORDER BY id DESC LIMIT ${n}`,
|
|
19
21
|
);
|
|
20
22
|
return (rows as any[]).map((r) => ({
|
|
21
23
|
id: Number(r.id), parent_job_id: r.parent_job_id, channel: r.channel, recipient: r.recipient,
|
|
22
24
|
content_preview: r.content_preview ?? '', error: r.error ?? '', resolved: !!r.resolved,
|
|
25
|
+
delivery_kind: r.delivery_kind, notification_job_id: r.notification_job_id, executor_replay_key: r.executor_replay_key,
|
|
23
26
|
created_at: new Date(r.created_at).toISOString(), resolved_at: r.resolved_at ? new Date(r.resolved_at).toISOString() : null,
|
|
24
27
|
}));
|
|
25
28
|
}
|
|
26
29
|
|
|
27
|
-
async listByParentJob(parentJobId: string, includeResolved = true, limit = 100): Promise<Array<{ id: number; parent_job_id: string; channel: string; recipient: string; content_preview: string; error: string; resolved: boolean; created_at: string; resolved_at: string | null }>> {
|
|
30
|
+
async listByParentJob(parentJobId: string, includeResolved = true, limit = 100): Promise<Array<{ id: number; parent_job_id: string; channel: string; recipient: string; content_preview: string; error: string; resolved: boolean; created_at: string; resolved_at: string | null; delivery_kind?: DeliveryKind | null; notification_job_id?: string | null; executor_replay_key?: string | null }>> {
|
|
28
31
|
const n = Math.min(Math.max(Number(limit) || 100, 1), 500);
|
|
29
32
|
const [rows] = await this.pool.query(
|
|
30
|
-
`SELECT id,parent_job_id,channel,recipient,LEFT(content,500) AS content_preview,error,resolved,created_at,resolved_at FROM bz_delivery_dlq WHERE parent_job_id=? ${includeResolved ? '' : 'AND resolved=0'} ORDER BY id DESC LIMIT ${n}`,
|
|
33
|
+
`SELECT id,parent_job_id,channel,recipient,LEFT(content,500) AS content_preview,error,resolved,created_at,resolved_at,delivery_kind,notification_job_id,executor_replay_key FROM bz_delivery_dlq WHERE parent_job_id=? ${includeResolved ? '' : 'AND resolved=0'} ORDER BY id DESC LIMIT ${n}`,
|
|
31
34
|
[parentJobId],
|
|
32
35
|
);
|
|
33
36
|
return (rows as any[]).map((r) => ({
|
|
34
37
|
id: Number(r.id), parent_job_id: r.parent_job_id, channel: r.channel, recipient: r.recipient,
|
|
35
38
|
content_preview: r.content_preview ?? '', error: r.error ?? '', resolved: !!r.resolved,
|
|
39
|
+
delivery_kind: r.delivery_kind, notification_job_id: r.notification_job_id, executor_replay_key: r.executor_replay_key,
|
|
36
40
|
created_at: new Date(r.created_at).toISOString(), resolved_at: r.resolved_at ? new Date(r.resolved_at).toISOString() : null,
|
|
37
41
|
}));
|
|
38
42
|
}
|
|
39
43
|
|
|
40
|
-
async get(id: number): Promise<
|
|
41
|
-
const [rows] = await this.pool.query('SELECT id,channel,recipient,content,resolved FROM bz_delivery_dlq WHERE id=? LIMIT 1', [id]);
|
|
44
|
+
async get(id: number): Promise<DeliveryDlqRecord | null> {
|
|
45
|
+
const [rows] = await this.pool.query('SELECT id,parent_job_id,channel,recipient,content,resolved,delivery_kind,notification_job_id,executor_replay_key FROM bz_delivery_dlq WHERE id=? LIMIT 1', [id]);
|
|
42
46
|
const r = (rows as any[])[0];
|
|
43
|
-
return r ? { id: Number(r.id),
|
|
47
|
+
return r ? { id: Number(r.id), parent_job_id: r.parent_job_id, channel: r.channel, recipient: r.recipient,
|
|
48
|
+
content: r.content ?? '', resolved: !!r.resolved, delivery_kind: r.delivery_kind,
|
|
49
|
+
notification_job_id: r.notification_job_id, executor_replay_key: r.executor_replay_key } : null;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Stable replay identity is initialized once; it never acts as an expiring owner lease. */
|
|
53
|
+
async ensureExecutorReplay(id: number, notificationJobId: string): Promise<{ key: string; created: boolean } | null> {
|
|
54
|
+
const key = deliveryReplayKey(id);
|
|
55
|
+
const conn = await this.pool.getConnection();
|
|
56
|
+
try {
|
|
57
|
+
await conn.beginTransaction();
|
|
58
|
+
const [rows] = await conn.query('SELECT * FROM bz_delivery_dlq WHERE id=? FOR UPDATE', [id]);
|
|
59
|
+
const row = (rows as any[])[0];
|
|
60
|
+
if (!row || row.resolved) { await conn.commit(); return null; }
|
|
61
|
+
if (row.parent_job_id !== notificationJobId || (row.notification_job_id && row.notification_job_id !== notificationJobId)
|
|
62
|
+
|| (row.delivery_kind && row.delivery_kind !== 'executor_target') || (row.executor_replay_key && row.executor_replay_key !== key)) throw new Error('delivery_dlq_replay_conflict');
|
|
63
|
+
const created = !row.executor_replay_key;
|
|
64
|
+
if (created) await conn.query("UPDATE bz_delivery_dlq SET delivery_kind='executor_target',notification_job_id=?,executor_replay_key=? WHERE id=?", [notificationJobId, key, id]);
|
|
65
|
+
await conn.commit();
|
|
66
|
+
return { key, created };
|
|
67
|
+
} catch (error) {
|
|
68
|
+
await conn.rollback().catch(() => undefined); throw error;
|
|
69
|
+
} finally { conn.release(); }
|
|
44
70
|
}
|
|
45
71
|
|
|
46
72
|
async resolve(id: number): Promise<void> {
|
|
@@ -63,7 +63,8 @@ export type ToolEmbeddingRepositoryContract = ToolEmbeddingRepository;
|
|
|
63
63
|
export type KnowledgeRepositoryContract = Pick<MysqlKnowledgeRepository, keyof MysqlKnowledgeRepository>;
|
|
64
64
|
export type KbDatasourceRepositoryContract = Pick<MysqlKbDatasourceRepository, keyof MysqlKbDatasourceRepository>;
|
|
65
65
|
export type { InstanceBrandingRepositoryContract };
|
|
66
|
-
export type DeliveryDlqLedgerContract = Pick<DeliveryDlqLedger, keyof DeliveryDlqLedger
|
|
66
|
+
export type DeliveryDlqLedgerContract = Pick<DeliveryDlqLedger, Exclude<keyof DeliveryDlqLedger, 'ensureExecutorReplay'>>
|
|
67
|
+
& Partial<Pick<DeliveryDlqLedger, 'ensureExecutorReplay'>>;
|
|
67
68
|
export type ObservabilityLedgerContract =
|
|
68
69
|
Omit<Pick<ObservabilityLedger, keyof ObservabilityLedger>, 'operationalMetricsSnapshot' | 'agentToolJobCandidatesForRun' | 'auditsForJobs'>
|
|
69
70
|
& Partial<Pick<ObservabilityLedger, 'operationalMetricsSnapshot' | 'agentToolJobCandidatesForRun' | 'auditsForJobs'>>;
|
|
@@ -7,6 +7,8 @@ import { JOB_STATUSES, TERMINAL_JOB_STATUSES, type AuditEntry, type Job } from '
|
|
|
7
7
|
import type { JobOperationalMetricsSnapshot, RuntimeStateStore } from '../../core/state/state-contracts';
|
|
8
8
|
import type { ApprovalRequeueInput, ApprovalRequeueOutcome } from '../../core/contracts/approval-continuation';
|
|
9
9
|
import { approvalRequeuePlan } from '../../core/state/approval-continuation';
|
|
10
|
+
import { deliveryRequeuePlan } from '../../core/state/delivery-replay';
|
|
11
|
+
import type { DeliveryRequeueInput, DeliveryRequeueOutcome } from '../../core/contracts/delivery-replay';
|
|
10
12
|
|
|
11
13
|
/** jsonl 后端:本地烟测与最小私有部署。状态仍是中枢自己的,不进业务库。 */
|
|
12
14
|
export class JsonlStore implements RuntimeStateStore {
|
|
@@ -62,7 +64,7 @@ export class JsonlStore implements RuntimeStateStore {
|
|
|
62
64
|
private async writeJob(jobId: string, patch: Partial<Job>, expectedStatuses?: Array<Job['status']>): Promise<Job | null> {
|
|
63
65
|
const cur = this.jobs.get(jobId);
|
|
64
66
|
if (!cur || (expectedStatuses && !expectedStatuses.includes(cur.status))) return null;
|
|
65
|
-
const { approval_continuation_keys: _ignored, ...ordinaryPatch } = patch;
|
|
67
|
+
const { approval_continuation_keys: _ignored, delivery_replay_keys: _ignoredDelivery, ...ordinaryPatch } = patch;
|
|
66
68
|
const next: Job = { ...cur, ...ordinaryPatch, updated_at: new Date().toISOString() };
|
|
67
69
|
await this.persist(next);
|
|
68
70
|
this.jobs.set(jobId, next);
|
|
@@ -94,6 +96,19 @@ export class JsonlStore implements RuntimeStateStore {
|
|
|
94
96
|
return this.jobs.get(jobId) ?? null;
|
|
95
97
|
}
|
|
96
98
|
|
|
99
|
+
async requeueDeliveryJobOnce(input: DeliveryRequeueInput): Promise<DeliveryRequeueOutcome> {
|
|
100
|
+
return await this.serialJobWrite(async () => {
|
|
101
|
+
const plan = deliveryRequeuePlan(this.jobs.get(input.job_id) ?? null, input);
|
|
102
|
+
if (plan.patch) {
|
|
103
|
+
if (!input.isOriginalDelivery || !await input.isOriginalDelivery()) return 'conflict';
|
|
104
|
+
const next = { ...this.jobs.get(input.job_id)!, ...plan.patch, updated_at: new Date().toISOString() };
|
|
105
|
+
await this.persist(next);
|
|
106
|
+
this.jobs.set(input.job_id, next);
|
|
107
|
+
}
|
|
108
|
+
return plan.outcome;
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
|
|
97
112
|
async claimNextJob(targets: string[], executorId: string, leaseMs: number): Promise<Job | null> {
|
|
98
113
|
if (!targets.length) return null;
|
|
99
114
|
const nowMs = Date.now();
|
|
@@ -9,6 +9,8 @@ import { mysqlJobUpdatePlan } from './state-mysql-update-plan';
|
|
|
9
9
|
import { MysqlPoolOwner, type MysqlPoolResource } from '../mysql/pool-owner';
|
|
10
10
|
import type { ApprovalRequeueInput, ApprovalRequeueOutcome } from '../../core/contracts/approval-continuation';
|
|
11
11
|
import { approvalRequeuePlan } from '../../core/state/approval-continuation';
|
|
12
|
+
import { deliveryRequeuePlan } from '../../core/state/delivery-replay';
|
|
13
|
+
import { isOriginalExecutorDelivery, type DeliveryRequeueInput, type DeliveryRequeueOutcome } from '../../core/contracts/delivery-replay';
|
|
12
14
|
|
|
13
15
|
/** mysql 后端:生产状态库。对应 sql/001_init_state.sql 的 bz_ 表。 */
|
|
14
16
|
export class MysqlStore implements RuntimeStateStore {
|
|
@@ -82,6 +84,31 @@ export class MysqlStore implements RuntimeStateStore {
|
|
|
82
84
|
return this.writeJob(jobId, patch, expectedStatuses);
|
|
83
85
|
}
|
|
84
86
|
|
|
87
|
+
async requeueDeliveryJobOnce(input: DeliveryRequeueInput): Promise<DeliveryRequeueOutcome> {
|
|
88
|
+
const conn = await this.pool.getConnection();
|
|
89
|
+
try {
|
|
90
|
+
await conn.beginTransaction();
|
|
91
|
+
const [rows] = await conn.query('SELECT * FROM bz_jobs WHERE job_id=? FOR UPDATE', [input.job_id]);
|
|
92
|
+
const row = (rows as any[])[0];
|
|
93
|
+
const job = row ? rowToJob(row) : null;
|
|
94
|
+
const plan = deliveryRequeuePlan(job, input);
|
|
95
|
+
if (plan.patch) {
|
|
96
|
+
const [dlqs] = await conn.query('SELECT * FROM bz_delivery_dlq WHERE id=? FOR UPDATE', [input.dlq_id]);
|
|
97
|
+
const dlq = (dlqs as any[])[0];
|
|
98
|
+
if (!dlq || dlq.resolved || dlq.executor_replay_key !== input.replay_key || !isOriginalExecutorDelivery(dlq, job)) {
|
|
99
|
+
await conn.commit(); return 'conflict';
|
|
100
|
+
}
|
|
101
|
+
const update = mysqlJobUpdatePlan(plan.patch, new Date().toISOString());
|
|
102
|
+
await conn.query(`UPDATE bz_jobs SET ${update.assignments.join(',')},delivery_replay_keys=? WHERE job_id=?`,
|
|
103
|
+
[...update.values, json(plan.patch.delivery_replay_keys), input.job_id]);
|
|
104
|
+
}
|
|
105
|
+
await conn.commit();
|
|
106
|
+
return plan.outcome;
|
|
107
|
+
} catch (error) {
|
|
108
|
+
await conn.rollback().catch(() => undefined); throw error;
|
|
109
|
+
} finally { conn.release(); }
|
|
110
|
+
}
|
|
111
|
+
|
|
85
112
|
private async writeJob(jobId: string, patch: Partial<Job>, expectedStatuses?: Array<Job['status']>): Promise<Job | null> {
|
|
86
113
|
const plan = mysqlJobUpdatePlan(patch, new Date().toISOString());
|
|
87
114
|
const whereStatus = expectedStatuses?.length ? ` AND status IN (${expectedStatuses.map(() => '?').join(',')})` : '';
|
|
@@ -142,3 +142,31 @@ test('a throwing failure reporter cannot keep rejected work live or replace its
|
|
|
142
142
|
owner.beginDrain();
|
|
143
143
|
assert.equal(await owner.drain(100), true);
|
|
144
144
|
});
|
|
145
|
+
|
|
146
|
+
test('fixed-kind snapshots expose accepted work age and outcomes without error bodies or mutable state', async () => {
|
|
147
|
+
let now = 1000;
|
|
148
|
+
const owner = new UsageBackgroundWork(() => now), held = gate();
|
|
149
|
+
const pending = owner.track('model-completion', () => held.promise);
|
|
150
|
+
const failed = owner.track('settlement', async () => { throw new Error('PRIVATE_PROVIDER_BODY_TOKEN'); });
|
|
151
|
+
await assert.rejects(failed);
|
|
152
|
+
now = 5000;
|
|
153
|
+
const snapshot = owner.snapshot();
|
|
154
|
+
assert.equal(snapshot.kinds.find(value => value.kind === 'model-completion')!.inFlight, 1);
|
|
155
|
+
assert.equal(snapshot.kinds.find(value => value.kind === 'model-completion')!.oldestPendingAgeMs, 4000);
|
|
156
|
+
assert.equal(snapshot.kinds.find(value => value.kind === 'settlement')!.failed, 1);
|
|
157
|
+
assert.equal(snapshot.kinds.find(value => value.kind === 'settlement')!.lastFailedAt, new Date(1000).toISOString());
|
|
158
|
+
assert.doesNotMatch(JSON.stringify(snapshot), /PRIVATE_PROVIDER|TOKEN/);
|
|
159
|
+
snapshot.kinds[0]!.completed = 1000;
|
|
160
|
+
assert.equal(owner.snapshot().kinds[0]!.completed, 0);
|
|
161
|
+
owner.beginDrain();
|
|
162
|
+
assert.equal(await owner.drain(0), false);
|
|
163
|
+
assert.equal(owner.snapshot().drainTimeouts, 1);
|
|
164
|
+
held.release(); await pending;
|
|
165
|
+
assert.equal(await owner.drain(100), true);
|
|
166
|
+
const done = owner.snapshot();
|
|
167
|
+
assert.equal(done.draining, true);
|
|
168
|
+
assert.equal(done.kinds[0]!.inFlight, 0);
|
|
169
|
+
assert.equal(done.kinds[0]!.oldestPendingAgeMs, 0);
|
|
170
|
+
assert.equal(done.kinds[0]!.completed, 1);
|
|
171
|
+
assert.equal(done.kinds[0]!.lastCompletedAt, new Date(5000).toISOString());
|
|
172
|
+
});
|
|
@@ -1,23 +1,59 @@
|
|
|
1
|
-
|
|
1
|
+
import type { BackgroundWorkMetricsSnapshot } from '../../core/observability/openmetrics';
|
|
2
|
+
|
|
3
|
+
export const USAGE_BACKGROUND_KINDS = ['model-completion', 'settlement', 'response-cleanup', 'usage-reconciliation', 'reference-price-refresh'] as const;
|
|
4
|
+
export type UsageBackgroundKind = typeof USAGE_BACKGROUND_KINDS[number];
|
|
2
5
|
type MaintenanceKind = Exclude<UsageBackgroundKind, 'model-completion' | 'settlement'>;
|
|
3
6
|
|
|
4
7
|
/** One UsageRepository owns its accepted work, including children created during drain. */
|
|
5
8
|
export class UsageBackgroundWork {
|
|
6
|
-
private readonly pending = new
|
|
9
|
+
private readonly pending = new Map<Promise<unknown>, { kind: UsageBackgroundKind; startedAt: number }>();
|
|
10
|
+
private readonly counts = new Map(USAGE_BACKGROUND_KINDS.map(kind => [kind, {
|
|
11
|
+
completed: 0, failed: 0,
|
|
12
|
+
lastStartedAt: null as string | null, lastCompletedAt: null as string | null, lastFailedAt: null as string | null,
|
|
13
|
+
}]));
|
|
7
14
|
private draining = false;
|
|
15
|
+
private drainTimeouts = 0;
|
|
8
16
|
private failureReporter: ((kind: UsageBackgroundKind) => void) | undefined;
|
|
9
17
|
|
|
18
|
+
constructor(private readonly clock: () => number = Date.now) {}
|
|
19
|
+
|
|
10
20
|
get acceptingRequests(): boolean { return !this.draining; }
|
|
11
21
|
setFailureReporter(reporter: (kind: UsageBackgroundKind) => void): void { this.failureReporter = reporter; }
|
|
12
22
|
beginDrain(): void { this.draining = true; }
|
|
13
23
|
|
|
24
|
+
/** Process-local fixed-kind values only; snapshots never start work or access SQL. */
|
|
25
|
+
snapshot(nowMs = this.clock()): BackgroundWorkMetricsSnapshot {
|
|
26
|
+
const live = new Map(USAGE_BACKGROUND_KINDS.map(kind => [kind, { count: 0, oldest: Infinity }]));
|
|
27
|
+
for (const work of this.pending.values()) {
|
|
28
|
+
const value = live.get(work.kind)!;
|
|
29
|
+
value.count++; value.oldest = Math.min(value.oldest, work.startedAt);
|
|
30
|
+
}
|
|
31
|
+
return {
|
|
32
|
+
draining: this.draining,
|
|
33
|
+
drainTimeouts: this.drainTimeouts,
|
|
34
|
+
kinds: USAGE_BACKGROUND_KINDS.map(kind => {
|
|
35
|
+
const value = live.get(kind)!;
|
|
36
|
+
return { kind, ...this.counts.get(kind)!, inFlight: value.count,
|
|
37
|
+
oldestPendingAgeMs: value.count ? Math.max(0, nowMs - value.oldest) : 0 };
|
|
38
|
+
}),
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
|
|
14
42
|
track<T>(kind: UsageBackgroundKind, run: () => Promise<T>): Promise<T> {
|
|
15
43
|
// Register before invoking run: even an immediately resolving parent must not
|
|
16
44
|
// leave a gap before its SQL/settlement continuation has been registered.
|
|
17
45
|
const work = Promise.resolve().then(run);
|
|
18
|
-
this.
|
|
19
|
-
|
|
46
|
+
const startedAt = this.clock(), counts = this.counts.get(kind)!;
|
|
47
|
+
this.pending.set(work, { kind, startedAt });
|
|
48
|
+
counts.lastStartedAt = new Date(startedAt).toISOString();
|
|
49
|
+
void work.then(() => {
|
|
50
|
+
this.pending.delete(work);
|
|
51
|
+
counts.completed++;
|
|
52
|
+
counts.lastCompletedAt = new Date(this.clock()).toISOString();
|
|
53
|
+
}, () => {
|
|
20
54
|
this.pending.delete(work);
|
|
55
|
+
counts.failed++;
|
|
56
|
+
counts.lastFailedAt = new Date(this.clock()).toISOString();
|
|
21
57
|
// Report only the fixed work kind; provider bodies, SQL and credentials
|
|
22
58
|
// are never included in lifecycle diagnostics.
|
|
23
59
|
try { this.failureReporter?.(kind); } catch { /* diagnostics cannot own lifecycle */ }
|
|
@@ -33,14 +69,14 @@ export class UsageBackgroundWork {
|
|
|
33
69
|
const deadline = Date.now() + Math.max(0, drainMs);
|
|
34
70
|
while (this.pending.size) {
|
|
35
71
|
const remaining = deadline - Date.now();
|
|
36
|
-
if (remaining <= 0) return false;
|
|
72
|
+
if (remaining <= 0) { this.drainTimeouts++; return false; }
|
|
37
73
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
38
74
|
try {
|
|
39
75
|
const drained = await Promise.race([
|
|
40
|
-
Promise.allSettled([...this.pending]).then(() => true),
|
|
76
|
+
Promise.allSettled([...this.pending.keys()]).then(() => true),
|
|
41
77
|
new Promise<boolean>(resolve => { timer = setTimeout(() => resolve(false), remaining); }),
|
|
42
78
|
]);
|
|
43
|
-
if (!drained) return false;
|
|
79
|
+
if (!drained) { this.drainTimeouts++; return false; }
|
|
44
80
|
} finally { if (timer) clearTimeout(timer); }
|
|
45
81
|
// A tracked completion can register settlement after drain started. Do
|
|
46
82
|
// not mistake a finished snapshot for a quiescent repository.
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import test from 'node:test';
|
|
2
2
|
import assert from 'node:assert/strict';
|
|
3
3
|
import type { UsageRepository } from './repository';
|
|
4
|
-
import {
|
|
4
|
+
import { getBillingRepository, usageReconciliationSnapshotFor } from './billing-repository';
|
|
5
5
|
|
|
6
6
|
const price = { source: 'openrouter', currency: 'USD', modelId: 'synthetic', endpointId: 'synthetic', fetchedAt: 1,
|
|
7
7
|
lines: [{ billable: 'output_image', unit: 'image', costUsd: '0.1' }] };
|
|
@@ -43,7 +43,7 @@ function fixture(count = 51) {
|
|
|
43
43
|
throw new Error('Unexpected synthetic statement');
|
|
44
44
|
} };
|
|
45
45
|
const repository = { getPool: () => executor, withTransaction: async (fn: (c: any) => Promise<any>) => fn(executor) } as unknown as UsageRepository;
|
|
46
|
-
return { tokens:
|
|
46
|
+
return { tokens: getBillingRepository(repository), records, ledger, attempts, statements, period };
|
|
47
47
|
}
|
|
48
48
|
test('fifty unpriceable originals cannot starve the fifty-first payable result, including equal timestamps', async () => {
|
|
49
49
|
const h = fixture();
|
|
@@ -69,3 +69,17 @@ test('concurrent reconciliation shares one page rather than skipping its cursor'
|
|
|
69
69
|
await first;
|
|
70
70
|
assert.equal(h.attempts.length, 50);
|
|
71
71
|
});
|
|
72
|
+
|
|
73
|
+
test('readonly reconciliation snapshot is absent before the first page and returns detached aggregate values afterward', async () => {
|
|
74
|
+
const h = fixture(2);
|
|
75
|
+
assert.equal(usageReconciliationSnapshotFor(h.tokens.repository), undefined);
|
|
76
|
+
const before = h.statements.length;
|
|
77
|
+
assert.equal(usageReconciliationSnapshotFor(h.tokens.repository), undefined);
|
|
78
|
+
assert.equal(h.statements.length, before);
|
|
79
|
+
await h.tokens.reconcilePendingUsage();
|
|
80
|
+
const snapshot = usageReconciliationSnapshotFor(h.tokens.repository)!;
|
|
81
|
+
assert.equal(snapshot.scanned, 2);
|
|
82
|
+
snapshot.scanned = 999;
|
|
83
|
+
assert.equal(usageReconciliationSnapshotFor(h.tokens.repository)!.scanned, 2);
|
|
84
|
+
assert.doesNotMatch(JSON.stringify(snapshot), /account|request|SYNTHETIC|result_json/);
|
|
85
|
+
});
|
|
@@ -413,8 +413,12 @@ export class BillingRepository {
|
|
|
413
413
|
}
|
|
414
414
|
private reconciliationCursor: { updatedAt: number; id: string } | null = null;
|
|
415
415
|
private reconciliationFlight: Promise<void> | null = null;
|
|
416
|
+
private reconciliationStarted = false;
|
|
416
417
|
private reconciliationProgress: UsageReconciliationProgress = { scanned: 0, settled: 0, deferred: 0, failed: 0, hasMore: false };
|
|
417
418
|
getReconciliationProgress(): UsageReconciliationProgress { return { ...this.reconciliationProgress }; }
|
|
419
|
+
getReconciliationSnapshot(): UsageReconciliationProgress | undefined {
|
|
420
|
+
return this.reconciliationStarted ? this.getReconciliationProgress() : undefined;
|
|
421
|
+
}
|
|
418
422
|
reconcilePendingUsage(): Promise<void> {
|
|
419
423
|
if (this.reconciliationFlight) return this.reconciliationFlight;
|
|
420
424
|
const work = this.reconcilePage();
|
|
@@ -427,6 +431,7 @@ export class BillingRepository {
|
|
|
427
431
|
// advances past unpriceable/failing records; no row can pin the oldest page.
|
|
428
432
|
// A new owner starts from the beginning, then makes the same bounded progress.
|
|
429
433
|
const progress: UsageReconciliationProgress = { scanned: 0, settled: 0, deferred: 0, failed: 0, hasMore: false };
|
|
434
|
+
this.reconciliationStarted = true;
|
|
430
435
|
this.reconciliationProgress = progress;
|
|
431
436
|
const scan = () => {
|
|
432
437
|
const cursor = this.reconciliationCursor;
|
|
@@ -501,6 +506,10 @@ export class BillingRepository {
|
|
|
501
506
|
}
|
|
502
507
|
}
|
|
503
508
|
const repositories = new WeakMap<UsageRepository, BillingRepository>();
|
|
509
|
+
/** Read the last bounded page only. Does not initialize billing or query records. */
|
|
510
|
+
export function usageReconciliationSnapshotFor(repository: UsageRepository): UsageReconciliationProgress | undefined {
|
|
511
|
+
return repositories.get(repository)?.getReconciliationSnapshot();
|
|
512
|
+
}
|
|
504
513
|
export function getBillingRepository(repository: UsageRepository): BillingRepository {
|
|
505
514
|
let value = repositories.get(repository);
|
|
506
515
|
if (!value) { value = new BillingRepository(repository); repositories.set(repository, value); }
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import test from 'node:test';
|
|
2
2
|
import assert from 'node:assert/strict';
|
|
3
3
|
import { UsageRepository } from './repository';
|
|
4
|
-
import { getBillingRepository } from './billing-repository';
|
|
5
|
-
import { runUsageMaintenanceFor } from './maintenance';
|
|
4
|
+
import { getBillingRepository, usageReconciliationSnapshotFor } from './billing-repository';
|
|
5
|
+
import { runUsageMaintenanceFor, usageMaintenanceSnapshotFor } from './maintenance';
|
|
6
6
|
|
|
7
7
|
function owner() {
|
|
8
8
|
const repository = new UsageRepository(() => { throw new Error('No database is used in this synthetic port test'); });
|
|
@@ -60,3 +60,19 @@ test('a slow SQL failure starts its bounded retry delay at failure completion',
|
|
|
60
60
|
clock = 180000;
|
|
61
61
|
await runUsageMaintenanceFor(repository, () => clock); assert.equal(attempts, 2);
|
|
62
62
|
});
|
|
63
|
+
|
|
64
|
+
test('maintenance and reconciliation snapshots remain readonly during backoff and do not initialize billing', async () => {
|
|
65
|
+
const untouched = new UsageRepository(() => { throw new Error('Snapshot must not access SQL'); });
|
|
66
|
+
assert.equal(usageReconciliationSnapshotFor(untouched), undefined);
|
|
67
|
+
assert.deepEqual(usageMaintenanceSnapshotFor(untouched, 0), { running: false, consecutiveFailures: 0, retryAfterMs: 0 });
|
|
68
|
+
assert.equal(usageReconciliationSnapshotFor(untouched), undefined);
|
|
69
|
+
const { repository, tokens } = owner();
|
|
70
|
+
tokens.reconcilePendingUsage = async () => { throw new Error('PRIVATE_DATABASE_BODY'); };
|
|
71
|
+
await runUsageMaintenanceFor(repository, 1000);
|
|
72
|
+
const snapshot = usageMaintenanceSnapshotFor(repository, 2000);
|
|
73
|
+
assert.deepEqual(snapshot, { running: false, consecutiveFailures: 1, retryAfterMs: 59000 });
|
|
74
|
+
snapshot.consecutiveFailures = 100;
|
|
75
|
+
assert.equal(usageMaintenanceSnapshotFor(repository, 61000).consecutiveFailures, 1);
|
|
76
|
+
assert.equal(usageReconciliationSnapshotFor(repository), undefined); // The mocked method did not start a real bounded page.
|
|
77
|
+
assert.doesNotMatch(JSON.stringify(snapshot), /PRIVATE_DATABASE/);
|
|
78
|
+
});
|
|
@@ -6,6 +6,14 @@ const RETRY_MAX_MS = 5 * 60_000;
|
|
|
6
6
|
interface MaintenanceState { flight: Promise<void> | null; retryAt: number; failures: number }
|
|
7
7
|
const owners = new WeakMap<UsageRepository, MaintenanceState>();
|
|
8
8
|
|
|
9
|
+
export function usageMaintenanceSnapshotFor(repository: UsageRepository, clock = performance.now()): {
|
|
10
|
+
running: boolean; consecutiveFailures: number; retryAfterMs: number;
|
|
11
|
+
} {
|
|
12
|
+
const state = owners.get(repository);
|
|
13
|
+
return { running: Boolean(state?.flight), consecutiveFailures: state?.failures ?? 0,
|
|
14
|
+
retryAfterMs: Math.max(0, (state?.retryAt ?? 0) - clock) };
|
|
15
|
+
}
|
|
16
|
+
|
|
9
17
|
/** Shared startup/tick/HTTP fallback port. No timer, credentials or provider transport. */
|
|
10
18
|
export function runUsageMaintenanceFor(repository: UsageRepository | null, clock: number | (() => number) = () => performance.now()): Promise<void> {
|
|
11
19
|
if (!repository || !repository.backgroundWork.acceptingRequests) return Promise.resolve();
|
|
@@ -14,6 +14,7 @@ import type { Principal } from '../app/auth';
|
|
|
14
14
|
import type { ChannelMessage, ChannelSendResult } from '../app/channels';
|
|
15
15
|
import { isAgentToolInvocationJob } from '../app/agent-tool-job';
|
|
16
16
|
import { continueApprovalDecisionFor, supportsApprovalContinuations } from '../app/approval-continuations';
|
|
17
|
+
import { classifyDeliveryDlq, replayExecutorDeliveryDlq, DeliveryReplayError } from '../app/delivery-dlq-replay';
|
|
17
18
|
|
|
18
19
|
export type AdminChannelSender = (channelName: string, recipient: string, message: string | ChannelMessage) => Promise<ChannelSendResult>;
|
|
19
20
|
|
|
@@ -292,6 +293,19 @@ export async function handleAdminRuntimeApiFor(
|
|
|
292
293
|
const d = await configStore.deliveryDlq.get(id);
|
|
293
294
|
if (!d) { send(res, 404, { error: '死信不存在' }); return true; }
|
|
294
295
|
if (d.resolved) { send(res, 200, { ok: true, note: '已处理过,未重复重投' }); return true; }
|
|
296
|
+
try {
|
|
297
|
+
if (await classifyDeliveryDlq(d, stateStore) === 'executor_target') {
|
|
298
|
+
const replay = await replayExecutorDeliveryDlq(d, configStore.deliveryDlq, stateStore);
|
|
299
|
+
await stateStore.appendAudit({ ts: deps.now(), job_id: d.notification_job_id || d.parent_job_id || '-', request_id: 'delivery-dlq',
|
|
300
|
+
event: 'dlq_executor_requeued', detail: { id, target: d.channel, ...replay } }).catch(() => undefined);
|
|
301
|
+
send(res, 200, { ok: true, ...replay, notification_job_id: d.notification_job_id || d.parent_job_id });
|
|
302
|
+
return true;
|
|
303
|
+
}
|
|
304
|
+
} catch (error) {
|
|
305
|
+
const status = error instanceof DeliveryReplayError ? error.status : 503;
|
|
306
|
+
const code = error instanceof DeliveryReplayError ? error.code : 'delivery_dlq_replay_unavailable';
|
|
307
|
+
send(res, status, { error: code, code }); return true;
|
|
308
|
+
}
|
|
295
309
|
const sent = await deps.channelSend(d.channel, d.recipient, d.content).catch((e) => ({ ok: false as const, error: String(e) }));
|
|
296
310
|
if (sent.ok) await configStore.deliveryDlq.resolve(id);
|
|
297
311
|
await stateStore.appendAudit({ ts: deps.now(), job_id: '-', request_id: 'delivery-dlq', event: sent.ok ? 'dlq_resend_ok' : 'dlq_resend_failed', detail: { id, channel: d.channel, to: d.recipient, ...(sent.ok ? {} : { error: (sent as { error?: string }).error }) } }).catch(() => undefined);
|