diff --git a/doc/muse-personal-agent.md b/doc/muse-personal-agent.md index 496bafb8e2d..75138fc82d1 100644 --- a/doc/muse-personal-agent.md +++ b/doc/muse-personal-agent.md @@ -121,3 +121,36 @@ node --test scripts/smoke/muse-qualification-report.test.mjs scripts/smoke/muse- Cloud must deploy the matching exact protocol manifest and preserve tenant authority. Its companion generator verifies parity with `packages/shared/src/muse-protocol.ts`. Current hosted coverage can retain receiver contacts while the tenant is idle. Without that coverage, a connected receiver inhibits tenant sleep. Unavailable ingress returns a retryable failure and never implies a delivered task. Retained contact pages for deleted bindings settle through their original exact acknowledgement. They never create new receiver-contact or verification evidence. A retired qualified OAuth binding still blocks sleep until its existing detector-removal requirement is satisfied; a Cloud retirement receipt does not confirm that the device hook stopped. Local quiet evidence alone does not prove deployed host or database suspension. + + +### Public signal resource bounds + +Public presence requests still check current binding, credential, company, +operator, agent and resource authority. A managed HTTP 200 confirms that its +contact has committed; overload never returns a substitute idle 200. The existing +in-flight contact flush can coalesce accepted requests, and each accepted +request waits for its own retained batch to persist. + +One receiver admission owner is shared across bindings in each App process. +It permits at most 32 concurrent signals and uses 60-second ingress windows: +60 admissions per binding, 1200 per request source and 6000 total, with at most 4096 +window keys. The source is the existing Express request-IP identity, not an +untrusted forwarding header. State expires lazily on ingress; no idle timer or +permission/response cache is added. These are abuse ceilings, not measured +capacity or a guarantee of availability at those rates. The normal five-second +detector schedule is 12 checks per minute, below the binding ceiling. + +Over-budget requests return 429 with Retry-After before database access or contact +ownership. A handoff or full in-flight budget returns retryable 503. The current +v9 detector retains its hook on these responses and backs off for 30 seconds; +only 410 disconnects it. Overload can therefore delay observation and make cadence +qualification incomplete; it does not manufacture successful presence evidence. + +Hosted handoff fences new local signal admission, joins its finite accepted +frontier and persists all retained contact debt. The fence remains held through +the actual local mirror receipt/cutover transaction and reopens after commit or +rollback. A permanent stop remains independent. Cloud's complete ACK may already +exist before local handoff; a failure keeps the normal pending publication and +five-second retry, without claiming a remote rollback. The finite admission +frontier does not cancel an already-issued SQL statement or promise instantaneous +backend cancellation. diff --git a/server/src/routes/muse.ts b/server/src/routes/muse.ts index dbcc48943a2..38b8d1b7188 100644 --- a/server/src/routes/muse.ts +++ b/server/src/routes/muse.ts @@ -68,7 +68,20 @@ export function museTransportRoutes(db:Db,publicOrigin?:string,options:{allowLeg } if(route.path.endsWith("/pair")) {if(!options.allowLegacyCredentials)throw notFound("Legacy test pairing is unavailable.");const value=musePairSchema.parse(req.body);res.json(await identity.pair(value.ticket,value.clientVersion));return;} if(route.path.endsWith("/refresh")) {if(!options.allowLegacyCredentials)throw notFound("Legacy test refresh is unavailable.");const value=museRefreshSchema.parse(req.body);res.json(await identity.refresh(value.refreshToken));return;} - if(route.path.endsWith("/signal")) {const bindingId=z.uuid().parse(req.get("X-Paperclip-Muse-Binding"));res.json(await receiver.signal(bindingId,musePublicOrigin(publicOrigin)+MUSE_RESOURCE_PATH));return;} + if(route.path.endsWith("/signal")) { + const bindingId=z.uuid().parse(req.get("X-Paperclip-Muse-Binding")); + // Match the existing OAuth source identity: Express owns proxy trust. + const source=req.ip??req.socket.remoteAddress??"unknown"; + try {res.json(await receiver.signal(bindingId,musePublicOrigin(publicOrigin)+MUSE_RESOURCE_PATH,source));} + catch(error){ + if(error instanceof HttpError&&error.status===429){ + const details=error.details as {retryAfterSeconds?:number}|undefined; + res.set("Retry-After",String(details?.retryAfterSeconds??60)); + } + throw error; + } + return; + } if(route.path.endsWith("/cleanup")) {const value=museCleanupSchema.parse(req.body);const subject=await authenticateWorker(req,"cleanup",true);res.json(await broker.cleanup(subject,value));return;} if(route.path.endsWith("/detector-cleanup")) {const value=museDetectorCleanupSchema.parse(req.body),subject=await authenticateWorker(req,"detector_cleanup");if(value.bindingId!==subject.bindingId||value.generation!==subject.generation)throw forbidden("Detector cleanup identity mismatch.");res.json(await broker.detectorCleanup(subject,"detectorRemoved" in value));return;} const query=route.path.endsWith("/queries")?museQuerySchema.safeParse(req.body):null; diff --git a/server/src/services/muse-receiver.ts b/server/src/services/muse-receiver.ts index 8f4ba683752..8ea89167548 100644 --- a/server/src/services/muse-receiver.ts +++ b/server/src/services/muse-receiver.ts @@ -7,6 +7,10 @@ import { assertMuseReceiverAuthority, assertMuseCurrentAuthority, inspectMuseCon import { canConfigureAgentConnection } from "../modules/agent-lifecycle/index.js"; import { HttpError } from "../errors.js"; const PERSISTENCE_LAG_MS=30_000; +// Per-process abuse ceilings, not capacity guarantees. A normal detector checks +// every five seconds (12/minute); the binding budget leaves fivefold headroom. +const SIGNAL_WINDOW_MS=60_000, SIGNAL_BINDING_LIMIT=60, SIGNAL_SOURCE_LIMIT=1200; +const SIGNAL_GLOBAL_LIMIT=6000, SIGNAL_MAX_INFLIGHT=32, SIGNAL_MAX_KEYS=4096; const instances=new WeakMap>(); export function museReceiver(db:Db) {let receiver=instances.get(db);if(!receiver){receiver=createReceiver(db);instances.set(db,receiver);}return receiver;} function createReceiver(db:Db) { @@ -15,6 +19,33 @@ function createReceiver(db:Db) { const previous=new Map(); let flushPromise:Promise|undefined; const admittedSignals=new Set>(); + // One receiver is cached per production Db, shared by every binding/router. + // No authority or response is cached. Expiry is checked only on ingress. + const signalWindows=new Map(); + let nextWindowSweep=0, handoffOwners=0; + function admitSignal(bindingId:string,source:string) { + if(admittedSignals.size>=SIGNAL_MAX_INFLIGHT)throw new HttpError(503,"Muse receiver is busy."); + const now=Date.now(); + if(now>=nextWindowSweep){ + for(const [key,value]of signalWindows)if(value.until<=now)signalWindows.delete(key); + nextWindowSweep=now+SIGNAL_WINDOW_MS; + } + const budgets:[[string,number],[string,number],[string,number]]=[ + ["global",SIGNAL_GLOBAL_LIMIT],["binding:"+bindingId,SIGNAL_BINDING_LIMIT],["source:"+source,SIGNAL_SOURCE_LIMIT], + ]; + // Preflight every budget and required key before mutating counters/state; + // a denied request cannot fill the map with unused zero-count entries. + const entries=budgets.map(([key,limit])=>{ + const existing=signalWindows.get(key); + const value=existing&&existing.until>now?existing:{until:now+SIGNAL_WINDOW_MS,count:0}; + if(value.count>=limit)throw new HttpError(429,"Muse signal admission is temporarily limited.", + {retryAfterSeconds:Math.max(1,Math.ceil((value.until-now)/1000))}); + return{key,value,isNew:!existing}; + }); + if(signalWindows.size+entries.filter(entry=>entry.isNew).length>SIGNAL_MAX_KEYS) + throw new HttpError(429,"Muse signal admission is temporarily limited.",{retryAfterSeconds:60}); + for(const {key,value}of entries){value.count++;signalWindows.set(key,value);} + } let stopping=false; let stopPromise:Promise|undefined; async function flush() { @@ -132,19 +163,33 @@ function createReceiver(db:Db) { } return result; } - function signal(bindingId:string,expectedResource?:string) { - if(stopping)return Promise.reject(new HttpError(503,"Muse receiver is stopping.")); + function signal(bindingId:string,expectedResource?:string,source="local") { + if(stopping||handoffOwners)return Promise.reject(new HttpError(503,"Muse receiver is temporarily unavailable.")); + try {admitSignal(bindingId,source);}catch(error){return Promise.reject(error);} const admitted=signalOnce(bindingId,expectedResource); admittedSignals.add(admitted); void admitted.then(()=>admittedSignals.delete(admitted),()=>admittedSignals.delete(admitted)); return admitted; } - async function prepareHostedHandoff(signal:AbortSignal) { - do { + async function prepareHostedHandoff(signal:AbortSignal,completeCutover?:()=>Promise) { + // Fence synchronously before the snapshot. New requests own no contact and + // receive a retryable503; overlapping handoffs cannot reopen one another. + handoffOwners++; + try { signal.throwIfAborted(); await Promise.allSettled([...admittedSignals]); + signal.throwIfAborted(); + // The first join may belong to a timer's previously captured batch. + // With admission fenced, the next flush owns the finite remaining batch. await flush(); - } while(admittedSignals.size||pending.size); + await flush(); + signal.throwIfAborted(); + if(admittedSignals.size||pending.size)throw new Error("Muse handoff still owns contact persistence debt."); + // The existing mirror owner keeps its authority/revision checks. Once + // entered, await its actual commit/rollback even if this signal aborts. + // This closure must not await new signal admission from this receiver. + if(completeCutover)await completeCutover(); + } finally {handoffOwners--;} } let timer:NodeJS.Timeout|undefined; function start() { diff --git a/server/src/services/public-mcp/client-mirror-sync.ts b/server/src/services/public-mcp/client-mirror-sync.ts index 2be565f43a4..3015da95b30 100644 --- a/server/src/services/public-mcp/client-mirror-sync.ts +++ b/server/src/services/public-mcp/client-mirror-sync.ts @@ -153,9 +153,8 @@ export function startMcpClientMirrorSync(db: Db, coordinator: Pick{ + const commitCutover=async()=>{await db.transaction(async tx=>{ await tx.execute(sql`SELECT pg_advisory_xact_lock(736721042)`); const [current]=await tx.select().from(state).where(eq(state.id,"public")).for("update"); assertCurrentAuthority(); @@ -174,7 +173,12 @@ export function startMcpClientMirrorSync(db: Db, coordinator: Pick