Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: let in-flight API requests finish before the server shuts down (#8323)

[._.]/ Adam Eivy6a724cc696f1
diff --git a/server/lib/README.md b/server/lib/README.md
index 1d5281b3fc..151d62fc34 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -390,6 +390,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `commandSecurity.js` | Two allowlists, one parser. `validateCommand(cmd)` gates the OPERATOR-driven runner against `ALLOWED_COMMANDS` (+ `validatePm2Command(args)`, which rejects daemon-wide `pm2 kill`/`startup`/`unstartup` and `<verb> all`). `validateUnattendedCommand(cmd)` gates the UNATTENDED lane (Layered Intelligence `cmd` sources) against the far narrower `UNATTENDED_READONLY_COMMANDS` — read-only inspection binaries only, no `npx`/`node`/`python`/`pip`/`curl`/`wget`/`brew`, since those execute network code with no shell metacharacter — then applies a per-binary SUBCOMMAND gate to the multi-purpose survivors, so `git reset --hard` / `git commit`, `find -delete` / `-exec`, and `gh`/`glab` writes (`api -X POST`, `pr merge`) are rejected while `git log`, `find -name` and `gh pr list` pass. Both share one parse + `DANGEROUS_SHELL_CHARS` body. Mirrored by the `agentGuard/` PATH shim for agentic paths. |
| `detachedSpawn.js` | `spawnDetached(bin, args, {controlDir,env,cwd,killProcessGroup?})` → ChildProcess-like handle for a long media job that SURVIVES `pm2 restart portos-server`. A pure-`sh` double-fork reparents the job to init (escaping pm2's PPID-based TreeKill — `detached:true` alone doesn't, since it only changes the process group); the server tails on-disk log files for `stdout`/`stderr`/`close`. Group-kill mode persists a marker so cancel, reattach, and orphan reaping terminate a group-leader wrapper plus every runtime child together. Windows reaches the same place through a powershell supervisor started by a launcher that exits (never `detached:true`, which there means DETACHED_PROCESS and leaves a console host no console to run in), writing the same control files — so both platforms survive the restart AND take the runner's children down on cancel (`taskkill /T /F` there, the process group on POSIX). Used by loraTraining + videoGen. Also exports `reattachDetached(controlDir)` / `isReattachable(controlDir)` to RE-ATTACH a survivor after a restart, `isDetachedRunning(controlDir, expectedProcess?)` with optional executable/argument validation for fixed-command control dirs, and `reapDetached` to checkpoint-kill one when re-attach isn't possible. |
| `hostShutdown.js` | Tells "PortOS was restarted out from under a running agent" apart from "the agent failed" (#3202). `markHostShuttingDown()` / `isHostShuttingDown()` are the in-process latch the SIGTERM/SIGINT handler sets first thing; `shouldAbandonForHostShutdown({sentinelPresent,terminatedByUser,paused})` keeps every spawn path on the same preserve-vs-finalize policy. `writeHostShutdownMarker({agentIds,signal})` / `readHostShutdownMarker()` / `clearHostShutdownMarker()` persist that verdict to `data/cos/host-shutdown.json` so the NEXT boot's orphan sweep can requeue those agents as *interrupted* — no orphan-retry charge, no 30-minute cooldown. All non-throwing: a missing marker degrades to the ordinary orphan path. |
+| `httpDrain.js` | `createHttpDrain(servers)` tracks every ordinary request the HTTP listeners accept; `begin(windowMs)` is the synchronous shutdown step that stops intake on all of them (`server.close()` plus a 503 `Connection: close` gate for requests arriving on still-open keep-alive sockets), turns off keep-alive on in-flight responses, drops open SSE streams, and resolves `{ remaining }` once accepted requests finish or the window ends (#8323). |
| `execGit.js` | `execGit(args, cwd, options)` and `execGitSafe(args, cwd, options)` shared process boundary for Git operations, worktrees, and `services/forgeAuth.js` credential resolution. The safe variant converts rejections into `{ exitCode: 1, stdout: '', stderr }`; `services/git.js` re-exports both for compatibility. `cwd` is REQUIRED — it rejects on a missing/blank one rather than letting `spawn` fall back to `process.cwd()` and run git against PortOS's own checkout (#4554). |
| `ffmpeg.js` | Shared ffmpeg helpers (videoGen + videoTimeline). Includes `probeFrameCount(videoPath)` (metadata `nb_frames`, falling back to a real `-count_frames` pass — expensive, so call it once per file) and `trimVideoFromFrame(videoPath, outPath, {startFrame, fps})` — a frame-EXACT head cut via the `trim` filter (an `-ss` seek can drift a frame, which reads as a stutter at a stitch seam), keeping audio in sync with `atrim` when the clip has a soundtrack and taking `-an` when it doesn't. Re-encodes by necessity, so a later concat must re-encode too; `outPath` may equal the input (temp-file + rename install). Used by the chained-render context window — see `videoContinuity.js`. `buildTrimConcatArgs({inputs, outPath, width, height, fps, withAudio})` builds the argv for the other half of that job: a concat that drops leading frames from some of its inputs inside a `filter_complex` graph, so the cuts ride along with the timeline encode instead of costing one pre-encode per clip (pass `withAudio` only when EVERY input has an audio stream — check with `hasAudioStream`). `H264_ENCODE_ARGS` / `AAC_ENCODE_ARGS` are the shared encode profile: clips produced by different paths here get concatenated together, so a mismatch shows up as one segment graded differently from its neighbours — spread these rather than re-typing the flags. Every re-encode here also pins BT.709: `BT709_CONTAINER_ARGS` (the `colr` atom, always emitted) plus `bt709TagFilter()` → the `BT709_TAG_FILTER` `setparams=…` string, or `null` on an ffmpeg without that filter (`supportsSetparamsFilter()` probes `-filters` once per process; `null` = not probed, and a probe that couldn't run stays uncached). Both halves are required — from ffmpeg 8 the encoder reads color properties off the FRAMES, silently overriding the container flags, so a flags-only output decodes washed-out. `buildTrimConcatArgs` takes the filter as its `colorTagFilter` option rather than probing, to stay pure. `installEncodedVideo(tmpPath, targetPath, label)` is the shared in-place install: move the original aside to a `.bak` on Windows (where `fs.rename` refuses an existing destination), rename the new file over it, and restore the backup — plus unlink the temp — on any failure, returning `{ok:true,outPath}` / `{ok:false,reason}` so the worst case is "skipped", never "the video is gone". Use it for EVERY replace-a-video-with-its-re-encode path; `pipeline/audioMux.js` is the out-of-module caller. |
| `forgeAccessErrors.js` | `isForgeNoAccessError(err)` / `isForgeNoAccessMessage(text)` / `logForgeNoAccessOnce(scope, repoSpec, detail)` / `forgeNoAccessRemedy(repoSpec)` — tells a PERMANENT `gh` no-access 404 (`Could not resolve to a Repository`, `HTTP 404`) apart from a transient blip. `execGh` stamps `ghNoAccess` on the rejection and keeps it OUT of the consecutive-failure backoff (which caps at 15 min and then re-fires forever), and the polling jobs (`branchReconcile`, `prWatcher`) narrate it exactly once per scope+repo per process with a remedy line instead of once per tick. `__resetForgeNoAccessLog()` is the test seam. |
diff --git a/server/lib/httpDrain.js b/server/lib/httpDrain.js
new file mode 100644
index 0000000000..1d3cbcd70c
--- /dev/null
+++ b/server/lib/httpDrain.js
@@ -0,0 +1,88 @@
+// Graceful request drain for the HTTP listeners at shutdown (#8323).
+//
+// `createHttpDrain(servers)` starts tracking every ordinary request the given
+// servers accept (upgrades never emit 'request', so WebSockets are not tracked —
+// their owners close them). `begin(windowMs)` is the synchronous "stop intake"
+// step the signal handler calls before it first awaits:
+//
+// - each listener stops accepting connections (`server.close()`, which also
+// drops idle keep-alive sockets);
+// - every request listener is swapped for a 503 + `Connection: close` refusal,
+// so a request that arrives on a still-open keep-alive socket is never
+// handed to the app — `server.close()` alone keeps serving those;
+// - in-flight responses are told not to keep their socket alive, and an open
+// SSE stream (which never ends on its own) is dropped outright.
+//
+// It returns a promise that resolves once every accepted request has finished,
+// or at the window's deadline, with `{ remaining }` — the count still running.
+// Force-closing whatever remains (`closeAllConnections()`) is the caller's next
+// step. The deadline timer is unref'd so it never holds the process open.
+
+const EVENT_STREAM = /^content-type:\s*text\/event-stream/im;
+
+// `writeHead(status, headersObject)` writes the header block without populating
+// `getHeader()`, so fall back to the serialized header once it has been sent.
+const isEventStream = (res) =>
+ /text\/event-stream/i.test(String(res.getHeader('content-type') ?? ''))
+ || EVENT_STREAM.test(res._header || '');
+
+const refuseDuringDrain = (req, res) => {
+ res.shouldKeepAlive = false;
+ res.writeHead(503, { 'Content-Type': 'application/json', Connection: 'close', 'Retry-After': '5' });
+ res.end(JSON.stringify({ error: 'Server is shutting down', code: 'SHUTTING_DOWN' }));
+};
+
+export const createHttpDrain = (servers) => {
+ const listeners = servers.filter(Boolean);
+ const inFlight = new Set();
+ let draining = null;
+ let settle = null;
+
+ const settleIfIdle = () => {
+ if (settle && inFlight.size === 0) settle();
+ };
+
+ const track = (req, res) => {
+ inFlight.add(res);
+ res.once('close', () => {
+ inFlight.delete(res);
+ if (!draining) return;
+ // A response whose headers went out before the drain began still
+ // advertised keep-alive; its socket turns idle now, so drop it before a
+ // next request can arrive on it.
+ setImmediate(() => { for (const server of listeners) server.closeIdleConnections?.(); });
+ settleIfIdle();
+ });
+ };
+ for (const server of listeners) server.prependListener('request', track);
+
+ const begin = (windowMs) => {
+ if (draining) return draining;
+ draining = new Promise((resolve) => {
+ let timer = null;
+ settle = () => {
+ clearTimeout(timer);
+ settle = null;
+ resolve({ remaining: inFlight.size });
+ };
+ timer = setTimeout(() => settle?.(), windowMs);
+ timer.unref?.();
+ });
+
+ for (const server of listeners) {
+ server.removeAllListeners('request');
+ server.on('request', refuseDuringDrain);
+ // Already-closed (never listened) is fine — the refusal gate above is
+ // what matters for sockets that are still open.
+ server.close(() => {});
+ }
+ for (const res of inFlight) {
+ if (isEventStream(res)) res.socket?.destroy();
+ else if (!res.headersSent) res.shouldKeepAlive = false;
+ }
+ settleIfIdle();
+ return draining;
+ };
+
+ return { begin };
+};
diff --git a/server/lib/httpDrain.test.js b/server/lib/httpDrain.test.js
new file mode 100644
index 0000000000..d7bba71ffd
--- /dev/null
+++ b/server/lib/httpDrain.test.js
@@ -0,0 +1,116 @@
+/**
+ * Shutdown drain contract (#8323), exercised against real listeners because the
+ * behaviour under test is Node's own connection handling: `server.close()` alone
+ * keeps serving requests on already-open keep-alive sockets, and the drain has to
+ * both let accepted work finish and keep new work out.
+ */
+import { describe, it, expect, afterEach } from 'vitest';
+import http from 'node:http';
+import net from 'node:net';
+import { createHttpDrain } from './httpDrain.js';
+
+const opened = [];
+afterEach(() => {
+ for (const server of opened.splice(0)) server.closeAllConnections();
+});
+
+const listen = async (handler) => {
+ const server = http.createServer(handler);
+ opened.push(server);
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
+ return { server, port: server.address().port };
+};
+
+const request = (port, path, agent = false) => new Promise((resolve) => {
+ http.get({ host: '127.0.0.1', port, path, agent }, (res) => {
+ let body = '';
+ res.on('data', (chunk) => { body += chunk; });
+ res.on('end', () => resolve({ status: res.statusCode, connection: res.headers.connection, body }));
+ res.on('error', (err) => resolve({ error: err.code }));
+ }).on('error', (err) => resolve({ error: err.code }));
+});
+
+// A raw connection whose request is only partly written — the server has
+// accepted the socket, but the request is not complete until `finish()`.
+const openPartialRequest = async (port, path) => {
+ const socket = net.connect(port, '127.0.0.1');
+ await new Promise((resolve) => socket.once('connect', resolve));
+ socket.write(`GET ${path} HTTP/1.1\r\nHost: localhost\r\n`);
+ let raw = '';
+ socket.on('data', (chunk) => { raw += chunk; });
+ const closed = new Promise((resolve) => socket.once('close', () => resolve(raw)));
+ return { finish: () => { socket.write('\r\n'); return closed; } };
+};
+
+const deferred = () => {
+ let resolve;
+ const promise = new Promise((r) => { resolve = r; });
+ return { promise, resolve };
+};
+
+describe('createHttpDrain', () => {
+ it('lets an accepted request finish while both listeners refuse new requests', async () => {
+ const handled = [];
+ const release = deferred();
+ const handler = async (req, res) => {
+ handled.push(req.url);
+ if (req.url === '/slow') await release.promise;
+ res.end(`done ${req.url}`);
+ };
+ const primary = await listen(handler);
+ const mirror = await listen(handler);
+ const drain = createHttpDrain([primary.server, mirror.server, null]);
+
+ // A keep-alive client, so the response must actively opt out of reuse.
+ const keepAlive = new http.Agent({ keepAlive: true });
+ const slow = request(primary.port, '/slow', keepAlive);
+ const pending = await openPartialRequest(mirror.port, '/late');
+ while (!handled.includes('/slow')) await new Promise((r) => setImmediate(r));
+
+ let drained = null;
+ drain.begin(5000).then((result) => { drained = result; });
+
+ // New connections are refused on both listeners, and a request completed on
+ // a socket accepted before the drain never reaches the handler.
+ expect(await request(primary.port, '/new')).toEqual({ error: 'ECONNREFUSED' });
+ expect(await request(mirror.port, '/new')).toEqual({ error: 'ECONNREFUSED' });
+ const refused = await pending.finish();
+ expect(refused).toMatch(/^HTTP\/1\.1 503 /);
+ expect(refused).toMatch(/connection: close/i);
+ expect(drained).toBeNull();
+
+ release.resolve();
+ expect(await slow).toEqual({ status: 200, connection: 'close', body: 'done /slow' });
+ await new Promise((r) => setImmediate(r));
+ expect(drained).toEqual({ remaining: 0 });
+ expect(handled).toEqual(['/slow']);
+ keepAlive.destroy();
+ });
+
+ it('drops event streams at once and stops waiting on stuck requests at the deadline', async () => {
+ const { server, port } = await listen((req, res) => {
+ if (req.url === '/events') {
+ res.writeHead(200, { 'Content-Type': 'text/event-stream' });
+ res.write('data: hello\n\n');
+ }
+ // '/stuck' never answers.
+ });
+ const drain = createHttpDrain([server]);
+
+ const events = new Promise((resolve) => {
+ http.get({ host: '127.0.0.1', port, path: '/events', agent: false }, (res) => {
+ res.once('data', () => resolve({ closed: new Promise((done) => res.once('close', done)) }));
+ });
+ });
+ const { closed: streamClosed } = await events;
+ const stuck = request(port, '/stuck');
+ await new Promise((r) => setTimeout(r, 20));
+
+ const drained = drain.begin(100);
+ await streamClosed;
+ expect(await drained).toEqual({ remaining: 1 });
+
+ server.closeAllConnections();
+ expect(await stuck).toEqual({ error: 'ECONNRESET' });
+ });
+});
diff --git a/server/lib/index.js b/server/lib/index.js
index e2e73a0e35..ad4a6fc041 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -366,6 +366,7 @@ export * from './commandSecurity.js';
export * from './detachedSpawn.js';
export * from './setupScriptRunner.js';
export * from './hostShutdown.js';
+export * from './httpDrain.js';
export * from './execGit.js';
export * from './ffmpeg.js';
export * from './forgeAccessErrors.js';
diff --git a/server/services/bootstrap.js b/server/services/bootstrap.js
index 701c1c1a69..7a82f33e95 100644
--- a/server/services/bootstrap.js
+++ b/server/services/bootstrap.js
@@ -39,6 +39,7 @@ import { adoptNpmGlobalBinDir } from '../lib/npmGlobalBin.js';
import { conflictJournalStore } from '../lib/conflictJournal.js';
import { markHostShuttingDown, writeHostShutdownMarker } from '../lib/hostShutdown.js';
import { signalDetachedGroups } from '../lib/credentialBootstrap.js';
+import { createHttpDrain } from '../lib/httpDrain.js';
import { setUserCatalogTypes } from '../lib/catalogTypes.js';
import { runMigrations } from '../../scripts/run-migrations.js';
@@ -958,8 +959,9 @@ const withGrace = (label, ms, run) => new Promise((resolve) => {
setTimeout(() => finishWithError(`⚠️ ${label} close exceeded ${ms}ms — proceeding`), ms).unref?.();
});
-// graceMs is deliberately bounded: closeAllConnections() force-drops every
-// connection, so there is no graceful drain left to wait for. The close callback
+// graceMs is deliberately bounded: this runs after the request drain's deadline,
+// and closeAllConnections() force-drops every connection still open, so there is
+// no graceful drain left to wait for. The close callback
// still needs a short window for TLS/socket teardown — the only thing that can
// outlast it is a WebSocket-upgraded socket the server no longer tracks (and
// io.close()'s engine.close() already tore those down protocol-side; the OS reaps
@@ -972,8 +974,9 @@ const closeServer = (server, label, graceMs = 1000) => withGrace(label, graceMs,
if (err && err.code !== 'ERR_SERVER_NOT_RUNNING') finishWithError(`⚠️ Error closing ${label}`, err);
else finish(`✅ ${label} closed`);
});
- // Order matters: close() above stops accepting NEW connections; NOW force-drop
- // the existing long-lived ones (SSE + keep-alive). (Node 18.2+.)
+ // Order matters: close() above stops accepting NEW connections (the drain has
+ // normally done that already); NOW force-drop whatever outlived the drain
+ // window. (Node 18.2+.)
server.closeAllConnections?.();
});
@@ -981,11 +984,19 @@ const closeServer = (server, label, graceMs = 1000) => withGrace(label, graceMs,
// window, force-exit so PM2 isn't left waiting on a hung process.
const GRACEFUL_SHUTDOWN_TIMEOUT_MS = 10000;
+// How long an already-accepted ordinary API request may keep running after the
+// signal (#8323). Measured from the signal, so it overlaps the teardown steps
+// before the HTTP close rather than adding to them: the drain (5s) + HTTP close
+// grace (1s) + DB pool grace (3s) stays under the ceiling above.
+const HTTP_DRAIN_WINDOW_MS = 5000;
+
/**
* Wire SIGTERM/SIGINT to the graceful-shutdown state machine. Idempotent per
* signal: once shutdown starts, later signals are ignored.
*/
export const registerShutdownHandlers = ({ io, httpServer, localHttpServer }) => {
+ // Track in-flight requests from boot so shutdown knows what it is waiting on.
+ const httpDrain = createHttpDrain([httpServer, localHttpServer]);
let shuttingDown = false;
const shutdown = async (signal) => {
if (shuttingDown) return;
@@ -995,6 +1006,10 @@ export const registerShutdownHandlers = ({ io, httpServer, localHttpServer }) =>
// microseconds from now — and its exit handler must already know the PTY
// died because PortOS is going down, not because the agent finished (#3202).
markHostShuttingDown();
+ // Stop request intake on BOTH listeners before the first await, so nothing
+ // new is accepted while the teardown below runs; requests already accepted
+ // keep running and are waited on (bounded) just before the HTTP close.
+ const requestsDrained = httpDrain.begin(HTTP_DRAIN_WINDOW_MS);
await import('./tailcatPeer.js').then(({ stopAllForwards }) => stopAllForwards())
.catch((err) => logBootstrapFailure('❌ Tailcat forward shutdown failed', err));
await import('./tailcatServe.js').then(({ stopServeProcess }) => stopServeProcess())
@@ -1079,11 +1094,6 @@ export const registerShutdownHandlers = ({ io, httpServer, localHttpServer }) =>
(err) => finishWithError('⚠️ Codex app-server stop failed', err),
));
- // Drop existing long-lived sockets (SSE + keep-alive) up front so the closes
- // below don't wait on connections that never end on their own.
- try { httpServer.closeAllConnections?.(); } catch (e) { logBootstrapFailure('⚠️ closeAllConnections(http)', e); }
- try { localHttpServer?.closeAllConnections?.(); } catch (e) { logBootstrapFailure('⚠️ closeAllConnections(mirror)', e); }
-
// socket.io's io.close() closes engine.io AND its current this.httpServer — and
// every io.attach() reassigns this.httpServer (socket.io index.js:303), so with
// HTTPS on (io.attach(localHttpServer) at boot) io.close() closes the *mirror*,
@@ -1091,15 +1101,24 @@ export const registerShutdownHandlers = ({ io, httpServer, localHttpServer }) =>
// time on that already-closed server: Node registers the callback as a one-time
// 'close' listener for an event that already fired, so it never runs and shutdown
// hangs forever — the real cause of the reconcile "stopping apps" hang.
+ // The drain already stopped that server, so io.close() reporting
+ // ERR_SERVER_NOT_RUNNING is the expected outcome, not a failure. Its callback
+ // still waits for that server's connections to end, so while a slow request
+ // is draining this grace can lapse first — Socket.IO itself is torn down by
+ // then, and the drain wait below bounds the rest.
await withGrace('Socket.IO', 3000, ({ finish, finishWithError }) =>
io.close((err) => {
- if (err) finishWithError('⚠️ Error closing Socket.IO', err);
+ if (err && err.code !== 'ERR_SERVER_NOT_RUNNING') finishWithError('⚠️ Error closing Socket.IO', err);
else finish('✅ Socket.IO closed');
}));
await import('./tailcatIngress.js').then(({ stopTailcatIngress }) => stopTailcatIngress())
.catch((err) => logBootstrapFailure('❌ Tailcat ingress shutdown failed', err));
- // Close BOTH servers explicitly. Whichever one io.close() already closed resolves
- // immediately (ERR_SERVER_NOT_RUNNING → treated as success by closeServer), and
+ // Let accepted requests finish (bounded by the drain window), then force the
+ // rest closed below — a handler mid-write loses its response only at the deadline.
+ const { remaining } = await requestsDrained;
+ if (remaining > 0) console.warn(`⚠️ ${remaining} request(s) still running after the ${HTTP_DRAIN_WINDOW_MS}ms drain — closing them`);
+ // Close BOTH servers explicitly. The drain already stopped both listeners
+ // (ERR_SERVER_NOT_RUNNING → treated as success by closeServer), and
// the bounded backstop in closeServer guarantees neither can hang shutdown even
// if a future socket.io version changes which server it owns.
await Promise.all([
diff --git a/server/services/bootstrap.shutdown.test.js b/server/services/bootstrap.shutdown.test.js
index 55ed3edc1f..434c02b57a 100644
--- a/server/services/bootstrap.shutdown.test.js
+++ b/server/services/bootstrap.shutdown.test.js
@@ -67,12 +67,39 @@ describe('shutdown handler — host-restart bookkeeping (#3202)', () => {
const exitAt = code.indexOf('process.exit(0)');
expect(startAt).toBeGreaterThan(-1);
- expect(startAt).toBeLessThan(code.indexOf('closeAllConnections'));
+ expect(startAt).toBeLessThan(code.indexOf('closeServer('));
expect(awaitAt).toBeGreaterThan(startAt);
expect(awaitAt).toBeLessThan(exitAt);
});
});
+// #8323. The drain itself (intake refusal, in-flight completion, deadline) is
+// exercised against real listeners in lib/httpDrain.test.js; what only this
+// handler can get wrong is WHEN it runs relative to the rest of the teardown.
+describe('shutdown handler — request drain ordering (#8323)', () => {
+ const code = stripCommentsAndNormalize(extractDeclaration(SRC, 'shutdown') || '');
+
+ it('stops request intake before the first await and waits on it before the forced close', () => {
+ const beginAt = code.indexOf('httpDrain.begin(HTTP_DRAIN_WINDOW_MS)');
+ expect(beginAt, 'httpDrain.begin(...) is not called in shutdown()').toBeGreaterThan(-1);
+ expect(beginAt).toBeLessThan(code.search(/\bawait\b/));
+
+ const drainedAt = code.indexOf('await requestsDrained');
+ expect(drainedAt).toBeGreaterThan(code.indexOf('io.close('));
+ expect(drainedAt).toBeLessThan(code.indexOf('closeServer('));
+ // Force-dropping connections up front would cut the requests being drained.
+ expect(code.indexOf('closeAllConnections')).toBe(-1);
+ });
+
+ it('fits the drain window and the close graces inside the shutdown ceiling', () => {
+ const constant = (name) => Number(SRC.match(new RegExp(`const ${name} = (\\d+);`))?.[1]);
+ const closeGrace = Number(SRC.match(/const closeServer = \(server, label, graceMs = (\d+)\)/)?.[1]);
+ const dbGrace = Number(code.match(/withGrace\('DB pool', (\d+)/)?.[1]);
+ expect(constant('HTTP_DRAIN_WINDOW_MS') + closeGrace + dbGrace)
+ .toBeLessThan(constant('GRACEFUL_SHUTDOWN_TIMEOUT_MS'));
+ });
+});
+
// Execute only the close boundary; importing bootstrap loads the live service
// graph. Fake time pins the shutdown deadline without production sleeps.
describe('bounded server shutdown', () => {
@@ -147,6 +174,6 @@ describe('shutdown handler — detached-group teardown (#7496)', () => {
it('signals the groups before dropping connections', () => {
// Signalling after the server has begun closing would race process.exit.
- expect(code.indexOf('signalDetachedGroups(')).toBeLessThan(code.indexOf('closeAllConnections'));
+ expect(code.indexOf('signalDetachedGroups(')).toBeLessThan(code.indexOf('closeServer('));
});
});