Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -614,7 +614,7 @@ function sameRuntimeNodeLeaseExists(runtimeFile, key) {
function cleanupLastDetach(runtimeFile, key, cleanupScript) {
if (sameRuntimeNodeLeaseExists(runtimeFile, key)) return;
const script = cleanupScript || path.join(__dirname, "start-sympp-mcp.ps1");
const args = ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", script, "-CleanupRuntimeKey", key, "-PreserveCurrentArtifactRuntime"];
const args = ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", script, "-CleanupRuntimeKey", key];
let result = spawnSync("pwsh.exe", args, { stdio: ["ignore", "ignore", "inherit"] });
if (result.error && result.error.code === "ENOENT") result = spawnSync("powershell.exe", args, { stdio: ["ignore", "ignore", "inherit"] });
if (result.error || result.status !== 0) diagnostic(`Symphony++ last-detach cleanup failed: ${result.error ? result.error.message : `exit ${result.status}`}`);
Expand Down
22 changes: 8 additions & 14 deletions plugins/symphony-plus-plus-mcp/scripts/start-sympp-mcp.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ param(
[switch]$ValidateOnly,
[switch]$PrepareRuntimeOnly,
[switch]$CleanupPreparedRuntime,
[switch]$PreserveCurrentArtifactRuntime,
[string]$CleanupRuntimeKey
)

Expand Down Expand Up @@ -1304,10 +1303,9 @@ function Test-RuntimeStateExternalLoopback($RuntimeState) {
[string]$RuntimeState.frontend.status -eq "external_loopback"
}

function Test-BackendShouldShutdownOnIdle($BackendPlan, $DashboardPlan, [string]$RuntimeMode) {
function Test-BackendShouldShutdownOnIdle($BackendPlan, $DashboardPlan) {
return ($BackendPlan.managed -eq $true) -and
($DashboardPlan.managed -ne $true) -and
-not ($RuntimeMode -eq "artifact" -and [string]$DashboardPlan.status -eq "artifact_static")
($DashboardPlan.managed -ne $true)
}

function Test-RuntimeEntryEndpointMatches([string]$Role, $Entry, [string]$Endpoint) {
Expand Down Expand Up @@ -1610,7 +1608,7 @@ function Get-ManagedListenerPid([string]$Role, [int]$Port) {
return $null
}

function Stop-ManagedServersIfUnused([string]$RuntimeFile, [string]$RuntimeKey, [bool]$PreserveCurrentArtifactRuntime = $false) {
function Stop-ManagedServersIfUnused([string]$RuntimeFile, [string]$RuntimeKey) {
$lock = Enter-FileLock (Resolve-StartupLockFile $RuntimeFile) 30
try {
$activeLeases = @(Get-ActiveBridgeLeases $RuntimeFile)
Expand All @@ -1628,11 +1626,7 @@ function Stop-ManagedServersIfUnused([string]$RuntimeFile, [string]$RuntimeKey,
if ((Test-ActiveLegacyBridgeLease $activeLeases) -or (Test-ActiveBridgeLeaseForRuntimeKey $activeLeases $RuntimeKey)) {
return
}
$preserveCurrent = $PreserveCurrentArtifactRuntime -and
[string]$state.runtime_kind -eq "artifact" -and
[string]$state.runtime_mode -eq "artifact" -and
[string]$state.frontend.status -eq "artifact_static"
if ([System.StringComparer]::OrdinalIgnoreCase.Equals($stateKey, $RuntimeKey) -and -not $preserveCurrent) {
if ([System.StringComparer]::OrdinalIgnoreCase.Equals($stateKey, $RuntimeKey)) {
[void](Stop-CurrentManagedRuntimeStateEntries $state $activeLeases)
}
$supersededStates = Stop-SupersededRuntimeStatesIfUnused $RuntimeFile (Get-SupersededRuntimeStates $state)
Expand Down Expand Up @@ -2075,7 +2069,7 @@ function Invoke-WarmAttachFromRuntimeState {
} finally {
Remove-BridgeLease $leasePath
if ($attached) {
Stop-ManagedServersIfUnused $RuntimeFile $identity.runtime_key $true
Stop-ManagedServersIfUnused $RuntimeFile $identity.runtime_key
}
}
}
Expand Down Expand Up @@ -2242,7 +2236,7 @@ if ($Help) {
}

if (-not [string]::IsNullOrWhiteSpace($CleanupRuntimeKey)) {
Stop-ManagedServersIfUnused (Resolve-RuntimeFile) $CleanupRuntimeKey ([bool]$PreserveCurrentArtifactRuntime)
Stop-ManagedServersIfUnused (Resolve-RuntimeFile) $CleanupRuntimeKey
exit 0
}
if ($CleanupPreparedRuntime) {
Expand Down Expand Up @@ -2549,7 +2543,7 @@ try {
[void](Initialize-ElixirRuntime $elixirDir $launcher $mix $mise $logDir $elixirSetupTimeout)
}
$backendDashboardOrigin = if ($runtimeMode -eq "artifact" -and [string]$dashboardPlan.status -eq "artifact_static") { $null } else { $dashboardPlan.origin }
$backendShutdownOnIdle = Test-BackendShouldShutdownOnIdle $backendPlan $dashboardPlan $runtimeMode
$backendShutdownOnIdle = Test-BackendShouldShutdownOnIdle $backendPlan $dashboardPlan
$startingRuntimeRoot = if ($runtimeMode -eq "artifact") { [string]$artifactRuntime.root } else { [string]$repoRoot }
if ($installedHttpCold) {
$startingState.runtime_mode = $runtimeMode; $startingState.runtime_kind = $runtimeMode
Expand Down Expand Up @@ -2695,5 +2689,5 @@ try {
Invoke-HttpMcpBridge $backendPlan.mcp_url $bridgeTimeout (New-McpClientLeaseId) $clientHeartbeatInterval
} finally {
Remove-BridgeLease $bridgeLeasePath
Stop-ManagedServersIfUnused $runtimeFile $runtimeKey $true
Stop-ManagedServersIfUnused $runtimeFile $runtimeKey
}
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,14 @@ async function freePort() {
return port;
}

function portAvailable(port) {
return new Promise((resolve) => {
const server = net.createServer();
server.once("error", () => resolve(false));
server.listen(port, "127.0.0.1", () => server.close(() => resolve(true)));
});
}

async function barrierClient() {
const [, , , barrier, launcher] = process.argv;
process.stderr.write("BARRIER_READY\n");
Expand Down Expand Up @@ -297,21 +305,21 @@ async function runCase(clientCount, shell, mode = "normal") {
} finally {
clearTimeout(readyTimeout);
}
const activeBackend = readJson(backendState);
const ownersResult = spawnSync(shell, ["-NoProfile", "-NonInteractive", "-Command", "@(Get-NetTCPConnection -LocalPort $env:FIXTURE_PORT -State Listen -ErrorAction Stop | Select-Object -ExpandProperty OwningProcess -Unique) | ConvertTo-Json -Compress"], { env: { ...process.env, FIXTURE_PORT: String(backendPort) }, encoding: "utf8", windowsHide: true });
assert.equal(ownersResult.status, 0, ownersResult.stderr);
assert.deepEqual([].concat(JSON.parse(ownersResult.stdout.trim())), [activeBackend.pid]);
for (const client of clients) { try { client.child.stdin.end(); } catch (_) { } }
const results = await Promise.all(clients.map((client) => client.result));
const expectedFailures = mode.endsWith("_death") ? 1 : 0;
assert.equal(results.filter((result) => result.code !== 0).length, expectedFailures, results.map((result) => result.stderr).join("\n"));
assert.equal(results.filter((result) => result.code === 0).length, clientCount);
await waitFor(() => readJson(backendState)?.active_leases === 0, "Backend leases did not drain.");
const state = readJson(runtimeFile);
const backend = readJson(backendState);
backendPid = backend.pid;
const ownersResult = spawnSync(shell, ["-NoProfile", "-NonInteractive", "-Command", "@(Get-NetTCPConnection -LocalPort $env:FIXTURE_PORT -State Listen -ErrorAction Stop | Select-Object -ExpandProperty OwningProcess -Unique) | ConvertTo-Json -Compress"], { env: { ...process.env, FIXTURE_PORT: String(backendPort) }, encoding: "utf8", windowsHide: true });
assert.equal(ownersResult.status, 0, ownersResult.stderr);
const owners = JSON.parse(ownersResult.stdout.trim());
assert.deepEqual([].concat(owners), [backendPid]);
await waitFor(() => portAvailable(backendPort), "Backend listener did not stop after the final client exited.");
const state = await waitFor(() => { const value = readJson(runtimeFile); return value?.backend?.status === "stopped" && value.backend.pid === null && value; }, "Runtime state did not record zero-client backend shutdown.");
assert.equal(state.publication.status, "ready");
assert.equal(state.backend.pid, backendPid);
assert.equal(backend.starts, 1);
assert.equal(backend.initialize, clientCount);
assert.equal(backend.tools_list, clientCount);
Expand All @@ -336,7 +344,7 @@ async function runCase(clientCount, shell, mode = "normal") {
for (const directory of [symppHome, environment.TEMP]) if (fs.existsSync(directory)) for (const entry of fs.readdirSync(directory, { recursive: true })) if (/artifact\.zip\.tmp-|\.extracting-|codex-plugin\.json\.tmp-/.test(String(entry))) leftovers.push(entry);
assert.deepEqual(leftovers, []);
assert.ok(percentile(latencies, 0.95) < 60000 && Math.max(...latencies) < 90000);
return { mode, shell: path.basename(shell), clients: clientCount, p95_ms: percentile(latencies, 0.95), max_ms: Math.max(...latencies), manifest: channel.counts.manifest_successes, manifest_attempts: channel.counts.manifest_attempts, artifact: channel.counts.archive_successes, artifact_attempts: channel.counts.archive_attempts, preparations: traceCount(traceDir, "artifact_prepare_end"), backends: backend.starts, pids: 1, listeners: 1, initializes: backend.initialize, tools_list: backend.tools_list, lease_peak: backend.lease_peak, leases_after: backend.active_leases, adopted: traceCount(traceDir, "backend_adopted") };
return { mode, shell: path.basename(shell), clients: clientCount, p95_ms: percentile(latencies, 0.95), max_ms: Math.max(...latencies), manifest: channel.counts.manifest_successes, manifest_attempts: channel.counts.manifest_attempts, artifact: channel.counts.archive_successes, artifact_attempts: channel.counts.archive_attempts, preparations: traceCount(traceDir, "artifact_prepare_end"), backends: backend.starts, pids: 1, listeners: 0, initializes: backend.initialize, tools_list: backend.tools_list, lease_peak: backend.lease_peak, leases_after: backend.active_leases, adopted: traceCount(traceDir, "backend_adopted") };
} finally {
terminateTrees(clients.filter((client) => client.child.exitCode === null).map((client) => client.child.pid));
if (!backendPid) backendPid = readJson(backendState)?.pid || 0;
Expand Down
Loading