Skip to content
Merged
Show file tree
Hide file tree
Changes from 21 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
772a115
Share SSH monitoring connections and persist host retry backoff
sox8502 Oct 22, 2026
ee67264
Fix explicit reconnect, growing logs, and long SSH setup
sox8502 Oct 22, 2026
97df5cd
Require idle SSH monitors before dev-slot data cleanup
sox8502 Oct 22, 2026
d2ee43a
Merge remote-tracking branch 'origin/main' into daniel/or-558-shared-ssh
sox8502 Oct 22, 2026
39cb2e4
Show SSH connection and run monitoring diagnostics
sox8502 Oct 22, 2026
aca6872
Preserve quoted SSH known-hosts filename lists
sox8502 Oct 22, 2026
b06a279
Merge remote-tracking branch 'origin/main' into daniel/or-558-shared-ssh
sox8502 Oct 22, 2026
6d046a0
Merge remote-tracking branch 'origin/main' into daniel/or-558-shared-ssh
sox8502 Oct 22, 2026
18157f6
Include shared SSH log files in run artifact cleanup
sox8502 Oct 22, 2026
575f8fa
Support Python 3.6 remote SSH helpers
sox8502 Oct 22, 2026
74d4901
Merge remote-tracking branch 'origin/main' into daniel/or-558-shared-ssh
sox8502 Oct 22, 2026
cc13526
Finish Slurm runs despite unavailable logs
sox8502 Oct 22, 2026
55af17d
Validate SSH log chunks during concurrent rewrites
sox8502 Oct 22, 2026
778114b
Merge origin/main and preserve shared SSH monitoring compatibility
sox8502 Oct 23, 2026
6025952
Detect full-prefix log rewrites and isolate legacy SSH monitors
sox8502 Oct 23, 2026
1e6c37d
Preserve whitespace in interactive SSH credentials
sox8502 Oct 23, 2026
21906b7
Reuse verified log digests and ignore unrelated obsolete SSH routes
sox8502 Oct 23, 2026
ca8fb01
Merge latest main and rebuild the reviewed dashboard
sox8502 Oct 23, 2026
99e8a39
Keep pinned SSH connections stable across unrelated config edits
sox8502 Oct 23, 2026
5cfb903
Merge current main and migrate saved SSH connection bindings
sox8502 Oct 23, 2026
cde56e5
Merge current main and isolate Slurm status read failures
sox8502 Oct 23, 2026
13b0bdf
Merge current main and close SSH retry and Slurm completion gaps
sox8502 Oct 23, 2026
6bee71f
Stream large SSH command input through bounded upload frames
sox8502 Oct 23, 2026
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
8 changes: 8 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,14 @@ jobs:
- uses: actions/checkout@v4
with:
ref: ${{ inputs.source-sha || github.sha }}
- name: Shared SSH helper protocol tests
run: |
python3 scripts/test_ssh_helper.py
for version in 3.6.15-slim-buster 3.7.17-slim-bullseye 3.8.20-slim-bookworm; do
docker run --rm --network none \
-v "$GITHUB_WORKSPACE:/work:ro" -w /work \
"python:$version" python scripts/test_ssh_helper.py
done
- name: Install Rust toolchain
uses: dtolnay/rust-toolchain@stable
with:
Expand Down
6 changes: 5 additions & 1 deletion agent-skills/orx-compute/references/slurm.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@

Use this backend only when the user explicitly requests their Slurm cluster or
it is the configured default. `orx` reaches the login node over SSH, stages the
committed snapshot, and submits the fixed command with `sbatch`.
committed snapshot, and submits the fixed command with `sbatch`. The login node
needs Python 3.6 or newer; no Python packages or administrator installation are required.
All runs on the same connection share one monitoring channel and batched scheduler
queries. Transport failures back off together, and fresh authentication requires
explicit Connect. Reconnect with `orx compute connect slurm --host login-node`.

