fix(mcp): опрос больше не создаёт AsyncLocalStorage на каждый вызов

Фабрики аренды обслуживания и production-зависимостей опроса создавали
по экземпляру AsyncLocalStorage на каждую сессию. Node держит включённые
экземпляры вечно и копирует каждый в каждый асинхронный ресурс, поэтому
опрос замедлялся и к ~170 операциям исчерпывал кучу (abort на Linux B2).
Теперь один экземпляр на процесс и свой ключ у каждой фабрики.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
DenozordecandClaude Opus 5.5 committed 2026-11-20 14:28:05 +07:00
1 parent dee79f35b7
commit 2999881586
6 files changed
+52 -9

No files matched your search

@@ -0,0 +1,21 @@
import assert from "node:assert/strict"
import { test } from "node:test"
import { scopedAsyncStorage } from "./scoped-async-storage.js"
test("nested owners see their own values, siblings and outer scopes do not leak", async () => {
const a = scopedAsyncStorage<string>(), b = scopedAsyncStorage<string>()
assert.equal(a.getStore(), undefined)
await a.run("a1", async () => {
await b.run("b1", async () => {
await new Promise(resolve => setImmediate(resolve))
assert.equal(a.getStore(), "a1")
assert.equal(b.getStore(), "b1")
a.run("a2", () => { assert.equal(a.getStore(), "a2"); assert.equal(b.getStore(), "b1") })
assert.equal(a.getStore(), "a1")
})
assert.equal(b.getStore(), undefined)
const sibling = scopedAsyncStorage<string>()
assert.equal(sibling.getStore(), undefined)
})
assert.equal(a.getStore(), undefined)
})
@@ -0,0 +1,15 @@
import { AsyncLocalStorage } from "node:async_hooks"
// Node keeps every enabled AsyncLocalStorage for the life of the process and copies each one into
// every new async resource, so a factory that runs per request must not create its own instance.
const shared = new AsyncLocalStorage<ReadonlyMap<object, unknown>>()
/** Per-factory async context (run/getStore only) backed by one process-wide AsyncLocalStorage.
* Nested contexts of different owners stay visible to each owner, as with separate instances. */
export function scopedAsyncStorage<T>() {
const key = {}
return {
getStore: (): T | undefined => shared.getStore()?.get(key) as T | undefined,
run: <R>(store: T, callback: () => R): R => shared.run(new Map(shared.getStore()).set(key, store), callback),
}
}
@@ -1,5 +1,5 @@
import { SERVER_POLL_WALL_BUDGET_MS } from "./server-poll-limits.js"
import { AsyncLocalStorage } from "node:async_hooks"
import { scopedAsyncStorage } from "./scoped-async-storage.js"
import { PARTITION_SPECS } from "../db/partitions.js"
import type { ServerPollSqlConnection } from "./server-poll-production.js"
import type { ServerPollBoundaryCoordinator } from "./server-poll-boundary.js"
@@ -61,7 +61,7 @@ export const isServerPollJournalOwner=(owner:ServerPollJournalOwner)=>journalOwn
* transaction. PostgreSQL shared advisory acquisition in its row triggers is
* reentrant on that same backend. No GUC, pool patch or bypass token exists. */
export function createServerPartitionMaintenanceLease(deps:ServerPartitionMaintenanceLeaseDependencies){
const now=deps.now??Date.now,held=new AsyncLocalStorage<Holder>(),transactions=new AsyncLocalStorage<TransactionScope>(),journal=new AsyncLocalStorage<Holder>()
const now=deps.now??Date.now,held=scopedAsyncStorage<Holder>(),transactions=scopedAsyncStorage<TransactionScope>(),journal=scopedAsyncStorage<Holder>()
const fail=(unknown=false):never=>{throw new ServerPartitionLeaseError(unknown)}
const checkOptions=(options:ServerPartitionTransactionOptions)=>{if(!Number.isSafeInteger(options.deadlineAt)||options.deadlineAt<=now()||options.deadlineAt-now()>SERVER_POLL_WALL_BUDGET_MS||options.signal?.aborted)fail()}
const local=(holder:Holder,options:ServerPartitionTransactionOptions)=>{
@@ -1,5 +1,5 @@
/** Explicit private v4 production assembly; no public registration or admission issuance. */
import { AsyncLocalStorage } from "node:async_hooks"
import { scopedAsyncStorage } from "./scoped-async-storage.js"
import { createServerPollProductionDependencies, type ServerPollProductionInput } from "./server-poll-production.js"
import { pollProblem } from "./server-poll-execution-model.js"
import { createServerPollExecution, type ServerPollDependencies } from "./server-poll-execution.js"
@@ -13,7 +13,7 @@ export function createAtomicServerPollProductionDependencies(input: ServerPollPr
const transaction = input.io?.transaction
if (typeof transaction !== "function") return pollProblem("STATE_UNAVAILABLE", "Atomic maintenance requires the original transaction owner")
const original = createServerPollProductionDependencies({ ...input, approvalProtocol: "configuration-epoch-v3" })
const held = new AsyncLocalStorage<Scope>(), request = structuredClone(input.request), now = input.now ?? Date.now
const held = scopedAsyncStorage<Scope>(), request = structuredClone(input.request), now = input.now ?? Date.now
const fail = (): never => pollProblem("PERMISSION_DENIED", "Atomic candidate owner is absent, expired or changed")
const local = (scope: Scope) => { scope.signal?.throwIfAborted(); if (!scope.active || now() >= scope.deadlineAt) fail() }
const fence = async (scope: Scope) => {
@@ -2,7 +2,7 @@ import { carryPollError } from "./server-poll-error-provenance.js"
import { projectServerPollApprovalContext } from "./server-poll-approval-context.js"
import { assertServerPollSettingsEpochCatalog, SERVER_POLL_SETTINGS_EPOCH_INVENTORY_SQL, SERVER_POLL_SETTINGS_TABLES } from "./server-poll-settings-epoch.js"
import { SERVER_POLL_WALL_BUDGET_MS } from "./server-poll-limits.js"
import { AsyncLocalStorage } from "node:async_hooks"
import { scopedAsyncStorage } from "./scoped-async-storage.js"
import type { QueryConfig } from "pg"
import type { ServerPartitionTransaction } from "./server-partition-maintenance-lease.js"
import type { ServerPollBoundaryCoordinator } from "./server-poll-boundary.js"
@@ -168,7 +168,7 @@ export function createServerPollProductionDependencies(input:ServerPollProductio
if(!input.request||!Number.isSafeInteger(input.request.serverId)||input.request.serverId<=0||!/^[a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12}$/i.test(input.request.receiptId)||!input.journal||!["intent","acknowledge","claim","complete"].every(key=>typeof input.journal[key as keyof typeof input.journal]==="function")||typeof input.maintenanceLease!=="function"||typeof input.authorize!=="function")pollProblem("INVALID_INPUT","Нужны bound request, durable journal и global writer lease server poll")
const io=input.io??createServerPollProductionIo(),now=input.now??Date.now
const proof=input.proof??(async(value:unknown)=>{const security=await import("../modules/mcp/security.js");return security.privateSecretFingerprint(security.fingerprint(value),"server-poll-production-v1")})
const held=new AsyncLocalStorage<{active:boolean;ids:number[];authorityProof:string;context?:ServerPollContext}>()
const held=scopedAsyncStorage<{active:boolean;ids:number[];authorityProof:string;context?:ServerPollContext}>()
const bound=(request:ServerPollRequest)=>{if(request.serverId!==input.request.serverId||request.receiptId!==input.request.receiptId)pollProblem("STATE_CONFLICT","Request не принадлежит server poll adapter")}
const check=async(ids:number[],options:{signal?:AbortSignal;deadlineAt:number},expected?:string):Promise<ServerPollGrant>=>{
options.signal?.throwIfAborted();if(now()>=options.deadlineAt)pollProblem("ABORTED","Истёк deadline server poll SQL")
+10 -3
View File
@@ -263,9 +263,16 @@ B2 остаётся **одним непрерывным прогоном** (пе
- **Главная гипотеза: рост кучи V8 с каждой операцией.**
- Интервал между планами внутри волны (приближение времени операции) растёт: операции 2–18 — 5,1 с, 19–35 — 7,4 с, 36–53 — 11,7 с, 54–70 — 22,5 с. Дальше ~60 с: это уже темп освобождения 8 слотов, операции перестали идти пачками. Так выглядит нарастающее давление на сборщик мусора.
- Задержки архивов оставались ограниченными (медиана 26 с, максимум 84 с): разбор очереди работал до конца.
- Пик RSS (`peakRssKiB`): smoke Windows 233 МиБ на 2 операциях, волна Windows 253 МиБ на 22, Linux 13.11 274 МиБ на 28, B2 290 МиБ на 169. На Windows это около 1 МиБ на операцию.
- Предел кучи 240 МиБ (old 192 + semi 16) исчерпывается порядка 170 операций.
- Не доказано: нужна живая куча после GC по числу операций и разница двух снимков кучи по конструкторам.
- Пик RSS (`peakRssKiB`): smoke Windows 233 МиБ на 2 операциях, волна Windows 253 МиБ на 22, Linux 13.11 274 МиБ на 28, B2 290 МиБ на 169. (Оценка «около 1 МиБ на операцию» по RSS неверна: живая куча после GC растёт примерно на 0,15 МиБ на операцию, см. ниже.)
- **Причина установлена (локальная диагностика, 2026-11-20): утечка `AsyncLocalStorage` в продукте на каждый опрос.**
- Зонд через инспектор (`process._debugProcess`, без смены `execArgv` фикстуры) на полной фикстуре Windows. Живая куча после GC: 130 МиБ на 8 операциях, 134–137 МиБ на 43.
- Разница снимков кучи 8 → 43 операций: **+280 экземпляров `AsyncLocalStorage` и ровно +280 символов**, по 8 на операцию, плюс рост словарей свойств (`object properties`, +2 МБ).
- Механизм Node 22: каждый включённый `AsyncLocalStorage` навсегда остаётся в глобальном списке, и при создании каждого асинхронного ресурса Node копирует в ресурс хранилище каждого экземпляра. Стоимость каждого промиса растёт линейно с числом экземпляров. Отсюда рост времени операции на Linux (5 → 22 с) и пиковой кучи во время операций.
- Источники — фабрики, вызываемые на каждый опрос: `createServerPartitionMaintenanceLease` (3 экземпляра на сессию), `createServerPollProductionDependencies` (1), `createAtomicServerPollProductionDependencies` (1).
- **Достаточность доказана.** В работающую фикстуру (43 операции) впрыснуто 1300 включённых экземпляров, столько же набралось бы к ~170-й операции. Пик кучи без GC вырос со ~135 до 174 МиБ ещё в простое. В начале следующей волны: `FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory`, код 134 (SIGABRT) — тот же `abort()`, что на VPS.
- Утечка есть и в развёрнутом backend `mmapp-test`: каждый опрос сервера добавляет экземпляры, процесс деградирует до перезапуска.
- Второе отличие Linux (`autovacuum=off`, `shared_buffers=32MB` у PostgreSQL владельца, `durable.py:457–458`) пока не проверено. Это условие стенда, менять его — решение владельца.
- **Исправление:** `scopedAsyncStorage` (`backend/src/services/scoped-async-storage.ts`) — один `AsyncLocalStorage` на процесс, у каждой фабрики свой ключ в неизменяемой карте. Вложенные контексты разных владельцев видны так же, как при отдельных экземплярах; общее хранилище не экспортируется. Заменены 5 экземпляров в трёх фабриках опроса. Синглтоны процесса (охрана записи RouterOS, адаптеры проб, stdio) не трогались.
- **Решения, которые за владельцем:** поднять предел кучи или контейнера; изменить, что удерживает фикстура. Исправление в продукте — это новая сборка и переразвёртывание `mmapp-test`, значит, B1 повторяется.
- **Перед любым следующим Linux-прогоном** владелец должен сохранять код выхода, `OOMKilled`, сработавший `demand`, ограниченный хвост журнала приложения и по каждому heartbeat анонимную и файловую память cgroup и `pids.current`.