diff --git a/.env.example b/.env.example index 67841a147..3b5a44c7f 100644 --- a/.env.example +++ b/.env.example @@ -493,7 +493,16 @@ MCP_RATE_LIMIT_PER_MINUTE=60 # HEALTH_HEAP_PERCENT /health reports the process down at or above this, so # a probe sees the decline before the crash. 0 disables. # Default 90. +# NODE_MAX_SEMI_SPACE_MB V8 young-generation semi-space in MB (start.sh passes +# --max-semi-space-size). Unset or 0 keeps V8's default +# of 16. A busy instance promotes the garbage of every +# tool call to the old space with that default; 64 +# makes the old-space collections that stall the event +# loop rarer (the `gc` block of the vitals line shows +# them). Costs about three times its value in RSS. +# Cloud default 64 (docker-compose.cloud.yml). # VITALS_INTERVAL_SEC=30 +# NODE_MAX_SEMI_SPACE_MB=64 # HEAP_WARN_PERCENT=75 # HEAP_SNAPSHOT_PERCENT=0 # HEAP_SNAPSHOT_DIR=/tmp/anythingmcp-diagnostics diff --git a/deploy/cloud/Caddyfile b/deploy/cloud/Caddyfile index bcca4b297..d9a6ad7b0 100644 --- a/deploy/cloud/Caddyfile +++ b/deploy/cloud/Caddyfile @@ -41,14 +41,31 @@ } } +# Idle upstream connections are dropped after 55 s, before the app drops +# them itself: the backend at 65 s (keepAliveTimeout, main.ts), the frontend +# at 65 s (KEEP_ALIVE_TIMEOUT, docker-compose.cloud.yml). With Caddy's +# default of 2 minutes the app closed first, and a POST sent on a connection +# it had just closed came back as a 502 "connection reset by peer" (the +# uptime probe's /mcp/demo call on 2026-12-06 07:36 UTC, right after a long +# GC pause had let the backend's idle timers expire all at once). +(upstream_keepalive) { + transport http { + keepalive 55s + } +} + (backend) { @blue vars amcp_colour blue @green vars amcp_colour green handle @blue { - reverse_proxy backend-blue:4000 + reverse_proxy backend-blue:4000 { + import upstream_keepalive + } } handle @green { - reverse_proxy backend-green:4000 + reverse_proxy backend-green:4000 { + import upstream_keepalive + } } handle { respond "No live release selected" 503 @@ -59,10 +76,14 @@ @blue vars amcp_colour blue @green vars amcp_colour green handle @blue { - reverse_proxy frontend-blue:3000 + reverse_proxy frontend-blue:3000 { + import upstream_keepalive + } } handle @green { - reverse_proxy frontend-green:3000 + reverse_proxy frontend-green:3000 { + import upstream_keepalive + } } handle { respond "No live release selected" 503 @@ -233,6 +254,7 @@ header_up -X-Forwarded-For header_up -X-Real-IP header_up -Forwarded + import upstream_keepalive } } handle @green { @@ -240,6 +262,7 @@ header_up -X-Forwarded-For header_up -X-Real-IP header_up -Forwarded + import upstream_keepalive } } handle { diff --git a/docker-compose.cloud.yml b/docker-compose.cloud.yml index a66cd7dfd..b13ab97ea 100644 --- a/docker-compose.cloud.yml +++ b/docker-compose.cloud.yml @@ -67,6 +67,12 @@ x-backend: &backend # .env when the host has the RAM to back it — roughly half of total is a # safe ceiling, since postgres, redis, motis and caddy share the box. - NODE_MAX_OLD_SPACE_MB=${NODE_MAX_OLD_SPACE_MB:-2048} + # V8 semi-space (young generation) in MB, read by start.sh; 0 keeps V8's + # default of 16. 64 keeps the garbage of a tool call out of the old + # space, so the old-space collections that stall the event loop come + # less often (reasoning in start.sh). The `gc` block of the vitals log + # line shows the effect. + - NODE_MAX_SEMI_SPACE_MB=${NODE_MAX_SEMI_SPACE_MB:-64} # Heap guard (packages/backend/src/common/process-vitals.ts; every var # documented in .env.example). The snapshot stays OFF here: on a heap # this size V8's snapshot builder is what pushed RSS into the cgroup @@ -358,6 +364,11 @@ x-frontend: &frontend environment: - NODE_ENV=production - NEXT_PUBLIC_API_URL=https://${DOMAIN} + # Next's standalone server closes idle keep-alive connections after 5 s + # unless told otherwise. Caddy reuses them for longer, and a POST sent + # on a connection just closed came back as a 502. 65 s, as the backend + # has; Caddy lets go first, at 55 s (deploy/cloud/Caddyfile). + - KEEP_ALIVE_TIMEOUT=65000 - GTM_ID=${GTM_ID:-} - COOKIE_DOMAIN=${COOKIE_DOMAIN:-} # Sentry: server runtime, and handed to the browser by the root layout diff --git a/package-lock.json b/package-lock.json index a6f4c223a..ae0608581 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "anythingmcp", - "version": "0.55.23", + "version": "0.55.24", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "anythingmcp", - "version": "0.55.23", + "version": "0.55.24", "license": "AGPL-3.0-only", "workspaces": [ "packages/backend", @@ -26542,7 +26542,7 @@ }, "packages/backend": { "name": "@anythingmcp/backend", - "version": "0.55.23", + "version": "0.55.24", "license": "AGPL-3.0-only", "dependencies": { "@aws-sdk/client-s3": "3.1175.0", @@ -26820,7 +26820,7 @@ }, "packages/frontend": { "name": "@anythingmcp/frontend", - "version": "0.55.23", + "version": "0.55.24", "license": "AGPL-3.0-only", "dependencies": { "@radix-ui/react-dialog": "^1.3.1", diff --git a/package.json b/package.json index f2fe8d5c5..3dd049fb6 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "anythingmcp", - "version": "0.55.23", + "version": "0.55.24", "description": "Turn any REST/OpenAPI, SOAP/WSDL, GraphQL, OData or SQL API into MCP tools for Claude, ChatGPT and Copilot, no code. 977 pre-built adapters for ERP, e-commerce and more (SAP S/4HANA, SAP Business One, Odoo, Xentral, JTL-Wawi, Shopware, WooCommerce, Amazon Seller). Self-hosted, open source (AGPL-3.0).", "private": true, "license": "AGPL-3.0-only", diff --git a/packages/backend/package.json b/packages/backend/package.json index 504cc95a6..adc23f440 100644 --- a/packages/backend/package.json +++ b/packages/backend/package.json @@ -1,6 +1,6 @@ { "name": "@anythingmcp/backend", - "version": "0.55.23", + "version": "0.55.24", "description": "AnythingMCP — NestJS Backend + Dynamic MCP Server", "private": true, "license": "AGPL-3.0-only", diff --git a/packages/backend/src/common/process-vitals.service.ts b/packages/backend/src/common/process-vitals.service.ts index cc409cbfa..4efc7af94 100644 --- a/packages/backend/src/common/process-vitals.service.ts +++ b/packages/backend/src/common/process-vitals.service.ts @@ -1,10 +1,12 @@ import { Injectable, Logger, OnModuleDestroy, OnModuleInit } from '@nestjs/common'; import { mkdirSync, statSync } from 'node:fs'; import { join } from 'node:path'; -import { monitorEventLoopDelay, IntervalHistogram } from 'node:perf_hooks'; +import { monitorEventLoopDelay, IntervalHistogram, PerformanceObserver } from 'node:perf_hooks'; import * as v8 from 'node:v8'; import { evaluateHeap, + gcKind, + GcWindow, HeapPolicy, HeapSample, HeapState, @@ -70,7 +72,8 @@ const mb = (n: number | undefined) => (n === undefined ? undefined : Math.round( * What it does each tick: * * 1. read memory, the heap limit, the cgroup limit, event-loop delay, - * active handles and the live gauges other modules maintain; + * garbage-collection pauses by kind, active handles and the live gauges + * other modules maintain; * 2. log them as one structured line, so the trend before any incident is * in the log rather than reconstructed from `docker stats` afterwards; * 3. warn once when the heap crosses HEAP_WARN_PERCENT; @@ -90,6 +93,9 @@ export class ProcessVitalsService implements OnModuleInit, OnModuleDestroy { private readonly logger = new Logger(ProcessVitalsService.name); private timer?: ReturnType; private loopDelay?: IntervalHistogram; + private gcObserver?: PerformanceObserver; + /** Public so tests can feed collections without a real GC. */ + readonly gc = new GcWindow(); private state: HeapState = { ...INITIAL_HEAP_STATE }; private exitRequested = false; private rssLimit: number | undefined; @@ -109,6 +115,17 @@ export class ProcessVitalsService implements OnModuleInit, OnModuleDestroy { } this.loopDelay = monitorEventLoopDelay({ resolution: 20 }); this.loopDelay.enable(); + try { + this.gcObserver = new PerformanceObserver((list) => { + for (const entry of list.getEntries()) { + this.gc.record(gcKind((entry as { detail?: { kind?: unknown } }).detail?.kind), entry.duration); + } + }); + this.gcObserver.observe({ entryTypes: ['gc'] }); + } catch (err) { + // Diagnostics only: a runtime without GC entries still gets its vitals. + this.logger.warn(`GC observer not available: ${(err as Error)?.message ?? err}`); + } this.rssLimit = this.collector.rssLimit(); const limit = this.collector.heapLimit(); @@ -128,6 +145,7 @@ export class ProcessVitalsService implements OnModuleInit, OnModuleDestroy { onModuleDestroy(): void { if (this.timer) clearInterval(this.timer); this.loopDelay?.disable(); + this.gcObserver?.disconnect(); } /** One tick. Never throws: a diagnostics failure must not become an outage. */ @@ -176,6 +194,7 @@ export class ProcessVitalsService implements OnModuleInit, OnModuleDestroy { activeResources: resources.length, activeByType: byType, eventLoop: loop, + gc: this.gc.snapshotAndReset(), gauges: processGauges.snapshot(), }; // An object message: nestjs-pino merges it into the JSON line, so every diff --git a/packages/backend/src/common/process-vitals.spec.ts b/packages/backend/src/common/process-vitals.spec.ts index 6410f80bf..92baec999 100644 --- a/packages/backend/src/common/process-vitals.spec.ts +++ b/packages/backend/src/common/process-vitals.spec.ts @@ -1,5 +1,7 @@ import { evaluateHeap, + gcKind, + GcWindow, heapStatus, HeapPolicy, INITIAL_HEAP_STATE, @@ -227,6 +229,26 @@ describe('ProcessGauges', () => { }); }); +describe('GcWindow', () => { + it('counts collections by kind, keeps the longest, and starts over after a snapshot', () => { + const gc = new GcWindow(); + gc.record('major', 1200.4); + gc.record('major', 8100.2); + gc.record('minor', 3.2); + gc.record('minor', NaN); + gc.record('minor', -1); + expect(gc.snapshotAndReset()).toEqual({ + major: { count: 2, totalMs: 9301, maxMs: 8100 }, + minor: { count: 1, totalMs: 3, maxMs: 3 }, + }); + expect(gc.snapshotAndReset()).toEqual({}); + }); + + it('maps perf_hooks GC kinds', () => { + expect([1, 4, 8, 16, undefined].map(gcKind)).toEqual(['minor', 'major', 'incremental', 'other', 'other']); + }); +}); + describe('ProcessVitalsService.tick', () => { function service(samples: Array<{ heapPct: number; rss?: number }>, overrides: Partial = {}) { const svc = new ProcessVitalsService(); @@ -267,6 +289,20 @@ describe('ProcessVitalsService.tick', () => { expect(typeof line.vitals.rssPercent).toBe('number'); expect(line.vitals.activeByType).toEqual({ TCPSocketWrap: 2, Timeout: 1 }); expect(typeof line.vitals.gauges).toBe('object'); + expect(line.vitals.gc).toEqual({}); + }); + + it('reports the GC pauses of the interval once', async () => { + const { svc, log } = service([{ heapPct: 40 }]); + svc.gc.record('major', 1500); + svc.gc.record('minor', 4); + await svc.tick(); + await svc.tick(); + expect(log.log.mock.calls[0][0].vitals.gc).toEqual({ + major: { count: 1, totalMs: 1500, maxMs: 1500 }, + minor: { count: 1, totalMs: 4, maxMs: 4 }, + }); + expect(log.log.mock.calls[1][0].vitals.gc).toEqual({}); }); it('pauses to flush the log before writing the snapshot, writes once, and requests exit once', async () => { diff --git a/packages/backend/src/common/process-vitals.ts b/packages/backend/src/common/process-vitals.ts index 64caaff42..91bbec9c8 100644 --- a/packages/backend/src/common/process-vitals.ts +++ b/packages/backend/src/common/process-vitals.ts @@ -299,3 +299,55 @@ export class ProcessGauges { } export const processGauges = new ProcessGauges(); + +/** What one garbage collection was, as far as the vitals line cares. */ +export type GcKind = 'major' | 'minor' | 'incremental' | 'other'; + +export interface GcKindStats { + count: number; + totalMs: number; + maxMs: number; +} + +/** + * Garbage-collection pauses since the last vitals line. + * + * The event-loop delay in the vitals line says THAT the loop stalled; it + * cannot say why. On Cloud the long stalls (1-2 s with a 4 GB heap, up to + * 8 s with 6 GB, 2026-12-06) lined up with old-space collections, but that + * was read off heap sizes before and after, 30 s apart. Counting the + * collections themselves, by kind, makes the next heap or semi-space change + * a measurement instead of a guess: `major` is a stop-the-world old-space + * collection, `minor` a young-generation scavenge. + */ +export class GcWindow { + private stats = new Map(); + + record(kind: GcKind, durationMs: number): void { + if (!Number.isFinite(durationMs) || durationMs < 0) return; + const s = this.stats.get(kind) ?? { count: 0, totalMs: 0, maxMs: 0 }; + s.count += 1; + s.totalMs += durationMs; + if (durationMs > s.maxMs) s.maxMs = durationMs; + this.stats.set(kind, s); + } + + /** The window so far, rounded to whole milliseconds; then starts a new one. */ + snapshotAndReset(): Partial> { + const out: Partial> = {}; + for (const [kind, s] of this.stats) { + out[kind] = { count: s.count, totalMs: Math.round(s.totalMs), maxMs: Math.round(s.maxMs) }; + } + this.stats = new Map(); + return out; + } +} + +/** Map a `PerformanceEntry.detail.kind` of a `gc` entry (perf_hooks constants) to a GcKind. */ +export function gcKind(kind: unknown): GcKind { + // NODE_PERFORMANCE_GC_MINOR = 1, _MAJOR = 4, _INCREMENTAL = 8, _WEAKCB = 16. + if (kind === 4) return 'major'; + if (kind === 1) return 'minor'; + if (kind === 8) return 'incremental'; + return 'other'; +} diff --git a/packages/frontend/package.json b/packages/frontend/package.json index b2f51600b..490beebcb 100644 --- a/packages/frontend/package.json +++ b/packages/frontend/package.json @@ -1,6 +1,6 @@ { "name": "@anythingmcp/frontend", - "version": "0.55.23", + "version": "0.55.24", "description": "AnythingMCP — Next.js Admin UI", "private": true, "license": "AGPL-3.0-only", diff --git a/server.json b/server.json index 3cb9ace17..511b837c8 100644 --- a/server.json +++ b/server.json @@ -7,7 +7,7 @@ "url": "https://github.com/HelpCode-ai/anythingmcp", "source": "github" }, - "version": "0.55.23", + "version": "0.55.24", "websiteUrl": "https://anythingmcp.com", "icons": [ { diff --git a/start.sh b/start.sh index 03d2a82d1..221c86681 100644 --- a/start.sh +++ b/start.sh @@ -62,7 +62,20 @@ REPORT_FLAGS="" if node --report-exclude-env -e 0 >/dev/null 2>&1; then REPORT_FLAGS="--report-on-fatalerror --report-exclude-env --report-compact --report-directory=${HEAP_SNAPSHOT_DIR:-/tmp}" fi -BACKEND_CMD="node --max-old-space-size=${NODE_MAX_OLD_SPACE_MB:-2048} ${REPORT_FLAGS} dist/src/main.js" +# Young generation. V8's default semi-space (16 MB) fills several times a +# second under load, so objects that live only as long as one tool call (a +# second or two) survive two scavenges and are promoted to the old space, +# which then needs frequent stop-the-world collections: on Cloud, 1-2 s every +# few minutes with a 4 GB heap, up to 8 s with 6 GB (2026-12-06). A larger +# semi-space lets request garbage die young. Opt-in via NODE_MAX_SEMI_SPACE_MB +# (MB, digits only); unset or 0 keeps V8's default. Costs about three times +# its value in RSS. +SEMI_SPACE_FLAG="" +case "${NODE_MAX_SEMI_SPACE_MB:-}" in + ''|0|*[!0-9]*) ;; + *) SEMI_SPACE_FLAG="--max-semi-space-size=${NODE_MAX_SEMI_SPACE_MB}" ;; +esac +BACKEND_CMD="node --max-old-space-size=${NODE_MAX_OLD_SPACE_MB:-2048} ${SEMI_SPACE_FLAG} ${REPORT_FLAGS} dist/src/main.js" case "$MODE" in backend)