```sh
orx exp run <expId> --backend slurm --host login-node --flavor h100:2 --timeout 4h
Expand Down
8 changes: 7 additions & 1 deletion agent-skills/orx-compute/references/ssh.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@ socket naming, reconnect once; existing masters are not terminated.
Changing a configured route requires reconnecting before ordinary commands can
reuse it. For command-line proxy overrides, use a separate configured alias or
`-S none`; native SSH does not expose those overrides to the sharing predicate.
Experiment monitors share one persistent SSH channel per resolved host and authentication
context. Windows Connect keeps the authenticated SSH process alive after its dialog closes.
Background monitoring never starts a fresh login on user hosts. Transport failures
back off together (5 seconds up to 5 minutes); restarting OpenResearch or adding
runs does not reset the retry schedule. Remote command errors do not reset the connection.
Monitoring outages are reported after 60 seconds without declaring the remote
job stopped. Reconnecting resumes status and log polling.

Expand All @@ -49,7 +54,8 @@ example, a committed `run.sh` can source Conda, activate the environment, and
then run the experiment. Those paths must exist in the selected execution
environment (host or container). There is no separate SSH setup command.

The SSH host needs Bash and tar. Container execution also requires host Docker
The SSH host needs Bash, tar, and Python 3.6 or newer (standard library only).
OpenResearch does not install Python automatically. Container execution also requires host Docker
access and an already running, unpaused Linux container with Bash, tar, working
`setsid --wait`, and an absolute writable `$HOME`. Execution uses the container's
configured user. There is no `sudo`, user override, Podman support, container
Expand Down
46 changes: 43 additions & 3 deletions scripts/dev-slot.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@

import { execFileSync, spawn } from 'node:child_process'
import { createHash, randomUUID } from 'node:crypto'
import { closeSync, cpSync, existsSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs'
import { closeSync, cpSync, existsSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs'
import http from 'node:http'
import net from 'node:net'
import os from 'node:os'
import path from 'node:path'
import process from 'node:process'
Expand Down Expand Up @@ -312,7 +313,7 @@ function removeManagedDirectories(slotPaths, configuration, mainCheckout) {
return true
}

function reclaimStaleReservations(info, registry) {
async function reclaimStaleReservations(info, registry) {
const configurations = [...registry.configurations]
const removed = new Set()
for (let slot = FIRST_SLOT; slot <= LAST_SLOT; slot += 1) {
Expand All @@ -327,6 +328,7 @@ function reclaimStaleReservations(info, registry) {
const owner = { worktreePath: path.dirname(manifest), manifestPath: manifest }
if (!managedStateMatches(state, owner, slotPaths)) continue
if (processGroupExists(state.backendProcess?.pid) || processGroupExists(state.uiProcess?.pid)) continue
try { await stopSshServices(slotPaths, true) } catch { continue }
if (!removeManagedDirectories(slotPaths, backend, info.mainCheckout)) continue
removed.add(slot)
}
Expand Down Expand Up @@ -383,7 +385,7 @@ async function reserveSlot(info, dbMode) {
const release = await acquireAllocatorLock(info)
try {
const registry = loadRegistry(info)
reclaimStaleReservations(info, registry)
await reclaimStaleReservations(info, registry)
const existing = registry.configurations.find((configuration) =>
configuration.port >= 4901
&& configuration.port <= 4909
Expand Down Expand Up @@ -706,6 +708,42 @@ function printStatus(info) {
console.log(` State: ${state ? slotPaths.statePath : 'legacy/unmanaged'}`)
}

export async function stopSshServices(slotPaths, requireIdle = false) {
if (!existsSync(slotPaths.dataDir)) return
for (const name of readdirSync(slotPaths.dataDir)) {
if (!/^ssh-service-[a-f0-9]{64}$/.test(name)) continue
const endpoint = readJson(path.join(slotPaths.dataDir, name, 'endpoint.json'))
if (!endpoint) continue
const stopped = await new Promise((resolve, reject) => {
const socket = net.createConnection({ host: '127.0.0.1', port: endpoint.port })
let received = Buffer.alloc(0)
socket.setTimeout(15_000, () => socket.destroy(new Error('SSH service shutdown timed out')))
socket.once('error', (error) => error.code === 'ECONNREFUSED' ? resolve(true) : reject(error))
socket.once('connect', () => {
const body = Buffer.from(JSON.stringify({ ...endpoint, port: undefined, target: null, operation: { op: requireIdle ? 'shutdown' : 'shutdown_if_idle' } }))
const header = Buffer.alloc(4)
header.writeUInt32BE(body.length)
socket.write(Buffer.concat([header, body]))
})
socket.on('data', (chunk) => {
received = Buffer.concat([received, chunk])
if (received.length < 4) return
const length = received.readUInt32BE()
if (length > 1024 * 1024) return socket.destroy(new Error('Invalid SSH service response'))
if (received.length < 4 + length) return
try {
const response = JSON.parse(received.subarray(4, 4 + length).toString())
socket.destroy()
if (response.error) reject(new Error(response.error))
else resolve(response.value?.busy !== true)
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
} catch (error) { socket.destroy(error) }
})
socket.once('end', () => { if (received.length === 0) reject(new Error('SSH service closed without acknowledging shutdown')) })
})
if (stopped) await waitFor('SSH service to stop', 10_000, () => listenerPids(endpoint.port).length === 0)
}
}

async function stopOwnedProcessesUnlocked(info) {
const reservation = reservationFor(info)
if (!reservation) return null
Expand Down Expand Up @@ -740,6 +778,7 @@ async function stopOwnedProcessesUnlocked(info) {
&& !processGroupExists(state.uiProcess?.pid)
&& listenerPids(slotPaths.backendPort).length === 0
&& listenerPids(slotPaths.uiPort).length === 0)
await stopSshServices(slotPaths)
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
state.backendProcess = null
state.uiProcess = null
state.phase = 'stopped'
Expand Down Expand Up @@ -769,6 +808,7 @@ async function cleanupUnlocked(info) {
reservation = reservationFor(info)
if (!reservation) return
const { slotPaths, state, backend } = reservation
await stopSshServices(slotPaths, true)
if (listenerPids(slotPaths.backendPort).length > 0 || listenerPids(slotPaths.uiPort).length > 0) {
throw new Error(`Refusing to clean ${slotPaths.slotKey} while its ports are listening`)
}
Expand Down
34 changes: 34 additions & 0 deletions scripts/dev-slot.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import assert from 'node:assert/strict'
import { execFileSync } from 'node:child_process'
import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import os from 'node:os'
import net from 'node:net'
import path from 'node:path'
import test from 'node:test'

Expand All @@ -12,6 +13,7 @@ import {
parseArgs,
resolveLiveDataDir,
slotEnvironment,
stopSshServices,
sqliteBackupCommand,
supervisorCommandMatches,
} from './dev-slot.mjs'
Expand Down Expand Up @@ -132,3 +134,35 @@ test('supervisor identity includes its unguessable launch token', () => {
assert.equal(supervisorCommandMatches(command, 'token-b', helper), false)
assert.equal(supervisorCommandMatches(command, 'token-a', '/tmp/other-helper.mjs'), false)
})

test('stopping a dashboard leaves busy SSH monitoring alive', async () => {
const dataDir = mkdtempSync(path.join(os.tmpdir(), 'orx-busy-service-'))
const root = path.join(dataDir, `ssh-service-${'a'.repeat(64)}`)
mkdirSync(root)
const server = net.createServer((socket) => {
let received = Buffer.alloc(0)
socket.on('data', (chunk) => {
received = Buffer.concat([received, chunk])
if (received.length < 4 || received.length < 4 + received.readUInt32BE()) return
const request = JSON.parse(received.subarray(4).toString())
assert.ok(['shutdown_if_idle', 'shutdown'].includes(request.operation.op))
const response = Buffer.from(JSON.stringify(request.operation.op === 'shutdown'
? { value: null, error: 'SSH monitoring is busy' }
: { value: { busy: true }, error: null }))
const header = Buffer.alloc(4)
header.writeUInt32BE(response.length)
socket.end(Buffer.concat([header, response]))
})
})
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
try {
writeFileSync(path.join(root, 'endpoint.json'), JSON.stringify({ port: server.address().port, token: 'fixture', version: 1 }))
await stopSshServices({ dataDir })
assert.equal(server.listening, true)
await assert.rejects(stopSshServices({ dataDir }, true), /SSH monitoring is busy/)
assert.equal(server.listening, true)
} finally {
await new Promise((resolve) => server.close(resolve))
rmSync(dataDir, { recursive: true, force: true })
}
})
66 changes: 66 additions & 0 deletions scripts/ssh-test-proxy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
#!/usr/bin/env python3
"""Disposable fixture: lose one launch response after the remote command executes."""
import json
import os
import re
import struct
import subprocess
import sys
import threading
from pathlib import Path

command = os.environ['SSH_ORIGINAL_COMMAND']
bootstrap = re.search(r'sys.stdin.buffer.read\((\d+)\)', command)
if not bootstrap:
os.execl('/bin/sh', 'sh', '-c', command)
child = subprocess.Popen(command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
launches = set()


def exact(source, count):
result = bytearray()
while len(result) < count:
chunk = source.read(count - len(result))
if not chunk:
raise EOFError()
result.extend(chunk)
return bytes(result)


def frame(source):
header = exact(source, 4)
body = exact(source, struct.unpack('!I', header)[0])
return header + body, json.loads(body)


def requests():
try:
child.stdin.write(exact(sys.stdin.buffer, int(bootstrap[1])))
child.stdin.flush()
while True:
data, request = frame(sys.stdin.buffer)
if 'date +%s > launch_time' in request.get('command', ''):
launches.add(request['id'])
child.stdin.write(data)
child.stdin.flush()
except (EOFError, BrokenPipeError):
child.stdin.close()


threading.Thread(target=requests, daemon=True).start()
try:
sys.stdout.buffer.write(child.stdout.readline())
sys.stdout.buffer.flush()
while True:
data, response = frame(child.stdout)
marker = Path('/tmp/drop-launch-ack')
if response.get('id') in launches and marker.exists():
marker.unlink()
child.kill()
child.wait()
os._exit(255)
sys.stdout.buffer.write(data)
sys.stdout.buffer.flush()
except (EOFError, BrokenPipeError):
child.kill()
child.wait()
17 changes: 4 additions & 13 deletions scripts/test-ssh-container.sh
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@
set -euo pipefail
# Only the uniquely named test containers are changed or removed.
fixture=$(mktemp -d)
export ORX_DATA_DIR="$fixture/data" XDG_CONFIG_HOME="$fixture/config" ORX_CACHE_DIR="$fixture/cache"
prefix="orx-ssh-test-$$"
cleanup() {
"${CARGO_TARGET_DIR:-target}/debug/orx" ssh-service stop >/dev/null 2>&1 || true
docker rm -f "$prefix-host" "$prefix-inner" >/dev/null 2>&1 || true
docker image rm "$prefix" >/dev/null 2>&1 || true
rm -rf "$fixture"
Expand All @@ -12,25 +14,14 @@ trap cleanup EXIT
ssh-keygen -q -t ed25519 -N '' -f "$fixture/key"
cat > "$fixture/Dockerfile" <<'DOCKER'
FROM docker:28-cli
RUN apk add --no-cache openssh bash util-linux coreutils procps && ssh-keygen -A && mkdir -p /root/.ssh && chmod 700 /root/.ssh
RUN apk add --no-cache openssh bash util-linux coreutils procps python3 && ssh-keygen -A && mkdir -p /root/.ssh && chmod 700 /root/.ssh
COPY key.pub /root/.ssh/authorized_keys
COPY ssh-dispatch /usr/local/bin/ssh-dispatch
RUN chmod +x /usr/local/bin/ssh-dispatch && echo "ForceCommand /usr/local/bin/ssh-dispatch" >> /etc/ssh/sshd_config
RUN chmod 600 /root/.ssh/authorized_keys
ENTRYPOINT ["/usr/sbin/sshd", "-D", "-e"]
DOCKER
cat > "$fixture/ssh-dispatch" <<'DISPATCH'
#!/bin/sh
case "$SSH_ORIGINAL_COMMAND" in
*'date +%s > launch_time'*)
if [ -f /tmp/drop-launch-ack ]; then
rm /tmp/drop-launch-ack
sh -c "$SSH_ORIGINAL_COMMAND"
exit 255
fi ;;
esac
exec sh -c "$SSH_ORIGINAL_COMMAND"
DISPATCH
cp scripts/ssh-test-proxy.py "$fixture/ssh-dispatch"
docker build -q -t "$prefix" "$fixture"
docker run -d --name "$prefix-host" -p 127.0.0.1::22 -v /var/run/docker.sock:/var/run/docker.sock "$prefix"
docker run -d --name "$prefix-inner" --user 1000:1000 --env CONDA_ENVS_PATH=/tmp/conda-envs --env "HOME=/tmp/orx home'quoted" --entrypoint bash condaforge/miniforge3 -c 'mkdir -p "$HOME"; exec sleep infinity'
Expand Down
Loading
Loading