Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Preserve port ownership evidence across candidate changes (#5689)
Nick Gomez0bd286d18f0a
diff --git a/packages/app/tests/integration/loopback-bind-discipline.test.ts b/packages/app/tests/integration/loopback-bind-discipline.test.tsindex 50c9c624f..e16cb9f1d 100644--- a/packages/app/tests/integration/loopback-bind-discipline.test.ts+++ b/packages/app/tests/integration/loopback-bind-discipline.test.ts@@ -63,6 +63,55 @@ export function findNonLoopbackListenCalls(lines: string[]): Array<{ line: numbereturn violations;}+interface ListenExemption {+ path: string;+ call: string;+ reason: string;+}++const RECORDING_OWNERSHIP_CASE = 'tests/stress/_helpers/port-ownership/recording.ownership-case.ts';++const LISTEN_EXEMPTIONS: readonly ListenExemption[] = [+ {+ path: RECORDING_OWNERSHIP_CASE,+ call: 'server.listen(port, host);',+ reason:+ "Wildcard occupant bound to '0.0.0.0': holds the candidate port on the wildcard address so Vite's availability preflight skips it; it is never dialed.",+ },+ {+ path: RECORDING_OWNERSHIP_CASE,+ call: 'await vite.listen();',+ reason:+ "Vite's listen(port?, isRestart?) accepts no host; the server binds the loopback host configured in server.host.",+ },+];++function findUnexemptedListenCalls(+ path: string,+ lines: string[],+): Array<{ line: number; text: string }> {+ const remaining = LISTEN_EXEMPTIONS.filter((exemption) => exemption.path === path);+ return findNonLoopbackListenCalls(lines).filter((violation) => {+ const match = remaining.findIndex((exemption) => exemption.call === violation.text);+ if (match === -1) return true;+ remaining.splice(match, 1);+ return false;+ });+}++function findStaleListenExemptions(files: readonly FileLines[]): ListenExemption[] {+ const unclaimed = new Map(+ files.map((file) => [file.path, findNonLoopbackListenCalls(file.lines).map((v) => v.text)]),+ );+ return LISTEN_EXEMPTIONS.filter((exemption) => {+ const calls = unclaimed.get(exemption.path) ?? [];+ const match = calls.indexOf(exemption.call);+ if (match === -1) return true;+ calls.splice(match, 1);+ return false;+ });+}+const AMBIGUOUS_LOCALHOST_DIAL = /\b(?:https?|wss?):\/\/localhost:\$\{/;export function findAmbiguousLocalhostDials(@@ -92,7 +141,7 @@ describe('loopback bind discipline (app test sources)', () => {test('every .listen( call binds an explicit loopback host literal', () => {const violations: string[] = [];for (const file of files) {- for (const v of findNonLoopbackListenCalls(file.lines)) {+ for (const v of findUnexemptedListenCalls(file.path, file.lines)) {violations.push(` ${file.path}:${v.line} ${v.text}`);}}@@ -147,6 +196,85 @@ describe('loopback bind discipline (app test sources)', () => {expect(findNonLoopbackListenCalls([" s.listen(0, '0.0.0.0', cb);"]).length).toBe(1);});+ test('listen exemptions admit each keyed call once in its own file and nowhere else', () => {+ const exemptedPath = 'tests/stress/_helpers/port-ownership/recording.ownership-case.ts';+ const exemptedCalls = [' server.listen(port, host);', ' await vite.listen();'];++ expect(findNonLoopbackListenCalls(exemptedCalls).length).toBe(2);+ expect(findUnexemptedListenCalls(exemptedPath, exemptedCalls)).toEqual([]);++ expect(+ findUnexemptedListenCalls(+ 'tests/stress/_helpers/port-ownership/startup.ownership-case.ts',+ exemptedCalls,+ ).length,+ ).toBe(2);+ expect(+ findUnexemptedListenCalls('tests/integration/recording.ownership-case.ts', exemptedCalls)+ .length,+ ).toBe(2);++ expect(+ findUnexemptedListenCalls(exemptedPath, [+ ...exemptedCalls,+ ' s.listen(0, cb);',+ " s.listen(0, '0.0.0.0', cb);",+ ]),+ ).toEqual([+ { line: 3, text: 's.listen(0, cb);' },+ { line: 4, text: "s.listen(0, '0.0.0.0', cb);" },+ ]);++ expect(findUnexemptedListenCalls(exemptedPath, [...exemptedCalls, ...exemptedCalls])).toEqual([+ { line: 3, text: 'server.listen(port, host);' },+ { line: 4, text: 'await vite.listen();' },+ ]);+ });++ test('every listen exemption still matches a call in its own file', () => {+ expect(+ findStaleListenExemptions(files).map(+ (exemption) => ` ${exemption.path} ${exemption.call}`,+ ),+ 'These LISTEN_EXEMPTIONS entries match no non-loopback .listen( call in their own file: ' ++ 'the call changed or was removed. Delete the entry, or update its call text',+ ).toEqual([]);+ });++ test('stale exemptions are reported for a removed, rebound or relocated call and not for the live shape', () => {+ const exemptedPath = 'tests/stress/_helpers/port-ownership/recording.ownership-case.ts';+ const occupant = ' server.listen(port, host);';+ const viteListen = ' await vite.listen();';++ expect(+ findStaleListenExemptions([{ path: exemptedPath, lines: [occupant, viteListen] }]),+ ).toEqual([]);++ expect(+ findStaleListenExemptions([{ path: exemptedPath, lines: [occupant] }]).map((e) => e.call),+ ).toEqual(['await vite.listen();']);+ expect(+ findStaleListenExemptions([+ { path: exemptedPath, lines: [" server.listen(port, '127.0.0.1');", viteListen] },+ ]).map((e) => e.call),+ ).toEqual(['server.listen(port, host);']);+ expect(+ findStaleListenExemptions([+ { path: exemptedPath, lines: [occupant, ' // await vite.listen();'] },+ ]).map((e) => e.call),+ ).toEqual(['await vite.listen();']);++ expect(+ findStaleListenExemptions([+ {+ path: 'tests/stress/_helpers/port-ownership/startup.ownership-case.ts',+ lines: [occupant, viteListen],+ },+ ]).length,+ ).toBe(2);+ expect(findStaleListenExemptions([]).length).toBe(2);+ });+test('dial predicate fires on planted violations and not on adjacent negatives', () => {expect(findAmbiguousLocalhostDials([diff --git a/packages/app/tests/stress/_helpers/port-ownership/occupy-selected-port.cjs b/packages/app/tests/stress/_helpers/port-ownership/occupy-selected-port.cjsindex 662de62d0..91e5a775b 100644--- a/packages/app/tests/stress/_helpers/port-ownership/occupy-selected-port.cjs+++ b/packages/app/tests/stress/_helpers/port-ownership/occupy-selected-port.cjs@@ -96,23 +96,24 @@ childProcess.spawn = function (...args) {return child;};-let bindTakeoverAttempted = false;+let bindTakeoverComplete = false;http.Server.prototype.listen = function (...args) {const rawRequest = process.env.OK_TEST_VITE_START_REQUEST;- if (!rawRequest || bindTakeoverAttempted) return listenHttp.apply(this, args);+ if (!rawRequest || bindTakeoverComplete) return listenHttp.apply(this, args);const request = JSON.parse(rawRequest);const port = args[0];- if (port !== request.candidatePort) return listenHttp.apply(this, args);- bindTakeoverAttempted = true;+ if (typeof port !== 'number' || port < request.candidatePort) return listenHttp.apply(this, args);+ record('vite-bind-attempt', { port, candidatePort: request.candidatePort, host: request.host });const occupant = createServer((socket) => socket.destroy());occupant.once('error', (error) => {record('vite-bind-takeover-error', { port, code: error.code });- listenHttp.apply(this, args);+ this.emit('error', error);});occupant.listen(port, request.host, () => {occupants.set(port, occupant);occupant.unref();record('vite-bind-takeover', { port, host: request.host });+ bindTakeoverComplete = true;listenHttp.apply(this, args);});return this;diff --git a/packages/app/tests/stress/_helpers/port-ownership/recording.ownership-case.ts b/packages/app/tests/stress/_helpers/port-ownership/recording.ownership-case.tsnew file mode 100644index 000000000..9ee9dc358--- /dev/null+++ b/packages/app/tests/stress/_helpers/port-ownership/recording.ownership-case.ts@@ -0,0 +1,154 @@+import { randomInt } from 'node:crypto';+import { once } from 'node:events';+import { mkdtemp, rm } from 'node:fs/promises';+import { createServer as createNetServer, Server } from 'node:net';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { expect, test } from '@playwright/test';+import { createServer } from 'vite';+import {+ isTestServerHost,+ TEST_SERVER_CANDIDATE_PORTS,+ TEST_SERVER_HOST_FAMILY,+ TEST_SERVER_STARTUP_ENV,+} from '../../../../src/build/test-server-startup-contract.ts';+import { createViteStartupRequest, type ViteStartupRequest } from '../server-process.ts';+import { readOwnershipRecords } from './run-case.test-helper.ts';++async function listen(server: Server, host: string): Promise<number> {+ const { start, end } = TEST_SERVER_CANDIDATE_PORTS;+ const first = randomInt(start, end);+ for (let offset = 0; offset < end - start; offset += 1) {+ const port = start + ((first - start + offset) % (end - start));+ try {+ const listening = once(server, 'listening');+ server.listen(port, host);+ await listening;+ return port;+ } catch (error) {+ if (!(error instanceof Error) || !('code' in error) || error.code !== 'EADDRINUSE')+ throw error;+ }+ }+ throw new Error('no candidate port is available for the recording case');+}++async function close(server: Server): Promise<void> {+ if (!server.listening) return;+ await new Promise<void>((resolve, reject) => {+ server.close((error) => (error ? reject(error) : resolve()));+ });+}++for (const host of Object.keys(TEST_SERVER_HOST_FAMILY).filter(isTestServerHost)) {+ const family = TEST_SERVER_HOST_FAMILY[host];+ for (const [collision, ordering] of Object.entries({+ 'an unavailable candidate': {+ candidateSkipped: true,+ candidateContended: false,+ contenderListening: true,+ },+ 'a bind contender': {+ candidateSkipped: false,+ candidateContended: true,+ contenderListening: true,+ },+ 'a released bind contender': {+ candidateSkipped: false,+ candidateContended: true,+ contenderListening: false,+ },+ })) {+ test(`records ownership evidence after ${collision} on ${family}`, async () => {+ const root = await mkdtemp(join(tmpdir(), 'ok-recording-'));+ const contender = createNetServer((socket) => socket.destroy());+ const previousRequest = process.env[TEST_SERVER_STARTUP_ENV];+ const originalEmit = Server.prototype.emit;+ let request: ViteStartupRequest | undefined;+ let vite: Awaited<ReturnType<typeof createServer>> | undefined;+ try {+ const candidatePort = await listen(contender, '0.0.0.0');+ if (collision !== 'an unavailable candidate') await close(contender);+ request = createViteStartupRequest(host, candidatePort);+ process.env[TEST_SERVER_STARTUP_ENV] = request.environment[TEST_SERVER_STARTUP_ENV];+ vite = await createServer({+ root,+ configFile: false,+ logLevel: 'silent',+ server: { host, port: candidatePort, strictPort: false, hmr: false },+ optimizeDeps: { noDiscovery: true, include: [] },+ });+ const httpServer = vite.httpServer;+ if (!httpServer) throw new Error('expected an HTTP server');+ if (collision === 'a released bind contender') {+ Server.prototype.emit = function (event, ...values) {+ const error = values[0];+ if (+ event === 'error' &&+ this !== contender &&+ this !== httpServer &&+ contender.listening &&+ error instanceof Error &&+ 'code' in error &&+ error.code === 'EADDRINUSE'+ ) {+ Server.prototype.emit = originalEmit;+ contender.close((closeError) => {+ if (closeError) throw closeError;+ Reflect.apply(originalEmit, this, [event, ...values]);+ });+ return true;+ }+ return Reflect.apply(originalEmit, this, [event, ...values]);+ };+ }+ if (collision !== 'an unavailable candidate') {+ const originalListen = httpServer.listen;+ httpServer.listen = (...args) => {+ httpServer.listen = originalListen;+ const port = args[0];+ if (typeof port !== 'number') throw new Error('expected a TCP port');+ contender.once('error', (error) => httpServer.emit('error', error));+ contender.listen(port, host === '::1' ? '::1' : '127.0.0.1', () =>+ Reflect.apply(originalListen, httpServer, args),+ );+ return httpServer;+ };+ }+ await vite.listen();+ const recordsPath = process.env.OK_PORT_OWNERSHIP_RECORDS;+ if (!recordsPath) throw new Error('expected an ownership records path');+ const records = readOwnershipRecords(recordsPath).filter(+ (record): record is Record<string, unknown> =>+ typeof record === 'object' && record !== null,+ );+ const firstAttemptPort = records.find(+ (record) => record.event === 'vite-bind-attempt',+ )?.port;+ expect(firstAttemptPort, JSON.stringify(records)).toEqual(expect.any(Number));+ expect(+ {+ candidateSkipped:+ typeof firstAttemptPort === 'number' && firstAttemptPort > candidatePort,+ candidateContended: records.some(+ (record) =>+ record.event === 'vite-bind-takeover-error' &&+ record.port === candidatePort &&+ record.code === 'EADDRINUSE',+ ),+ contenderListening: contender.listening,+ },+ JSON.stringify(records),+ ).toEqual(ordering);+ } finally {+ Server.prototype.emit = originalEmit;+ await vite?.close();+ await close(contender);+ if (previousRequest === undefined) delete process.env[TEST_SERVER_STARTUP_ENV];+ else process.env[TEST_SERVER_STARTUP_ENV] = previousRequest;+ request?.dispose();+ await rm(root, { recursive: true, force: true });+ }+ });+ }+}diff --git a/packages/app/tests/stress/harness-port-ownership.e2e.ts b/packages/app/tests/stress/harness-port-ownership.e2e.tsindex c17f89a01..88095b142 100644--- a/packages/app/tests/stress/harness-port-ownership.e2e.ts+++ b/packages/app/tests/stress/harness-port-ownership.e2e.ts@@ -104,3 +104,20 @@ test('automatically selected warm-cache server publishes a seed', async () => {caller: 'global-warm-cache.ts',});});++for (const family of ['IPv4', 'IPv6']) {+ for (const collision of [+ 'an unavailable candidate',+ 'a bind contender',+ 'a released bind contender',+ ]) {+ const name = `records ownership evidence after ${collision} on ${family}`;+ test(name, async () => {+ await expectOwnedServerRun({+ file: 'tests/stress/_helpers/port-ownership/recording.ownership-case.ts',+ name,+ caller: 'vite-bind-interception',+ });+ });+ }+}