Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(mcp): accepted_pending request-log class out of the admin error rate (#5249)
garrytand5ed540079e4
diff --git a/src/commands/serve-http-admin-api.ts b/src/commands/serve-http-admin-api.tsindex 6ebcdea28d..cc2b122bfe 100644--- a/src/commands/serve-http-admin-api.ts+++ b/src/commands/serve-http-admin-api.ts@@ -62,6 +62,43 @@ export function openAdminSseStream(res: AdminSseResponse): void {* Falls back to `[]` on any SQL error (pre-v0.38 brains where the v82-v84* tables/columns don't yet exist).*/+/** The `/admin/api/health-indicators` body; SQL lives here so tests pin the served query. */+export async function queryHealthIndicators(engine: BrainEngine): Promise<{+ expiring_soon: number; error_rate: string; pending_writes: number;+ oldest_pending_write_age_seconds: number; pending_writes_later_failed: number;+}> {+ const sql = sqlQueryForEngine(engine);+ const now = Math.floor(Date.now() / 1000);+ const [expiring] = await sql`SELECT count(*)::int as count FROM oauth_tokens WHERE token_type = 'access' AND expires_at BETWEEN ${now} AND ${now + 86400}`;+ // Excluded from the error numerator: success, success_with_warnings+ // (a warn-mode success) and accepted_pending (#5249: an admitted write+ // still in flight; its eventual failure is counted separately below);+ // denied_after_list stays counted — a denied call IS a failure signal.+ // surface_change is an OPERATION value (audit rows carry+ // status='success'), so audit rows are excluded from BOTH counts —+ // they are records of operator/self actions, not traffic.+ const [errors] = await sql`SELECT count(*)::int as count FROM mcp_request_log WHERE status NOT IN ('success', 'success_with_warnings', 'accepted_pending') AND operation != 'surface_change' AND created_at > now() - interval '24 hours'`;+ const [total] = await sql`SELECT count(*)::int as count FROM mcp_request_log WHERE operation != 'surface_change' AND created_at > now() - interval '24 hours'`;+ const errorRate = (total as any).count > 0 ? ((errors as any).count / (total as any).count * 100).toFixed(1) : '0';+ // #5249/O-CEO-14: pending writes are tracked apart from the error rate —+ // how many are still in flight, how old the oldest is, and how many+ // reported as pending in the last 24 hours later ended without committing.+ const [pending] = await sql`SELECT count(*)::int AS count,+ COALESCE(floor(extract(epoch FROM now() - min(created_at))), 0)::int AS oldest_age_seconds+ FROM persistence_requests WHERE state IN ('queued', 'running', 'recovering')`;+ const [laterFailed] = await sql`SELECT count(DISTINCT r.id)::int AS count FROM mcp_request_log l+ JOIN persistence_requests r ON r.request_id::text = l.params->>'write_request_id'+ WHERE l.status = 'accepted_pending' AND l.created_at > now() - interval '24 hours'+ AND r.state IN ('conflict', 'failed', 'cancelled')`;+ return {+ expiring_soon: (expiring as any).count,+ error_rate: `${errorRate}%`,+ pending_writes: (pending as any).count,+ oldest_pending_write_age_seconds: (pending as any).oldest_age_seconds,+ pending_writes_later_failed: (laterFailed as any).count,+ };+}+export interface AgentClientSpend {client_id: string;client_name: string;@@ -297,20 +334,7 @@ function mountAdminOverviewApi(app: Express, ctx: ServeHttpContext): void {app.get('/admin/api/health-indicators', requireAdmin, async (_req: Request, res: Response) => {try {- const now = Math.floor(Date.now() / 1000);- const [expiring] = await sql`SELECT count(*)::int as count FROM oauth_tokens WHERE token_type = 'access' AND expires_at BETWEEN ${now} AND ${now + 86400}`;- // Excluded from the error numerator: success and success_with_warnings- // (a warn-mode success); denied_after_list stays counted — a denied- // call IS a failure signal. surface_change is an OPERATION value (audit- // rows carry status='success'), so audit rows are excluded from BOTH- // counts — they are records of operator/self actions, not traffic.- const [errors] = await sql`SELECT count(*)::int as count FROM mcp_request_log WHERE status NOT IN ('success', 'success_with_warnings') AND operation != 'surface_change' AND created_at > now() - interval '24 hours'`;- const [total] = await sql`SELECT count(*)::int as count FROM mcp_request_log WHERE operation != 'surface_change' AND created_at > now() - interval '24 hours'`;- const errorRate = (total as any).count > 0 ? ((errors as any).count / (total as any).count * 100).toFixed(1) : '0';- res.json({- expiring_soon: (expiring as any).count,- error_rate: `${errorRate}%`,- });+ res.json(await queryHealthIndicators(engine));} catch {res.status(503).json({ error: 'service_unavailable' });}diff --git a/src/commands/serve-http-mcp.ts b/src/commands/serve-http-mcp.tsindex 12de158eec..a1640e3699 100644--- a/src/commands/serve-http-mcp.ts+++ b/src/commands/serve-http-mcp.ts@@ -18,7 +18,7 @@ import { createSkillResources } from '../mcp/skill-resources.ts';import { resolveAuthCapabilities } from '../core/harness/capabilities.ts';import { resolveWritebackConfig, ambientOptsFrom } from '../core/facts/writeback-config.ts';import { hasScope, operationScopesAllowed } from '../core/scope.ts';-import { summarizeMcpParams, dispatchToolCall, requestLogStatusForResult, type ToolResult } from '../mcp/dispatch.ts';+import { summarizeMcpParams, dispatchToolCall, requestLogStatusForResult, acceptedPendingReceipt, type ToolResult } from '../mcp/dispatch.ts';import { resolveStrictParamsMode } from '../mcp/validate-params.ts';import { buildToolDefs } from '../mcp/tool-defs.ts';import {@@ -504,13 +504,15 @@ async function recordMcpToolResult(errMsg = parsed.error?.message ?? parsed.message ?? errMsg;} catch { /* ignore */ }const errStatus = requestLogStatusForResult(toolResult);+ // #5249: the opaque request id lets admin stats count pending writes that later fail.+ const pending = errStatus === 'accepted_pending' ? acceptedPendingReceipt(toolResult) : null;try {await executeRawJsonb(engine,`INSERT INTO mcp_request_log (token_name, agent_name, operation, latency_ms, status, error_message, params)VALUES ($1, $2, $3, $4, $5, $6, $7::jsonb)`,[authInfo.clientId, agentName, name, latency, errStatus, errMsg],- [logParamsObj],+ [pending ? { ...(logParamsObj && typeof logParamsObj === 'object' ? logParamsObj : {}), write_request_id: pending.request_id } : logParamsObj],);} catch { /* best effort */ }broadcastEvent({diff --git a/test/accepted-pending-status.test.ts b/test/accepted-pending-status.test.tsnew file mode 100644index 0000000000..4097309562--- /dev/null+++ b/test/accepted-pending-status.test.ts@@ -0,0 +1,100 @@+/**+ * #5249: an accepted write still in flight is its own request-log class+ * (`accepted_pending`), never an `error`, and the admin health indicators+ * keep it out of the error rate while counting pending writes, their age and+ * those that later end without committing.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { randomUUID } from 'node:crypto';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { withEnv } from './helpers/with-env.ts';+import { acceptedPendingReceipt, dispatchToolCall, requestLogStatusForResult, type ToolResult } from '../src/mcp/dispatch.ts';+import { acquireWorktree, getWorktreeBinding } from '../src/core/persistence/ownership.ts';+import { registerLocalWriter, withVerifiedLocalRegistration } from '../src/core/persistence/identity.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { queryHealthIndicators } from '../src/commands/serve-http-admin-api.ts';+import { _resetWriteThroughCacheForTest } from '../src/core/write-through.ts';++const errorResult = (envelope: Record<string, unknown>): ToolResult => ({ isError: true, content: [{ type: 'text', text: JSON.stringify(envelope) }] });+const RID = '30000000-0000-4000-8000-000000000001';++describe('requestLogStatusForResult: accepted_pending (pure)', () => {+ test('a write_pending envelope with a non-terminal receipt is accepted_pending', () => {+ for (const state of ['queued', 'running', 'recovering']) {+ const result = errorResult({ error: 'write_pending', message: 'pending', write_request: { request_id: RID, state, retry_after_ms: 1000 } });+ expect(requestLogStatusForResult(result)).toBe('accepted_pending');+ expect(acceptedPendingReceipt(result)?.request_id).toBe(RID);+ }+ });+ test('the frozen verb shape (unavailable + write_error) is accepted_pending too', () => {+ expect(requestLogStatusForResult(errorResult({ error: 'unavailable', write_error: 'write_pending', protocol_version: 1,+ write_request: { request_id: RID, state: 'queued', retry_after_ms: 1000 } }))).toBe('accepted_pending');+ });+ test('without an admitted receipt, or with a terminal one, it stays an error', () => {+ expect(requestLogStatusForResult(errorResult({ error: 'write_pending', message: 'pending' }))).toBe('error');+ expect(requestLogStatusForResult(errorResult({ error: 'write_pending', write_request: { request_id: RID, state: 'failed', retry_after_ms: null } }))).toBe('error');+ expect(requestLogStatusForResult(errorResult({ error: 'unavailable', message: 'The persistence owner is closing.' }))).toBe('error');+ expect(acceptedPendingReceipt({ content: [{ type: 'text', text: '{}' }] })).toBeNull();+ });+});++let engine: PGLiteEngine;+let fixture: string;+beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);+afterAll(async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); });+beforeEach(async () => {+ await disposePersistenceConsumer(engine);+ await resetPgliteState(engine);+ _resetWriteThroughCacheForTest();+ fixture = mkdtempSync(join(tmpdir(), 'gb-accepted-pending-'));+ mkdirSync(join(fixture, 'brain'));+ await engine.setConfig('sync.repo_path', join(fixture, 'brain'));+});++describe('a real pending write over the dispatcher', () => {+ test('dispatch with a short wait returns accepted_pending, and the health indicators exclude it from the error rate', async () => {+ await withEnv({ GBRAIN_HOME: join(fixture, 'home') }, async () => {+ const registration = await registerLocalWriter(engine, 'stdio', { sourceIds: ['*'], operations: null, scopes: ['read', 'write'], slugPrefixes: ['notes'] });+ const auth = { token: 'fixture', clientId: 'fixture-client', scopes: ['read', 'write'], sourceId: 'default', boundSlugPrefixes: ['notes'] };+ const put = (slug: string, writeWaitMs?: number) => withVerifiedLocalRegistration(engine, registration, () => dispatchToolCall(engine, 'put_page', {+ slug, content: `---\ntitle: Example\n---\n\n${slug} body.\n`, request_id: randomUUID(),+ }, { remote: true, config: { engine: 'pglite' }, sourceId: 'default', auth, logger: { info() {}, warn() {}, error() {} },+ ...(writeWaitMs !== undefined ? { writeWaitMs } : {}) }));+ try {+ expect(requestLogStatusForResult(await put('notes/seed'))).toBe('success');+ const binding = await getWorktreeBinding(engine, 'default');+ const lock = (await acquireWorktree(binding!))!;+ let pendingA: ToolResult, pendingB: ToolResult;+ try {+ const started = Date.now();+ pendingA = await put('notes/a', 200);+ pendingB = await put('notes/b', 200);+ expect(Date.now() - started).toBeLessThan(4_000);+ } finally { await lock.release(); }+ expect(requestLogStatusForResult(pendingA)).toBe('accepted_pending');+ expect(requestLogStatusForResult(pendingB)).toBe('accepted_pending');+ await disposePersistenceConsumer(engine);+ const a = acceptedPendingReceipt(pendingA)!, b = acceptedPendingReceipt(pendingB)!;+ await engine.executeRaw("UPDATE persistence_requests SET state='failed', error_code='storage_error' WHERE request_id=$1::uuid", [a.request_id]);+ const log = (status: string, params: Record<string, unknown> | null = null) => engine.executeRaw(+ 'INSERT INTO mcp_request_log (token_name, operation, status, params) VALUES ($1, $2, $3, $4::jsonb)',+ ['fixture-client', 'put_page', status, params === null ? null : JSON.stringify(params)]);+ await log('success');+ await log('error');+ await log('denied_after_list');+ await log('accepted_pending', { write_request_id: a.request_id });+ await log('accepted_pending', { write_request_id: b.request_id });+ await engine.executeRaw("UPDATE persistence_requests SET created_at = now() - interval '90 seconds' WHERE request_id=$1::uuid", [b.request_id]);+ const health = await queryHealthIndicators(engine);+ expect(health.error_rate).toBe('40.0%');+ expect(health.pending_writes).toBe(1);+ expect(health.oldest_pending_write_age_seconds).toBeGreaterThanOrEqual(90);+ expect(health.pending_writes_later_failed).toBe(1);+ } finally { await disposePersistenceConsumer(engine); rmSync(fixture, { recursive: true, force: true }); }+ });+ }, 60_000);+});