diff --git a/.github/workflows/build-host.yml b/.github/workflows/build-host.yml new file mode 100644 index 000000000..f70cdd170 --- /dev/null +++ b/.github/workflows/build-host.yml @@ -0,0 +1,40 @@ +name: Build host binaries + +on: + workflow_call: + inputs: + source-sha: + required: true + type: string + +permissions: + contents: read + +jobs: + build: + runs-on: macos-14 + steps: + - uses: actions/checkout@v6 + with: + ref: ${{ inputs.source-sha }} + persist-credentials: false + - uses: actions/setup-node@v4 + with: + node-version: 22 + - uses: dtolnay/rust-toolchain@stable + with: + targets: x86_64-unknown-linux-musl,aarch64-unknown-linux-musl,x86_64-apple-darwin,aarch64-apple-darwin + - uses: Swatinem/rust-cache@v2 + with: + shared-key: host-binaries + - uses: mlugg/setup-zig@d1434d08867e3ee9daa34448df10607b98908d29 # v2 + with: + version: 0.13.0 + - name: Install musl cross linker + run: cargo install cargo-zigbuild --locked --version 0.20.1 + - run: node scripts/build-host.mjs + - uses: actions/upload-artifact@v7 + with: + name: release-host + path: target/host-binaries + if-no-files-found: error diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fa7a00345..12a3be6c8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -53,7 +53,7 @@ jobs: with: node-version: 22 - name: CI selection and release safety tests - run: node --test scripts/ci-changes.test.mjs scripts/ci-workflows.test.mjs scripts/canary-tag.test.mjs + run: node --test scripts/ci-changes.test.mjs scripts/ci-workflows.test.mjs scripts/canary-tag.test.mjs scripts/build-host.test.mjs - name: Select checks for changed files id: changes env: @@ -128,6 +128,13 @@ jobs: - uses: actions/checkout@v4 with: ref: ${{ inputs.source-sha || github.sha }} + - name: Install OpenSSH server + run: | + if ! command -v sshd >/dev/null 2>&1 && [ ! -x /usr/sbin/sshd ]; then + sudo apt-get update + sudo apt-get install -y --no-install-recommends openssh-server + fi + sudo mkdir -p /run/sshd - name: Shared SSH helper protocol tests run: | python3 scripts/test_ssh_helper.py @@ -170,13 +177,32 @@ jobs: with: name: release-ui path: ui/dist + - name: Download release hosts + if: inputs.release && github.event_name != 'pull_request' + uses: actions/download-artifact@v8 + with: + name: release-host + path: target/host-binaries + - name: Verify embedded host lookup + if: inputs.release && github.event_name != 'pull_request' + env: + ORX_EMBED_HOST_DIR: ${{ github.workspace }}/target/host-binaries + run: cargo test --locked embedded_hosts_keep_their_digest_and_allow_directory_overrides - name: Optimized source builds disable production telemetry if: inputs.release && github.event_name != 'pull_request' + env: + ORX_EMBED_HOST_DIR: ${{ github.workspace }}/target/host-binaries shell: bash run: | set -euo pipefail cargo build --release --locked test "$(target/release/orx --no-telemetry version --build-channel)" = "development" + - name: Packaged binary bootstraps SSH host without a binary directory + if: inputs.release && github.event_name != 'pull_request' + env: + ORX_EMBED_HOST_DIR: ${{ github.workspace }}/target/host-binaries + ORX_PACKAGED_BINARY: ${{ github.workspace }}/target/release/orx + run: env -u ORX_HOST_BIN_DIR cargo test --locked --test packaged_host -- --ignored --nocapture linux-app: name: linux app (${{ matrix.arch }}, ${{ matrix.mode }}) @@ -194,7 +220,8 @@ jobs: - name: Install WebKitGTK run: | sudo apt-get update - sudo apt-get install -y --no-install-recommends libwebkit2gtk-4.1-dev libgtk-3-dev + sudo apt-get install -y --no-install-recommends libwebkit2gtk-4.1-dev libgtk-3-dev openssh-server + sudo mkdir -p /run/sshd - name: Install Rust toolchain uses: dtolnay/rust-toolchain@stable with: diff --git a/.github/workflows/release-canary.yml b/.github/workflows/release-canary.yml index 60f3ebb2b..e8d09ebb1 100644 --- a/.github/workflows/release-canary.yml +++ b/.github/workflows/release-canary.yml @@ -47,13 +47,19 @@ jobs: echo "version=$version" >> "$GITHUB_OUTPUT" ci: - needs: [identity, ui] + needs: [identity, ui, build-host] uses: ./.github/workflows/ci.yml with: plan: '{}' source-sha: ${{ github.sha }} release: true + build-host: + needs: identity + uses: ./.github/workflows/build-host.yml + with: + source-sha: ${{ github.sha }} + ui: needs: identity runs-on: ubuntu-24.04 @@ -78,7 +84,7 @@ jobs: if-no-files-found: error macos-build: - needs: [identity, ui] + needs: [identity, ui, build-host] if: vars.MACOS_SIGNING_ENABLED == 'true' strategy: matrix: @@ -94,6 +100,11 @@ jobs: with: name: release-ui path: ui/dist + - name: Download release hosts + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c + with: + name: release-host + path: target/host-binaries - run: rustup target add ${{ matrix.target }} - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 with: @@ -103,6 +114,7 @@ jobs: - name: Build orx env: ORX_OFFICIAL_RELEASE_BUILD: '1' + ORX_EMBED_HOST_DIR: ${{ github.workspace }}/target/host-binaries ORX_DESKTOP_CANARY_TAG: ${{ needs.identity.outputs.tag }} ORX_DESKTOP_CANARY_SHA: ${{ github.sha }} ORX_DESKTOP_CANARY_CHANGES: ${{ needs.identity.outputs.changes }} @@ -115,6 +127,7 @@ jobs: macos: needs: [identity, macos-build] + if: vars.MACOS_SIGNING_ENABLED == 'true' runs-on: macos-latest timeout-minutes: 45 environment: release-signing @@ -155,7 +168,7 @@ jobs: if-no-files-found: error linux: - needs: [identity, ui] + needs: [identity, ui, build-host] if: vars.LINUX_APP_ENABLED == 'true' strategy: fail-fast: false @@ -176,6 +189,11 @@ jobs: with: name: release-ui path: ui/dist + - name: Download release hosts + uses: actions/download-artifact@v4 + with: + name: release-host + path: target/host-binaries - run: | sudo apt-get update sudo apt-get install -y libwebkit2gtk-4.1-dev libgtk-3-dev librsvg2-dev file patchelf xvfb xdotool @@ -186,6 +204,7 @@ jobs: - name: Build app env: ORX_OFFICIAL_RELEASE_BUILD: '1' + ORX_EMBED_HOST_DIR: ${{ github.workspace }}/target/host-binaries ORX_DESKTOP_CANARY_TAG: ${{ needs.identity.outputs.tag }} ORX_DESKTOP_CANARY_SHA: ${{ github.sha }} ORX_DESKTOP_CANARY_CHANGES: ${{ needs.identity.outputs.changes }} @@ -203,7 +222,7 @@ jobs: if-no-files-found: error windows: - needs: [identity, ui] + needs: [identity, ui, build-host] if: vars.WINDOWS_APP_ENABLED == 'true' runs-on: windows-latest timeout-minutes: 45 @@ -227,9 +246,15 @@ jobs: workspaces: | . -> target windows/launcher -> target + - name: Download release hosts + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c + with: + name: release-host + path: target/host-binaries - name: Build app env: ORX_OFFICIAL_RELEASE_BUILD: '1' + ORX_EMBED_HOST_DIR: ${{ github.workspace }}/target/host-binaries ORX_DESKTOP_CANARY_TAG: ${{ needs.identity.outputs.tag }} ORX_DESKTOP_CANARY_SHA: ${{ github.sha }} ORX_DESKTOP_CANARY_CHANGES: ${{ needs.identity.outputs.changes }} diff --git a/.github/workflows/release-linux-app.yml b/.github/workflows/release-linux-app.yml index 3a2994856..60084681a 100644 --- a/.github/workflows/release-linux-app.yml +++ b/.github/workflows/release-linux-app.yml @@ -67,7 +67,7 @@ jobs: if [ -n "${expected_sha:-}" ]; then test "$sha" = "$expected_sha"; fi version=$(git show "$sha:Cargo.toml" | grep -m1 '^version = ' | sed -E 's/version = "(.*)"/\1/') test "$tag" = "v$version" - if [ -z "$RELEASE_RUN_ID" ] && ! git cat-file -e "$sha:ui/dist/index.html" 2>/dev/null; then + if [ -z "$RELEASE_RUN_ID" ] && { git cat-file -e "$sha:scripts/build-host.mjs" 2>/dev/null || ! git cat-file -e "$sha:ui/dist/index.html" 2>/dev/null; }; then RELEASE_RUN_ID=$(bash scripts/find-release-run.sh "$tag" "$sha") fi echo "ok=true" >> "$GITHUB_OUTPUT" @@ -104,6 +104,15 @@ jobs: run-id: ${{ needs.check.outputs.release-run-id }} github-token: ${{ github.token }} + - name: Download release hosts + if: needs.check.outputs.release-run-id != '' && hashFiles('scripts/build-host.mjs') != '' + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 + with: + name: release-host + path: target/host-binaries + run-id: ${{ needs.check.outputs.release-run-id }} + github-token: ${{ github.token }} + - name: Install WebKitGTK and packaging tools run: | sudo apt-get update @@ -111,6 +120,8 @@ jobs: # The runner's preinstalled stable toolchain, as release-macos-app.yml uses. - name: Build the production orx + env: + ORX_EMBED_HOST_DIR: ${{ github.workspace }}/target/host-binaries run: ORX_OFFICIAL_RELEASE_BUILD=1 cargo build --release --locked --features desktop - name: Verify the production channel diff --git a/.github/workflows/release-macos-app.yml b/.github/workflows/release-macos-app.yml index d3f1a8c80..207ecfa0c 100644 --- a/.github/workflows/release-macos-app.yml +++ b/.github/workflows/release-macos-app.yml @@ -82,7 +82,7 @@ jobs: if [ -n "${expected_sha:-}" ]; then test "$sha" = "$expected_sha"; fi version=$(git show "$sha:Cargo.toml" | grep -m1 '^version = ' | sed -E 's/version = "(.*)"/\1/') test "$tag" = "v$version" - if [ -z "$RELEASE_RUN_ID" ] && ! git cat-file -e "$sha:ui/dist/index.html" 2>/dev/null; then + if [ -z "$RELEASE_RUN_ID" ] && { git cat-file -e "$sha:scripts/build-host.mjs" 2>/dev/null || ! git cat-file -e "$sha:ui/dist/index.html" 2>/dev/null; }; then RELEASE_RUN_ID=$(bash scripts/find-release-run.sh "$tag" "$sha") fi echo "ok=true" >> "$GITHUB_OUTPUT" @@ -117,6 +117,15 @@ jobs: run-id: ${{ needs.check.outputs.release-run-id }} github-token: ${{ github.token }} + - name: Download release hosts + if: needs.check.outputs.release-run-id != '' && hashFiles('scripts/build-host.mjs') != '' + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 + with: + name: release-host + path: target/host-binaries + run-id: ${{ needs.check.outputs.release-run-id }} + github-token: ${{ github.token }} + - name: Take signing action from the workflow revision uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: @@ -140,6 +149,8 @@ jobs: notary-password: ${{ secrets.MACOS_NOTARY_PASSWORD }} - name: Build universal app + env: + ORX_EMBED_HOST_DIR: ${{ github.workspace }}/target/host-binaries run: ORX_OFFICIAL_RELEASE_BUILD=1 ORX_APP_UNIVERSAL=1 bash scripts/build-macos-app.sh - name: Verify bundled production channel diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index ffaaf9983..c66493d4e 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -143,6 +143,12 @@ jobs: path: ui/dist/ if-no-files-found: error + build-host: + needs: plan + uses: ./.github/workflows/build-host.yml + with: + source-sha: ${{ needs.plan.outputs.source-sha }} + # Build and packages all the platform-specific things build-local-artifacts: name: build-local-artifacts (${{ join(matrix.targets, ', ') }}) @@ -150,6 +156,7 @@ jobs: needs: - plan - build-ui + - build-host if: ${{ fromJson(needs.plan.outputs.val).ci.github.artifacts_matrix.include != null }} strategy: fail-fast: false @@ -209,7 +216,14 @@ jobs: with: name: release-ui path: ui/dist + - name: Download release hosts + uses: actions/download-artifact@v8 + with: + name: release-host + path: target/host-binaries - name: Build artifacts + env: + ORX_EMBED_HOST_DIR: ${{ github.workspace }}/target/host-binaries run: | # Actually do builds and make zips and whatnot dist build ${{ needs.plan.outputs.tag-flag }} --print=linkage --output-format=json ${{ matrix.dist_args }} > dist-manifest.json @@ -343,6 +357,7 @@ jobs: needs: - plan - build-ui + - build-host - build-local-artifacts - custom-sign-macos-cli - custom-sign-windows-cli @@ -355,7 +370,7 @@ jobs: issues: read pull-requests: read # Only run if we're "publishing", and only if plan, local and global didn't fail (skipped is fine) - if: ${{ always() && needs.plan.result == 'success' && needs.plan.outputs.publishing == 'true' && needs.build-ui.result == 'success' && (needs.build-global-artifacts.result == 'skipped' || needs.build-global-artifacts.result == 'success') && needs.custom-verify-build-channel.result == 'success' && needs.custom-telemetry-contract.result == 'success' && needs.custom-ci.result == 'success' && (needs.build-local-artifacts.result == 'skipped' || needs.build-local-artifacts.result == 'success') && (needs.custom-sign-macos-cli.result == 'skipped' || needs.custom-sign-macos-cli.result == 'success') && (needs.custom-sign-windows-cli.result == 'skipped' || needs.custom-sign-windows-cli.result == 'success') }} + if: ${{ always() && needs.plan.result == 'success' && needs.plan.outputs.publishing == 'true' && needs.build-ui.result == 'success' && needs.build-host.result == 'success' && (needs.build-global-artifacts.result == 'skipped' || needs.build-global-artifacts.result == 'success') && needs.custom-verify-build-channel.result == 'success' && needs.custom-telemetry-contract.result == 'success' && needs.custom-ci.result == 'success' && (needs.build-local-artifacts.result == 'skipped' || needs.build-local-artifacts.result == 'success') && (needs.custom-sign-macos-cli.result == 'skipped' || needs.custom-sign-macos-cli.result == 'success') && (needs.custom-sign-windows-cli.result == 'skipped' || needs.custom-sign-windows-cli.result == 'success') }} env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} runs-on: "ubuntu-22.04" diff --git a/.gitignore b/.gitignore index d0bc20cf8..cb737f5e6 100644 --- a/.gitignore +++ b/.gitignore @@ -26,3 +26,4 @@ ui/package-lock.json # Per-worktree dev data, binaries, and states (dev.ts). /.dev/ +/.shots/ diff --git a/AGENTS.md b/AGENTS.md index f3b0a60f9..feaea8753 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -11,7 +11,8 @@ catalogs; when you change an API it serves, keep both sides compatible. | --- | --- | | `src/commands/` | One module per `orx` command; `up` is the server and its API, `app` the window. | | `src/local/` | Projects and Git, chats (`chat/`), agent harnesses (`harness/`), skills, papers. | -| `src/jobs/`, `src/compute.rs` | Compute backends and the run lifecycle `orx supervise` drives. | +| `src/engine/`, `crates/orx-host*` | The run engine in `orx up` and the `orx-host` binary that runs jobs on hosts. | +| `src/jobs/`, `src/compute.rs` | Backend clients, SSH config sharing, and the SSH service kept for 0.2.x runs. | | `src/store.rs` | The SQLite store and its schema. | | `src/client.rs`, `src/config.rs` | The openresearch.sh client, credentials, settings paths. | | `src/updates*` | Self-update for the CLI and the desktop apps. | @@ -41,10 +42,9 @@ catalogs; when you change an API it serves, keep both sides compatible. A message reaches `orx up`, which starts or reuses the chat's agent in the chat's own worktree, with orx's playbook, skills and the `orx` CLI on its `PATH`. The agent commits and runs `orx exp run`: the dashboard archives the -experiment's commit, submits it to a backend, and a detached `orx supervise` -watches the job and tails its logs into the run. When it ends, the chat that -asked is woken with the result. The page follows it all through one event -stream. +experiment's commit and submits it to a backend. A supervisor or the engine +watches it and delivers results to the chat that asked. The page follows it +through one event stream. See [the run engine setting](arc/experiments.md#choosing-the-run-engine). ## Architecture essays @@ -53,8 +53,8 @@ one for the area you touch, and fix any statement your change makes false. - [Where state lives](arc/storage.md): directories, the store, locks, egress. - [Chats and agents](arc/agents.md): harnesses, isolation, permissions, recovery. -- [Experiments and compute](arc/experiments.md): snapshots, backends, rentals. -- [Remote machines](arc/remote.md): the persistent host and the SSH service. +- [Experiments and compute](arc/experiments.md): snapshots, backends, the run engine. +- [Remote machines](arc/remote.md): the persistent host, `orx-host` and SSH transport. - [The dashboard](arc/dashboard.md): the guard, live state, the React app. - [The desktop app and releases](arc/desktop.md): app mode, updates, shipping. diff --git a/Cargo.lock b/Cargo.lock index 92a85568b..462bca491 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2662,6 +2662,7 @@ dependencies = [ "futures", "glob", "gtk", + "hmac", "httpdate", "hyper", "hyper-util", @@ -2671,6 +2672,10 @@ dependencies = [ "objc2-app-kit", "objc2-foundation", "objc2-web-kit", + "once_cell", + "orx-host", + "orx-host-proto", + "orx-test-support", "pbkdf2", "png", "portable-pty", @@ -2713,6 +2718,40 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" +[[package]] +name = "orx-host" +version = "0.1.0" +dependencies = [ + "cc", + "libc", + "orx-host", + "orx-host-proto", + "orx-test-support", + "serde", + "serde_json", + "sha2", +] + +[[package]] +name = "orx-host-proto" +version = "0.1.0" +dependencies = [ + "base64 0.22.1", + "serde", + "serde_json", +] + +[[package]] +name = "orx-test-support" +version = "0.0.0" +dependencies = [ + "anyhow", + "libc", + "sha2", + "socket2", + "tempfile", +] + [[package]] name = "pango" version = "0.18.3" @@ -4013,6 +4052,19 @@ version = "0.12.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1" +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.2", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + [[package]] name = "tendril" version = "0.5.1" diff --git a/Cargo.toml b/Cargo.toml index dff4d9715..ca4ff402f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,6 +6,15 @@ description = "OpenResearch CLI (orx) — Rust port" repository = "https://github.com/alphaXiv/OpenResearch" license = "MIT" +[workspace] +members = ["tests/support", "crates/orx-host-proto", "crates/orx-host"] +exclude = ["windows/launcher"] +default-members = [".", "tests/support", "crates/orx-host-proto", "crates/orx-host"] + +[target.'cfg(unix)'.dev-dependencies] +tokio = { version = "1", features = ["test-util"] } +orx-test-support = { path = "tests/support" } + [[bin]] name = "orx" path = "src/main.rs" @@ -46,6 +55,7 @@ uuid = { version = "1", features = ["v4"] } semver = "1" fd-lock = "4" base64 = "0.22" +once_cell = "1" # Extract user-uploaded skills shipped as a .zip of a SKILL.md folder. Lean: # deflate only, no bzip2/zstd/time/aes. zip = { version = "2", default-features = false, features = ["deflate"] } @@ -59,7 +69,9 @@ futures = "0.3" portable-pty = "0.9" # async fns in the Harness trait (object-safe `dyn Harness` in the registry). async-trait = "0.1" +orx-host-proto = { path = "crates/orx-host-proto" } sha2 = "0.10" +hmac = "0.12" # Import the Overleaf editor session cookie from a local browser store, so the # user need not paste it. Chromium on macOS encrypts cookies with AES-128-CBC # under a Keychain-held key (PBKDF2-HMAC-SHA1). Pure-Rust RustCrypto crates, so @@ -79,6 +91,7 @@ same-file = "1.0" roxmltree = "0.21" [target.'cfg(unix)'.dependencies] +orx-host = { path = "crates/orx-host" } # Free-space pre-check for the data-dir move (statvfs). Already in the tree # transitively; taken as a direct dep only on unix, where we call it. libc = "0.2" @@ -114,13 +127,14 @@ png = { version = "0.18", optional = true } # muda builds the menu bar, and objc2-app-kit's NSAlert backs `window.confirm`. objc2 = "0.6" objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSAlert", "NSApplication", "NSButton", "NSControl", "NSResponder", "NSTextCheckingClient", "NSGraphics", "NSView", "NSVisualEffectView", "NSWindow"] } -objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSString"] } +objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSString", "NSAppleEventManager", "NSAppleEventDescriptor"] } objc2-web-kit = { version = "0.3", default-features = false, features = ["WKWebViewConfiguration"] } muda = "0.20" # `window.confirm` panel added to wry's WKUIDelegate (src/commands/app.rs). block2 = "0.6" [build-dependencies] +sha2 = "0.10" # Embeds the Windows icon in orx.exe; a no-op for other targets. embed-resource = "3" @@ -136,3 +150,24 @@ debug = "line-tables-only" # Third-party crates need no line info; saves another ~0.2 GiB per build. [profile.dev.package."*"] debug = false + +# Large-page tests need native JSON and SSH proxy throughput. +[profile.test.package.orx-host] +opt-level = 3 + +[profile.test.package.orx-host-proto] +opt-level = 3 + +[profile.test.package.serde_json] +opt-level = 3 + +[profile.test.package.orx-test-support] +opt-level = 3 + +[profile.host] +inherits = "release" +opt-level = "z" +lto = true +codegen-units = 1 +strip = true +panic = "abort" diff --git a/agent-skills/orx-compute/SKILL.md b/agent-skills/orx-compute/SKILL.md index 961543ef2..62b50dc19 100644 --- a/agent-skills/orx-compute/SKILL.md +++ b/agent-skills/orx-compute/SKILL.md @@ -1,6 +1,6 @@ --- name: orx-compute -description: "Launch and monitor experiment runs and route guidance for hf, modal, k8s/Kubernetes, ssh, slurm, ray, vercel, OpenResearch, Tinker, and local backends. Covers the fixed run contract, sizing, cancellation, and wait versus wake. Use before any launch or relaunch, when authoring a k8s manifest, choosing or switching compute, or handling an OOM, stall, or timeout; then read one backend reference." +description: "Launch and monitor experiment runs and route guidance for hf, modal, k8s/Kubernetes, ssh, slurm, ray, vercel, OpenResearch, Tinker, and local backends. Covers the fixed run contract, sizing, cancellation, and result messages. Use before any launch or relaunch, when authoring a k8s manifest, choosing or switching compute, or handling an OOM, stall, or timeout; then read one backend reference." --- Each run uses an immutable snapshot of the experiment branch's recorded commit. @@ -56,8 +56,8 @@ change the configured backend or authorize bypassing the launch contract. - **Commit before launching.** Every backend runs the recorded commit's immutable source snapshot. Uncommitted files are excluded; no backend needs a GitHub push. -- `orx exp run` queues the run and returns immediately. Follow it with `orx - runs`, `orx logs`, `orx exp wait`, or `orx exp wake`. +- `orx exp run` queues the run and returns immediately. End your turn once the + ready runs are launched; relevant results arrive as messages in this chat. - `--force` permits a deliberate concurrent run on the same experiment. Without it, `orx` rejects a launch while that node already has a run in flight. @@ -117,39 +117,52 @@ For Slurm, `--cpus` and `--mem` request `#SBATCH --cpus-per-task` and partition default. Read `references/slurm.md` before choosing values. -## Waiting on runs — `orx exp wait` - -Block until a run changes state when you want to act as soon as it finishes: - -```sh -orx exp wait # wait for this experiment's latest run -orx exp wait --project # return on the first project completion -orx exp wait --interval 10 --timeout 3600 -``` - -- Pass exactly one of `` or `--project`. -- `--project` is the budget-loop primitive: it returns on the first completion, - not on starts or queued-to-running transitions. Reissue it once per loop tick. -- A wait is a sleep-until-change signal, not the source of truth. After every - return, read `orx runs ` and reconcile all newly terminal runs. -- When nothing is in flight, project wait returns `drained: no runs in flight`. -- The default interval is 5 seconds and timeout is 1800 seconds. Timeout exits - non-zero and means nothing changed yet, not that the run failed. -- Cancel only a run that is broken or no longer wanted; after a wait timeout, - wait again instead of cancelling. -- Failed runs include a `reason:` line. Provider-capacity failures are often - retryable; failures after startup require reading the file located by `orx logs `. -- A failed run is not a new node. Repair and relaunch the same experiment as - described by `orx-experiment-tree`. - -### Going idle instead — `orx exp wake` - -After launching, use `orx exp wake ` when you want to end the turn and -resume after that run succeeds or fails. Wake-up is opt-in, fires only for -`done` or `failed`, and waits behind queued user messages. If orx cannot -monitor a live Slurm run for over a minute, it tells you once per outage; the -final wake-up comes once orx can see the run finish. Use either wait or wake -for a run, not both. +## Run engine setting + +Stable and dev builds use detached supervisors by default; +`ORX_RUN_ENGINE=1|0` on `orx up` overrides the saved opt-in. Canary builds +always use the new engine being tested and ignore both the setting and +environment override. Leave the user's setting alone unless asked. Existing +runs keep their launch mode when the setting changes. In supervised mode, a +detached `orx supervise` watches each run and streams logs; do not kill it. +With the new engine, the OpenResearch server watches runs and catches up when +reopened. Jobs keep running while the server is closed in both modes. The +snapshot, command, result-message and wake contracts apply in both modes. +Engine-specific contact states, Abandon and interim notify messages apply to +engine-owned runs. + +## Results arrive in the chat + +Launch ready runs with `orx exp run`, then end your turn. The launching chat is +subscribed automatically. Results wait until the chat is idle and may combine +several updates into one message. No waiting command or live agent session is +needed to keep the runs monitored. Silence does not mean a run failed. A run +can post an interim result with the new engine by appending a line to +`$ORX_NOTIFY_FILE` (`>>`) when set; it arrives at most once per run per 10 +minutes, with later lines coalesced. + +When a result message arrives, read `orx runs ` and reconcile every +newly terminal run, including runs that finished while you were analyzing an +earlier result. Read the file located by `orx logs ` and compare metrics +before deciding whether to repair, refill a slot, promote a result, or stop. +A failed run is not a new node: repair and relaunch the same experiment as +specified by `orx-experiment-tree`. + +With the new engine, attention messages also arrive when monitoring or +cancellation needs action. Supervised runs show monitoring errors in their +status. Inspect `orx exp status ` and tell the user what needs +fixing. Cancel only a run that is broken or no longer wanted. + +With the new engine, **Cancellation pending** means the cancel has been +accepted but has not reached the machine. It will be sent when the machine is +reachable again or the launch is confirmed. **Cancelling…** means the machine +is stopping the run. To stop tracking an unreachable run, use +`orx exp abandon `; double-check that the actual compute is shut down. +The cancel stays pending after Abandon. + +Use `orx exp wake ` to subscribe this chat to a run launched elsewhere. +`orx exp wait` remains available for humans; do not use it to keep an agent +session waiting for results. ## Sizing compute diff --git a/agent-skills/orx-compute/references/hf.md b/agent-skills/orx-compute/references/hf.md index 9aa6d4095..220ff831b 100644 --- a/agent-skills/orx-compute/references/hf.md +++ b/agent-skills/orx-compute/references/hf.md @@ -23,5 +23,5 @@ orx exp run --backend hf --flavor cpu-upgrade --image python:3.12 shapes and `python:3.12` for CPU shapes. - `orx` uploads the committed snapshot into a private job volume. The job never clones a repository or needs repository credentials. -- A detached `orx supervise` process records provider status and logs; do not - kill it. + +See [run monitoring](../SKILL.md#run-engine-setting). diff --git a/agent-skills/orx-compute/references/k8s.md b/agent-skills/orx-compute/references/k8s.md index ae7b95bfb..d7c80100b 100644 --- a/agent-skills/orx-compute/references/k8s.md +++ b/agent-skills/orx-compute/references/k8s.md @@ -49,5 +49,5 @@ The submit-time contract is: - Auxiliary resources may accompany the Job and are deleted on cancellation. They must reference the `orx-env` Secret themselves when needed. - The run log follows the primary Job's sole pod. -- A detached `orx supervise` process watches the Job through `kubectl`; do not - kill it. + +See [run monitoring](../SKILL.md#run-engine-setting). diff --git a/agent-skills/orx-compute/references/local.md b/agent-skills/orx-compute/references/local.md index 3872548eb..1b4f33b13 100644 --- a/agent-skills/orx-compute/references/local.md +++ b/agent-skills/orx-compute/references/local.md @@ -17,4 +17,5 @@ orx exp run --backend local the process group. - Finished runs older than each project's three newest local runs lose `repo/.venv` and `repo/.cache/uv`; logs, TensorBoard files, and other outputs stay. -- A detached `orx supervise` process watches the run; do not kill it. + +See [run monitoring](../SKILL.md#run-engine-setting). diff --git a/agent-skills/orx-compute/references/modal.md b/agent-skills/orx-compute/references/modal.md index f39cfab61..1904b8a45 100644 --- a/agent-skills/orx-compute/references/modal.md +++ b/agent-skills/orx-compute/references/modal.md @@ -23,5 +23,5 @@ orx exp run --backend modal --flavor cpu --image python:3.12 adds `uv` to every image's PATH; an image's own `uv` on its PATH takes precedence. - `orx` copies the committed snapshot into the Sandbox; Modal never needs repository access. -- A detached `orx supervise` process records provider status and logs; do not - kill it. + +See [run monitoring](../SKILL.md#run-engine-setting). diff --git a/agent-skills/orx-compute/references/openresearch.md b/agent-skills/orx-compute/references/openresearch.md index 9f088737c..1be910907 100644 --- a/agent-skills/orx-compute/references/openresearch.md +++ b/agent-skills/orx-compute/references/openresearch.md @@ -17,5 +17,5 @@ orx exp run --backend openresearch --flavor cpu5c:32 --org - Timeout defaults to 4 hours. The machine and its storage disappear when the run ends, so all evidence must reach the run log. - `orx` streams the committed snapshot to the provisioned machine. -- A detached `orx supervise` process records machine status and logs; do not - kill it. + +See [run monitoring](../SKILL.md#run-engine-setting). diff --git a/agent-skills/orx-compute/references/ray.md b/agent-skills/orx-compute/references/ray.md index fe9a17322..6bccc9662 100644 --- a/agent-skills/orx-compute/references/ray.md +++ b/agent-skills/orx-compute/references/ray.md @@ -18,5 +18,5 @@ orx exp run --backend ray --flavor cpu:2,mem:8GiB - Omit the flavor to reserve nothing, which avoids Pending on small heads. - There is no image, host, or timeout flag. Bound the work in the run command. - Ray receives the committed snapshot as its `working_dir` package. -- A detached `orx supervise` process records job status and logs; do not kill - it. + +See [run monitoring](../SKILL.md#run-engine-setting). diff --git a/agent-skills/orx-compute/references/slurm.md b/agent-skills/orx-compute/references/slurm.md index 18c9a1f40..5059dd933 100644 --- a/agent-skills/orx-compute/references/slurm.md +++ b/agent-skills/orx-compute/references/slurm.md @@ -3,7 +3,8 @@ 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`. The login node -needs Python 3.6 or newer; no Python packages or administrator installation are required. +needs Python 3.6 or newer for supervised runs; engine runs use `orx-host`. +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`. @@ -16,6 +17,9 @@ orx exp run --backend slurm - `--host` is an alias from `~/.ssh/config`; omit it only when a Slurm default host is configured. +- `--partition` overrides the saved Slurm partition for one run. A list such as + `gpu,batch` lets Slurm choose between partitions; omit it to use the saved or + cluster default. - `--flavor` is an optional GRES GPU request such as `h100:2`. Omit it for CPU. - `--cpus` and `--mem` set `#SBATCH --cpus-per-task` and `#SBATCH --mem` (`64G`, `4000M`, or a bare number for megabytes). Unset falls back to @@ -26,19 +30,19 @@ orx exp run --backend slurm profile—is used as-is. - `--timeout` covers the batch job. Unset falls back to the Slurm time-limit setting, then the cluster's limit. -- Runs and the cached source archive live under `~/.orx` on the cluster unless - `orx compute configure slurm --remote-root /scratch/alice/orx` names another - absolute directory, such as scratch space when home quota is small. It must - be on a filesystem the compute nodes share. Each run keeps the root it was - submitted with; `--clear remote-root` restores the default for new runs. -- Each project's three newest SSH and Slurm runs, counted together across - hosts and including unfinished ones, stay whole. Once an older finished - run's log is collected, the running OpenResearch app removes its remote run - dir except `tensorboard/`. It also removes orx's cached source archives that - no active run uses and that have been idle for an hour, then checks again an - hour later. Anything the job wrote into `repo/` goes with it. To keep every run - on the cluster, set `orx compute configure slurm --keep-remote-runs true` - (it covers runs not yet cleaned up), or write outputs outside the run dir. - Deleting a project removes its runs' remote dirs entirely regardless. -- A detached `orx supervise` process records scheduler status and logs; do not - kill it. +- With the new engine enabled, runs and cached source archives live under + `~/.orx/engine` on the cluster unless `orx compute configure slurm --remote-root /scratch/alice/orx` names + another absolute directory (runs then live in its `engine/` subdirectory), + such as scratch space when home quota is small. It must be on a filesystem + the compute nodes share. Each run keeps the root it was submitted with; + `--clear remote-root` restores the default for new runs. +- Run dirs stay on the cluster after the run; OpenResearch keeps each run's + log on this computer. Remove old dirs under `/engine/runs/` when space + runs short. +- Supervised runs (the stable/dev default) use `/runs/`. Each project's three newest + SSH and Slurm runs stay whole, older finished ones lose their remote run dir + except `tensorboard/`, and idle cached source archives are removed. + `orx compute configure slurm --keep-remote-runs true` keeps them all; deleting + a project removes them regardless. + +See [run monitoring](../SKILL.md#run-engine-setting). diff --git a/agent-skills/orx-compute/references/ssh.md b/agent-skills/orx-compute/references/ssh.md index aff3478fe..f5a256d8b 100644 --- a/agent-skills/orx-compute/references/ssh.md +++ b/agent-skills/orx-compute/references/ssh.md @@ -4,32 +4,20 @@ Use this backend when the user asks to run on their own server, or when SSH is the configured compute default. Authentication uses SSH config, keys and the agent; `orx` never reads private keys. -On Unix, `orx compute connect ssh --host lab` authenticates once for background -commands. Its master stays available for 24 hours of idle time and sends -keepalives every 30 seconds. Use `--persist ` to set a new master's idle -lifetime (`0` keeps it indefinitely); an existing master retains its settings. -Reconnect to recover an expired login. -On Unix with OpenSSH 8.4 or newer, successful connections automatically install -`Include openresearch_config` in `~/.ssh/config`. Agents and ordinary `ssh`, -`scp`, and `rsync` commands reuse a live connection for the same user, host, -and port of a connected alias. Configured `ProxyJump` and `ProxyCommand` routes -remain separate. Existing user `ControlPath` settings, including `Match final`, -take precedence; the managed Include appears after your settings. -Symlinked configs require adding the reported Include manually. -OpenResearch-launched agents select their instance's connection directory; -external terminals use the default configuration unless they export -`ORX_SSH_CONTROL_DIR` to the instance's directory. After upgrading from older -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. +With the new experiment engine enabled, the OpenResearch server keeps one SSH +connection per host for all of its runs, logs, and checks. Its first contact with a host is a single key-only attempt: a +host that accepts your keys or agent never needs Connect. If that attempt needs +a password, passphrase, or MFA, nothing retries until you run +`orx compute connect ssh --host lab` (or press Connect), which asks the questions +and keeps an orx-owned connection. On Unix, its shared master survives +OpenResearch restarts; on Windows, engine and supervised runs need separate +connections, so Connect may ask for MFA twice. A changed host route also waits +for Connect. Network failures back off from 5 seconds up to 15 minutes without +declaring any run stopped; the chat hears once +when a host has been unreachable for 10 minutes and again when it returns. +On OpenSSH 8.4 and later, plain `ssh`, `scp` and `rsync` share that interactive +connection through a managed file. orx adds its `Include openresearch_config` +to `~/.ssh/config` once, preserving the existing contents. ```sh orx exp run --backend ssh --host lab @@ -38,9 +26,10 @@ orx exp run --backend ssh --host lab --no-container ``` Machine-local SSH settings can save a container name or ID for each host, and -an absolute remote storage root (`--remote-root /data/alice/orx`) used instead -of `~/.orx` for that host's runs and cached source archives. Each run keeps the -root it was launched with. +an absolute remote storage root (`--remote-root /data/alice/orx`). Runs and +cached source archives live under `/engine/` (`~/.orx/engine/` by +default) with the new engine, or directly under `` (`~/.orx`) with +supervisors. Each run keeps the root it was launched with. A saved default SSH host lets launches omit `--host`. These defaults apply only to SSH experiments; dashboards, terminals and coding agents still connect directly to the host. @@ -48,17 +37,9 @@ agents still connect directly to the host. - Omitted container selection uses the host's saved target. `--container` overrides it; `--no-container` explicitly runs on the host. The flags conflict. -Each project's three newest SSH and Slurm runs, counted together across hosts -and including unfinished ones, stay whole. Once an older finished run's log is -collected, the running OpenResearch app removes its host dir except -`tensorboard/`, and the container's copy entirely (retried while the container -is stopped), so anything written into `repo/` goes with it. While cleaning a host it also removes orx's cached source -archives that no active run uses and that have been idle for an hour, and -checks again an hour later. -Unreachable hosts are retried later. -`orx compute configure ssh --host lab --keep-remote-runs true` keeps all of -that host's runs not yet cleaned up. Deleting a project removes its runs' -remote dirs entirely, regardless of that setting. +OpenResearch keeps each run's log on this computer and each project's three +newest SSH and Slurm run dirs on the host. Older finished runs lose their host +dir except `tensorboard/`; `--keep-remote-runs true` keeps them all. Keep environment preparation in the project's committed setup/run scripts and invoke them through the fixed run command, just as with other backends. For @@ -66,8 +47,10 @@ 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, tar, and Python 3.6 or newer (standard library only). -OpenResearch does not install Python automatically. Container execution also requires host Docker +With the new engine, the SSH host needs Linux (x86_64 or aarch64, kernel 3.2 +or newer) or macOS, +with Bash and tar. OpenResearch installs its small `orx-host` helper under the +storage root on first use. 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 @@ -75,17 +58,27 @@ creation or lifecycle management. `--image` and `--flavor` are unsupported. The committed source archive is cached on the host, then streamed into the container's `$HOME/.orx/runs//repo`. Host logs and exit status stay in the -host's `/runs//` (`~/.orx` unless a remote root is saved), so -container removal does not erase them before they are collected. A detached -supervisor reattaches using the saved container ID and start time; later -settings changes cannot redirect an existing run. Do not kill the supervisor. +host's run directory (`/engine/runs//` with the new engine, +`/runs//` with supervisors), so container removal does not erase them. +A run is bound to the container ID and start time it launched with; later +settings changes cannot redirect it. Cancellation targets only the experiment process group, waits five seconds for TERM, then uses KILL if needed. It leaves the container and unrelated processes -running. Paused containers must be unpaused by the user before cancellation can -finish. Stopping, removing or restarting a container fails its experiment. +running. A paused container keeps cancellation pending: the stop hook retries +with backoff until the user unpauses it or the container stops or disappears. Stopping, removing or restarting a container fails its experiment. Docker/SSH outages are retried rather than reported as container removal. +A cancelled run with surviving processes shows Not fully stopped and their count +and host until they stop. Cancelled with an unchecked-process note names the +containment the host could not inspect. Host authentication and container readiness are separate checks. Preflight must check the explicitly selected container; host readiness does not imply container readiness. + +With the engine setting off, a detached `orx supervise` watches each run through +the shared SSH service. Background monitoring reuses an authenticated connection +and never starts a fresh login. The host also needs Python 3.6 or newer. +Monitoring outages appear in run status after 60 seconds; reconnect to resume +monitoring. +The new engine’s surviving-process and contact states above do not apply. diff --git a/agent-skills/orx-compute/references/vercel.md b/agent-skills/orx-compute/references/vercel.md index 14415c544..e2c555fce 100644 --- a/agent-skills/orx-compute/references/vercel.md +++ b/agent-skills/orx-compute/references/vercel.md @@ -34,9 +34,12 @@ orx exp run --backend vercel --flavor 4 --image vercel/sandbox/universal `uv` and GNU `tail`. Images come from Vercel Container Registry. A custom image without GNU `tail --pid` (busybox or alpine) still streams logs: orx detects that and polls the log until the job exits. If the image cannot read - the log at all, the supervisor reports an error instead of an empty log. + the log at all, the run reports an error instead of an empty log. - `ORX_VERCEL_REGION` picks a region; otherwise Vercel uses the project default. - `orx` copies the committed snapshot into the sandbox; Vercel never needs repository access. -- A detached `orx supervise` process records status and logs, then stops and - destroys the sandbox when the run ends; do not kill it. + +OpenResearch stops and destroys the sandbox once the run ends and its logs +are collected. + +See [run monitoring](../SKILL.md#run-engine-setting). diff --git a/agent-skills/orx-experiment-tree/SKILL.md b/agent-skills/orx-experiment-tree/SKILL.md index babdd9002..5276c971a 100644 --- a/agent-skills/orx-experiment-tree/SKILL.md +++ b/agent-skills/orx-experiment-tree/SKILL.md @@ -1,6 +1,6 @@ --- name: orx-experiment-tree -description: "Plan and drive the experiment tree: first-launch setup, fixed run contract, frozen nodes, stacked-bush tree shape, branch/launch/wait/promote, repair limits, notes, and turn summaries. Use before creating or changing experiments, launching a first run, deciding what to try next, handling a completed run, or reporting experiment progress." +description: "Plan and drive the experiment tree: first-launch setup, fixed run contract, frozen nodes, stacked-bush tree shape, branch/launch/reconcile/promote, repair limits, notes, and turn summaries. Use before creating or changing experiments, launching a first run, deciding what to try next, handling a completed run, or reporting experiment progress." --- A project is a **tree of experiment nodes**. The root (**baseline**) holds the @@ -138,43 +138,15 @@ intended flow — do **not** edit a frozen node or rewrite the run command: (or omit `--backend` when a default target is set — see `orx-compute`). Remote backends can run siblings in parallel; `--backend local` shares this machine's CPU, RAM, and GPU. -6. **Keep the round moving — drive a per-completion loop, not a wait-for-all - barrier.** You want control back the moment *any one* run finishes so you can - analyze it and either refill its slot or stop — not after the whole batch - drains. `orx exp wait --project ` is built for exactly this: it - returns on the **first** completion. Treat it as one **tick** of a loop, where - *you* are the loop body: - - ``` - # after launching your runs, loop until the project is drained: - loop: - orx exp wait --project # sleeps; returns on the first completion - orx runs # SOURCE OF TRUTH: re-read all run states - # for each run now terminal that you haven't handled yet: - # - read its results (step 7) and decide: launch a refill? promote it? stop? - # - launch the next queued child to refill the freed slot (step 5) - # if `exp wait` printed "drained: no runs in flight" → batch is done, break - ``` - - Three things make this robust — follow all of them: - - **`exp wait --project` is a sleep-until-change signal, not the source of - truth.** It only reports completions it observed *during that one call*. A - run that finishes while you're analyzing the previous one is already terminal - by the next call and **won't be reported**. So on every wake, re-read - `orx runs ` and reconcile against the set of runs you've already - handled — act on *every* newly-terminal run, not just the line `exp wait` - printed. (This is the one time you do look at `orx runs` in a loop — as the - reconcile after each wake, **not** as a tight poll in place of `exp wait`.) - - **Re-issue `exp wait` each tick.** One completion → one return → you decide → - you call it again. Don't expect a single `exp wait` to block until everything - is done; that's the failure mode this loop avoids. - - **Terminate on drained.** When no runs are in flight, `exp wait --project` - returns immediately printing `drained: no runs in flight`. That — or seeing - every run terminal in `orx runs` with no more children to launch — is your - exit condition. Don't keep calling it into a timeout. -7. **Analyze each finish as it lands, then iterate.** Do the per-completion read - *inside the loop above*, not deferred to the end — when a run finishes, - **actually read its results** from the file reported by `orx logs ` +6. **Launch, then end your turn.** Relevant run results arrive as messages in + this chat once it is idle. No waiting process or live agent session is needed. + On each message, read `orx runs ` and reconcile every newly terminal + run, including those that finished while you were analyzing another result. + Analyze each result and refill its slot as appropriate; other runs can keep + going. End your turn again after launching ready children. When every run is + terminal and no children remain to launch, the round is complete. +7. **Analyze each finish as it lands, then iterate.** When a result message + arrives, read its results from the file reported by `orx logs ` (see `orx-logs`) and, when it logged to Trackio, its curves with `orx metrics `, then use `orx-results` to interpret the outcome. To see exactly what a finished node changed, diff its branch against its parent's diff --git a/agent-skills/orx-logs/SKILL.md b/agent-skills/orx-logs/SKILL.md index 8cc8225cb..d4e6dcf51 100644 --- a/agent-skills/orx-logs/SKILL.md +++ b/agent-skills/orx-logs/SKILL.md @@ -5,15 +5,19 @@ description: "Locate and read persisted experiment output with `orx logs`. Invok ## Reading run logs — `orx logs` -A run's terminal output is captured live while it runs and persisted afterwards. +A run's terminal output is kept on this computer when the run finishes. While +it runs, engine-owned output stays on its compute host; supervised runs also +stream it into a local log. ```sh orx logs # local path, byte size, and last ~500 characters rg -n 'metric|summary' # search the file for relevant evidence ``` -- The command prints the local log path, exact byte size, a short preview of - the end, and a search hint. The preview is not the complete result. +- For a finished run the command prints the local log path, exact byte size, a + short preview of the end, and a search hint. For a run still in flight it + prints the size so far and the end of the available log. The preview is not + the complete result. - Use native file tools on the printed path to search or read the portions you need. Cite the lines supporting each claim. - `` comes from `orx runs `. diff --git a/arc/agents.md b/arc/agents.md index b3d97e346..392171bf2 100644 --- a/arc/agents.md +++ b/arc/agents.md @@ -198,11 +198,12 @@ derived from the request. **Any chat can subscribe to any other.** A subscription tells its subscriber each finished turn of its target, and each question the target asks, as the -first message of the subscriber's next turn. Run wake-ups go through the same -delivery: a chat's news, from runs and chats alike, is never lost, never -duplicated, never interrupts a running turn, and arrives as one turn however -much of it is waiting, each piece kept in the transcript as its own message. A turn that ends while its own delegates are -still working is not an answer yet. An agent can collect the same news inside +first message of the subscriber's next turn. Pending chat news arrives in one +visible turn, each piece kept in the transcript as its own message. Run results +use the engine's durable outbox in separate hidden turns; chat-news batching +never reads run wakeups or results. Both wait for the chat to be idle and keep +delivery claims to avoid duplicates. A turn that ends while its own delegates +are still working is not an answer yet. An agent can collect the same news inside its turn with `wait`, which marks it told. A delegator subscribes to its delegates. Once the user writes in a delegate, its composer lets them keep it: it stops reporting to the chat that started it and stands as that chat's side @@ -210,12 +211,13 @@ chat, or on its own with its own worktree, and the delegator's later `subscribe` or `wait` does not undo that. A side chat reports only when its agent `send`s. Agents answer questions through orx; approvals stay with the user. -**Agents write to each other in the open.** Everything orx or another chat's -agent writes into a chat (a task, a message, news) reaches its agent opening -with `[orx]`, so the agent can tell it from the user. The transcript records -it with its kind and sender and keeps what the sender wrote, refs included; +**Agents write to each other in the open.** A task, message or piece of chat +news that orx or another chat's agent writes into a chat reaches its agent +opening with `[orx]`, so the agent can tell it from the user. The transcript +records it with its kind and sender and keeps what the sender wrote, refs included; only the agent reads the refs expanded and the instructions around them. The -dashboard shows it as the sender's message, and a finished run by its outcome. +dashboard shows it as the sender's message. Run results and monitoring notices +reach agents in hidden turns; the transcript records only the agent's reply. **Messages travel by reference.** Each user message reaches its agent tagged with a short ref from its id. A ref in a task or message, the user's included, diff --git a/arc/dashboard.md b/arc/dashboard.md index e30ecfadb..7e1c29e85 100644 --- a/arc/dashboard.md +++ b/arc/dashboard.md @@ -16,14 +16,15 @@ it runs it owns the work that needs a resident process: ([agents](agents.md)); - terminals, each a PTY relayed over a websocket; - file serving for the editor, previews and artifacts, with byte ranges; -- background passes: agent detection and model catalogs, starting a - supervisor for any active run that has none, sweeping remote run +- the run engine: watching, cancelling and reporting runs, and launching new + runs when enabled ([experiments](experiments.md)); +- background passes: agent detection and model catalogs, sweeping remote run directories and orphaned files; - remote workspace gateways ([remote](remote.md)). -Runs are not on this list. A run's supervisor is its own process -([experiments](experiments.md)), so a dashboard can stop or restart without -losing a job. +The jobs themselves are not. Each run's wrapper is its own process on the +machine that runs it, so a dashboard can stop or restart without losing a +job; the engine reconnects and catches up from the wrapper's receipts. ## The loopback guard diff --git a/arc/desktop.md b/arc/desktop.md index fe98888ca..09af1812e 100644 --- a/arc/desktop.md +++ b/arc/desktop.md @@ -48,6 +48,10 @@ single-threaded runtime would deadlock here. binds the same port every time. If a terminal `orx up` or another install holds it, the app falls back to a free port. After an update relaunch it keeps the port it had. +- **One server per data directory.** If an `orx up` already owns the data + directory, the window opens on it instead of starting a second engine. + Closing the window while runs are active hides it and keeps the engine + running until it is idle. - **One app per user.** macOS enforces this itself. On Windows a named event and on Linux a socket in the user's private runtime directory let a second launch bring the running window forward, handing it any link it was opened diff --git a/arc/experiments.md b/arc/experiments.md index b50a4809e..2b1418778 100644 --- a/arc/experiments.md +++ b/arc/experiments.md @@ -35,13 +35,33 @@ environment are a fixed contract inherited down the tree, and an experiment whose run has answered its question is frozen. Further changes go on a child, so a recorded result always matches the code on its branch. +## Choosing the run engine + +New experiment engine in Compute and Settings opts new runs into the engine being +tested; it defaults to off on stable and dev builds. `ORX_RUN_ENGINE=1` or `0` +in the `orx up` server's environment overrides the saved `runEngine` setting. +Canary builds always use the engine, ignoring the setting and environment. +Both launch APIs make the same choice. With it off, the backend launchers and +detached `orx supervise` processes launch and watch runs as in 0.2.x. The +engine still runs, importing their results and wakeups and recovering engine +runs already in flight. Existing owners stay in place; the setting chooses +which path recovers orphaned supervised runs. + +Engine runs keep their first payload start in `started_at` and finish in +`ended_at`, using source timestamps when available and observation time otherwise. + +The snapshot contract below applies in both modes. The engine lifecycle and +`orx-host` sections describe engine-owned runs; supervised runs keep their +backend descriptors and stop semantics. + ## A run is an immutable snapshot ```text -orx exp run ─► archive the experiment branch's commit (tar, plus zip for Ray) +orx exp run ─► POST /api/v2/runs to this data directory's `orx up` + ─► archive the experiment branch's commit (tar, plus zip for Ray) ─► name the archive by its SHA-256, store it once - ─► backend: preflight ─► submit ─► descriptor saved on the run - ─► spawn a detached `orx supervise` + ─► record the pending run and its snapshot identity + ─► backend launch ─► handle saved on the run ``` **A backend never sees the project's history.** A launch archives the @@ -51,72 +71,185 @@ backend never clones the repository and never touches an agent's worktree. The run executes exactly what was committed: uncommitted edits do not ship, and two runs of the same commit share one archive. -When an agent runs `orx exp run` inside a chat, the command hands the launch -to the dashboard that owns the chat, which submits it and records which chat -asked. Without a dashboard, the CLI launches the run itself. +The CLI never launches a run itself. Inside a chat it reaches the dashboard +that owns the chat, which records which chat asked; elsewhere it finds the +running `orx up` through an owner-only descriptor and an HMAC hello, or starts +a headless one. ## Backends -Every backend implements one lifecycle: preflight (can this run start here?), -stage the source, submit, then status, logs, cancel and cleanup. Submission -returns a **backend descriptor**, a serialized handle stored on the run with -everything a later process needs to find the job again: a job ID, a host and -directory, a Kubernetes context, a rental capability. The descriptor's fields -only ever grow. A field a backend needs must exist on the descriptor, because -a parse and reserialize drops anything it does not name. +Every backend implements one lifecycle: launch, recover a launch whose outcome +is unknown, observe, cancel, and serve logs. Launching returns a **handle**, +stored on the run with everything a later process needs to find the job +again: a host and run directory, a Slurm job, an API account and the resources +the run owns, primary job first. Handles only ever grow; unknown stored data +is preserved on rewrite or rejected, never dropped. The families differ in where the job runs and how the source gets there: | Family | Runs on | Source travels | | --- | --- | --- | -| this machine | a detached process | extracted locally | -| SSH, Slurm | the user's own hosts | a tar stream over SSH | +| this machine, Tinker | a detached `orx-host wrap` (a Job Object on Windows) | extracted locally | +| SSH, Slurm | the user's own hosts, under `orx-host` ([remote](remote.md)) | a content-addressed upload, resumable | | Kubernetes | the user's cluster | copied into the pod by `kubectl` | | Ray | the user's Ray cluster | the job's working-directory package | -| Hugging Face Jobs, Modal | hosted services | a private job volume, the sandbox filesystem | +| Hugging Face Jobs, Modal, Vercel | hosted services | a private job volume, the sandbox filesystem | | an OpenResearch box | a rented machine | a tar stream over SSH | -| Tinker | a local controller using remote model compute | extracted locally | Which backend a launch uses comes from the command line, else the user's default compute target. A default flavor applies only to its own backend and never leaks onto an explicitly chosen one. -## The supervisor - -**The process that watches a job is never the dashboard.** Each launch spawns -a detached `orx supervise` for the run. It polls the backend, tails the job's -output into the run's log file ([storage](storage.md)), records status -transitions, and honors cancellation. Closing the dashboard, quitting the app -or restarting it for an update leaves every job watched. - -- **One supervisor per run.** A per-run file lock makes a second supervisor - exit at once. -- **Restart-idempotent.** All of a supervisor's state is the store, the - backend and the log file. A new supervisor reattaches from the descriptor - and replays the backend's log over the local copy, truncating only once - replay begins, so a supervisor started while the backend is unreachable - keeps what is already there. The dashboard starts a supervisor for any - submitted, active run that has none. -- **Statuses move forward only.** A run is starting, running, done, failed, - cancelled or lost. An active run finishes once, and a terminal outcome never - changes, however late a stale update arrives. -- **Cancellation is recorded locally and honored remotely.** Cancelling writes - the intent and its reason to the run; the supervisor sees it and stops the - job through the backend. The intent survives if the backend is briefly - unreachable. -- **Monitoring trouble is reported, not hidden.** A supervisor that cannot - reach its backend for a while records that on the run, and chats waiting on - the run hear about it. - -When a run ends, the chats that asked to be woken for it get a wake-up turn -with the outcome. Asking is explicit (`orx exp wake`), and the wake-ups are -rows in the store with a claim and a TTL, so a crash between claiming and -delivering never loses or duplicates one, and a wake-up never interrupts a -turn already running or a message the user queued. They are delivered with a -chat's other news, so runs and delegates that finish together wake it once. - -Remote run directories are removed later by a background pass, in bounded -batches per host, which keeps the source archives that live runs still need. +## The engine + +**One engine per data directory, inside `orx up`.** The dashboard, the +desktop window, the CLI and agents are all clients of it; none of them writes +run state. + +```text +dashboard, app, orx CLI, agents ─HTTP + SSE─► orx up (engine lock: exclusive) + ├─ reconciler sole writer of run state and notices + ├─ observers one per host root or API account + ├─ outbox notices ─► hidden chat turns + └─ one ssh per (host, root) ─► orx-host serve + └─ orx-host wrap, one per run +``` + +**The process that runs a job is never the engine.** Each run's wrapper owns +its payload and records the outcome in receipts on the machine that ran it. +`orx up` may restart, sleep or update; it reconnects, reads the receipts and +catches up. A headless `orx up` exits only after ten idle minutes with no +unfinished run, no undelivered notice and no client +([desktop](desktop.md) for the window). + +### Phase and contact + +A run has two independent fields. **Phase** is the lifecycle: submitting, +starting, running, done, failed, cancelled or lost. **Contact** is how fresh +that knowledge is: live, unreachable, needs auth (SSH Connect or provider +credentials), unreconciled (an outcome the engine cannot establish), or stopping +(a cancelled run with processes left). A non-live contact marks the shown phase +stale with its `since`. + +- **Phases move forward only**, and submitting leaves only by recording a + handle or ending. Contact never moves the phase. +- **Never terminal on a timer.** A phase becomes terminal only on evidence: a + receipt, a verified stop, a changed boot ID on the host, a scheduler's + terminal state, a launch proven absent after a cancel, or Abandon. No + outage, backoff cap or silence ends a run; jobs run for days. +- **Never silent.** Losing live contact raises an attention notice to the + run's chats: at once for needs-auth and unreconciled, after ten minutes for + an outage, with a recovered notice when it heals. One outage yields one + notice per chat. + +### Submission + +The run is committed as submitting, with its launch spec, before any side +effect; from then on recovery owns it. A fence is written before the backend +is called, and any launcher subprocess records itself on it, so a crashed +launch can be found and its launcher killed before anything retries. + +```text +launch ─► handle → starting + ─► rejected → failed + ─► never sent → stay submitting, with that contact; relaunch next tick + ─► reply lost → recover: found → starting + absent → relaunch once, then back off with the error shown + unknown → unreconciled, retried with backoff +``` + +**A launch is idempotent in the run ID.** On a host, the first launch intent +is published exclusively; an identical retry adopts it, a different one is a +conflict, and the wrapper refuses to start if the run has already started. A +payload never runs twice. API backends find a lost launch by a label carrying +the run ID where the provider allows it; where it does not, the run stays +unreconciled until the user abandons it. + +### Cancel and Abandon + +Cancelling records the intent and its reason on the run. For a run on a hosted +service, a nonzero exit or signal after an accepted cancel ends Cancelled, +preserving the reported exit code. The engine delivers the stop whenever the +run's machine is reachable, and the run's wrapper performs the stop, so +verification never races its own exit: a container's cancel hook, TERM, a +grace period, KILL, then fresh scans of every process carrying the run's tag. +Completion of a run is its direct child's exit; processes it left behind are listed, raise one notice, and are stopped only on request. + +| State | Meaning | +| --- | --- | +| Cancellation pending | The cancel has not reached the machine. Abandon is offered, with a warning to double-check that the actual compute is shut down. | +| Cancelling… | The stop is running. | +| Cancelled | The stop finished and a complete scan found nothing left. | +| Not fully stopped · N processes still running on *host* | Survivors outlived the stop; the wrapper keeps killing them, and Stop now retries. | +| Cancelled · couldn't confirm | Rare: the stop succeeded but some processes could not be checked, as inside a container. | + +**Abandon** ends an unfinished run that has no live contact as lost, and sends +its chats the terminal notice. The kill stays pending: a terminal run without +live contact is a **tombstone**, still watched, whose stop is delivered +whenever the job or host comes back, and which settles on the next proof that +nothing is left. + +### Logs + +A run's log is written on the machine that ran it. While someone watches, the +engine follows its length and pages it from the host by byte range and file +identity; a changed identity resets the reader rather than splicing different +bytes. API backends offer no random access, so their logs stream into a local +spool. + +When a run ends, keeping its log becomes an obligation recorded in the same +transaction as the terminal phase: + +- A log up to 1 GiB is kept whole; a larger one keeps its first 64 MiB and its + last 256 MiB, where setup and results live. The middle stays readable from + the host until its run directory is cleaned up. +- Collection resumes from its last synced offset and never gives up: it backs + off to hourly, raises one notice after repeated failures, and retries at + once when the host returns. +- A kept range claims end-of-file only if its last page reached the host's + length, so a log that grew afterwards is served on from the host. +- A page the laptop does not hold, from a host that is down, answers "Page not + on this computer", and the viewer retries when the host returns. + +### Notices + +**Results reach chats as messages.** The chat that launched a run is +subscribed implicitly; another chat subscribes with `orx exp wake`. Every +terminal phase and attention event writes one notice row per subscribed chat +in the reconciler's transaction, and the outbox delivers them as one hidden +turn when the chat is idle, never interrupting a turn or a queued message. + +- **Exactly once.** A batch's membership is frozen and its turn ID fixed + before sending, so a resend after a crash is recognised as the same turn. +- **Never blocking.** Transient failures retry for a day; a permanent one (the + chat deleted) retires the batch at once, and its error shows on the run. +- **The payload can speak.** A job appends free text to `$ORX_NOTIFY_FILE`; + new bytes become at most one notice per run per ten minutes. Notice text is + data for the agent, never instructions. + +Agents are taught to launch, end their turn, and reconcile with `orx runs` +when a message arrives. A blocking wait would hold a turn open for days and +die with the agent process; a queued message survives both. + +### Runs from 0.2.x + +A run started under a detached `orx supervise` stays with that supervisor +until it ends; the engine only reads it. With the setting off, `orx up` +re-spawns missing supervisors at startup and periodically. With it on, only +the engine adopts orphans, after the run has had no update for five minutes +and its supervisor locks are free. Adopted runs keep their original +descriptors and stop semantics. Changing the setting leaves engine-owned +runs and live supervisors in place. + +The engine imports each 0.2.x wake-up subscription once, including subscriptions +accepted after a downgrade or while the engine is running. + +Remote run directories are cleaned up later in bounded batches per host, +keeping each project's newest finished runs and the source archives live runs +still need. + +The on-disk and wire formats above are frozen for the life of every queued +job and lingering cleanup: [FROZEN.md](../crates/orx-host-proto/FROZEN.md). ## Results @@ -155,8 +288,20 @@ collect log + exit code ◄─ssh─ wait for "collected", 60 s max that it saved the final log and exit code, or 60 seconds, whichever comes first, then releases the rental, retrying until the service accepts. The service closes billing and deletes the machine on its own schedule. +- **Cancel and Abandon release the rental** from the laptop as well, so + stopping billing never waits on the box being reachable. A successful + release is stop proof: Cancel ends Cancelled, Abandon ends Lost with no kill + pending. After a box that was reachable during this run rejects its SSH + key continuously for 15 minutes, the engine checks the companion API and + issues Cancel if the rental is still active; Connect or Live contact resets + the clock, and network outages never qualify. + The timer requests cancellation, while release proof makes the run terminal; + an already released rental settles as Lost without another release. +- The engine drives the box over its own SSH connection, so first contact, + backoff and the auth breaker ([remote](remote.md)) apply to it. - **No research data crosses this protocol.** Logs, commands, source, experiment IDs, outcomes and artifacts never reach the billing service. +- Manual teardown follows the run engine's Cancel and Abandon path above. - Collection is best effort. Data left only on the machine is lost when it is deleted, and a run whose final outcome could not be collected ends as **lost** ("Outcome unavailable") instead of running forever. The chat is diff --git a/arc/remote.md b/arc/remote.md index 31fc8d4d1..b6877948b 100644 --- a/arc/remote.md +++ b/arc/remote.md @@ -12,8 +12,9 @@ shared host is an open door to the account that runs it. Everything in this essay keeps the server on `127.0.0.1` and carries the user to it over SSH. This essay covers the dashboard on a remote machine. SSH as a place to run -jobs belongs to [experiments](experiments.md); both share the SSH machinery -described at the end. +jobs belongs to [experiments](experiments.md); the host side of those jobs and +the SSH transport they share are described at the end. Their on-disk and wire +formats are frozen in [FROZEN.md](../crates/orx-host-proto/FROZEN.md). ## Inside an SSH session @@ -77,8 +78,8 @@ orx remote-host attach ──ssh──► control socket ─► register token, gateway ── forward + token ───► host's loopback port ``` -- **One host per remote data directory.** A host holds the data directory's - dashboard lock exclusively, so a second dashboard on the same database +- **One host per remote data directory.** Like every `orx up`, a host holds + the data directory's engine lock, so a second dashboard on the same database refuses to start, and a start lock serializes concurrent `ensure` calls. - **A private control channel.** The laptop never talks to the host over the network. It runs `orx remote-host` over SSH, which speaks to the host @@ -120,28 +121,114 @@ Any change to the remote API or the control channel's shape is a protocol change: bump the number, and keep the laptop able to tell the user what to do with a mismatched peer. -## The SSH service - -Every orx process that talks to remote machines, each dashboard and every -supervisor, goes through one detached SSH service per data directory instead -of opening its own connections. It listens on loopback, accepts only callers -that present the token in its owner-only state directory, and keeps one -session per host, with a small helper on the remote end for monitoring and -transfers. Repeated questions are batched: one Slurm queue poll per host -answers every run on that host. - -- **The user's SSH, unmodified in behavior.** Transport is the system `ssh` - with the user's own config, agent and keys; orx never reads a key. On - OpenSSH versions that support it, orx shares connections with the user's - own `ssh` through a managed file their SSH config includes, adding that one - line and leaving the rest of the file byte for byte. -- **Prompts reach the screen.** A passphrase, password or host-key question - from `ssh` is routed through an askpass bridge to the dashboard's connect - dialog and answered there. An unanswered prompt times out instead of - hanging the connection. -- **It stops when the data moves.** A data-directory move asks the service to - shut down when idle, meaning no active runs and no connection in progress, - and refuses to move while it is busy. +## orx-host + +With the new experiment engine enabled, runs on an SSH host or Slurm cluster +are driven by `orx-host`, a small static binary (Linux 3.2 or newer on x86_64 +and aarch64, and macOS) that needs +only `/bin/sh`, Bash, tar and coreutils on the host. Releases embed it, and it +is named by its SHA-256, so one root holds several versions and each is +uploaded once, in the same SSH session that first needs it. + +```text + ~/.orx/engine, or /engine; beside the 0.2.x run directories + bin/orx-host- + sources/ content-addressed source archives + runs// launch.json run.sh repo/ log notify + wrapper.json started exit.json cleanup.json + +orx-host serve one per SSH session; dies with it +orx-host wrap one per run, in its own session; outlives SSH and `orx up` +``` + +There is no daemon to install, upgrade or restart: what persists is files and +each run's wrapper. + +- **At most one start.** The wrapper takes its lock, publishes its identity + (node, boot ID, PID, start time), then creates `started` exclusively and + fsyncs it before spawning the payload. Its presence forbids another start, + even if a crash prevented the spawn, and a dead wrapper never authorizes a + rerun. +- **Receipts are whole.** Every receipt is written to a temporary file, + fsynced and renamed, so a reader on NFS sees all of it or none. Failing to + read, parse or inspect is uncertainty, never absence or a verified stop. +- **Identity bounds what a host can prove.** Process checks and signals run + only on the recorded node and boot. The same node with a new boot proves the + old execution ended; another node proves nothing about local PIDs. +- **The kill set** is the wrapper's descendants (it is their subreaper on + Linux), every same-user process carrying the run's tag, and every process + already seen. A scan is complete only when no candidate was unreadable. +- **Updates never touch a running wrapper.** It keeps its binary and code + until it exits; a newer `serve` reads its receipts unchanged. + +`serve` answers length-prefixed JSON frames on the SSH session's stdio, out of +order. Observation is a long poll: the engine sends its last summary of each +watched run and the host answers when any differs, so there is no journal on +the host and nothing to replay. + +## Slurm authority + +On a cluster, `serve` runs on the login node and the payload on a compute +node whose processes the login node cannot see, so the login node never judges +liveness. The batch script execs `orx-host wrap`, and receipts cross the shared +filesystem. + +```text +1 exit.json on the shared filesystem → the outcome +2 squeue --states=all → starting, running, or terminal until MinJobAge +3 sacct → jobs squeue forgot +4 scheduler terminal, no receipt after 120 s → cancelled, failed or lost + scheduler silent or unanswered, no receipt → unreconciled until Abandon +``` + +Jobs are submitted with `--no-requeue`, named by the run ID so a lost +submission is found again. Cancel writes the request the wrapper acts on; +`scancel` is used only before the wrapper has started, because it would kill +the wrapper before it wrote its receipt. + +## Transport and the auth breaker + +The engine talks to each host root over one system `ssh` child, multiplexing +every request on it, with the user's own config, agent and keys; orx never +reads a key. Requests queue in lanes (control, feed, logs, upload), and cheaper +lanes stop dispatching first, so bulk uploads and log pages can never take the +slots a cancel needs. + +```text +Idle ─► Connecting ─► Live ─(EOF, 35 s without a reply, clock jump)─► Backoff ─► Connecting + └─ auth failure, host key, changed route, dead master ─► NeedsAuth +Backoff: 5 s, 15 s, 60 s, 5 min, 15 min cap, jittered, persisted per root +``` + +**After an authentication failure, no automatic login.** Repeated logins lock +accounts and trip MFA, so the breaker is one per SSH alias, shared by all its +roots, and only the user's Connect closes it. + +- **First contact is one batch-mode attempt.** Success classifies the alias as + a key host, which then connects with no click. A network failure before + authentication backs off like any key host. Anything that could have reached + authentication marks the host interactive with the breaker open. +- **Interactive hosts keep an authenticated master on Unix.** Connect relays + passphrase, password and host-key prompts to the dashboard or CLI. Key hosts + keep a master only when supervised work needs it: the setting is off, or an + active supervised SSH or Slurm run uses the alias. Background work attaches + with prompts disabled. +- **The route is pinned.** `ssh -G` yields the hostname, user, port, proxy and + identity settings; a changed route opens the breaker until Connect approves + it. +- Every engine `ssh` runs without a terminal and with askpass disabled, because + a jump host ignores the outer batch mode and would otherwise prompt. + +**Plain ssh shares an interactive master.** On OpenSSH 8.4 and later, a live +master is published through a managed file the user's SSH config includes, +adding that include once and leaving the rest byte for byte. A `Match … exec` +check selects the socket only while its pinned route matches and the socket +exists, so `ssh`, `scp` and `rsync` to that alias reuse the authenticated +session; without a live master they authenticate as usual and never start an +engine login. + +On Windows there is no shared master. Connect recovers the transports needed +by existing runs; a second MFA prompt may be required. ## What must stay true @@ -153,4 +240,8 @@ answers every run on that host. - orx never executes a remote binary that another user could have replaced, and never changes permissions on its own. - Keys and passphrases never pass through orx's storage. +- After an authentication failure, nothing logs in to that alias until the + user connects. +- A run's payload starts at most once, and only a receipt, a scheduler verdict + or a changed boot ends it. - A version mismatch is reported with a way forward, never papered over. diff --git a/arc/storage.md b/arc/storage.md index 101dad71c..bc366bda5 100644 --- a/arc/storage.md +++ b/arc/storage.md @@ -3,10 +3,10 @@ orx keeps a researcher's work on their own machine. Projects, experiments, runs, chats and their transcripts never pass through a service, so the only copy is the one on disk, and every orx process on the machine reads and writes -it at once: the dashboard, the desktop app, a terminal `orx`, an agent's `orx`, -a detached supervisor watching a job. This essay covers where those bytes -live, how the processes share them without corrupting each other, and the -short list of things that leave the machine. +it at once: the dashboard and its run engine, the desktop app, a terminal +`orx`, an agent's `orx`, a supervisor an older orx left watching a job. This +essay covers where those bytes live, how the processes share them without +corrupting each other, and the short list of things that leave the machine. ## Three directories @@ -43,11 +43,11 @@ and a terminal `orx` on the same machine would open different databases. ## The store A SQLite database in WAL mode is orx's truth for everything that is not code: -projects, the experiment records, runs and their backend descriptors, chat -sessions, messages and turn leases, wake-up registrations, chat delegations -and subscriptions, UI and workspace state. Many short-lived processes open it -concurrently, each with a busy timeout; WAL lets readers proceed while one -writer commits. +projects, the experiment records, runs with their handles and launch fences, +chat sessions, messages and turn leases, run subscriptions and the notice +outbox, log-collection obligations, each SSH host's backoff and auth breaker, +chat delegations and subscriptions, UI and workspace state. Many short-lived processes open it concurrently, +each with a busy timeout; WAL lets readers proceed while one writer commits. **The schema only grows.** Every open of the store applies the whole schema: tables are created if missing, and each added column is an `ALTER TABLE ADD @@ -79,10 +79,12 @@ the folder. ## Run logs are files -A run's output is an append-only file named by the run, not rows in the -store. The supervisor appends as the job prints; the dashboard and `orx logs` -tail the file. Neither ever contends for a database write lock, and a chatty -job cannot bloat the database or slow every other writer. +A run's output is an append-only file, never rows in the store. It is +written on the machine that ran the job, paged from there while the run is +live, and kept in the data directory's `run-logs/` once it ends +([experiments](experiments.md)). Reading it never contends for a database +write lock, and a chatty job cannot bloat the database or slow every other +writer. ## Agent homes @@ -99,9 +101,10 @@ the homes exist. ```text lifecycle lock (config) shared: nearly every orx command, `orx up`, the app, - each detached supervisor + each 0.2.x supervisor exclusive: `orx delete`, a one-time storage migration -dashboard lock (data) shared: each dashboard; exclusive: a persistent remote host +engine lock (data) exclusive: the one `orx up` that owns the data directory's runs +supervisor locks (data) per 0.2.x run: its supervisor, or the engine once it adopts the run move lock + move lease exclusive: a data-directory move turn and claim leases rows in the store, with heartbeats and a TTL ``` @@ -109,9 +112,9 @@ turn and claim leases rows in the store, with heartbeats and a TTL **The lifecycle lock** is an advisory file lock in the config directory. Ordinary commands hold it shared for their whole life, so the operations that destroy or relocate shared state can take it exclusively and know nothing else -is running. A supervisor holds it too, which keeps `orx delete` out until -every watched job has finished or been detached. The lock sits in a directory -of its own so a sandboxed agent can be granted write access to exactly that +is running. A headless `orx up` stays up while any run is unfinished, so the +lock is held for as long as orx watches a job. The lock sits in a directory of +its own so a sandboxed agent can be granted write access to exactly that directory and nothing else in config. When the lock file's location changed, the old and new paths became hard links to one file, so old and new binaries contend on the same lock; orx refuses to run if the two paths stop being the diff --git a/build.rs b/build.rs index c74f4ef47..2cf3a9dee 100644 --- a/build.rs +++ b/build.rs @@ -1,3 +1,5 @@ +use sha2::{Digest, Sha256}; + fn main() { if std::path::Path::new("ui/dist").exists() { println!("cargo:rerun-if-changed=ui/dist"); @@ -61,6 +63,7 @@ fn main() { println!("cargo:rustc-cfg=desktop_app"); } + embed_host_binaries(channel == "production"); embed_windows_icon(); } @@ -80,3 +83,60 @@ fn embed_windows_icon() { .manifest_required() .unwrap(); } + +fn embed_host_binaries(required: bool) { + use std::{fmt::Write, path::PathBuf}; + + println!("cargo:rerun-if-env-changed=ORX_EMBED_HOST_DIR"); + let mut generated = String::from("&[\n"); + if let Some(directory) = std::env::var_os("ORX_EMBED_HOST_DIR") { + let directory = std::path::absolute(directory).unwrap(); + println!("cargo:rerun-if-changed={}", directory.display()); + for (host_os, arch) in [ + ("linux", "x86_64"), + ("linux", "aarch64"), + ("darwin", "universal"), + ] { + let path = directory.join(format!("orx-host-{host_os}-{arch}")); + if !path.exists() && !required { + continue; + } + let bytes = std::fs::read(&path).unwrap_or_else(|error| { + panic!( + "Missing {}: {error}; run node scripts/build-host.mjs", + path.display() + ) + }); + assert!( + !bytes.is_empty() && bytes.len() <= 4 * 1024 * 1024, + "Invalid orx-host size: {}", + path.display() + ); + let sha = format!("{:x}", Sha256::digest(&bytes)); + // Snapshot the hashed bytes so include_bytes! cannot race an input replacement. + let snapshot = + PathBuf::from(std::env::var_os("OUT_DIR").unwrap()).join(path.file_name().unwrap()); + std::fs::write(&snapshot, bytes).unwrap(); + let arches: &[&str] = if arch == "universal" { + &["x86_64", "aarch64"] + } else { + std::slice::from_ref(&arch) + }; + for arch in arches { + writeln!( + generated, + "({host_os:?}, {arch:?}, {sha:?}, include_bytes!({snapshot:?}).as_slice())," + ) + .unwrap(); + } + } + } else { + assert!(!required, "Official builds require ORX_EMBED_HOST_DIR; run node scripts/build-host.mjs and set it to the output directory"); + } + generated.push_str("]\n"); + std::fs::write( + PathBuf::from(std::env::var_os("OUT_DIR").unwrap()).join("host_binaries.rs"), + generated, + ) + .unwrap(); +} diff --git a/crates/orx-host-proto/Cargo.toml b/crates/orx-host-proto/Cargo.toml new file mode 100644 index 000000000..d96d3484b --- /dev/null +++ b/crates/orx-host-proto/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "orx-host-proto" +version = "0.1.0" +edition = "2021" +publish = false + +[package.metadata.dist] +dist = false + +[dependencies] +base64 = "0.22" +serde = { version = "1", features = ["derive"] } +serde_json = "1" diff --git a/crates/orx-host-proto/FROZEN.md b/crates/orx-host-proto/FROZEN.md new file mode 100644 index 000000000..96bd1f9b9 --- /dev/null +++ b/crates/orx-host-proto/FROZEN.md @@ -0,0 +1,99 @@ +# Frozen run-engine surfaces + +This is the canonical compatibility contract for the first run-engine release. +It covers the full lifetime of queued jobs, payloads and lingering cleanup; +there is no time-based compatibility cutoff. Shipped 0.2.x supervisors and +Windows local runs retain their existing formats. Draft engine formats have +no migration or backfill obligation. + +## Evolution + +There is no per-run `v` field. Presence-authority files are never renamed: +`launch.json`, `wrapper.json`, `started`, `cancel.req`, `cleanup.req`, +`job.sbatch`, `slurm.job`. They may only gain optional fields. A missing new +name must never let an older reader infer that an existing execution is absent. +Required proof fields remain required; `#[serde(default)]` is only for optional +additions. Unknown object fields are tolerated; unknown variants and malformed +JSON are uncertainty. Read bytes before parsing so I/O errors retain their type. + +Any breaking host-disk change also raises the database `min_reader_version`. +Every launching laptop checks that floor before migrations, which fences its +run-directory readers after a downgrade. New binaries cannot fence an already +running or shipped 0.2.x writer: database changes remain additive while those +writers may exist. A new receipt filename can introduce a breaking receipt +shape only alongside that floor; it cannot replace a presence-authority file. + +The JSON files in `tests/fixtures/` are append-only. Historical fixtures must +remain readable and today's writers must match an approved fixture. Add a +fixture for an intentional extension; never rewrite an old fixture to hide an +incompatible writer. After release, also exercise the actual shipped reader +and wrapper. A new control cannot require an old wrapper to understand it. + +## Host disk and execution + +| Surface | Contract | +|---|---| +| Private root | `bin/`, `runs//`, `sources/`; run IDs are 1–200 ASCII alphanumeric, `-` or `_` bytes. Source IDs are lowercase SHA-256 of the archive bytes. One run directory permits at most one payload start. | +| `launch.json` | `LaunchIntent`: `run`, `digest`, `run_sh`, `env`, optional `source` and `cancel_sh`. Identity is `(run, digest)`; digest includes source identity. The first accepted intent governs scripts, environment, source, container ID/generation and Slurm directives. Retries adopt those bytes. | +| `job.sbatch`, `slurm.job` | The batch script is both Slurm ownership and a pinned executable reference; the job ID is numeric text. Direct/Slurm ownership is checked under `launch.lock`. A batch-only preparation interrupted before `launch.json` can resume its first submission; sbatch only runs after that identity is published. Execution evidence (`slurm.job`, `wrapper.json`, `started`, `exit.json`) without a readable launch key is uncertainty, never permission to submit a replacement. | +| Slurm submission | Job name is the run ID; scheduler output is `slurm.out` in the run directory. Submit with `--no-requeue`. PREEMPTED/NODE_FAIL without a receipt become Failed after receipt grace; a forced requeue cannot rerun the payload and may end Lost. No automatic attempts. | +| `slurm-terminal.json` | Optional per-run retained scheduler evidence: required `job`, `state`, `since` (SystemTime object with `secs_since_epoch` and `nanos_since_epoch`). Receipt grace starts at `since` and survives serve replacement and unavailable accounting. A subsequent live scheduler state clears it. It confers no launch or deletion authority; future fields must be optional. | +| `wrapper.json` | Current attempt identity: required `node`, `boot_id`, `pid`, `starttime`. Linux node identity is hostname; macOS is `gethostuuid()` and errors fail closed. Linux starttime is `/proc//stat` field 22 in clock ticks since boot; macOS is process start time in microseconds since epoch. Local scans, liveness and signals require the recorded node and boot. Same-node reboot proves loss; another node proves nothing about local PIDs. | +| `started` | Exclusive, fsynced text `:\n`. Presence forbids another start, even if a crash prevented spawn. It is an at-most-once fence, not proof the child ran. | +| Locks | `fcntl(F_SETLK)` on `launch.lock` protects launch preparation and PinSource; `wrapper.lock` is held for the wrapper lifetime; `start.lock` orders cancel/control publication against the last pre-spawn check and `started`. A process-local run mutex also serializes mutators because fcntl locks are per process. Shared filesystems must honor cross-node locks. Wrapper-ownership probes are nonblocking. | +| Publication | Write temporary file, fsync, rename (exclusive hard link for initial intent), then fsync parent. Readers see whole receipts. Scripts/staging resume under launch ownership; never rewrite accepted bytes from a retry. | +| `exit.json` | Immutable final run receipt: optional `code`, `signal` and `finished_at` (wall-clock milliseconds at completion), required `reason`, `processes`, `outcome`. Reason spellings: `exited`, `cancelled`, `spawn_failed`. Direct-child exit is the result even when descendants remain. Cancel before start has no code/signal and verified-empty proof; spawn failure has `spawn_failed`. | +| Proof | `Survivor` requires `pid`, `starttime`, `state`. Outcome spellings are `verified`, `survivors`, `unverifiable` (required `unreadable` list). Empty processes alone is not Verified. Native proof is limited to the scanned process/tag domain. A container hook never verifies all in-container processes. Slurm step teardown owns allocation containment, so the wrapper exits after its receipt, including a cancelled receipt with survivors. | +| `cleanup.json` | Latest `ProcessOutcome {processes,outcome}` renewal. After wrapper death on the recorded node, serve renews proof by a fresh tag/known-identity scan and kill pass; a changed boot verifies emptiness. It supersedes containment evidence, never the result in `exit.json`. After cancelling with survivors the wrapper keeps scanning and killing on a 1–30 s backoff, without re-running the hook or TERM grace. A prior incomplete scan or hook cannot become Verified merely because a fixed PID list emptied. | +| Controls | `cancel.req` / `cleanup.req` are presence markers, fsynced with their directory under `start.lock`. SIGUSR1 only wakes polling; it does not itself encode cancellation. Failed cancel hooks retry with backoff before any cancelled receipt; paused containers keep cancellation pending. | +| Output/staging | Raw append bytes in `log` and `notify`; diagnostics in `wrapper.log`; accepted scripts in `run.sh` / `cancel.sh`; `source.tar`, extracted `repo/` and resumable `.part` / `.synced` files keep their meanings. Unknown optional files confer no launch/deletion authority. | +| Binaries | `bin/orx-host-` remains runnable while a pending batch script references it or live supervision/cleanup needs it. A running wrapper keeps its code; updating `serve` never upgrades that wrapper in place. | +| Native Unix local | Local/Tinker directories use the same host intent, identity, markers, receipt and proof semantics; launch detaches without leaving the engine as parent. Windows and actual 0.2.x directories remain distinct. | +| Windows local | Preserve `windows_job`, `pid`, `pid_script`, `pid_identity` where used, `started`, digest launch file, payload/run scripts and atomic integer `exit_code`. Completion of the direct child does not imply Job Object emptiness. A missing Job Object proves no member remains. | + +The wrapper locks before publishing identity; `start.lock` covers its final +cancel check through `started`. A dead wrapper never authorizes rerun. Read, +parse or inspection failure is not absence, payload failure or verified stop. +On Linux without pidfd support, starttime recheck followed by `kill` is the +accepted unpinned signalling fallback. Disconnect survival requires the host +not to kill the session through logind `KillUserProcesses=yes`. + +## Payload-facing surface + +`ORX_RUN_TAG` is opaque and inherited. The wrapper sets `ORX_NOTIFY_FILE` to its +append-only free-text input path, uses the run directory as cwd, null stdin, +and combines stdout/stderr into `log`. Container/provider jobs only have a +usable notify path where that backend explicitly wires it. Existing processes +retain their environment and scripts across engine updates. + +Keep the run context names `ORX_RUN_ID`, `ORX_EXPERIMENT`, +`ORX_EXPERIMENT_TITLE`, `ORX_PARENT_EXPERIMENT`, `ORX_COMMIT` and +`TRACKIO_PROJECT`. Reserve the log-line prefix `::orx::` and the run-view field +`progress` for future payload progress. Progress is advisory and cannot change +lifecycle `status`, settle containment or complete a wait. No progress protocol +or authenticated payload endpoint is implemented by this reservation. + +## Laptop persistence and public clients + +| Surface | Contract | +|---|---| +| SQLite / stored JSON | Additive schema; phases `submitting`, `starting`, `running`, `done`, `failed`, `cancelled`, `lost`; Contact NULL means Live, otherwise serialized Unreachable/NeedsAuth/Unreconciled/Stopping. Stopping carries `since` and survivor `count`; the host is derived from the run handle or alias. Preserve Handle (`Ssh`, `Slurm`, `Local`, `Tinker`, `Api{provider, account:{target, context}, ids}`, `Legacy{descriptor}`; API ids list owned resources, primary first; `vercel_job` ids are `[sandbox_name, process_id]`), LaunchSpec/options, SubmissionFence/SubmitterIdentity, NotifyCursor, subscriptions, notices, collection obligations and queued cleanup meanings. Unknown stored data must be preserved on rewrite or rejected. | +| Tombstone | Terminal phase plus non-Live contact continues recovery/kill without changing the result or sending another terminal notice. A recovered handle attaches to the same fenced attempt. Tombstones do not block idle; latest authoritative empty proof settles contact. A cancelled receipt with survivors encodes `cancelled` + Stopping (kill pending), displayed as Not fully stopped with their count and host. An empty proof encodes `cancelled` + Live, with `cancel_unconfirmed` recording incomplete containment independently of editable result prose (null for confirmed, unreadable PIDs for an incomplete scan, an empty list for uncovered processes); the dashboard localizes its note from that list and displays “Cancelled · couldn't confirm”, while CLI and chat use English. Cancel remains pending throughout the stop window; time alone never ends a run. A cancelled tombstone settles on the latest empty process proof or authoritative scheduler teardown. Only a prior Not fully stopped terminal notice permits the deduped cleanup follow-up; it is an attention notice, never a second terminal notice. | +| Kept output | `run-logs/.log`, `.tail.log`, `.ranges.json`; resumable `.part` plus collection-marker identity/offset tuples. Preserve KeptRange and FileIdent encodings, byte ranges and EOF meaning. Treat identities as opaque; mismatch resets reading, never validates different bytes. | +| Discovery | Private server descriptor: `proto:2`, instance, pid/starttime, endpoint and token; authenticated HMAC hello verifies the owner. Live but not-ready/incompatible is distinct from absent. Restart/discovery must not spawn a competitor while the recorded owner remains alive. | +| API v2 | Preserve route/method/query/action semantics and run-view field names/types (including `id`, `experimentId`, lifecycle string `status`, `durationSecs`, `updatedDisplay`, `cancelUnconfirmed` nullable unreadable-PID list (empty for uncovered processes) and derived `host`). Contact and derived cancelling stay independent of phase. Launch, cancel, abandon, cleanup, logs, data/reset pages, ident/eof and unavailable/503 retain their meanings. Optional additions cannot replace existing fields. New lifecycle meanings require deliberate API versioning. | +| SSE | `snapshot`, `run`, `error`, `resync`, `drained`; preserve payload shapes, reconnect/refetch and lag behavior. Unknown event names must be skipped by the first shipped CLI (O6), so future events cannot hang or end an old wait. SSE is a live feed, not a durable telemetry journal; dashboard `/api/events` is another consumer. | +| Agent notices | Persist frozen batch membership and `client_turn_id` dedupe/retry/retirement state. Delivered means harness acceptance, with uncertain delivery retained for recovery. Payload text is data, never instructions. Terminal collection and notice ingestion must survive a restart. | +| SSH sharing | Keep `~/.ssh/openresearch_config`, `openresearch_match`, `openresearch_connections.json` and the shared `.orx-config.lock`. First use adds the shipped `Host *` / `Include openresearch_config` footer once; never remove the user's Include. Preserve Publication's `host`, `native_id`, `socket_name`, `queries` shape and the `Match final originalhost … exec openresearch_match … %C` route/socket check. Set `ORX_SSH_CONTROL_DIR` selects that scope; unset selects the default production directory. Withdraw closed or changed-route masters; absent a matching live master, plain ssh falls back normally and cannot cause an engine login. | + +O6 (unknown-SSE-name handling) and O7 (database reader floor before migrations) +are first-ship-only mechanisms: an already-shipped binary cannot acquire them +retroactively. The floor protects deliberate incompatible changes, not routine +additive migrations. + +## Not frozen + +`RunState`, `Summary` and `Request` are internal matching engine/serve RPC types; +Hello requires the exact protocol version and binary SHA. Notice prose, +`result_markdown` wording, retention policy and implementation details are not +frozen. The persisted/public contracts above still constrain any implementation. diff --git a/crates/orx-host-proto/src/lib.rs b/crates/orx-host-proto/src/lib.rs new file mode 100644 index 000000000..6ef97aa22 --- /dev/null +++ b/crates/orx-host-proto/src/lib.rs @@ -0,0 +1,466 @@ +use serde::{de::DeserializeOwned, Deserialize, Serialize}; +use std::collections::BTreeMap; +use std::io::{self, Read, Write}; + +pub const PROTOCOL_VERSION: u32 = 5; +pub const MAX_FRAME_LEN: usize = 8 * 1024 * 1024; +pub const MAX_PAGE_LEN: u64 = 1024 * 1024; +pub const MAX_WAIT_MS: u32 = 30_000; +pub type RunId = String; +pub type Sha = String; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Message { + pub id: u64, + pub body: T, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "op", rename_all = "snake_case")] +pub enum Request { + Hello { + proto: u32, + }, + Launch(LaunchIntent), + Inspect { + run: RunId, + }, + Changes { + watch: Vec<(RunId, Summary)>, + follow_logs: Vec, + wait_ms: u32, + }, + ReadLog { + target: LogTarget, + file: LogFile, + ident: Option, + range: ByteRange, + #[serde( + serialize_with = "bytes::serialize_optional", + deserialize_with = "bytes::deserialize_optional" + )] + anchor: Option<[u8; 64]>, + }, + Cancel { + run: RunId, + }, + Cleanup { + run: RunId, + }, + CancelLegacy { + dir: String, + container: Option, + }, + Exec { + command: String, + #[serde(with = "bytes")] + stdin: Vec, + timeout_ms: u32, + }, + HasBlob { + sha: Sha, + len: u64, + }, + /// Holds a staged blob in a run dir as `source.tar`; across filesystems each request copies + /// a bounded slice, so the client repeats it until `pinned`. + PinSource { + run: RunId, + sha: Sha, + }, + PutBlob { + sha: Sha, + offset: u64, + #[serde(with = "bytes")] + bytes: Vec, + }, + /// Publishes the launch like `Launch` without starting it, and submits a batch job of + /// `directives` (`#SBATCH` lines) that starts it. + SlurmSubmit { + intent: LaunchIntent, + directives: String, + }, + SlurmQueue { + names: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + legacy: Vec, + }, + SlurmCancelLegacy { + job: String, + }, + InspectLegacy { + dir: String, + }, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(tag = "op", rename_all = "snake_case")] +pub enum Response { + Hello { + proto: u32, + binary_sha: Sha, + boot_id: String, + os: String, + arch: String, + kernel: String, + }, + Launch { + summary: Summary, + }, + Inspect { + summary: Summary, + }, + Changes { + runs: Vec<(RunId, Summary)>, + }, + ReadLog { + page: LogPage, + }, + Cancel { + outcome: CancelAck, + }, + Cleanup { + outcome: CleanupAck, + }, + CancelLegacy { + outcome: LegacyCancelOutcome, + }, + Exec { + result: ExecResult, + }, + HasBlob { + present: bool, + }, + PinSource { + pinned: bool, + }, + PutBlob { + len: u64, + }, + SlurmSubmit { + job: String, + }, + SlurmQueue { + jobs: Vec, + }, + InspectLegacy { + inspection: LegacyInspection, + }, + SlurmCancelLegacy, + Error { + code: ErrorCode, + message: String, + }, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ErrorCode { + InvalidRequest, + Conflict, + NotFound, + Unsupported, + Busy, + Io, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum LogFile { + Log, + Notify, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", content = "value", rename_all = "snake_case")] +pub enum LogTarget { + Run(RunId), + Dir(String), +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ContainerRun { + pub reference: String, + pub id: String, + pub started_at: String, + pub run_dir: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ByteRange { + pub start: u64, + pub end: u64, +} + +/// A log file's inode; runs write each log once at a run-unique path. Serialized as the +/// opaque string `dev-ino`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(into = "String", try_from = "String")] +pub struct FileIdent { + pub dev: u64, + pub ino: u64, +} + +impl From for String { + fn from(ident: FileIdent) -> Self { + format!("{}-{}", ident.dev, ident.ino) + } +} + +impl TryFrom for FileIdent { + type Error = String; + fn try_from(text: String) -> Result { + let (dev, ino) = text.split_once('-').ok_or("invalid log identity")?; + Ok(Self { + dev: dev.parse().map_err(|_| "invalid log identity")?, + ino: ino.parse().map_err(|_| "invalid log identity")?, + }) + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct LogInfo { + pub ident: FileIdent, + pub len: u64, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum LogPage { + Data { + len: Option, + ident: FileIdent, + start: u64, + #[serde(rename = "data", with = "bytes")] + bytes: Vec, + eof: bool, + }, + Reset { + info: Option, + }, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ProcessIdentity { + pub node: String, + pub boot_id: String, + pub pid: u32, + pub starttime: u64, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Survivor { + pub pid: u32, + pub starttime: u64, + pub state: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum CancelOutcome { + Verified, + Survivors, + Unverifiable { unreadable: Vec }, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ExitReason { + Exited, + Cancelled, + SpawnFailed, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum CancelAck { + Accepted, + NotRunning, + WrapperGone, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum CleanupAck { + Accepted, + NothingLingering, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum LegacyCancelOutcome { + GroupGone, + Survivors { pids: Vec }, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ExecResult { + pub code: Option, + pub signal: Option, + pub timed_out: bool, + #[serde(with = "bytes")] + pub stdout: Vec, + #[serde(with = "bytes")] + pub stderr: Vec, + pub stdout_truncated: bool, + pub stderr_truncated: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ExitReceipt { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub finished_at: Option, + pub code: Option, + pub signal: Option, + pub reason: ExitReason, + pub processes: Vec, + pub outcome: CancelOutcome, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ProcessOutcome { + pub processes: Vec, + pub outcome: CancelOutcome, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "phase", rename_all = "snake_case")] +pub enum RunState { + Missing, + Staging, + Starting, + Running, + Exited { receipt: ExitReceipt }, + Failed { reason: String }, + Lost { reason: String }, + Cancelled { reason: String }, + Unreconciled { detail: String }, + InvalidData { detail: String }, + Unreachable { cause: String }, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Summary { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub started_at: Option, + pub state: RunState, + pub log_len: Option, + pub notify_len: u64, + pub cleanup: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct LaunchIntent { + pub run: RunId, + pub digest: Sha, + pub run_sh: String, + pub env: BTreeMap, + pub source: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cancel_sh: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct SlurmJob { + pub run: RunId, + pub job: String, + pub state: String, + pub summary: Summary, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct SlurmLegacyRun { + pub run: RunId, + pub job: String, + pub dir: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct LegacyInspection { + pub pid: Option, + pub alive: bool, + pub exit_code: Option, + pub receipt_unreadable: bool, +} + +/// A clean EOF is distinct from a truncated header or payload; lengths are big-endian. +pub fn read_frame(reader: &mut impl Read) -> io::Result> { + let mut header = [0; 4]; + loop { + match reader.read(&mut header[..1]) { + Ok(0) => return Ok(None), + Ok(_) => break, + Err(error) if error.kind() == io::ErrorKind::Interrupted => continue, + Err(error) => return Err(error), + } + } + reader.read_exact(&mut header[1..])?; + let len = u32::from_be_bytes(header) as usize; + if len == 0 || len > MAX_FRAME_LEN { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "invalid frame length", + )); + } + let mut payload = vec![0; len]; + reader.read_exact(&mut payload)?; + serde_json::from_slice(&payload) + .map(Some) + .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error)) +} + +pub fn write_frame(writer: &mut impl Write, value: &T) -> io::Result<()> { + let payload = serde_json::to_vec(value).map_err(io::Error::other)?; + if payload.len() > MAX_FRAME_LEN { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "frame too large", + )); + } + writer.write_all(&(payload.len() as u32).to_be_bytes())?; + writer.write_all(&payload)?; + writer.flush() +} + +mod bytes { + use base64::{engine::general_purpose::STANDARD, Engine}; + use serde::{Deserialize, Deserializer, Serialize, Serializer}; + + pub fn serialize>( + value: &T, + serializer: S, + ) -> Result { + STANDARD.encode(value).serialize(serializer) + } + + pub fn deserialize<'de, D: Deserializer<'de>, T: TryFrom>>( + deserializer: D, + ) -> Result { + let value = String::deserialize(deserializer)?; + let bytes = STANDARD.decode(value).map_err(serde::de::Error::custom)?; + T::try_from(bytes).map_err(|_| serde::de::Error::custom("invalid byte field length")) + } + + pub fn serialize_optional( + value: &Option<[u8; 64]>, + serializer: S, + ) -> Result { + value + .as_ref() + .map(|bytes| STANDARD.encode(bytes)) + .serialize(serializer) + } + + pub fn deserialize_optional<'de, D: Deserializer<'de>>( + deserializer: D, + ) -> Result, D::Error> { + Option::::deserialize(deserializer)? + .map(|value| { + let bytes = STANDARD.decode(value).map_err(serde::de::Error::custom)?; + bytes + .try_into() + .map_err(|_| serde::de::Error::custom("anchor must contain 64 bytes")) + }) + .transpose() + } +} diff --git a/crates/orx-host-proto/tests/disk.rs b/crates/orx-host-proto/tests/disk.rs new file mode 100644 index 000000000..f13bda2c8 --- /dev/null +++ b/crates/orx-host-proto/tests/disk.rs @@ -0,0 +1,162 @@ +use orx_host_proto::*; +use serde::{de::DeserializeOwned, Serialize}; +use serde_json::Value; + +fn fixtures() -> Vec { + std::fs::read_dir(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures")) + .unwrap() + .map(|entry| { + serde_json::from_slice(&std::fs::read(entry.unwrap().path()).unwrap()).unwrap() + }) + .collect() +} + +fn roundtrip(value: &Value) { + let decoded: T = serde_json::from_value(value.clone()).unwrap(); + assert_eq!(serde_json::to_value(decoded).unwrap(), *value); +} + +#[test] +fn every_historical_disk_fixture_roundtrips() { + for fixture in fixtures() { + for value in fixture["launch"].as_array().unwrap() { + roundtrip::(value); + } + for value in fixture["identity"].as_array().unwrap() { + roundtrip::(value); + } + for value in fixture["exit"].as_array().unwrap() { + roundtrip::(value); + } + for value in fixture["cleanup"].as_array().unwrap() { + roundtrip::(value); + } + } +} + +#[test] +fn todays_disk_writer_matches_an_append_only_fixture() { + let fixtures = fixtures(); + let check = |kind: &str, value: Value| { + assert!( + fixtures + .iter() + .any(|fixture| fixture[kind].as_array().unwrap().contains(&value)), + "unfrozen {kind}: {value}" + ); + }; + let mut launch = LaunchIntent { + run: "r1".into(), + digest: "a".repeat(64), + run_sh: "true".into(), + env: Default::default(), + source: None, + cancel_sh: None, + }; + check("launch", serde_json::to_value(&launch).unwrap()); + launch.run_sh = "bash repo/run.sh".into(); + launch.env.insert("TOKEN".into(), "value".into()); + launch.source = Some("b".repeat(64)); + launch.cancel_sh = Some("true".into()); + check("launch", serde_json::to_value(launch).unwrap()); + check( + "identity", + serde_json::to_value(ProcessIdentity { + node: "node-id".into(), + boot_id: "boot-id".into(), + pid: 42, + starttime: 1234, + }) + .unwrap(), + ); + for reason in [ + ExitReason::Exited, + ExitReason::Cancelled, + ExitReason::SpawnFailed, + ] { + let code = (reason == ExitReason::Exited).then_some(0); + check( + "exit", + serde_json::to_value(ExitReceipt { + finished_at: Some(1234567), + code, + signal: None, + reason, + processes: vec![], + outcome: CancelOutcome::Verified, + }) + .unwrap(), + ); + } + for (processes, outcome) in [ + (vec![], CancelOutcome::Verified), + ( + vec![Survivor { + pid: 43, + starttime: 5678, + state: "S".into(), + }], + CancelOutcome::Survivors, + ), + ( + vec![], + CancelOutcome::Unverifiable { + unreadable: vec![44], + }, + ), + ] { + check( + "cleanup", + serde_json::to_value(ProcessOutcome { + processes: processes.clone(), + outcome: outcome.clone(), + }) + .unwrap(), + ); + if outcome != CancelOutcome::Verified { + let cancelled = matches!(outcome, CancelOutcome::Unverifiable { .. }); + check( + "exit", + serde_json::to_value(ExitReceipt { + finished_at: Some(1234567), + code: (!cancelled).then_some(0), + signal: cancelled.then_some(15), + reason: if cancelled { + ExitReason::Cancelled + } else { + ExitReason::Exited + }, + processes, + outcome, + }) + .unwrap(), + ); + } + } +} + +#[test] +fn required_proof_never_defaults_and_unknown_variants_are_rejected() { + let fixture: Value = serde_json::from_str(include_str!("fixtures/disk-v1.json")).unwrap(); + for field in ["node", "boot_id", "pid", "starttime"] { + let mut value = fixture["identity"][0].clone(); + value.as_object_mut().unwrap().remove(field); + assert!(serde_json::from_value::(value).is_err()); + } + for field in ["reason", "processes", "outcome"] { + let mut value = fixture["exit"][0].clone(); + value.as_object_mut().unwrap().remove(field); + assert!(serde_json::from_value::(value).is_err()); + } + for field in ["processes", "outcome"] { + let mut value = fixture["cleanup"][0].clone(); + value.as_object_mut().unwrap().remove(field); + assert!(serde_json::from_value::(value).is_err()); + } + let mut value = fixture["exit"][0].clone(); + value["reason"] = "future".into(); + assert!(serde_json::from_value::(value).is_err()); + let mut value = fixture["exit"][0].clone(); + value["outcome"]["kind"] = "future".into(); + assert!(serde_json::from_value::(value).is_err()); +} diff --git a/crates/orx-host-proto/tests/fixtures/disk-finished-at.json b/crates/orx-host-proto/tests/fixtures/disk-finished-at.json new file mode 100644 index 000000000..71c694c9c --- /dev/null +++ b/crates/orx-host-proto/tests/fixtures/disk-finished-at.json @@ -0,0 +1,66 @@ +{ + "launch": [], + "identity": [], + "exit": [ + { + "code": 0, + "signal": null, + "reason": "exited", + "processes": [], + "outcome": { + "kind": "verified" + }, + "finished_at": 1234567 + }, + { + "code": null, + "signal": null, + "reason": "cancelled", + "processes": [], + "outcome": { + "kind": "verified" + }, + "finished_at": 1234567 + }, + { + "code": null, + "signal": null, + "reason": "spawn_failed", + "processes": [], + "outcome": { + "kind": "verified" + }, + "finished_at": 1234567 + }, + { + "code": 0, + "signal": null, + "reason": "exited", + "processes": [ + { + "pid": 43, + "starttime": 5678, + "state": "S" + } + ], + "outcome": { + "kind": "survivors" + }, + "finished_at": 1234567 + }, + { + "code": null, + "signal": 15, + "reason": "cancelled", + "processes": [], + "outcome": { + "kind": "unverifiable", + "unreadable": [ + 44 + ] + }, + "finished_at": 1234567 + } + ], + "cleanup": [] +} diff --git a/crates/orx-host-proto/tests/fixtures/disk-v1.json b/crates/orx-host-proto/tests/fixtures/disk-v1.json new file mode 100644 index 000000000..48a8d2212 --- /dev/null +++ b/crates/orx-host-proto/tests/fixtures/disk-v1.json @@ -0,0 +1,21 @@ +{ + "launch": [ + {"run":"r1","digest":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","run_sh":"true","env":{},"source":null}, + {"run":"r1","digest":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","run_sh":"bash repo/run.sh","env":{"TOKEN":"value"},"source":"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb","cancel_sh":"true"} + ], + "identity": [ + {"node":"node-id","boot_id":"boot-id","pid":42,"starttime":1234} + ], + "exit": [ + {"code":0,"signal":null,"reason":"exited","processes":[],"outcome":{"kind":"verified"}}, + {"code":null,"signal":null,"reason":"cancelled","processes":[],"outcome":{"kind":"verified"}}, + {"code":null,"signal":null,"reason":"spawn_failed","processes":[],"outcome":{"kind":"verified"}}, + {"code":0,"signal":null,"reason":"exited","processes":[{"pid":43,"starttime":5678,"state":"S"}],"outcome":{"kind":"survivors"}}, + {"code":null,"signal":15,"reason":"cancelled","processes":[],"outcome":{"kind":"unverifiable","unreadable":[44]}} + ], + "cleanup": [ + {"processes":[],"outcome":{"kind":"verified"}}, + {"processes":[{"pid":43,"starttime":5678,"state":"S"}],"outcome":{"kind":"survivors"}}, + {"processes":[],"outcome":{"kind":"unverifiable","unreadable":[44]}} + ] +} diff --git a/crates/orx-host-proto/tests/wire.rs b/crates/orx-host-proto/tests/wire.rs new file mode 100644 index 000000000..0e0f4be39 --- /dev/null +++ b/crates/orx-host-proto/tests/wire.rs @@ -0,0 +1,275 @@ +use orx_host_proto::*; +use std::io::{self, Cursor, Read}; + +#[test] +fn golden_request_and_response() { + let request = Message { + id: 7, + body: Request::Hello { + proto: PROTOCOL_VERSION, + }, + }; + let json = format!(r#"{{"id":7,"body":{{"op":"hello","proto":{PROTOCOL_VERSION}}}}}"#); + let mut golden = (json.len() as u32).to_be_bytes().to_vec(); + golden.extend_from_slice(json.as_bytes()); + let mut encoded = Vec::new(); + write_frame(&mut encoded, &request).unwrap(); + assert_eq!(encoded, golden); + assert_eq!( + read_frame::>(&mut golden.as_slice()).unwrap(), + Some(request) + ); + + let response = Message { + id: 7, + body: Response::Cancel { + outcome: CancelAck::Accepted, + }, + }; + let json = br#"{"id":7,"body":{"op":"cancel","outcome":"accepted"}}"#; + let mut golden = (json.len() as u32).to_be_bytes().to_vec(); + golden.extend_from_slice(json); + encoded.clear(); + write_frame(&mut encoded, &response).unwrap(); + assert_eq!(encoded, golden); + assert_eq!( + read_frame::>(&mut golden.as_slice()).unwrap(), + Some(response) + ); +} + +#[test] +fn launch_reuses_the_intent_without_changing_its_wire_shape() { + let json = + r#"{"op":"launch","run":"r1","digest":"sha","run_sh":"true","env":{},"source":null}"#; + let request: Request = serde_json::from_str(json).unwrap(); + assert!(matches!(&request, Request::Launch(intent) if intent.run == "r1")); + assert_eq!(serde_json::to_string(&request).unwrap(), json); +} + +#[test] +fn golden_receipt_and_summary() { + let json = r#"{"state":{"phase":"exited","receipt":{"code":0,"signal":null,"reason":"exited","processes":[],"outcome":{"kind":"verified"}}},"log_len":23,"notify_len":0,"cleanup":null}"#; + let summary: Summary = serde_json::from_str(json).unwrap(); + assert_eq!(serde_json::to_string(&summary).unwrap(), json); + assert!(matches!( + summary.state, + RunState::Exited { + receipt: ExitReceipt { code: Some(0), .. } + } + )); +} + +#[test] +fn eof_truncation_and_invalid_lengths() { + assert!(read_frame::(&mut [].as_slice()).unwrap().is_none()); + for bytes in [vec![0], vec![0, 0, 0], vec![0, 0, 0, 2, b'{']] { + assert_eq!( + read_frame::(&mut bytes.as_slice()) + .unwrap_err() + .kind(), + io::ErrorKind::UnexpectedEof + ); + } + for len in [0, MAX_FRAME_LEN as u32 + 1, u32::MAX] { + assert_eq!( + read_frame::(&mut len.to_be_bytes().as_slice()) + .unwrap_err() + .kind(), + io::ErrorKind::InvalidData + ); + } + assert!(read_frame::(&mut [0, 0, 0, 1, b'?'].as_slice()).is_err()); +} + +struct Fragmented<'a>(&'a [u8]); +impl Read for Fragmented<'_> { + fn read(&mut self, bytes: &mut [u8]) -> io::Result { + let len = bytes.len().min(1); + self.0.read(&mut bytes[..len]) + } +} + +#[test] +fn fragmented_and_consecutive_frames() { + let mut bytes = Vec::new(); + for id in 0..12 { + write_frame( + &mut bytes, + &Message { + id, + body: Request::Hello { + proto: orx_host_proto::PROTOCOL_VERSION, + }, + }, + ) + .unwrap(); + } + let mut reader = Fragmented(&bytes); + for id in 0..12 { + assert_eq!( + read_frame::>(&mut reader) + .unwrap() + .unwrap() + .id, + id + ); + } + assert!(read_frame::(&mut reader).unwrap().is_none()); +} + +#[test] +fn random_frames_and_roundtrips() { + let mut seed = 0x7ad3_2915_1726_4401u64; + let mut next = || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed + }; + for _ in 0..10_000 { + let size = (next() % 1024) as usize; + let bytes: Vec<_> = (0..size).map(|_| next() as u8).collect(); + let mut frame = (size as u32).to_be_bytes().to_vec(); + frame.extend_from_slice(&bytes); + let _ = read_frame::>(&mut Cursor::new(frame)); + let offset = next(); + let request = Message { + id: next(), + body: Request::ReadLog { + target: LogTarget::Run(format!("run-{}", next())), + file: LogFile::Log, + ident: None, + range: ByteRange { + start: offset, + end: offset.saturating_add(next() % MAX_PAGE_LEN), + }, + anchor: Some([next() as u8; 64]), + }, + }; + let mut encoded = Vec::new(); + write_frame(&mut encoded, &request).unwrap(); + assert_eq!( + read_frame::>(&mut encoded.as_slice()).unwrap(), + Some(request) + ); + } +} + +#[test] +fn malformed_anchor_is_rejected() { + let mut json = serde_json::to_value(Request::ReadLog { + target: LogTarget::Run("r".into()), + file: LogFile::Log, + ident: None, + range: ByteRange { start: 0, end: 1 }, + anchor: Some([0; 64]), + }) + .unwrap(); + json["anchor"] = serde_json::json!([0, 1]); + assert!(serde_json::from_value::(json).is_err()); +} + +#[test] +fn legacy_container_descriptor_keeps_its_shipped_shape() { + let json = r#"{"reference":"worker","id":"abc123","startedAt":"generation","runDir":"/home/user/.orx/runs/r1"}"#; + let container: ContainerRun = serde_json::from_str(json).unwrap(); + assert_eq!(serde_json::to_string(&container).unwrap(), json); + let request = Request::CancelLegacy { + dir: "~/.orx/runs/r1".into(), + container: Some(container), + }; + let mut bytes = vec![]; + write_frame(&mut bytes, &request).unwrap(); + assert_eq!( + read_frame::(&mut bytes.as_slice()).unwrap(), + Some(request) + ); +} + +#[test] +fn cleanup_wire_and_verified_receipt_are_canonical() { + let request: Request = serde_json::from_str(r#"{"op":"cleanup","run":"r1"}"#).unwrap(); + assert_eq!(request, Request::Cleanup { run: "r1".into() }); + assert_eq!( + serde_json::to_string(&Response::Cleanup { + outcome: CleanupAck::NothingLingering + }) + .unwrap(), + r#"{"op":"cleanup","outcome":"nothing_lingering"}"# + ); + assert_eq!( + serde_json::to_string(&CancelOutcome::Verified).unwrap(), + r#"{"kind":"verified"}"# + ); +} + +#[test] +fn maximum_byte_payloads_fit_frames_with_base64_expansion() { + let bytes = vec![255; MAX_PAGE_LEN as usize]; + let requests = [ + Request::Exec { + command: "cat".into(), + stdin: bytes.clone(), + timeout_ms: 1, + }, + Request::PutBlob { + sha: "a".repeat(64), + offset: u64::MAX, + bytes: bytes[..256 * 1024].to_vec(), + }, + ]; + for body in requests { + let message = Message { id: u64::MAX, body }; + let mut frame = Vec::new(); + write_frame(&mut frame, &message).unwrap(); + assert!(frame.len() < MAX_FRAME_LEN); + assert_eq!( + read_frame::>(&mut frame.as_slice()).unwrap(), + Some(message) + ); + } + let responses = [ + Response::Exec { + result: ExecResult { + code: Some(0), + signal: None, + timed_out: false, + stdout: bytes.clone(), + stderr: bytes.clone(), + stdout_truncated: false, + stderr_truncated: false, + }, + }, + Response::ReadLog { + page: LogPage::Data { + len: None, + ident: FileIdent { + dev: u64::MAX, + ino: u64::MAX, + }, + start: u64::MAX, + bytes, + eof: false, + }, + }, + ]; + for body in responses { + let message = Message { id: u64::MAX, body }; + let mut frame = Vec::new(); + write_frame(&mut frame, &message).unwrap(); + assert!(frame.len() < MAX_FRAME_LEN); + assert_eq!( + read_frame::>(&mut frame.as_slice()).unwrap(), + Some(message) + ); + } + for invalid in [ + serde_json::json!([0, 255]), + serde_json::json!("!!!!"), + serde_json::json!("/x=="), + ] { + let value = serde_json::json!({"op":"put_blob", "sha":"a", "offset":0, "bytes":invalid}); + assert!(serde_json::from_value::(value).is_err()); + } +} diff --git a/crates/orx-host/Cargo.toml b/crates/orx-host/Cargo.toml new file mode 100644 index 000000000..5c919de38 --- /dev/null +++ b/crates/orx-host/Cargo.toml @@ -0,0 +1,25 @@ +[package] +name = "orx-host" +version = "0.1.0" +edition = "2021" +publish = false + +[package.metadata.dist] +dist = false + +[features] +test-hooks = [] + +[dependencies] +orx-host-proto = { path = "../orx-host-proto" } +libc = "0.2" +sha2 = "0.10" +serde = { version = "1", features = ["derive"] } +serde_json = "1" + +[target.'cfg(unix)'.dev-dependencies] +orx-host = { path = ".", features = ["test-hooks"] } +orx-test-support = { path = "../../tests/support" } + +[build-dependencies] +cc = "1" diff --git a/crates/orx-host/README.md b/crates/orx-host/README.md new file mode 100644 index 000000000..5b7a927a5 --- /dev/null +++ b/crates/orx-host/README.md @@ -0,0 +1,48 @@ +# orx-host + +`orx-host serve --root /absolute/root` speaks the types in +[`orx-host-proto`](../orx-host-proto/src/lib.rs) over stdin/stdout. Frames contain +`Message { id, body }`; replies may arrive out of order. EOF stops request work +and command sessions. Detached `wrap RUN_DIR` processes outlive the connection. +`verify-self SHA256` verifies the executable used by the bootstrap uploader. + +`PutBlob` resumes a `.part` file and checks overlapping retry bytes. `HasBlob` +checks the supplied total length and SHA before publishing the final source. +`Launch` records intent exclusively, stages a source into `repo/`, and starts a +wrapper. A missing source yields `Staging`; a later feed or repeated launch +resumes it. Equal run ids require equal intents. `SlurmSubmit` passes the supplied +batch script to `sbatch` and records `job.sbatch` to prevent login-node recovery +from starting a compute-node wrapper. The script prepares the shared run directory and +executes `wrap` on the compute node. + +The direct child's exit publishes `exit.json` immediately. Its `processes` list +records processes left alive; the wrapper keeps reaping them after the run ends. +`Cleanup` writes `cleanup.req` and wakes the wrapper to run the same stop sequence. +`cleanup.json` records the remaining `processes` and shared `CancelOutcome`, exposed as `Summary.cleanup` in +the feed. Natural disappearance of the last lingering process records that proof +too. Cleanup preserves the original exit receipt. + +`RunState::Exited` carries the receipt, including cancellation proof. A cancelled +receipt without `CancelOutcome::Verified` remains Cancelling + Unreconciled in the engine. +Darwin has no subreaper and never verifies cancellation. Unreadable process data +observed during cancellation remains part of the final incomplete scan, except +for processes proven to predate the wrapper and its tag. A +container hook that fails or exceeds 30 seconds also prevents verification. + +The `started` file contains the random run tag, allowing best-effort tagged +cleanup after wrapper death without treating an empty scan as containment proof. +The source and launch locks use fcntl across sessions. A process-wide mutex per +run directory serializes launch, cancel, and cleanup, since fcntl ownership is +shared by threads. Source uploads have their own thread mutex. + +`test-hooks` in debug builds enables `ORX_TEST_CRASH_AT`: `before_launch`, `launch_published`, +`wrapper_locked`, `wrapper_identity`, `wrapper_started`, `wrapper_spawned`, +`wrapper_before_receipt`, `wrapper_receipt`. Normal test runs cover the crash +states; feature-enabled tests also abort actual wrappers at every wrapper hook. + +Tests enable `test-hooks` through a dev dependency. `ORX_TEST_FAST_STOPS=1` +caps stop delays and hook budgets in debug builds; release builds ignore it. +The default-duration test checks the production grace and hook budget. +Large-page tests optimize the protocol, host, JSON and SSH proxy in the test +profile while still checking all 256 MiB, with a distinct header on each page +and four requests in flight to overlap encoding and decoding. diff --git a/crates/orx-host/build.rs b/crates/orx-host/build.rs new file mode 100644 index 000000000..5517c2300 --- /dev/null +++ b/crates/orx-host/build.rs @@ -0,0 +1,8 @@ +fn main() { + if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("macos") { + println!("cargo:rerun-if-changed=src/process_uid.c"); + cc::Build::new() + .file("src/process_uid.c") + .compile("process_uid"); + } +} diff --git a/crates/orx-host/src/exec.rs b/crates/orx-host/src/exec.rs new file mode 100644 index 000000000..093ede5ac --- /dev/null +++ b/crates/orx-host/src/exec.rs @@ -0,0 +1,262 @@ +use orx_host_proto::ExecResult; +use std::io::{self, Read, Write}; +use std::os::fd::AsRawFd; +use std::os::unix::process::{CommandExt, ExitStatusExt}; +use std::process::{Command, Stdio}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; + +pub fn run( + command: &mut Command, + input: &[u8], + timeout: Duration, + stop: Option<&AtomicBool>, +) -> io::Result { + unsafe { + command.pre_exec(|| { + if libc::setsid() == -1 { + Err(io::Error::last_os_error()) + } else { + Ok(()) + } + }); + } + let mut child = command + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn()?; + let pid = child.id(); + let result = (|| { + let mut stdin = child.stdin.take(); + let mut stdout = child + .stdout + .take() + .ok_or_else(|| io::Error::other("missing stdout"))?; + let mut stderr = child + .stderr + .take() + .ok_or_else(|| io::Error::other("missing stderr"))?; + for fd in [ + stdin.as_ref().map(AsRawFd::as_raw_fd), + Some(stdout.as_raw_fd()), + Some(stderr.as_raw_fd()), + ] + .into_iter() + .flatten() + { + let flags = unsafe { libc::fcntl(fd, libc::F_GETFL) }; + if flags == -1 + || unsafe { libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK) } == -1 + { + return Err(io::Error::last_os_error()); + } + } + let mut result = ExecResult { + code: None, + signal: None, + timed_out: false, + stdout: vec![], + stderr: vec![], + stdout_truncated: false, + stderr_truncated: false, + }; + let mut sent = 0; + let mut out_closed = false; + let mut err_closed = false; + let deadline = Instant::now() + timeout; + loop { + if let Some(pipe) = &mut stdin { + if sent == input.len() { + stdin = None; + } else { + match pipe.write(&input[sent..]) { + Ok(len) => sent += len, + Err(error) if error.kind() == io::ErrorKind::BrokenPipe => { + stdin = None; + } + Err(error) + if matches!( + error.kind(), + io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted + ) => {} + Err(error) => return Err(error), + } + } + } + out_closed |= drain( + &mut stdout, + &mut result.stdout, + 256 * 1024, + &mut result.stdout_truncated, + )?; + err_closed |= drain( + &mut stderr, + &mut result.stderr, + 16 * 1024, + &mut result.stderr_truncated, + )?; + let mut info = unsafe { std::mem::zeroed::() }; + if unsafe { + libc::waitid( + libc::P_PID, + pid, + &mut info, + libc::WEXITED | libc::WNOHANG | libc::WNOWAIT, + ) + } != 0 + { + return Err(io::Error::last_os_error()); + } + if unsafe { info.si_pid() } != 0 && out_closed && err_closed { + break; + } + if stop.is_some_and(|stop| stop.load(Ordering::Relaxed)) || Instant::now() >= deadline { + result.timed_out = true; + break; + } + let mut fds = Vec::new(); + if let Some(pipe) = &stdin { + fds.push(libc::pollfd { + fd: pipe.as_raw_fd(), + events: libc::POLLOUT, + revents: 0, + }); + } + if !out_closed { + fds.push(libc::pollfd { + fd: stdout.as_raw_fd(), + events: libc::POLLIN, + revents: 0, + }); + } + if !err_closed { + fds.push(libc::pollfd { + fd: stderr.as_raw_fd(), + events: libc::POLLIN, + revents: 0, + }); + } + let wait_ms = deadline + .saturating_duration_since(Instant::now()) + .as_millis() + .min(100) as i32; + if unsafe { libc::poll(fds.as_mut_ptr(), fds.len() as _, wait_ms) } == -1 { + let error = io::Error::last_os_error(); + if error.kind() != io::ErrorKind::Interrupted { + return Err(error); + } + } + } + Ok(result) + })(); + // WNOWAIT keeps the session leader reserved until the final group signal. + unsafe { + libc::kill(-(pid as i32), libc::SIGKILL); + } + let reap_deadline = Instant::now() + Duration::from_millis(100); + let status = loop { + if let Some(status) = child.try_wait()? { + break status; + } + if Instant::now() >= reap_deadline { + // A driver can leave SIGKILL pending in uninterruptible sleep. + std::thread::spawn(move || { + let _ = child.wait(); + }); + return result; + } + std::thread::sleep(Duration::from_millis(1)); + }; + result.map(|mut result| { + result.code = status.code(); + result.signal = status.signal(); + result + }) +} + +fn drain( + reader: &mut impl Read, + output: &mut Vec, + limit: usize, + truncated: &mut bool, +) -> io::Result { + let mut bytes = [0; 8192]; + for _ in 0..32 { + match reader.read(&mut bytes) { + Ok(0) => return Ok(true), + Ok(len) => { + let kept = len.min(limit - output.len()); + output.extend_from_slice(&bytes[..kept]); + *truncated |= kept < len; + } + Err(error) if error.kind() == io::ErrorKind::WouldBlock => return Ok(false), + Err(error) if error.kind() == io::ErrorKind::Interrupted => {} + Err(error) => return Err(error), + } + } + Ok(false) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn output_and_input_are_bounded_without_pipe_deadlock() { + let result = run( + Command::new("/bin/sh") + .arg("-c") + .arg("cat; head -c 400000 /dev/zero; head -c 40000 /dev/zero >&2"), + b"hello\n", + Duration::from_secs(5), + None, + ) + .unwrap(); + assert_eq!(result.code, Some(0)); + assert_eq!(result.stdout.len(), 256 * 1024); + assert_eq!(result.stderr.len(), 16 * 1024); + assert!(result.stdout.starts_with(b"hello\n")); + assert!(result.stdout_truncated && result.stderr_truncated); + } + + #[test] + fn timeout_kills_session_and_handles_inherited_pipes() { + let start = Instant::now(); + let result = run( + Command::new("/bin/sh").arg("-c").arg("sleep 60 & wait"), + &[], + Duration::from_millis(50), + None, + ) + .unwrap(); + assert!(result.timed_out); + assert_eq!(result.signal, Some(libc::SIGKILL)); + assert!(start.elapsed() < Duration::from_secs(2)); + } + + #[test] + fn detached_child_survives_command_group_cleanup() { + let dir = std::env::temp_dir().join(format!("orx-exec-detach-{}", crate::nonce().unwrap())); + std::fs::create_dir_all(&dir).unwrap(); + let launch = "python3 -c 'import os,subprocess; os.setsid(); subprocess.Popen([\"/bin/sh\", \"-c\", \"sleep 0.2; echo survived > marker\"], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)'; exit $?"; + let result = run( + Command::new("/bin/sh") + .args(["-c", launch]) + .current_dir(&dir), + &[], + Duration::from_secs(2), + None, + ) + .unwrap(); + assert_eq!(result.code, Some(0), "{result:?}"); + assert!(!result.timed_out); + + let deadline = Instant::now() + Duration::from_secs(2); + while std::fs::read_to_string(dir.join("marker")).ok().as_deref() != Some("survived\n") { + assert!(Instant::now() < deadline, "detached child was killed"); + std::thread::sleep(Duration::from_millis(10)); + } + std::fs::remove_dir_all(&dir).unwrap(); + } +} diff --git a/crates/orx-host/src/legacy.rs b/crates/orx-host/src/legacy.rs new file mode 100644 index 000000000..533f89427 --- /dev/null +++ b/crates/orx-host/src/legacy.rs @@ -0,0 +1,297 @@ +use crate::{exec, platform}; +use orx_host_proto::{ContainerRun, LegacyCancelOutcome, LegacyInspection}; +use std::fs; +use std::io; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; + +pub fn directory(value: &str) -> io::Result { + let relative = value + .strip_prefix("~/") + .or_else(|| value.strip_prefix("$HOME/")); + let components = relative.or_else(|| value.strip_prefix('/')); + let valid = components.is_some_and(|value| { + !value.is_empty() + && value.split('/').all(|part| { + !matches!(part, "" | "." | "..") + && part + .chars() + .all(|c| c.is_ascii_alphanumeric() || "._-+@".contains(c)) + }) + }); + if !valid { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "directory must be absolute or HOME-relative without shell metacharacters", + )); + } + if let Some(relative) = relative { + let home = std::env::var_os("HOME").ok_or_else(|| io::Error::other("HOME is unset"))?; + if !Path::new(&home).is_absolute() { + return Err(io::Error::other("HOME must be absolute")); + } + return Ok(PathBuf::from(home).join(relative)); + } + Ok(PathBuf::from(value)) +} + +pub fn inspect(dir: &Path) -> io::Result { + let pid = match fs::read_to_string(dir.join("pid")) { + Ok(text) => text + .trim() + .parse::() + .ok() + .filter(|&pid| (2..=i32::MAX as u32).contains(&pid)), + Err(error) if error.kind() == io::ErrorKind::NotFound => None, + Err(error) => return Err(error), + }; + let (exit_code, receipt_unreadable) = match fs::read_to_string(dir.join("exit_code")) { + Ok(text) => match text.trim().parse() { + Ok(code) => (Some(code), false), + Err(_) => (None, true), + }, + Err(error) if error.kind() == io::ErrorKind::NotFound => (None, false), + Err(_) => (None, true), + }; + let alive = if let Some(pid) = pid { + platform::process(pid).is_ok_and(|process| process.live()) || !group(pid)?.is_empty() + } else { + false + }; + Ok(LegacyInspection { + pid, + alive, + exit_code, + receipt_unreadable, + }) +} + +pub fn cancel( + dir: &Path, + container: Option<&ContainerRun>, + stop: Option<&AtomicBool>, +) -> io::Result { + if let Some(container) = container { + cancel_container(container, stop)?; + } + let Some(pid) = inspect(dir)?.pid else { + return Ok(LegacyCancelOutcome::GroupGone); + }; + let original = platform::process(pid).ok(); + let send = |signal| -> io::Result<()> { + if let Some(original) = &original { + if platform::process(pid).is_ok_and(|process| process.starttime != original.starttime) { + return Err(io::Error::other("legacy process identity changed")); + } + } + if unsafe { libc::kill(-(pid as i32), signal) } != 0 && signal == libc::SIGTERM { + if let Some(original) = &original { + let _ = platform::signal(original, signal); + } + } + Ok(()) + }; + cancel_group( + pid, + send, + stop, + crate::stop_duration(Duration::from_secs(5)), + crate::stop_duration(Duration::from_secs(1)), + ) +} + +fn cancel_group( + pid: u32, + mut send: impl FnMut(i32) -> io::Result<()>, + stop: Option<&AtomicBool>, + grace: Duration, + recheck: Duration, +) -> io::Result { + send(libc::SIGTERM)?; + let deadline = Instant::now() + grace; + loop { + let pids = group(pid)?; + if pids.is_empty() { + return Ok(LegacyCancelOutcome::GroupGone); + } + if stop.is_some_and(|stop| stop.load(Ordering::Relaxed)) || Instant::now() >= deadline { + break; + } + std::thread::sleep(Duration::from_millis(100)); + } + send(libc::SIGKILL)?; + let deadline = Instant::now() + recheck; + loop { + let pids = group(pid)?; + if pids.is_empty() { + return Ok(LegacyCancelOutcome::GroupGone); + } + if stop.is_some_and(|stop| stop.load(Ordering::Relaxed)) || Instant::now() >= deadline { + return Ok(LegacyCancelOutcome::Survivors { pids }); + } + std::thread::sleep(Duration::from_millis(100)); + } +} + +fn group(pgid: u32) -> io::Result> { + let mut result = Vec::new(); + for pid in platform::pids()? { + if let Ok(process) = platform::process(pid) { + if process.live() && unsafe { libc::getpgid(pid as i32) } == pgid as i32 { + result.push(pid); + } + } + } + Ok(result) +} + +fn cancel_container(container: &ContainerRun, stop: Option<&AtomicBool>) -> io::Result<()> { + if container.id.is_empty() + || !container + .id + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b"_.-".contains(&b)) + { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "invalid container id", + )); + } + if !container.run_dir.starts_with('/') || container.run_dir.contains(['\n', '\r', '\0']) { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "container run directory must be absolute", + )); + } + let result = exec::run( + Command::new("docker").args([ + "container", + "inspect", + "--format", + "{{.Id}}|{{.State.StartedAt}}|{{.State.Status}}", + "--", + &container.id, + ]), + &[], + Duration::from_secs(5), + stop, + )?; + if result.timed_out || result.stdout_truncated { + return Err(io::Error::other( + "container inspection timed out or exceeded its output bound", + )); + } + if result.code != Some(0) { + let list = exec::run( + Command::new("docker").args([ + "container", + "ls", + "--all", + "--no-trunc", + "--format", + "{{.ID}} {{.Names}}", + ]), + &[], + Duration::from_secs(5), + stop, + )?; + if list.code != Some(0) || list.timed_out || list.stdout_truncated { + return Err(io::Error::other("cannot inspect Docker daemon")); + } + if String::from_utf8_lossy(&list.stdout) + .split_whitespace() + .any(|value| value == container.id || value.starts_with(&container.id)) + { + return Err(io::Error::other("cannot inspect container")); + } + return Ok(()); + } + let output = String::from_utf8_lossy(&result.stdout); + let fields: Vec<_> = output.trim().split('|').collect(); + if fields.len() != 3 { + return Err(io::Error::other("invalid Docker inspection")); + } + if fields[0] != container.id || fields[1] != container.started_at { + return Ok(()); + } + if fields[2] == "paused" { + return Err(io::Error::other(format!( + "Container '{}' is paused. Unpause it to complete cancellation.", + container.reference + ))); + } + if fields[2] != "running" { + return Ok(()); + } + let directory = format!("'{}'", container.run_dir.replace('\'', "'\\''")); + let script = format!( + r#" +start_time() {{ local stat; IFS= read -r stat < "/proc/$1/stat" 2>/dev/null || return 1; stat=${{stat##*) }}; local fields; read -ra fields <<< "$stat"; printf '%s' "${{fields[19]}}"; }} +group_alive() {{ local file stat fields; for file in /proc/[0-9]*/stat; do IFS= read -r stat < "$file" 2>/dev/null || continue; stat=${{stat##*) }}; read -ra fields <<< "$stat"; if [ "${{fields[2]}}" = "$p" ] && [ "${{fields[0]}}" != Z ] && [ "${{fields[0]}}" != X ]; then return 0; fi; done; return 1; }} +cd {directory} || exit 1 +umask 077 +: > cancel +[ -f identity ] || exit 0 +read -r p started < identity +case "$p" in ''|*[!0-9]*) exit 1;; esac +[ "$p" -gt 1 ] || exit 1 +current=$(start_time "$p") +if [ -n "$current" ] && [ "$current" != "$started" ]; then echo 'Process identity changed; refusing to signal it' >&2; exit 1; fi +if ! group_alive; then exit 0; fi +kill -TERM -- -"$p" 2>/dev/null || true +for ((i=0; i<50; i++)); do group_alive || exit 0; sleep 0.1; done +kill -KILL -- -"$p" 2>/dev/null || true +for ((i=0; i<10; i++)); do group_alive || exit 0; sleep 0.1; done +echo 'Experiment process group is still alive' >&2 +exit 1 +"# + ); + let result = exec::run( + Command::new("docker").args(["exec", "-i", &container.id, "bash", "-c", &script]), + &[], + Duration::from_secs(8), + stop, + )?; + if result.code == Some(0) && !result.timed_out { + Ok(()) + } else { + let reason = if result.timed_out { + "Container cancellation timed out".to_owned() + } else { + String::from_utf8_lossy(&result.stderr).trim().to_owned() + }; + Err(io::Error::other(reason)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::os::unix::process::CommandExt; + + #[test] + fn surviving_fixture_group_is_reported_when_signals_cannot_remove_it() { + let mut child = Command::new("sleep") + .arg("60") + .process_group(0) + .spawn() + .unwrap(); + let pid = child.id(); + let result = cancel_group( + pid, + |_| Ok(()), + None, + Duration::from_millis(20), + Duration::from_millis(20), + ); + unsafe { + libc::kill(-(pid as i32), libc::SIGKILL); + } + child.wait().unwrap(); + assert!( + matches!(result.unwrap(), LegacyCancelOutcome::Survivors { pids } if pids.contains(&pid)) + ); + } +} diff --git a/crates/orx-host/src/lib.rs b/crates/orx-host/src/lib.rs new file mode 100644 index 000000000..035b4cb7f --- /dev/null +++ b/crates/orx-host/src/lib.rs @@ -0,0 +1,167 @@ +// Host processes inherit the host environment and the recorded run environment. +#![allow(clippy::disallowed_methods)] +#![cfg(unix)] + +pub mod exec; +pub mod legacy; +pub mod log; +pub mod platform; +pub mod server; +pub mod wrapper; + +use serde::{de::DeserializeOwned, Serialize}; +use sha2::{Digest, Sha256}; +use std::collections::HashMap; +use std::fs::{self, File, OpenOptions}; +use std::io::{self, Read, Write}; +use std::os::fd::AsRawFd; +use std::os::unix::fs::OpenOptionsExt; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex, OnceLock, Weak}; + +/// fcntl ownership is per process, so run mutations also need thread exclusion. +pub(crate) fn run_mutex(dir: &Path) -> io::Result>> { + static RUNS: OnceLock>>>> = OnceLock::new(); + let dir = fs::canonicalize(dir)?; + let mut runs = RUNS + .get_or_init(Mutex::default) + .lock() + .map_err(|_| io::Error::other("run lock registry poisoned"))?; + runs.retain(|_, mutex| mutex.strong_count() > 0); + let entry = runs.entry(dir).or_default(); + if let Some(mutex) = entry.upgrade() { + return Ok(mutex); + } + let mutex = Arc::new(Mutex::new(())); + *entry = Arc::downgrade(&mutex); + Ok(mutex) +} + +pub fn sha(bytes: &[u8]) -> String { + format!("{:x}", Sha256::digest(bytes)) +} + +pub fn nonce() -> io::Result { + let mut bytes = [0; 16]; + File::open("/dev/urandom")?.read_exact(&mut bytes)?; + Ok(sha(&bytes)) +} + +pub fn read_json(path: &Path) -> io::Result { + serde_json::from_slice(&fs::read(path)?) + .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error)) +} + +/// Rename publishes only complete, synced receipts, including on shared filesystems. +pub fn publish(path: &Path, value: &impl Serialize) -> io::Result<()> { + publish_bytes(path, &serde_json::to_vec(value)?) +} + +pub fn publish_bytes(path: &Path, bytes: &[u8]) -> io::Result<()> { + let temporary = path.with_extension(format!("tmp-{}", nonce()?)); + let result = (|| { + let mut file = OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(&temporary)?; + file.write_all(bytes)?; + file.flush()?; + file.sync_all()?; + fs::rename(&temporary, path)?; + File::open( + path.parent() + .ok_or_else(|| io::Error::other("missing parent"))?, + )? + .sync_all() + })(); + let _ = fs::remove_file(temporary); + result +} + +pub fn lock(path: &Path) -> io::Result> { + let file = OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .mode(0o600) + .open(path)?; + let mut lock = unsafe { std::mem::zeroed::() }; + lock.l_type = libc::F_WRLCK as _; + lock.l_whence = libc::SEEK_SET as _; + if unsafe { libc::fcntl(file.as_raw_fd(), libc::F_SETLK, &lock) } == -1 { + let error = io::Error::last_os_error(); + if matches!(error.raw_os_error(), Some(libc::EACCES | libc::EAGAIN)) { + return Ok(None); + } + return Err(error); + } + Ok(Some(file)) +} + +pub fn run_dir(root: &Path, run: &str) -> io::Result { + if run.is_empty() + || run.len() > 200 + || !run + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_')) + { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "invalid run id", + )); + } + Ok(root.join("runs").join(run)) +} + +pub fn crash_point(name: &str) { + #[cfg(all(feature = "test-hooks", debug_assertions))] + if std::env::var("ORX_TEST_CRASH_AT").as_deref() == Ok(name) { + std::process::abort(); + } + let _ = name; +} + +/// Holds a request back, to show what a slow host does to the requests behind it. +pub fn slow_request() { + #[cfg(all(feature = "test-hooks", debug_assertions))] + if let Some(millis) = std::env::var("ORX_TEST_SLOW_RPC") + .ok() + .and_then(|millis| millis.parse().ok()) + { + std::thread::sleep(std::time::Duration::from_millis(millis)); + } +} + +/// Whether to pin sources as if they were on another filesystem, one step per request. +pub(crate) fn cross_device() -> bool { + #[cfg(all(feature = "test-hooks", debug_assertions))] + if std::env::var("ORX_TEST_CROSS_DEVICE").as_deref() == Ok("1") { + return true; + } + false +} + +pub(crate) const TERM_GRACE: std::time::Duration = std::time::Duration::from_secs(10); +pub(crate) const HOOK_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30); + +pub(crate) fn stop_duration(production: std::time::Duration) -> std::time::Duration { + #[cfg(all(feature = "test-hooks", debug_assertions))] + if std::env::var("ORX_TEST_FAST_STOPS").as_deref() == Ok("1") { + return production.min(std::time::Duration::from_millis(100)); + } + production +} + +#[cfg(test)] +mod tests { + use super::*; + use std::time::Duration; + + #[test] + fn production_stop_durations_are_not_shortened_by_default() { + assert_eq!(stop_duration(TERM_GRACE), Duration::from_secs(10)); + assert_eq!(stop_duration(HOOK_TIMEOUT), Duration::from_secs(30)); + } +} diff --git a/crates/orx-host/src/log.rs b/crates/orx-host/src/log.rs new file mode 100644 index 000000000..722ba004f --- /dev/null +++ b/crates/orx-host/src/log.rs @@ -0,0 +1,95 @@ +use orx_host_proto::{ByteRange, FileIdent, LogInfo, LogPage, MAX_PAGE_LEN}; +use std::fs::File; +use std::io::{self, Read, Seek, SeekFrom}; +#[cfg(unix)] +use std::os::unix::fs::MetadataExt; +use std::path::Path; + +/// A run's log is written once at its run-unique path, so its inode names one generation. +fn open(path: &Path) -> io::Result> { + let file = match File::open(path) { + Ok(file) => file, + Err(error) if error.kind() == io::ErrorKind::NotFound => { + // Reading the directory revalidates NFS negative lookup caches. + let retry = path.parent().map(std::fs::read_dir).transpose(); + match retry.and_then(|_| File::open(path)) { + Ok(file) => file, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None), + Err(error) => return Err(error), + } + } + Err(error) => return Err(error), + }; + let metadata = file.metadata()?; + if !metadata.is_file() { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "log is not a regular file", + )); + } + #[cfg(unix)] + let (dev, ino) = (metadata.dev(), metadata.ino()); + #[cfg(windows)] + let (dev, ino) = { + use std::os::windows::io::AsRawHandle; + use windows_sys::Win32::Storage::FileSystem::{ + GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION, + }; + let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: the file owns a live handle and info has the required layout. + if unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut info) } == 0 { + return Err(io::Error::last_os_error()); + } + ( + u64::from(info.dwVolumeSerialNumber), + u64::from(info.nFileIndexHigh) << 32 | u64::from(info.nFileIndexLow), + ) + }; + let info = LogInfo { + ident: FileIdent { dev, ino }, + len: metadata.len(), + }; + Ok(Some((file, info))) +} + +/// `anchor`, when given, must be the 64 bytes just before `range.start`. +pub fn read( + path: &Path, + ident: Option<&FileIdent>, + range: &ByteRange, + anchor: Option<&[u8; 64]>, +) -> io::Result { + if range.end < range.start + || range.end - range.start > MAX_PAGE_LEN + || (anchor.is_some() && range.start < 64) + { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "invalid log range", + )); + } + let Some((mut file, info)) = open(path)? else { + return Ok(LogPage::Reset { info: None }); + }; + if ident.is_some_and(|ident| ident != &info.ident) || info.len < range.start { + return Ok(LogPage::Reset { info: Some(info) }); + } + if let Some(expected) = anchor { + let mut actual = [0; 64]; + file.seek(SeekFrom::Start(range.start - 64))?; + if file.read_exact(&mut actual).is_err() || &actual != expected { + return Ok(LogPage::Reset { info: Some(info) }); + } + } + let end = range.end.min(info.len); + file.seek(SeekFrom::Start(range.start))?; + let mut bytes = vec![0; (end - range.start) as usize]; + file.read_exact(&mut bytes)?; + Ok(LogPage::Data { + len: Some(info.len), + ident: info.ident, + start: range.start, + bytes, + eof: end >= info.len, + }) +} diff --git a/crates/orx-host/src/main.rs b/crates/orx-host/src/main.rs new file mode 100644 index 000000000..21d3b29fa --- /dev/null +++ b/crates/orx-host/src/main.rs @@ -0,0 +1,37 @@ +#[cfg(unix)] +fn main() { + use std::path::Path; + let args: Vec<_> = std::env::args().collect(); + let result = match args.get(1).map(String::as_str) { + Some("wrap") if args.len() == 3 => orx_host::wrapper::wrap(Path::new(&args[2])), + Some("check-run") if args.len() == 3 => orx_host::wrapper::has_live_processes(Path::new(&args[2])).map(|busy| { + println!("{}", if busy { "busy" } else { "idle" }); + }), + Some("serve") if args.len() == 4 && args[2] == "--root" => { + orx_host::legacy::directory(&args[3]) + .and_then(|root| orx_host::server::serve(root, std::env::current_exe()?)) + } + Some("verify-self") if args.len() == 3 => (|| { + let actual = orx_host::sha(&std::fs::read(std::env::current_exe()?)?); + if actual == args[2] { + Ok(()) + } else { + Err(std::io::Error::other("binary digest mismatch")) + } + })(), + _ => Err(std::io::Error::new( + std::io::ErrorKind::InvalidInput, + "usage: orx-host serve --root ROOT | wrap RUN_DIR | check-run RUN_DIR | verify-self SHA256", + )), + }; + if let Err(error) = result { + eprintln!("orx-host: {error}"); + std::process::exit(1); + } +} + +#[cfg(not(unix))] +fn main() { + eprintln!("orx-host requires a Unix host"); + std::process::exit(1); +} diff --git a/crates/orx-host/src/platform.rs b/crates/orx-host/src/platform.rs new file mode 100644 index 000000000..d63a96364 --- /dev/null +++ b/crates/orx-host/src/platform.rs @@ -0,0 +1,787 @@ +use orx_host_proto::{CancelOutcome, ProcessIdentity, Survivor}; +use std::collections::{BTreeMap, BTreeSet}; +use std::io; + +#[derive(Debug, Clone)] +pub struct Process { + pub pid: u32, + pub ppid: u32, + pub uid: u32, + pub starttime: u64, + pub state: String, +} + +impl Process { + pub fn survivor(&self) -> Survivor { + Survivor { + pid: self.pid, + starttime: self.starttime, + state: self.state.clone(), + } + } + + pub fn live(&self) -> bool { + !matches!(self.state.as_str(), "Z" | "X") + } +} + +#[cfg(not(target_os = "macos"))] +pub fn node() -> io::Result { + let mut bytes = [0u8; 256]; + if unsafe { libc::gethostname(bytes.as_mut_ptr().cast(), bytes.len()) } != 0 { + return Err(io::Error::last_os_error()); + } + let end = bytes.iter().position(|&b| b == 0).unwrap_or(bytes.len()); + Ok(String::from_utf8_lossy(&bytes[..end]).into_owned()) +} + +#[cfg(target_os = "macos")] +pub fn node() -> io::Result { + let mut uuid = [0u8; 16]; + let timeout = libc::timespec { + tv_sec: 5, + tv_nsec: 0, + }; + if unsafe { libc::gethostuuid(uuid.as_mut_ptr(), &timeout) } != 0 { + return Err(io::Error::last_os_error()); + } + Ok(uuid.iter().map(|byte| format!("{byte:02x}")).collect()) +} + +pub fn identity(pid: u32) -> io::Result { + Ok(ProcessIdentity { + node: node()?, + boot_id: boot_id()?, + pid, + starttime: process(pid)?.starttime, + }) +} + +pub fn alive(identity: &ProcessIdentity) -> io::Result { + if identity.node != node()? { + return Err(io::Error::new( + io::ErrorKind::NotConnected, + "wrapper belongs to another node", + )); + } + if identity.boot_id != boot_id()? { + return Ok(false); + } + match process(identity.pid) { + Ok(process) => Ok(process.starttime == identity.starttime && process.live()), + Err(error) if vanished(&error) => Ok(false), + Err(error) => Err(error), + } +} + +fn vanished(error: &io::Error) -> bool { + error.kind() == io::ErrorKind::NotFound || matches!(error.raw_os_error(), Some(libc::ESRCH)) +} + +#[derive(Debug)] +pub struct Scan { + pub processes: Vec, + pub unreadable: Vec, + pub complete: bool, +} + +impl Scan { + /// A previously seen process remains owned even after it scrubs its run tag. + pub(crate) fn include(&mut self, known: &[Survivor]) -> io::Result<()> { + for survivor in known { + match process(survivor.pid) { + Ok(process) if process.starttime == survivor.starttime && process.live() => { + if !self + .processes + .iter() + .any(|seen| seen.pid == process.pid && seen.starttime == process.starttime) + { + self.processes.push(process); + } + } + Ok(_) => {} + Err(error) if vanished(&error) => {} + Err(error) => return Err(error), + } + } + Ok(()) + } + + pub fn outcome(&self, children_reaped: bool) -> CancelOutcome { + if !self.processes.is_empty() { + return CancelOutcome::Survivors; + } + if self.complete && children_reaped { + CancelOutcome::Verified + } else { + CancelOutcome::Unverifiable { + unreadable: self.unreadable.clone(), + } + } + } +} + +#[cfg_attr(test, derive(Default))] +pub(crate) struct ProcessTable { + pub(crate) processes: BTreeMap, + pub(crate) tags: BTreeMap>, + unreadable: Vec, +} + +impl ProcessTable { + pub(crate) fn read() -> io::Result { + Ok(Self::from_pids(pids()?, process, process_uid)) + } + + fn from_pids( + pids: Vec, + process: impl Fn(u32) -> io::Result, + process_uid: impl Fn(u32) -> io::Result, + ) -> Self { + let mut table = Self { + processes: BTreeMap::new(), + tags: BTreeMap::new(), + unreadable: vec![], + }; + let uid = unsafe { libc::getuid() }; + for pid in pids { + let process = match process(pid) { + Ok(process) => process, + Err(error) if vanished(&error) => continue, + Err(_) => { + match process_uid(pid) { + Ok(owner) if owner != uid => {} + Err(error) if vanished(&error) => {} + _ => table.unreadable.push(pid), + } + continue; + } + }; + if process.uid == uid && process.live() { + match environment(pid) { + Ok(env) => { + for entry in env.split(|&byte| byte == 0) { + if let Some(tag) = entry + .strip_prefix(b"ORX_RUN_TAG=") + .and_then(|bytes| std::str::from_utf8(bytes).ok()) + { + table.tags.entry(tag.to_owned()).or_default().insert(pid); + } + } + } + Err(error) if vanished(&error) => continue, + Err(_) if openssh_session(pid) => {} + Err(_) => table.unreadable.push(pid), + } + } + table.processes.insert(pid, process); + } + table + } + + fn select(&self, wrapper: Option<&ProcessIdentity>, tag: &str, subreaper: bool) -> Scan { + let live_wrapper = wrapper.filter(|identity| alive(identity).unwrap_or(false)); + let mut descendants: BTreeSet<_> = live_wrapper + .map(|identity| identity.pid) + .into_iter() + .collect(); + loop { + let before = descendants.len(); + for process in self.processes.values() { + if descendants.contains(&process.ppid) { + descendants.insert(process.pid); + } + } + if descendants.len() == before { + break; + } + } + if let Some(pids) = self.tags.get(tag) { + descendants.extend(pids); + } + let processes = descendants + .into_iter() + .filter(|&pid| wrapper.is_none_or(|wrapper| pid != wrapper.pid)) + .filter_map(|pid| self.processes.get(&pid)) + .filter(|process| process.live()) + .cloned() + .collect(); + // Processes older than the wrapper cannot inherit its newly minted tag. + let unreadable: Vec<_> = self + .unreadable + .iter() + .copied() + .filter(|pid| { + wrapper.is_none_or(|wrapper| { + self.processes + .get(pid) + .is_none_or(|process| process.starttime >= wrapper.starttime) + }) + }) + .collect(); + Scan { + processes, + complete: (subreaper || cfg!(target_os = "macos")) + && unreadable.is_empty() + && live_wrapper.is_some() + && wrapper.is_some_and(|wrapper| alive(wrapper).unwrap_or(false)), + unreadable, + } + } +} + +pub fn scan(wrapper: Option<&ProcessIdentity>, tag: &str, subreaper: bool) -> io::Result { + if let Some(wrapper) = wrapper { + if wrapper.node != node()? || wrapper.boot_id != boot_id()? { + return Err(io::Error::new( + io::ErrorKind::NotConnected, + "wrapper belongs to another node or boot", + )); + } + } + Ok(ProcessTable::read()?.select(wrapper, tag, subreaper)) +} + +pub fn signal(process: &Process, signal: i32) -> io::Result<()> { + #[cfg(all(feature = "test-hooks", debug_assertions))] + if let Some(path) = std::env::var_os("ORX_TEST_DEFER_SIGNALS") { + let path = std::path::Path::new(&path); + if path.try_exists()? && matches!(signal, libc::SIGTERM | libc::SIGKILL) { + if signal == libc::SIGKILL && std::fs::read(path)? == b"once" { + std::fs::remove_file(path)?; + } + return Ok(()); + } + } + #[cfg(target_os = "linux")] + { + let fd = unsafe { libc::syscall(libc::SYS_pidfd_open, process.pid, 0) } as i32; + if fd >= 0 { + use std::os::fd::{AsRawFd, FromRawFd, OwnedFd}; + let fd = unsafe { OwnedFd::from_raw_fd(fd) }; + if self::process(process.pid)?.starttime != process.starttime { + return Ok(()); + } + if unsafe { + libc::syscall( + libc::SYS_pidfd_send_signal, + fd.as_raw_fd(), + signal, + std::ptr::null::(), + 0, + ) + } == 0 + { + return Ok(()); + } + return Err(io::Error::last_os_error()); + } + let error = io::Error::last_os_error(); + // Container seccomp profiles that predate pidfd answer EPERM, which pidfd_open never does. + if !matches!( + error.raw_os_error(), + Some(libc::ENOSYS | libc::EINVAL | libc::EPERM) + ) { + return Err(error); + } + } + if self::process(process.pid)?.starttime != process.starttime { + return Ok(()); + } + if unsafe { libc::kill(process.pid as i32, signal) } == 0 { + Ok(()) + } else { + Err(io::Error::last_os_error()) + } +} + +pub fn kernel() -> io::Result { + let mut info = unsafe { std::mem::zeroed::() }; + if unsafe { libc::uname(&mut info) } != 0 { + return Err(io::Error::last_os_error()); + } + Ok(unsafe { std::ffi::CStr::from_ptr(info.release.as_ptr()) } + .to_string_lossy() + .into_owned()) +} + +pub fn supported_kernel(release: &str) -> bool { + let mut parts = release + .split('.') + .filter_map(|part| part.parse::().ok()); + matches!((parts.next(), parts.next()), (Some(major), Some(minor)) if major > 3 || (major == 3 && minor >= 2)) +} + +#[cfg(target_os = "linux")] +pub fn subreaper() -> io::Result { + if unsafe { libc::prctl(libc::PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0) } == 0 { + return Ok(true); + } + let error = io::Error::last_os_error(); + if error.raw_os_error() == Some(libc::EINVAL) { + Ok(false) + } else { + Err(error) + } +} + +#[cfg(target_os = "linux")] +pub fn boot_id() -> io::Result { + Ok(std::fs::read_to_string("/proc/sys/kernel/random/boot_id")? + .trim() + .to_owned()) +} + +#[cfg(target_os = "linux")] +pub fn pids() -> io::Result> { + std::fs::read_dir("/proc")? + .filter_map(|entry| match entry { + Ok(entry) => entry + .file_name() + .to_str() + .and_then(|name| name.parse().ok()) + .map(Ok), + Err(error) => Some(Err(error)), + }) + .collect() +} + +pub fn parse_stat(pid: u32, uid: u32, stat: &str) -> io::Result { + let (_, fields) = stat + .rsplit_once(") ") + .ok_or_else(|| io::Error::other("invalid proc stat"))?; + let fields: Vec<_> = fields.split_whitespace().collect(); + let number = |index: usize| -> io::Result { + fields + .get(index) + .ok_or_else(|| io::Error::other("short proc stat"))? + .parse() + .map_err(io::Error::other) + }; + Ok(Process { + pid, + uid, + ppid: number(1)?.try_into().map_err(io::Error::other)?, + state: fields + .first() + .ok_or_else(|| io::Error::other("missing state"))? + .to_string(), + starttime: number(19)?, + }) +} + +#[cfg(target_os = "linux")] +pub fn process(pid: u32) -> io::Result { + let path = format!("/proc/{pid}"); + parse_stat( + pid, + process_uid(pid)?, + &std::fs::read_to_string(format!("{path}/stat"))?, + ) +} + +#[cfg(any(target_os = "linux", test))] +fn parse_uid(status: &str) -> io::Result { + status + .lines() + .find_map(|line| line.strip_prefix("Uid:")) + .and_then(|line| line.split_whitespace().next()) + .ok_or_else(|| io::Error::other("missing process Uid"))? + .parse() + .map_err(io::Error::other) +} + +#[cfg(target_os = "linux")] +fn process_uid(pid: u32) -> io::Result { + parse_uid(&std::fs::read_to_string(format!("/proc/{pid}/status"))?) +} + +#[cfg(target_os = "macos")] +fn process_uid(pid: u32) -> io::Result { + unsafe extern "C" { + fn orx_process_uid(pid: libc::pid_t, uid: *mut libc::uid_t) -> libc::c_int; + } + + let mut uid = 0; + if unsafe { orx_process_uid(pid as libc::pid_t, &mut uid) } != 0 { + return Err(io::Error::last_os_error()); + } + Ok(uid) +} + +#[cfg(target_os = "linux")] +fn environment(pid: u32) -> io::Result> { + std::fs::read(format!("/proc/{pid}/environ")) +} + +/// OpenSSH makes its processes non-dumpable, so their environment is unreadable even to the +/// owner; they never descend from a run. +#[cfg(target_os = "linux")] +fn openssh_session(pid: u32) -> bool { + std::fs::read_to_string(format!("/proc/{pid}/comm")) + .is_ok_and(|comm| comm.trim_end() == "sshd" || comm.starts_with("sshd-")) +} + +#[cfg(target_os = "macos")] +fn openssh_session(_: u32) -> bool { + false +} + +#[cfg(target_os = "macos")] +pub fn subreaper() -> io::Result { + Ok(false) +} + +#[cfg(target_os = "macos")] +pub fn boot_id() -> io::Result { + let mut bytes = [0u8; 128]; + let mut size = bytes.len(); + if unsafe { + libc::sysctlbyname( + c"kern.bootsessionuuid".as_ptr(), + bytes.as_mut_ptr().cast(), + &mut size, + std::ptr::null_mut(), + 0, + ) + } != 0 + { + return Err(io::Error::last_os_error()); + } + let uuid = std::ffi::CStr::from_bytes_until_nul(&bytes[..size]).map_err(io::Error::other)?; + Ok(uuid.to_string_lossy().into_owned()) +} + +#[cfg(target_os = "macos")] +pub fn pids() -> io::Result> { + let count = unsafe { libc::proc_listpids(1, 0, std::ptr::null_mut(), 0) }; + if count <= 0 { + return Err(io::Error::last_os_error()); + } + let mut pids = vec![0u32; count as usize / 4 + 1024]; + let bytes = + unsafe { libc::proc_listpids(1, 0, pids.as_mut_ptr().cast(), (pids.len() * 4) as i32) }; + if bytes <= 0 || bytes as usize >= pids.len() * 4 { + return Err(io::Error::other("incomplete process list")); + } + pids.truncate(bytes as usize / 4); + pids.retain(|&pid| pid > 0); + Ok(pids) +} + +#[cfg(target_os = "macos")] +pub fn process(pid: u32) -> io::Result { + let mut info = unsafe { std::mem::zeroed::() }; + let size = std::mem::size_of_val(&info) as i32; + let result = unsafe { + libc::proc_pidinfo( + pid as i32, + libc::PROC_PIDTBSDINFO, + 0, + (&mut info as *mut libc::proc_bsdinfo).cast(), + size, + ) + }; + if result != size { + return Err(io::Error::last_os_error()); + } + Ok(Process { + pid, + ppid: info.pbi_ppid, + uid: info.pbi_uid, + starttime: info.pbi_start_tvsec * 1_000_000 + info.pbi_start_tvusec, + state: if info.pbi_status == 5 { "Z" } else { "R" }.into(), + }) +} + +#[cfg(target_os = "macos")] +fn environment(pid: u32) -> io::Result> { + let mut mib = [libc::CTL_KERN, libc::KERN_PROCARGS2, pid as i32]; + let mut bytes = vec![0; 1024 * 1024]; + let mut size = bytes.len(); + if unsafe { + libc::sysctl( + mib.as_mut_ptr(), + 3, + bytes.as_mut_ptr().cast(), + &mut size, + std::ptr::null_mut(), + 0, + ) + } != 0 + { + return Err(io::Error::last_os_error()); + } + bytes.truncate(size); + // KERN_PROCARGS2 starts with argc, then the executable path, argv and env strings. + let argc = i32::from_ne_bytes( + bytes + .get(..4) + .ok_or_else(|| io::Error::other("short procargs"))? + .try_into() + .map_err(io::Error::other)?, + ); + if argc < 0 { + return Err(io::Error::other("invalid argc")); + } + let mut rest = &bytes[4..]; + let end = rest + .iter() + .position(|&b| b == 0) + .ok_or_else(|| io::Error::other("missing executable"))?; + rest = &rest[end..]; + while rest.first() == Some(&0) { + rest = &rest[1..]; + } + for _ in 0..argc { + let end = rest + .iter() + .position(|&b| b == 0) + .ok_or_else(|| io::Error::other("missing argument"))?; + rest = &rest[end + 1..]; + } + Ok(rest.to_vec()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_unreadable_processes_proven_to_predate_the_wrapper_can_be_excluded() { + let wrapper = identity(std::process::id()).unwrap(); + let mut table = ProcessTable::default(); + let pid = u32::MAX; + table.processes.insert( + pid, + Process { + pid, + ppid: 1, + uid: unsafe { libc::getuid() }, + starttime: wrapper.starttime - 1, + state: "S".into(), + }, + ); + table.unreadable.push(pid); + let scan = table.select(Some(&wrapper), "not-minted-yet", true); + assert_eq!(scan.outcome(true), CancelOutcome::Verified); + assert!(scan.unreadable.is_empty()); + for starttime in [wrapper.starttime, wrapper.starttime + 1] { + table.processes.get_mut(&pid).unwrap().starttime = starttime; + assert_eq!( + table.select(Some(&wrapper), "tag", true).outcome(true), + CancelOutcome::Unverifiable { + unreadable: vec![pid] + } + ); + } + table.processes.clear(); + assert_eq!( + table.select(Some(&wrapper), "tag", true).outcome(true), + CancelOutcome::Unverifiable { + unreadable: vec![pid] + } + ); + } + + #[test] + fn unknown_ownership_cannot_make_a_failed_inspection_verified() { + let wrapper = identity(std::process::id()).unwrap(); + let pid = u32::MAX; + let uid = unsafe { libc::getuid() }; + for owner in [None, Some(uid), Some(uid + 1)] { + let table = ProcessTable::from_pids( + vec![pid], + |_| Err(io::Error::from(io::ErrorKind::PermissionDenied)), + |_| owner.ok_or_else(|| io::Error::from(io::ErrorKind::PermissionDenied)), + ); + let outcome = table.select(Some(&wrapper), "tag", true).outcome(true); + if owner == Some(uid + 1) { + assert_eq!(outcome, CancelOutcome::Verified); + } else { + assert_eq!( + outcome, + CancelOutcome::Unverifiable { + unreadable: vec![pid] + } + ); + } + } + for code in [libc::ENOENT, libc::ESRCH] { + let table = ProcessTable::from_pids( + vec![pid], + |_| Err(io::Error::from(io::ErrorKind::PermissionDenied)), + |_| Err(io::Error::from_raw_os_error(code)), + ); + assert_eq!( + table.select(Some(&wrapper), "tag", true).outcome(true), + CancelOutcome::Verified + ); + } + } + + #[test] + fn identity_rejects_reused_pid_and_reboot() { + let mut own = identity(std::process::id()).unwrap(); + assert!(alive(&own).unwrap()); + own.starttime += 1; + assert!(!alive(&own).unwrap()); + own.starttime -= 1; + own.boot_id.push_str("-reboot"); + assert!(!alive(&own).unwrap()); + own = identity(std::process::id()).unwrap(); + own.node.push_str("-other-node"); + assert_eq!(alive(&own).unwrap_err().kind(), io::ErrorKind::NotConnected); + assert_eq!( + scan(Some(&own), "tag", false).unwrap_err().kind(), + io::ErrorKind::NotConnected + ); + own = identity(std::process::id()).unwrap(); + own.boot_id.push_str("-other-boot"); + assert_eq!( + scan(Some(&own), "tag", false).unwrap_err().kind(), + io::ErrorKind::NotConnected + ); + } + + #[cfg(target_os = "macos")] + #[test] + fn macos_zombies_are_gone_not_unreadable() { + let child = std::process::Command::new("true").spawn().unwrap(); + let pid = child.id(); + std::thread::sleep(std::time::Duration::from_millis(200)); + assert!(!ProcessTable::read().unwrap().unreadable.contains(&pid)); + drop(child); + } + + #[cfg(target_os = "macos")] + #[test] + fn macos_other_uid_processes_have_readable_ownership() { + let uid = unsafe { libc::getuid() }; + let mut other_uid = Vec::new(); + for pid in pids().unwrap() { + match process_uid(pid) { + Ok(owner) if owner != uid => other_uid.push(pid), + Ok(owner) => { + if let Ok(process) = process(pid) { + assert_eq!(owner, process.uid); + } + } + Err(error) if matches!(error.raw_os_error(), Some(libc::ESRCH)) => {} + Err(error) => panic!("owner of {pid}: {error}"), + } + } + assert!(!other_uid.is_empty(), "test requires other-uid processes"); + let table = ProcessTable::read().unwrap(); + assert!(other_uid.iter().all(|pid| !table.unreadable.contains(pid))); + assert!(table.unreadable.is_empty(), "{:?}", table.unreadable); + } + + #[cfg(target_os = "macos")] + #[test] + fn macos_node_is_the_hardware_uuid() { + let mut uuid = [0u8; 16]; + let timeout = libc::timespec { + tv_sec: 5, + tv_nsec: 0, + }; + assert_eq!(unsafe { libc::gethostuuid(uuid.as_mut_ptr(), &timeout) }, 0); + let expected: String = uuid.iter().map(|byte| format!("{byte:02x}")).collect(); + assert_eq!(node().unwrap(), expected); + assert_eq!(identity(std::process::id()).unwrap().node, expected); + } + + #[cfg(target_os = "macos")] + #[test] + fn macos_complete_tag_scan_and_reaped_children_verify_the_stop() { + let wrapper = identity(std::process::id()).unwrap(); + let mut table = ProcessTable::default(); + assert_eq!( + table.select(Some(&wrapper), "tag", false).outcome(true), + CancelOutcome::Verified + ); + assert!(matches!( + table.select(Some(&wrapper), "tag", false).outcome(false), + CancelOutcome::Unverifiable { .. } + )); + table.unreadable.push(u32::MAX); + assert!(matches!( + table.select(Some(&wrapper), "tag", false).outcome(true), + CancelOutcome::Unverifiable { .. } + )); + } + + #[test] + fn cancellation_requires_complete_scan_and_reaped_children() { + let mut scan = Scan { + processes: vec![], + unreadable: vec![], + complete: true, + }; + assert_eq!(scan.outcome(true), CancelOutcome::Verified); + assert!(matches!( + scan.outcome(false), + CancelOutcome::Unverifiable { .. } + )); + scan.complete = false; + scan.unreadable.push(123); + assert_eq!( + scan.outcome(true), + CancelOutcome::Unverifiable { + unreadable: vec![123] + } + ); + scan.processes.push(Process { + pid: 42, + ppid: 1, + uid: 0, + starttime: 3, + state: "D".into(), + }); + assert!(matches!(scan.outcome(true), CancelOutcome::Survivors)); + } + + #[test] + fn process_uid_uses_status_real_uid_instead_of_proc_directory_owner() { + assert_eq!( + parse_uid("Name:\tworker\nUid:\t501\t0\t0\t0\n").unwrap(), + 501 + ); + for status in ["", "Uid:\n", "Uid:\tnone\t0\t0\t0\n"] { + assert!(parse_uid(status).is_err()); + } + } + + #[test] + fn linux_stat_parser_handles_parentheses_and_field_positions() { + let mut fields = vec!["0"; 20]; + fields[0] = "S"; + fields[1] = "5"; + fields[19] = "123456"; + let stat = format!("42 (name ) with spaces) {}", fields.join(" ")); + let process = parse_stat(42, 501, &stat).unwrap(); + assert_eq!( + (process.pid, process.ppid, process.uid, process.starttime), + (42, 5, 501, 123456) + ); + assert!(parse_stat(42, 501, "42 (truncated)").is_err()); + } + + #[test] + fn linux_kernel_floor() { + for release in ["3.2.0", "3.4.1", "6.12.0-custom"] { + assert!(supported_kernel(release)); + } + for release in ["2.6.32", "3.1.9", "unknown"] { + assert!(!supported_kernel(release)); + } + } + + #[test] + fn wrong_starttime_never_signals_a_live_process() { + let mut own = process(std::process::id()).unwrap(); + own.starttime += 1; + signal(&own, libc::SIGKILL).unwrap(); + assert!(process(std::process::id()).is_ok()); + } +} diff --git a/crates/orx-host/src/process_uid.c b/crates/orx-host/src/process_uid.c new file mode 100644 index 000000000..9c233597c --- /dev/null +++ b/crates/orx-host/src/process_uid.c @@ -0,0 +1,17 @@ +#include +#include +#include + +int orx_process_uid(pid_t pid, uid_t *uid) { + int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, pid}; + struct kinfo_proc info; + size_t size = sizeof(info); + if (sysctl(mib, 4, &info, &size, NULL, 0) == -1) return -1; + if (size != sizeof(info)) { + errno = size == 0 ? ESRCH : EIO; + return -1; + } + /* Match proc_bsdinfo.pbi_uid, including setuid processes. */ + *uid = info.kp_eproc.e_ucred.cr_uid; + return 0; +} diff --git a/crates/orx-host/src/server.rs b/crates/orx-host/src/server.rs new file mode 100644 index 000000000..e38a8b2bb --- /dev/null +++ b/crates/orx-host/src/server.rs @@ -0,0 +1,1567 @@ +use crate::{ + crash_point, exec, legacy, lock, log, platform, publish, publish_bytes, read_json, run_dir, + wrapper, +}; +use orx_host_proto::*; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::collections::{BTreeMap, BTreeSet, HashMap}; +use std::fs::{self, File, OpenOptions}; +use std::io::{self, Read, Write}; +use std::os::unix::fs::{FileExt, OpenOptionsExt, PermissionsExt}; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Condvar, Mutex}; +use std::time::{Duration, Instant, SystemTime}; + +#[derive(Deserialize, Serialize)] +struct SchedulerTerminal { + job: String, + state: String, + since: SystemTime, +} + +pub struct Host { + root: PathBuf, + binary: PathBuf, + binary_sha: String, + /// Set when the client is gone, so long waits and commands end. + stop: Arc, + blobs: Mutex<()>, + recovery: Mutex>, +} + +impl Host { + pub fn new(root: PathBuf, binary: PathBuf) -> io::Result { + for path in [&root, &root.join("runs"), &root.join("sources")] { + fs::create_dir_all(path)?; + fs::set_permissions(path, fs::Permissions::from_mode(0o700))?; + } + let binary_sha = file_sha(&binary)?; + Ok(Self { + root, + binary, + binary_sha, + stop: Arc::default(), + blobs: Mutex::new(()), + recovery: Mutex::new(HashMap::new()), + }) + } + + pub fn handle(&self, request: Request) -> Response { + self.request(request) + .unwrap_or_else(|error| Response::Error { + code: match error.kind() { + io::ErrorKind::InvalidInput => ErrorCode::InvalidRequest, + io::ErrorKind::AlreadyExists => ErrorCode::Conflict, + io::ErrorKind::NotFound => ErrorCode::NotFound, + io::ErrorKind::Unsupported => ErrorCode::Unsupported, + io::ErrorKind::WouldBlock => ErrorCode::Busy, + _ => ErrorCode::Io, + }, + message: error.to_string(), + }) + } + + fn exec( + &self, + command: &mut Command, + input: &[u8], + timeout: Duration, + ) -> io::Result { + exec::run(command, input, timeout, Some(&self.stop)) + } + + fn request(&self, request: Request) -> io::Result { + match request { + Request::Hello { proto } => { + if proto != PROTOCOL_VERSION { + return Err(io::Error::new( + io::ErrorKind::Unsupported, + "unsupported protocol version", + )); + } + let kernel = platform::kernel()?; + if cfg!(target_os = "linux") && !platform::supported_kernel(&kernel) { + return Err(io::Error::new( + io::ErrorKind::Unsupported, + "Linux kernel 3.2 or newer is required", + )); + } + Ok(Response::Hello { + proto: PROTOCOL_VERSION, + binary_sha: self.binary_sha.clone(), + boot_id: platform::boot_id()?, + os: std::env::consts::OS.into(), + arch: std::env::consts::ARCH.into(), + kernel, + }) + } + Request::Launch(intent) => { + self.launch(&intent, None)?; + Ok(Response::Launch { + summary: self.summary(&intent.run, true, true)?, + }) + } + Request::Inspect { run } => Ok(Response::Inspect { + summary: self.summary(&run, false, false)?, + }), + Request::Changes { + watch, + follow_logs, + wait_ms, + } => { + if wait_ms > MAX_WAIT_MS { + return invalid("wait exceeds 30 seconds"); + } + let deadline = Instant::now() + Duration::from_millis(wait_ms.into()); + let names: BTreeSet<_> = watch.iter().map(|(run, _)| run.clone()).collect(); + for name in &names { + run_dir(&self.root, name)?; + } + for name in &follow_logs { + run_dir(&self.root, name)?; + } + loop { + let mut changes = Vec::new(); + for name in &names { + let summary = self + .summary(name, follow_logs.contains(name), true) + .unwrap_or_else(|error| { + let mut summary = watch + .iter() + .find(|(run, _)| run == name) + .map(|(_, summary)| summary.clone()) + .unwrap_or(Summary { + started_at: None, + state: RunState::Missing, + log_len: None, + notify_len: 0, + cleanup: None, + }); + summary.state = wrapper::read_error(error); + summary + }); + if !watch + .iter() + .any(|(run, old)| run == name && old == &summary) + { + changes.push((name.clone(), summary)); + } + } + if !changes.is_empty() + || Instant::now() >= deadline + || self.stop.load(Ordering::Relaxed) + { + return Ok(Response::Changes { runs: changes }); + } + std::thread::sleep( + Duration::from_secs(1) + .min(deadline.saturating_duration_since(Instant::now())), + ); + } + } + Request::ReadLog { + target, + file, + ident, + range, + anchor, + } => { + let dir = match target { + LogTarget::Run(run) => run_dir(&self.root, &run)?, + LogTarget::Dir(dir) => legacy::directory(&dir)?, + }; + crate::slow_request(); + let page = log::read( + &dir.join(log_name(file)), + ident.as_ref(), + &range, + anchor.as_ref(), + )?; + Ok(Response::ReadLog { page }) + } + Request::Cancel { run } => { + let dir = run_dir(&self.root, &run)?; + let outcome = wrapper::cancel(&dir)?; + // scancel would kill a started wrapper before its receipt; it reads cancel.req. + if dir.join("job.sbatch").try_exists()? && !dir.join("started").try_exists()? { + let result = self.exec( + Command::new("scancel").arg(format!("--name={run}")), + &[], + Duration::from_secs(10), + )?; + if result.code != Some(0) || result.timed_out { + return Err(io::Error::other("scancel did not acknowledge cancellation")); + } + } + Ok(Response::Cancel { outcome }) + } + Request::Cleanup { run } => Ok(Response::Cleanup { + outcome: wrapper::cleanup(&run_dir(&self.root, &run)?)?, + }), + Request::CancelLegacy { dir, container } => Ok(Response::CancelLegacy { + outcome: legacy::cancel( + &legacy::directory(&dir)?, + container.as_ref(), + Some(&self.stop), + )?, + }), + Request::Exec { + command, + stdin, + timeout_ms, + } => { + if timeout_ms == 0 || timeout_ms > 300_000 || stdin.len() > MAX_PAGE_LEN as usize { + return invalid("invalid command timeout or input length"); + } + Ok(Response::Exec { + result: self.exec( + Command::new("/bin/sh") + .args(["-c", &command]) + .env("ORX_HOST_BINARY", &self.binary), + &stdin, + Duration::from_millis(timeout_ms.into()), + )?, + }) + } + Request::HasBlob { sha, len } => Ok(Response::HasBlob { + present: self.has_blob(&sha, len)?, + }), + Request::PinSource { run, sha } => { + check_sha(&sha)?; + let dir = run_dir(&self.root, &run)?; + fs::create_dir_all(&dir)?; + let mutex = crate::run_mutex(&dir)?; + let _local = mutex + .lock() + .map_err(|_| io::Error::other("run lock poisoned"))?; + let Some(_ownership) = lock(&dir.join("launch.lock"))? else { + return Err(io::Error::new( + io::ErrorKind::WouldBlock, + "launch is being staged", + )); + }; + fs::set_permissions(&dir, fs::Permissions::from_mode(0o700))?; + crate::slow_request(); + let cross_device = crate::cross_device(); + Ok(Response::PinSource { + pinned: pin_source( + &self.root.join("sources"), + &sha, + &dir, + |blob, target| match cross_device { + true => Err(io::Error::from_raw_os_error(libc::EXDEV)), + false => fs::hard_link(blob, target), + }, + if cross_device { + Duration::ZERO + } else { + PIN_SLICE + }, + )?, + }) + } + Request::PutBlob { sha, offset, bytes } => Ok(Response::PutBlob { + len: self.put_blob(&sha, offset, &bytes)?, + }), + Request::SlurmSubmit { intent, directives } => { + let run = intent.run.clone(); + let dir = run_dir(&self.root, &run)?; + let submit = self.launch(&intent, Some(&directives))?; + match fs::read_to_string(dir.join("slurm.job")) { + Ok(job) => return Ok(Response::SlurmSubmit { job }), + Err(error) if error.kind() == io::ErrorKind::NotFound => {} + Err(error) => return Err(error), + } + if !submit { + return Err(io::Error::new( + io::ErrorKind::WouldBlock, + "Slurm submission outcome unknown; recover by job name", + )); + } + let sbatch = fs::read(dir.join("job.sbatch"))?; + let result = self.exec( + Command::new("sbatch").args([ + "--parsable", + "--no-requeue", + &format!("--job-name={run}"), + &format!("--output={}", dir.join("slurm.out").display()), + ]), + &sbatch, + Duration::from_secs(30), + )?; + let job = if result.code == Some(0) && !result.timed_out { + String::from_utf8_lossy(&result.stdout) + .trim() + .split(';') + .next() + .unwrap_or_default() + .to_owned() + } else { + let queued = self.exec( + Command::new("squeue").args([ + "--noheader", + "--format=%i|%j|%T", + &format!("--name={run}"), + ]), + &[], + Duration::from_secs(10), + )?; + if queued.code != Some(0) || queued.timed_out || queued.stdout_truncated { + return Err(io::Error::other( + "sbatch outcome unknown; scheduler query unavailable", + )); + } + let found = String::from_utf8_lossy(&queued.stdout) + .lines() + .find_map(|line| { + let fields: Vec<_> = line.trim().split('|').collect(); + if fields.len() == 3 + && fields[1] == run + && !fields[0].is_empty() + && fields[0].bytes().all(|byte| byte.is_ascii_digit()) + { + Some(fields[0].to_owned()) + } else { + None + } + }); + if let Some(job) = found { + job + } else { + let stderr = String::from_utf8_lossy(&result.stderr); + let lower = stderr.to_ascii_lowercase(); + let connectivity = + ["socket", "controller", "connection", "timed out", "timeout"] + .iter() + .any(|cause| lower.contains(cause)); + if result.timed_out || result.code.is_none() || connectivity { + return Err(io::Error::other(format!( + "sbatch outcome unknown: {}", + stderr.trim() + ))); + } + // The launch was never started: retract it whole. + fs::remove_file(dir.join("launch.json"))?; + fs::remove_file(dir.join("job.sbatch"))?; + File::open(&dir)?.sync_all()?; + return invalid(&format!("sbatch failed: {}", stderr.trim())); + } + }; + if job.is_empty() || !job.bytes().all(|byte| byte.is_ascii_digit()) { + return Err(io::Error::other("invalid sbatch job id")); + } + publish_bytes(&dir.join("slurm.job"), job.as_bytes())?; + Ok(Response::SlurmSubmit { job }) + } + Request::SlurmQueue { names, legacy } => self.slurm_queue(&names, &legacy), + Request::SlurmCancelLegacy { job } => { + if job.is_empty() || !job.bytes().all(|b| b.is_ascii_digit()) { + return invalid("invalid Slurm job id"); + } + let result = self.exec( + Command::new("scancel").arg(&job), + &[], + Duration::from_secs(10), + )?; + if result.code != Some(0) || result.timed_out { + return Err(io::Error::other("scancel did not acknowledge cancellation")); + } + Ok(Response::SlurmCancelLegacy) + } + Request::InspectLegacy { dir } => Ok(Response::InspectLegacy { + inspection: legacy::inspect(&legacy::directory(&dir)?)?, + }), + } + } + + fn summary(&self, run: &str, follow: bool, repair: bool) -> io::Result { + let dir = run_dir(&self.root, run)?; + if dir.join("job.sbatch").try_exists()? { + let fallback = if !slurm_execution(&dir)? + && (!dir.join("launch.json").try_exists()? || !dir.join("run.sh").try_exists()?) + { + RunState::Staging + } else { + RunState::Starting + }; + let mut summary = slurm_summary(&dir, None, fallback); + if follow { + summary.log_len = Some(length(&dir.join("log"))?); + } + return Ok(summary); + } + let mut state = wrapper::state(&dir)?; + if matches!(state, RunState::Starting) { + let intent: LaunchIntent = read_json(&dir.join("launch.json"))?; + if !repair || (intent.source.is_some() && !dir.join("source.tar").try_exists()?) { + return Ok(Summary { + started_at: None, + state: RunState::Staging, + log_len: if follow { + Some(length(&dir.join("log"))?) + } else { + None + }, + notify_len: length(&dir.join("notify"))?, + cleanup: wrapper::cleanup_result(&dir)?, + }); + } + match self.launch(&intent, None) { + Ok(_) => { + state = wrapper::state(&dir)?; + } + Err(error) if error.kind() == io::ErrorKind::WouldBlock => {} + Err(error) => return Err(error), + } + } + if !matches!(state, RunState::Starting) { + self.recovery + .lock() + .map_err(|_| io::Error::other("recovery lock poisoned"))? + .remove(run); + } + Ok(Summary { + started_at: wrapper::started_at(&dir), + state, + log_len: if follow { + Some(length(&dir.join("log"))?) + } else { + None + }, + notify_len: length(&dir.join("notify"))?, + cleanup: wrapper::cleanup_result(&dir)?, + }) + } + + /// True with directives means the accepted batch script still needs submission. + fn launch(&self, intent: &LaunchIntent, directives: Option<&str>) -> io::Result { + let dir = run_dir(&self.root, &intent.run)?; + check_sha(&intent.digest)?; + fs::create_dir_all(&dir)?; + let mutex = crate::run_mutex(&dir)?; + let _local = mutex + .lock() + .map_err(|_| io::Error::other("run lock poisoned"))?; + fs::set_permissions(&dir, fs::Permissions::from_mode(0o700))?; + let Some(_ownership) = lock(&dir.join("launch.lock"))? else { + return Err(io::Error::new( + io::ErrorKind::WouldBlock, + "launch is being staged", + )); + }; + let batch = dir.join("job.sbatch"); + let mut existing_batch = match fs::read_to_string(&batch) { + Ok(script) => Some(script), + Err(error) if error.kind() == io::ErrorKind::NotFound => None, + Err(error) => return Err(error), + }; + let launch = dir.join("launch.json"); + let existing = match read_json::(&launch) { + Ok(existing) if existing.run != intent.run || existing.digest != intent.digest => { + return Err(io::Error::new( + io::ErrorKind::AlreadyExists, + "run already has a different launch intent", + )); + } + Ok(existing) => Some(existing), + Err(error) if error.kind() == io::ErrorKind::NotFound => None, + Err(error) => return Err(error), + }; + match (directives, &existing_batch, &existing) { + (None, Some(_), _) => { + return Err(io::Error::new( + io::ErrorKind::AlreadyExists, + "run belongs to Slurm", + )) + } + (Some(_), None, Some(_)) => { + return Err(io::Error::new( + io::ErrorKind::AlreadyExists, + "run already has a direct launch", + )) + } + (Some(_), Some(_), None) => { + if slurm_execution(&dir)? { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "Slurm execution has no launch identity", + )); + } + fs::remove_file(&batch)?; + existing_batch = None; + } + _ => {} + } + let intent = existing.as_ref().unwrap_or(intent); + if intent + .cancel_sh + .as_ref() + .is_some_and(|script| script.len() > MAX_PAGE_LEN as usize) + || intent.run_sh.len() > MAX_PAGE_LEN as usize + || intent.env.iter().any(|(key, value)| { + key.is_empty() || key.contains(['=', '\0']) || value.contains('\0') + }) + { + return invalid("invalid payload or environment"); + } + if let Some(source) = &intent.source { + check_sha(source)?; + } + if existing_batch.is_some() && dir.join("run.sh").try_exists()? { + return Ok(false); + } + // PinSource and launch share ownership so accepted source bytes cannot change. + if intent.source.is_some() && !dir.join("source.tar").try_exists()? { + return Err(io::Error::new( + io::ErrorKind::NotFound, + "the run's source is not pinned", + )); + } + if existing.is_none() { + if let Some(directives) = directives { + if directives.lines().any(|line| !line.starts_with("#SBATCH ")) { + return invalid("invalid Slurm directives"); + } + let sbatch = format!( + "#!/bin/bash\n{directives}exec {} wrap {}\n", + quote(&self.binary), + quote(&dir), + ); + publish_bytes(&batch, sbatch.as_bytes())?; + } + crash_point("before_launch"); + let temporary = dir.join(format!("launch-{}.tmp", crate::nonce()?)); + publish(&temporary, intent)?; + let result = fs::hard_link(&temporary, &launch); + fs::remove_file(temporary)?; + result?; + File::open(&dir)?.sync_all()?; + crash_point("launch_published"); + } + if dir.join("started").try_exists()? || dir.join("exit.json").try_exists()? { + return Ok(false); + } + let Some(wrapper_lock) = lock(&dir.join("wrapper.lock"))? else { + return Ok(false); + }; + drop(wrapper_lock); + + if directives.is_none() { + let mut recovery = self + .recovery + .lock() + .map_err(|_| io::Error::other("recovery lock poisoned"))?; + let now = Instant::now(); + if recovery + .get(&intent.run) + .is_some_and(|(next, _)| *next > now) + { + return Ok(false); + } + let delay = recovery + .get(&intent.run) + .map_or(Duration::from_secs(1), |(_, delay)| { + (*delay * 2).min(Duration::from_secs(30)) + }); + recovery.insert( + intent.run.clone(), + (now + crate::stop_duration(delay), delay), + ); + } + if intent.source.is_some() && !dir.join("repo").try_exists()? { + let temporary = dir.join("repo.part"); + if temporary.try_exists()? { + fs::remove_dir_all(&temporary)?; + } + fs::create_dir(&temporary)?; + let result = self.exec( + Command::new("tar") + .arg("-xf") + .arg(dir.join("source.tar")) + .arg("-C") + .arg(&temporary), + &[], + Duration::from_secs(300), + )?; + if result.code != Some(0) || result.timed_out { + return Err(io::Error::other("source extraction failed")); + } + fs::rename(temporary, dir.join("repo"))?; + } + if !dir.join("run.sh").try_exists()? { + publish_bytes(&dir.join("run.sh"), intent.run_sh.as_bytes())?; + } + if let Some(script) = &intent.cancel_sh { + if !dir.join("cancel.sh").try_exists()? { + publish_bytes(&dir.join("cancel.sh"), script.as_bytes())?; + } + } + if directives.is_some() { + return Ok(true); + } + let diagnostics = OpenOptions::new() + .create(true) + .append(true) + .mode(0o600) + .open(dir.join("wrapper.log"))?; + let mut child = Command::new(&self.binary) + .arg("wrap") + .arg(&dir) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(diagnostics) + .spawn()?; + std::thread::spawn(move || { + let _ = child.wait(); + }); + Ok(true) + } + + fn has_blob(&self, hash: &str, len: u64) -> io::Result { + check_sha(hash)?; + let _ownership = self + .blobs + .lock() + .map_err(|_| io::Error::other("blob lock poisoned"))?; + let Some(_file_lock) = lock(&self.root.join("sources").join(format!("{hash}.lock")))? + else { + return Err(io::Error::new( + io::ErrorKind::WouldBlock, + "blob is being staged", + )); + }; + let path = self.root.join("sources").join(hash); + if path.try_exists()? { + return Ok(fs::metadata(&path)?.len() == len && file_sha(&path)? == hash); + } + let part = path.with_extension("part"); + if !part.try_exists()? || fs::metadata(&part)?.len() != len { + return Ok(false); + } + if file_sha(&part)? != hash { + fs::remove_file(part)?; + return Ok(false); + } + File::open(&part)?.sync_all()?; + fs::rename(part, &path)?; + File::open( + path.parent() + .ok_or_else(|| io::Error::other("missing sources"))?, + )? + .sync_all()?; + Ok(true) + } + + fn put_blob(&self, hash: &str, offset: u64, bytes: &[u8]) -> io::Result { + check_sha(hash)?; + if bytes.len() > 256 * 1024 || offset.checked_add(bytes.len() as u64).is_none() { + return invalid("invalid upload chunk"); + } + let _ownership = self + .blobs + .lock() + .map_err(|_| io::Error::other("blob lock poisoned"))?; + let Some(_file_lock) = lock(&self.root.join("sources").join(format!("{hash}.lock")))? + else { + return Err(io::Error::new( + io::ErrorKind::WouldBlock, + "blob is being staged", + )); + }; + let path = self.root.join("sources").join(hash); + let complete = path.try_exists()?; + let path = if complete { + path + } else { + path.with_extension("part") + }; + let file = OpenOptions::new() + .read(true) + .write(!complete) + .create(!complete) + .truncate(false) + .mode(0o600) + .open(path)?; + let len = file.metadata()?.len(); + if offset > len { + return invalid("upload offset exceeds staged length"); + } + let overlap = (len - offset).min(bytes.len() as u64) as usize; + let mut existing = vec![0; overlap]; + file.read_exact_at(&mut existing, offset)?; + if existing != bytes[..overlap] { + return Err(io::Error::new( + io::ErrorKind::AlreadyExists, + "upload retry differs from staged bytes", + )); + } + if complete && overlap < bytes.len() { + return Err(io::Error::new( + io::ErrorKind::AlreadyExists, + "completed blob is immutable", + )); + } + if overlap < bytes.len() { + file.write_all_at(&bytes[overlap..], offset + overlap as u64)?; + } + file.sync_data()?; + Ok(file.metadata()?.len()) + } + + fn slurm_queue(&self, names: &[RunId], legacy: &[SlurmLegacyRun]) -> io::Result { + for run in legacy { + run_dir(&self.root, &run.run)?; + legacy::directory(&run.dir)?; + } + let mut jobs = BTreeMap::new(); + let mut pending = Vec::new(); + for name in names { + let dir = run_dir(&self.root, name)?; + let old = legacy.iter().find(|old| old.run == *name); + if old.is_some_and(|old| { + old.job.is_empty() || !old.job.bytes().all(|b| b.is_ascii_digit()) + }) { + continue; + } + let summary = slurm_summary(&dir, old, RunState::Missing); + let survivors = matches!(&summary.state, RunState::Exited { receipt } + if receipt.reason == ExitReason::Cancelled + && !summary.cleanup.as_ref().map_or(&receipt.processes, |proof| &proof.processes).is_empty()); + if summary.state != RunState::Missing && !survivors { + jobs.insert( + name.clone(), + SlurmJob { + run: name.clone(), + job: old.map(|old| old.job.clone()).unwrap_or_else(|| { + fs::read_to_string(dir.join("slurm.job")).unwrap_or_default() + }), + state: "RECEIPT".into(), + summary, + }, + ); + } else { + pending.push(name.clone()); + } + } + let mut known_jobs = BTreeMap::new(); + for run in std::mem::take(&mut pending) { + let job = match legacy.iter().find(|old| old.run == run) { + Some(old) => old.job.clone(), + None => match fs::read_to_string(run_dir(&self.root, &run)?.join("slurm.job")) { + Ok(job) => job.trim().to_owned(), + Err(error) if error.kind() == io::ErrorKind::NotFound => { + pending.push(run); + continue; + } + Err(error) => return Err(error), + }, + }; + if job.is_empty() || !job.bytes().all(|byte| byte.is_ascii_digit()) { + continue; + } + known_jobs.insert(run.clone(), job); + pending.push(run); + } + if pending.is_empty() { + return Ok(Response::SlurmQueue { + jobs: jobs.into_values().collect(), + }); + } + let job_ids = known_jobs.values().cloned().collect::>().join(","); + let names = pending + .iter() + .filter(|run| !known_jobs.contains_key(*run)) + .cloned() + .collect::>() + .join(","); + let filters: Vec<_> = [("name", names), ("jobs", job_ids)] + .into_iter() + .filter(|(_, values)| !values.is_empty()) + .map(|(argument, values)| format!("--{argument}={values}")) + .collect(); + let find_run = |job: &str, name: &str| -> Option { + pending + .iter() + .find(|run| match known_jobs.get(*run) { + Some(id) => id == job, + None => **run == name, + }) + .cloned() + }; + let elapsed = |run: &str, job: &str, state: &str| -> io::Result { + let dir = run_dir(&self.root, run)?; + fs::create_dir_all(&dir)?; + let mutex = crate::run_mutex(&dir)?; + let _local = mutex + .lock() + .map_err(|_| io::Error::other("run lock poisoned"))?; + let path = dir.join("slurm-terminal.json"); + let state = state + .split_whitespace() + .next() + .unwrap_or_default() + .trim_end_matches('+'); + match scheduler_state(state, Duration::MAX) { + RunState::Starting | RunState::Running => { + match fs::remove_file(&path) { + Ok(()) => File::open(&dir)?.sync_all()?, + Err(error) if error.kind() == io::ErrorKind::NotFound => {} + Err(error) => return Err(error), + } + Ok(Duration::ZERO) + } + RunState::Failed { .. } | RunState::Lost { .. } | RunState::Cancelled { .. } => { + let previous = match read_json::(&path) { + Ok(fact) => Some(fact), + Err(error) if error.kind() == io::ErrorKind::NotFound => None, + Err(error) => return Err(error), + }; + let fact = match previous { + Some(fact) if fact.job == job && fact.state == state => fact, + _ => { + let fact = SchedulerTerminal { + job: job.into(), + state: state.into(), + since: SystemTime::now(), + }; + publish(&path, &fact)?; + fact + } + }; + Ok(fact.since.elapsed().unwrap_or_default()) + } + _ => Ok(Duration::ZERO), + } + }; + let deadline = Instant::now() + Duration::from_secs(30); + let budget = || { + deadline + .saturating_duration_since(Instant::now()) + .min(Duration::from_secs(10)) + }; + let queued: Vec<_> = filters + .iter() + .map(|filter| { + self.exec( + Command::new("squeue").args([ + "--noheader", + "--states=all", + "--format=%i|%j|%T", + filter, + ]), + &[], + budget(), + ) + }) + .collect(); + let mut unanswered = None; + for result in queued { + let result = match result { + Ok(result) + if result.code == Some(0) && !result.timed_out && !result.stdout_truncated => + { + result + } + other => { + unanswered = Some(match other { + Ok(result) => String::from_utf8_lossy(&result.stderr).trim().to_owned(), + Err(error) => error.to_string(), + }); + continue; + } + }; + for line in String::from_utf8_lossy(&result.stdout).lines() { + let fields: Vec<_> = line.trim().split('|').collect(); + if fields.len() != 3 { + unanswered = Some(line.to_owned()); + continue; + } + let Some(run) = find_run(fields[0], fields[1]) else { + continue; + }; + let state = scheduler_state(fields[2], elapsed(&run, fields[0], fields[2])?); + jobs.insert( + run.clone(), + SlurmJob { + run: run.clone(), + job: fields[0].into(), + state: fields[2].into(), + summary: slurm_summary( + &run_dir(&self.root, &run)?, + legacy.iter().find(|old| old.run == run), + state, + ), + }, + ); + } + } + let mut start = None; + for run in &pending { + let dir = match legacy.iter().find(|old| old.run == *run) { + Some(old) => legacy::directory(&old.dir)?, + None => run_dir(&self.root, run)?, + }; + for name in ["launch.json", "job.sbatch"] { + let modified = match fs::metadata(dir.join(name)) { + Ok(metadata) => metadata.modified()?, + Err(error) if error.kind() == io::ErrorKind::NotFound => continue, + Err(error) => return Err(error), + }; + start = Some(start.map_or(modified, |earliest: SystemTime| earliest.min(modified))); + break; + } + } + let start = start + .map(|time| -> io::Result { + let seconds = time + .duration_since(std::time::UNIX_EPOCH) + .map_err(io::Error::other)? + .as_secs() + .try_into() + .map_err(io::Error::other)?; + let mut local = unsafe { std::mem::zeroed::() }; + if unsafe { libc::localtime_r(&seconds, &mut local) }.is_null() { + return Err(io::Error::last_os_error()); + } + Ok(format!( + "--starttime={:04}-{:02}-{:02}T{:02}:{:02}:{:02}", + local.tm_year + 1900, + local.tm_mon + 1, + local.tm_mday, + local.tm_hour, + local.tm_min, + local.tm_sec + )) + }) + .transpose()?; + let accounting: Vec<_> = filters + .iter() + .map(|filter| { + self.exec( + Command::new("sacct") + .args([ + "--noheader", + "--parsable2", + "--format=JobIDRaw,JobName,State", + filter, + ]) + .args(start.as_ref()), + &[], + budget(), + ) + }) + .collect(); + let mut accounting_answered = accounting.iter().all(|result| { + matches!(result, Ok(result) if result.code == Some(0) && !result.timed_out && !result.stdout_truncated) + }); + for result in accounting.into_iter().flatten() { + if result.code == Some(0) && !result.timed_out && !result.stdout_truncated { + for line in String::from_utf8_lossy(&result.stdout).lines() { + let fields: Vec<_> = line.trim().split('|').collect(); + if fields.len() < 3 { + accounting_answered = false; + continue; + } + if fields[0].contains('.') { + continue; + } + let Some(run) = find_run(fields[0], fields[1]) else { + continue; + }; + if jobs.contains_key(&run) { + continue; + } + let state = scheduler_state(fields[2], elapsed(&run, fields[0], fields[2])?); + jobs.insert( + run.clone(), + SlurmJob { + run: run.clone(), + job: fields[0].into(), + state: fields[2].into(), + summary: slurm_summary( + &run_dir(&self.root, &run)?, + legacy.iter().find(|old| old.run == run), + state, + ), + }, + ); + } + } + } + let mut absent = BTreeSet::new(); + for run in pending { + if !jobs.contains_key(&run) { + let path = run_dir(&self.root, &run)?.join("slurm-terminal.json"); + let terminal = match read_json::(&path) { + Ok(fact) => Some(fact), + Err(error) if error.kind() == io::ErrorKind::NotFound => None, + Err(error) => return Err(error), + }; + if terminal.is_none() && unanswered.is_none() && accounting_answered { + absent.insert(run.clone()); + } + let fallback = match &terminal { + Some(fact) => { + scheduler_state(&fact.state, fact.since.elapsed().unwrap_or_default()) + } + None => RunState::Unreconciled { + detail: match &unanswered { + Some(error) => format!("scheduler unanswered: {error}"), + None => "scheduler has no record and no receipt".into(), + }, + }, + }; + let summary = slurm_summary( + &run_dir(&self.root, &run)?, + legacy.iter().find(|old| old.run == run), + fallback, + ); + jobs.insert( + run.clone(), + SlurmJob { + run, + job: terminal + .as_ref() + .map(|fact| fact.job.clone()) + .unwrap_or_default(), + state: terminal + .map(|fact| fact.state) + .unwrap_or_else(|| "UNKNOWN".into()), + summary, + }, + ); + } + } + for job in jobs.values_mut() { + let stopped = matches!( + scheduler_state(&job.state, Duration::MAX), + RunState::Failed { .. } | RunState::Lost { .. } | RunState::Cancelled { .. } + ) || absent.contains(&job.run); + if stopped + && matches!(&job.summary.state, RunState::Exited { receipt } if receipt.reason == ExitReason::Cancelled) + { + let proof = ProcessOutcome { + processes: Vec::new(), + outcome: CancelOutcome::Verified, + }; + publish(&run_dir(&self.root, &job.run)?.join("cleanup.json"), &proof)?; + job.summary.cleanup = Some(proof); + } + } + Ok(Response::SlurmQueue { + jobs: jobs.into_values().collect(), + }) + } +} + +fn invalid(message: &str) -> io::Result { + Err(io::Error::new(io::ErrorKind::InvalidInput, message)) +} + +fn slurm_execution(dir: &Path) -> io::Result { + for name in ["slurm.job", "wrapper.json", "started", "exit.json"] { + if dir.join(name).try_exists()? { + return Ok(true); + } + } + Ok(false) +} + +fn log_name(file: LogFile) -> &'static str { + match file { + LogFile::Log => "log", + LogFile::Notify => "notify", + } +} +fn length(path: &Path) -> io::Result { + match fs::metadata(path) { + Ok(metadata) => Ok(metadata.len()), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(0), + Err(error) => Err(error), + } +} +fn quote(path: &Path) -> String { + format!("'{}'", path.to_string_lossy().replace('\'', "'\\''")) +} + +fn check_sha(hash: &str) -> io::Result<()> { + if hash.len() == 64 + && hash + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) + { + Ok(()) + } else { + invalid("invalid SHA-256 digest") + } +} +fn file_sha(path: &Path) -> io::Result { + let mut file = File::open(path)?; + let mut hash = Sha256::new(); + let mut bytes = [0; 64 * 1024]; + loop { + let len = file.read(&mut bytes)?; + if len == 0 { + break; + } + hash.update(&bytes[..len]); + } + Ok(format!("{:x}", hash.finalize())) +} +fn slurm_summary(dir: &Path, old: Option<&SlurmLegacyRun>, fallback: RunState) -> Summary { + let result = (|| -> io::Result { + if let Some(old) = old { + let dir = legacy::directory(&old.dir)?; + let inspection = legacy::inspect(&dir)?; + let state = match inspection.exit_code { + Some(code) => RunState::Exited { + receipt: ExitReceipt { + finished_at: None, + code: Some(code), + signal: None, + reason: ExitReason::Exited, + processes: vec![], + outcome: CancelOutcome::Unverifiable { unreadable: vec![] }, + }, + }, + None if inspection.receipt_unreadable => RunState::Unreconciled { + detail: "legacy receipt unreadable".into(), + }, + None => fallback, + }; + return Ok(Summary { + started_at: None, + state, + log_len: None, + notify_len: length(&dir.join("notify"))?, + cleanup: None, + }); + } + // Refresh NFS visibility before reopening the receipt. + match fs::metadata(dir.join("exit.json")) { + Ok(_) => {} + Err(error) if error.kind() == io::ErrorKind::NotFound => {} + Err(error) => return Err(error), + } + let state = match wrapper::receipt(dir) { + Ok(Some(receipt)) => RunState::Exited { receipt }, + Ok(None) => fallback, + Err(error) => wrapper::read_error(error), + }; + Ok(Summary { + started_at: wrapper::started_at(dir), + state, + log_len: None, + notify_len: length(&dir.join("notify"))?, + cleanup: wrapper::cleanup_result(dir)?, + }) + })(); + result.unwrap_or_else(|error| Summary { + started_at: None, + state: wrapper::read_error(error), + log_len: None, + notify_len: 0, + cleanup: None, + }) +} + +fn scheduler_state(state: &str, elapsed: Duration) -> RunState { + let state = state + .split_whitespace() + .next() + .unwrap_or_default() + .trim_end_matches('+'); + if matches!(state, "PENDING" | "CONFIGURING") { + return RunState::Starting; + } + if matches!(state, "RUNNING" | "COMPLETING" | "SUSPENDED") { + return RunState::Running; + } + if !matches!( + state, + "COMPLETED" + | "CANCELLED" + | "FAILED" + | "TIMEOUT" + | "OUT_OF_MEMORY" + | "NODE_FAIL" + | "PREEMPTED" + | "BOOT_FAIL" + | "DEADLINE" + | "REVOKED" + ) { + return RunState::Unreconciled { + detail: format!("unknown scheduler state: {state}"), + }; + } + if elapsed < crate::stop_duration(Duration::from_secs(120)) { + return RunState::Unreconciled { + detail: "awaiting receipt visibility after scheduler terminal".into(), + }; + } + if state == "CANCELLED" { + RunState::Cancelled { + reason: "scheduler cancelled; no receipt".into(), + } + } else if matches!( + state, + "FAILED" + | "TIMEOUT" + | "OUT_OF_MEMORY" + | "NODE_FAIL" + | "PREEMPTED" + | "BOOT_FAIL" + | "DEADLINE" + | "REVOKED" + ) { + RunState::Failed { + reason: format!("scheduler {state}; no receipt"), + } + } else { + RunState::Lost { + reason: "no receipt".into(), + } + } +} + +fn write_response(writer: &mut impl Write, response: &Message) -> io::Result<()> { + let mut frame = Vec::new(); + if let Err(error) = write_frame(&mut frame, response) { + frame.clear(); + write_frame( + &mut frame, + &Message { + id: response.id, + body: Response::Error { + code: ErrorCode::Io, + message: error.to_string(), + }, + }, + )?; + } + writer.write_all(&frame)?; + writer.flush() +} + +/// How long one `PinSource` request may copy across filesystems before answering. +const PIN_SLICE: Duration = Duration::from_secs(5); + +/// Holds blob `sha` from `sources` in run dir `dir` as `source.tar`, against source sweeps: a +/// hard link, or across filesystems a copy built in a part named for the blob, a megabyte at +/// a time for about `budget` per call. Only what was synced counts, recorded beside the part, +/// so a retry cuts off whatever an interrupted writer left after it and continues. True once +/// the whole part is published. A blob already swept fails with NotFound, so the client +/// stages it again. +fn pin_source( + sources: &Path, + sha: &str, + dir: &Path, + link: impl Fn(&Path, &Path) -> io::Result<()>, + budget: Duration, +) -> io::Result { + let target = dir.join("source.tar"); + if target.try_exists()? { + return Ok(true); + } + let blob = sources.join(sha); + match link(&blob, &target) { + Err(error) if error.raw_os_error() == Some(libc::EXDEV) => {} + result => return result.map(|()| true), + } + let part = dir.join(format!("source.tar.{sha}.part")); + let synced = dir.join(format!("source.tar.{sha}.synced")); + for entry in fs::read_dir(dir)? { + let path = entry?.path(); + let name = path.file_name().and_then(|name| name.to_str()); + let ours = path == part || path == synced; + if !ours && name.is_some_and(|name| name.starts_with("source.tar.")) { + fs::remove_file(path)?; + } + } + let source = File::open(&blob)?; + let total = source.metadata()?.len(); + let mut len = fs::read_to_string(&synced) + .ok() + .and_then(|len| len.parse::().ok()) + .unwrap_or(0) + .min(total); + let copy = OpenOptions::new() + .write(true) + .create(true) + .truncate(false) + .mode(0o600) + .open(&part)?; + copy.set_len(len)?; + let mut buffer = vec![0; 1 << 20]; + let started = Instant::now(); + while len < total { + let step = (total - len).min(buffer.len() as u64) as usize; + source.read_exact_at(&mut buffer[..step], len)?; + copy.write_all_at(&buffer[..step], len)?; + len += step as u64; + if started.elapsed() >= budget { + break; + } + } + copy.sync_all()?; + if len < total { + crate::publish_bytes(&synced, len.to_string().as_bytes())?; + return Ok(false); + } + fs::rename(&part, &target)?; + let _ = fs::remove_file(&synced); + File::open(dir)?.sync_all()?; + Ok(true) +} + +pub fn serve(root: PathBuf, binary: PathBuf) -> io::Result<()> { + #[derive(Default)] + struct InFlight { + ids: BTreeSet, + running: usize, + } + + let host = Arc::new(Host::new(root, binary)?); + let output = Arc::new(Mutex::new(io::stdout())); + let inflight = Arc::new(Mutex::new(InFlight::default())); + let finished = Arc::new(Condvar::new()); + let mut input = io::stdin().lock(); + let result = (|| -> io::Result<()> { + while let Some(message) = read_frame::>(&mut input)? { + let mut active = inflight + .lock() + .map_err(|_| io::Error::other("request set poisoned"))?; + if active.ids.len() >= 32 || !active.ids.insert(message.id) { + write_frame( + &mut *output + .lock() + .map_err(|_| io::Error::other("output poisoned"))?, + &Message { + id: message.id, + body: Response::Error { + code: ErrorCode::Busy, + message: "too many requests or duplicate request id".into(), + }, + }, + )?; + continue; + } + active.running += 1; + drop(active); + let (host, output, inflight, finished) = ( + host.clone(), + output.clone(), + inflight.clone(), + finished.clone(), + ); + std::thread::spawn(move || { + let response = Message { + id: message.id, + body: host.handle(message.body), + }; + if let Ok(mut active) = inflight.lock() { + active.running -= 1; + finished.notify_all(); + } + if !host.stop.load(Ordering::Relaxed) { + if let Ok(mut output) = output.lock() { + if let Err(error) = write_response(&mut *output, &response) { + let _ = writeln!( + io::stderr(), + "orx-host: response {}: {error}", + response.id + ); + } + } + } + if let Ok(mut active) = inflight.lock() { + active.ids.remove(&message.id); + } + }); + } + Ok(()) + })(); + host.stop.store(true, Ordering::Relaxed); + let mut active = inflight + .lock() + .map_err(|_| io::Error::other("request set poisoned"))?; + while active.running > 0 { + active = finished + .wait(active) + .map_err(|_| io::Error::other("request set poisoned"))?; + } + result +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Across mounts the link fails with EXDEV. A copy slower than one request continues + /// across requests from what was synced; whatever an interrupted writer left past that is + /// cut off, never published; strays from other copies go. + #[test] + fn a_source_on_another_filesystem_is_pinned_by_resumable_copy() { + let root = std::env::temp_dir().join(format!("orx-host-{}", crate::nonce().unwrap())); + let (sources, dir) = (root.join("sources"), root.join("runs/r1")); + fs::create_dir_all(&sources).unwrap(); + fs::create_dir_all(&dir).unwrap(); + let archive: Vec = (0..3 << 20).map(|i: u32| (i % 251) as u8).collect(); + let sha = crate::sha(&archive); + fs::write(sources.join(&sha), &archive).unwrap(); + let cross_device = |_: &Path, _: &Path| Err(io::Error::from_raw_os_error(libc::EXDEV)); + let pin = || pin_source(&sources, &sha, &dir, cross_device, Duration::ZERO).unwrap(); + let part = dir.join(format!("source.tar.{sha}.part")); + let stray = dir.join(format!("source.tar.{}.part", "0".repeat(64))); + fs::write(&stray, b"another copy").unwrap(); + + // Each zero-budget request copies one megabyte, as a copy slower than the deadline would. + assert!(!pin()); + assert!(!stray.exists()); + // An interrupted writer left garbage past what was synced. + let mut torn = fs::read(&part).unwrap(); + torn.extend_from_slice(&[0xff; 4096]); + fs::write(&part, &torn).unwrap(); + assert!(!pin()); + assert_eq!(fs::metadata(&part).unwrap().len(), 2 << 20); + assert!(pin()); + assert_eq!(fs::read(dir.join("source.tar")).unwrap(), archive); + assert_eq!( + fs::read_dir(&dir).unwrap().count(), + 1, + "a part was left behind" + ); + assert!(pin()); + + let other = root.join("runs/r2"); + fs::create_dir_all(&other).unwrap(); + let swept = pin_source(&sources, &"1".repeat(64), &other, cross_device, PIN_SLICE); + assert_eq!(swept.unwrap_err().kind(), io::ErrorKind::NotFound); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn launch_cancel_and_cleanup_share_a_run_mutex_across_host_instances_and_path_aliases() { + let root = std::env::temp_dir().join(format!("orx-host-{}", crate::nonce().unwrap())); + let run = root.join("runs/r1"); + fs::create_dir_all(&run).unwrap(); + let binary = PathBuf::from("/usr/bin/true"); + let hosts: Vec<_> = (0..3) + .map(|_| Host::new(root.clone(), binary.clone()).unwrap()) + .collect(); + let mutex = crate::run_mutex(&run).unwrap(); + let alias = crate::run_mutex(&run.join(".")).unwrap(); + assert!(Arc::ptr_eq(&mutex, &alias)); + let other = root.join("runs/other"); + fs::create_dir(&other).unwrap(); + let other = crate::run_mutex(&other).unwrap(); + let held = mutex.lock().unwrap(); + assert!(other.try_lock().is_ok()); + let requests = [ + Request::Launch(LaunchIntent { + run: "r1".into(), + digest: crate::sha(b"true"), + run_sh: "true".into(), + env: BTreeMap::new(), + source: None, + cancel_sh: None, + }), + Request::Cancel { run: "r1".into() }, + Request::Cleanup { run: "r1".into() }, + ]; + let barrier = Arc::new(std::sync::Barrier::new(4)); + let (sent, received) = std::sync::mpsc::channel(); + let workers: Vec<_> = hosts + .into_iter() + .zip(requests) + .map(|(host, request)| { + let barrier = barrier.clone(); + let sent = sent.clone(); + std::thread::spawn(move || { + barrier.wait(); + sent.send(host.handle(request)).unwrap(); + }) + }) + .collect(); + barrier.wait(); + let blocked = received.recv_timeout(Duration::from_millis(50)).is_err(); + drop(held); + for worker in workers { + worker.join().unwrap(); + } + fs::remove_dir_all(root).unwrap(); + assert!(blocked, "a run mutation bypassed the in-process lock"); + assert_eq!(received.try_iter().count(), 3); + } + + #[test] + fn oversized_response_returns_an_error_for_the_same_id() { + let mut output = Vec::new(); + write_response( + &mut output, + &Message { + id: 17, + body: Response::Error { + code: ErrorCode::Io, + message: "x".repeat(MAX_FRAME_LEN + 1), + }, + }, + ) + .unwrap(); + let response: Message = read_frame(&mut output.as_slice()).unwrap().unwrap(); + assert_eq!(response.id, 17); + assert!( + matches!(response.body, Response::Error { message, .. } if message.contains("frame")) + ); + } + + #[test] + fn retained_scheduler_fact_preserves_its_disk_shape() { + let fixture = include_str!("../tests/fixtures/slurm-terminal.json"); + let fact: SchedulerTerminal = serde_json::from_str(fixture).unwrap(); + assert_eq!(fact.job, "123"); + assert_eq!(fact.state, "PREEMPTED"); + assert_eq!( + serde_json::to_value(&fact).unwrap(), + serde_json::from_str::(fixture).unwrap() + ); + } + + #[test] + fn scheduler_terminal_requires_visibility_grace_and_never_guesses_success() { + assert!(matches!( + scheduler_state("COMPLETED", Duration::from_secs(119)), + RunState::Unreconciled { .. } + )); + assert!( + matches!(scheduler_state("COMPLETED", Duration::from_secs(120)), RunState::Lost { reason } if reason == "no receipt") + ); + assert!(matches!( + scheduler_state("CANCELLED by 501", Duration::from_secs(120)), + RunState::Cancelled { .. } + )); + assert!(matches!( + scheduler_state("OUT_OF_MEMORY+", Duration::from_secs(120)), + RunState::Failed { .. } + )); + for state in ["PREEMPTED", "NODE_FAIL"] { + assert_eq!( + scheduler_state(state, Duration::from_secs(120)), + RunState::Failed { + reason: format!("scheduler {state}; no receipt"), + } + ); + } + assert_eq!( + scheduler_state("RUNNING", Duration::from_secs(500)), + RunState::Running + ); + assert_eq!( + scheduler_state("PENDING", Duration::from_secs(500)), + RunState::Starting + ); + } +} diff --git a/crates/orx-host/src/wrapper.rs b/crates/orx-host/src/wrapper.rs new file mode 100644 index 000000000..1f6c49ff5 --- /dev/null +++ b/crates/orx-host/src/wrapper.rs @@ -0,0 +1,744 @@ +use crate::{crash_point, lock, nonce, platform, publish, read_json}; +use orx_host_proto::{ + CancelAck, CancelOutcome, CleanupAck, ExitReason, ExitReceipt, LaunchIntent, ProcessIdentity, + ProcessOutcome, RunState, Survivor, +}; +use std::fs::{self, File, OpenOptions}; +use std::io; +use std::io::Write; +use std::os::unix::fs::OpenOptionsExt; +use std::path::Path; +use std::process::{Command, Stdio}; +use std::time::{Duration, Instant}; + +pub fn wrap(dir: &Path) -> io::Result<()> { + let Some(_ownership) = lock(&dir.join("wrapper.lock"))? else { + return Ok(()); + }; + if dir.join("exit.json").try_exists()? || dir.join("started").try_exists()? { + return Ok(()); + } + crash_point("wrapper_locked"); + // A detached wrapper must survive ssh hangup; only its payload receives the run tag. + unsafe { + libc::signal(libc::SIGHUP, libc::SIG_IGN); + libc::signal(libc::SIGCHLD, wake as *const () as libc::sighandler_t); + libc::signal(libc::SIGUSR1, wake as *const () as libc::sighandler_t); + } + if unsafe { libc::getsid(0) } != std::process::id() as i32 && unsafe { libc::setsid() } == -1 { + let error = io::Error::last_os_error(); + if error.raw_os_error() != Some(libc::EPERM) { + return Err(error); + } + } + let identity = platform::identity(std::process::id())?; + publish(&dir.join("wrapper.json"), &identity)?; + crash_point("wrapper_identity"); + let subreaper = platform::subreaper()?; + let intent: LaunchIntent = read_json(&dir.join("launch.json"))?; + let tag = format!("{}:{}", intent.run, nonce()?); + let gate = start_gate(dir)?; + if dir.join("cancel.req").try_exists()? { + publish(&dir.join("exit.json"), &cancelled_before_start())?; + return Ok(()); + } + let log = OpenOptions::new() + .append(true) + .create(true) + .mode(0o600) + .open(dir.join("log"))?; + let error_log = log.try_clone()?; + let mut started = OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(dir.join("started"))?; + writeln!(started, "{tag}")?; + started.sync_all()?; + File::open(dir)?.sync_all()?; + drop(started); + drop(gate); + + crash_point("wrapper_started"); + let mut command = Command::new("bash"); + command + .arg("run.sh") + .current_dir(dir) + .envs(&intent.env) + .env("ORX_RUN_TAG", &tag) + .env("ORX_NOTIFY_FILE", dir.join("notify")) + .stdin(Stdio::null()) + .stdout(log) + .stderr(error_log); + let child = match command.spawn() { + Ok(child) => child, + Err(error) => { + publish( + &dir.join("exit.json"), + &ExitReceipt { + finished_at: Some( + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_millis() as i64, + ), + code: None, + signal: None, + reason: ExitReason::SpawnFailed, + processes: vec![], + outcome: CancelOutcome::Verified, + }, + )?; + return Err(error); + } + }; + let child_pid = child.id(); + drop(command); + drop(child); + crash_point("wrapper_spawned"); + let mut direct_status = None; + let mut lingering: Option<(Vec, bool)> = None; + let mut stopping = false; + let mut renewal_delay = crate::stop_duration(Duration::from_secs(1)); + loop { + let no_children = retry(dir, child_pid, &mut direct_status, |empty, _| Ok(empty))?; + let cancel = lingering.is_none() + && retry(dir, child_pid, &mut direct_status, |_, _| { + dir.join("cancel.req").try_exists() + })?; + let cleanup = lingering.is_some() + && retry(dir, child_pid, &mut direct_status, |_, _| { + dir.join("cleanup.req").try_exists() + })?; + if cancel || cleanup || stopping { + let (scan, no_children) = stop( + dir, + &identity, + &tag, + subreaper, + child_pid, + &mut direct_status, + !stopping, + )?; + let outcome = scan.outcome(no_children); + let processes: Vec<_> = scan + .processes + .iter() + .map(platform::Process::survivor) + .collect(); + if cancel { + retry(dir, child_pid, &mut direct_status, |_, status| { + publish( + &dir.join("exit.json"), + &exit_receipt( + status, + ExitReason::Cancelled, + processes.clone(), + outcome.clone(), + ), + ) + })?; + if std::env::var_os("SLURM_JOB_ID").is_some() + || (processes.is_empty() && no_children) + { + return Ok(()); + } + } else { + retry(dir, child_pid, &mut direct_status, |_, _| { + publish( + &dir.join("cleanup.json"), + &ProcessOutcome { + processes: processes.clone(), + outcome: outcome.clone(), + }, + ) + })?; + retry( + dir, + child_pid, + &mut direct_status, + |_, _| match fs::remove_file(dir.join("cleanup.req")) { + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()), + result => result, + }, + )?; + } + lingering = Some((processes, scan.complete)); + stopping = true; + if scan.processes.is_empty() && no_children { + return Ok(()); + } + unsafe { + libc::poll( + std::ptr::null_mut(), + 0, + renewal_delay.as_millis() as libc::c_int, + ); + } + renewal_delay = (renewal_delay * 2).min(crate::stop_duration(Duration::from_secs(30))); + continue; + } else if let Some((processes, complete)) = &mut lingering { + retry(dir, child_pid, &mut direct_status, |_, _| { + let mut alive = Vec::new(); + for identity in processes.iter() { + match platform::process(identity.pid) { + Ok(process) + if process.starttime == identity.starttime && process.live() => + { + alive.push(identity.clone()) + } + Ok(_) => {} + Err(error) if missing_process(&error) => {} + Err(error) => return Err(error), + } + } + *processes = alive; + Ok(()) + })?; + if processes.is_empty() && no_children { + let result = ProcessOutcome { + processes: vec![], + outcome: if *complete { + CancelOutcome::Verified + } else { + CancelOutcome::Unverifiable { unreadable: vec![] } + }, + }; + retry(dir, child_pid, &mut direct_status, |_, _| { + publish(&dir.join("cleanup.json"), &result) + })?; + return Ok(()); + } + } else if direct_status.is_some() { + let (scan, no_children) = retry(dir, child_pid, &mut direct_status, |empty, _| { + let mut scan = platform::scan(Some(&identity), &tag, subreaper)?; + scan.complete &= !dir.join("cancel.sh").try_exists()?; + Ok((scan, empty)) + })?; + let processes: Vec<_> = scan + .processes + .iter() + .map(platform::Process::survivor) + .collect(); + let outcome = scan.outcome(no_children); + crash_point("wrapper_before_receipt"); + retry(dir, child_pid, &mut direct_status, |_, status| { + publish( + &dir.join("exit.json"), + &exit_receipt( + status, + ExitReason::Exited, + processes.clone(), + outcome.clone(), + ), + ) + })?; + crash_point("wrapper_receipt"); + if std::env::var_os("SLURM_JOB_ID").is_some() || (processes.is_empty() && no_children) { + return Ok(()); + } + lingering = Some((processes, scan.complete)); + } + unsafe { + libc::poll(std::ptr::null_mut(), 0, 1000); + } + } +} + +fn missing_process(error: &io::Error) -> bool { + error.kind() == io::ErrorKind::NotFound || error.raw_os_error() == Some(libc::ESRCH) +} + +fn exit_receipt( + status: Option, + reason: ExitReason, + processes: Vec, + outcome: CancelOutcome, +) -> ExitReceipt { + ExitReceipt { + finished_at: Some( + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_millis() as i64, + ), + code: status + .filter(|&status| libc::WIFEXITED(status)) + .map(|status| libc::WEXITSTATUS(status)), + signal: status + .filter(|&status| libc::WIFSIGNALED(status)) + .map(|status| libc::WTERMSIG(status)), + reason, + processes, + outcome, + } +} + +fn cancelled_before_start() -> ExitReceipt { + exit_receipt(None, ExitReason::Cancelled, vec![], CancelOutcome::Verified) +} + +fn start_gate(dir: &Path) -> io::Result { + loop { + if let Some(file) = lock(&dir.join("start.lock"))? { + return Ok(file); + } + std::thread::sleep(Duration::from_millis(10)); + } +} + +fn retry( + dir: &Path, + child: u32, + status: &mut Option, + mut operation: impl FnMut(bool, Option) -> io::Result, +) -> io::Result { + let mut delay = crate::stop_duration(Duration::from_millis(100)); + loop { + let result = match fs::metadata(dir) { + Ok(_) => reap(child, status).and_then(|empty| operation(empty, *status)), + Err(error) if error.kind() == io::ErrorKind::NotFound => return Err(error), + Err(error) => Err(error), + }; + match result { + Ok(value) => return Ok(value), + Err(error) => { + let _ = writeln!(io::stderr(), "orx-host: supervision retry: {error}"); + } + } + std::thread::sleep(delay); + delay = (delay * 2).min(crate::stop_duration(Duration::from_secs(5))); + } +} + +fn stop( + dir: &Path, + identity: &ProcessIdentity, + tag: &str, + subreaper: bool, + child: u32, + direct_status: &mut Option, + initial: bool, +) -> io::Result<(platform::Scan, bool)> { + let mut known = retry(dir, child, direct_status, |_, _| { + Ok(latest_proof(dir)?.map_or_else(Vec::new, |proof| proof.processes)) + })?; + let has_hook = retry(dir, child, direct_status, |_, _| { + dir.join("cancel.sh").try_exists() + })?; + if initial && has_hook { + retry(dir, child, direct_status, |_, _| { + let result = crate::exec::run( + Command::new("bash").arg("cancel.sh").current_dir(dir), + &[], + crate::stop_duration(crate::HOOK_TIMEOUT), + None, + )?; + if result.code == Some(0) && !result.timed_out { + Ok(()) + } else { + Err(io::Error::other("cancel hook did not complete")) + } + })?; + } + let kill_at = Instant::now() + + if initial { + crate::stop_duration(crate::TERM_GRACE) + } else { + Duration::ZERO + }; + let kill_window = Duration::from_secs(30); + #[cfg(all(feature = "test-hooks", debug_assertions))] + let kill_window = if std::env::var("ORX_TEST_FAST_STOPS").as_deref() == Ok("1") { + Duration::from_secs(1) + } else { + kill_window + }; + let mut killed_at = None; + let mut unreadable_since = None; + let mut termed = std::collections::BTreeSet::new(); + let mut delay = crate::stop_duration(Duration::from_millis(250)); + loop { + let (mut scan, no_children) = retry(dir, child, direct_status, |empty, _| { + let mut scan = platform::scan(Some(identity), tag, subreaper)?; + scan.include(&known)?; + Ok((scan, empty)) + })?; + scan.complete &= !has_hook; + known = scan + .processes + .iter() + .map(platform::Process::survivor) + .collect(); + if scan.processes.is_empty() && no_children { + // An unreadable process is usually mid-exec; give it a moment before the proof gives up. + let settled = scan.unreadable.is_empty() + || !initial + || unreadable_since.get_or_insert_with(Instant::now).elapsed() + >= Duration::from_secs(2); + if settled { + return Ok((scan, no_children)); + } + } + let killing = Instant::now() >= kill_at; + if killed_at.is_some_and(|since: Instant| since.elapsed() >= kill_window) { + return Ok((scan, no_children)); + } + for process in &scan.processes { + let key = (process.pid, process.starttime); + if killing || !termed.contains(&key) { + let signal = if killing { + libc::SIGKILL + } else { + libc::SIGTERM + }; + match platform::signal(process, signal) { + Ok(()) => { + termed.insert(key); + } + Err(error) if missing_process(&error) => {} + Err(error) => { + let _ = writeln!(io::stderr(), "orx-host: signal {}: {error}", process.pid); + } + } + } + } + if killing { + killed_at.get_or_insert_with(Instant::now); + if !initial { + return retry(dir, child, direct_status, |empty, _| { + let mut scan = platform::scan(Some(identity), tag, subreaper)?; + scan.include(&known)?; + scan.complete &= !has_hook; + Ok((scan, empty)) + }); + } + std::thread::sleep(delay); + delay = (delay * 2).min(crate::stop_duration(Duration::from_secs(2))); + } else { + std::thread::sleep(crate::stop_duration(Duration::from_millis(100))); + } + } +} + +extern "C" fn wake(_: libc::c_int) {} + +fn reap(direct: u32, status: &mut Option) -> io::Result { + loop { + let mut value = 0; + let pid = unsafe { libc::waitpid(-1, &mut value, libc::WNOHANG) }; + if pid > 0 { + if pid as u32 == direct { + *status = Some(value); + } + continue; + } + if pid == 0 { + return Ok(false); + } + let error = io::Error::last_os_error(); + if error.raw_os_error() == Some(libc::ECHILD) { + return Ok(true); + } + if error.kind() != io::ErrorKind::Interrupted { + return Err(error); + } + } +} + +pub fn receipt(dir: &Path) -> io::Result> { + match read_json(&dir.join("exit.json")) { + Ok(receipt) => Ok(Some(receipt)), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None), + Err(error) => Err(error), + } +} + +pub fn cleanup_result(dir: &Path) -> io::Result> { + match read_json(&dir.join("cleanup.json")) { + Ok(outcome) => Ok(Some(outcome)), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None), + Err(error) => Err(error), + } +} + +fn latest_proof(dir: &Path) -> io::Result> { + match cleanup_result(dir)? { + Some(proof) => Ok(Some(proof)), + None => Ok(receipt(dir)?.map(|receipt| ProcessOutcome { + processes: receipt.processes, + outcome: receipt.outcome, + })), + } +} + +pub fn cleanup(dir: &Path) -> io::Result { + let mutex = crate::run_mutex(dir)?; + let _local = mutex + .lock() + .map_err(|_| io::Error::other("run lock poisoned"))?; + let receipt = receipt(dir)? + .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "run has not finished"))?; + let proof = cleanup_result(dir)?.unwrap_or(ProcessOutcome { + processes: receipt.processes, + outcome: receipt.outcome, + }); + if proof.processes.is_empty() && proof.outcome == CancelOutcome::Verified { + return Ok(CleanupAck::NothingLingering); + } + let identity: ProcessIdentity = read_json(&dir.join("wrapper.json"))?; + if identity.node == platform::node()? && !platform::alive(&identity)? { + if let Some(_ownership) = lock(&dir.join("wrapper.lock"))? { + let proof = if identity.boot_id != platform::boot_id()? { + ProcessOutcome { + processes: Vec::new(), + outcome: CancelOutcome::Verified, + } + } else { + let tag = fs::read_to_string(dir.join("started"))?; + if tag.trim().is_empty() { + return Err(io::Error::new(io::ErrorKind::InvalidData, "empty run tag")); + } + let scan = |known: &[Survivor]| -> io::Result { + let mut scan = platform::scan(Some(&identity), tag.trim(), false)?; + scan.include(known)?; + scan.complete = + scan.unreadable.is_empty() && !dir.join("cancel.sh").try_exists()?; + Ok(scan) + }; + let before = scan(&proof.processes)?; + let known: Vec<_> = before + .processes + .iter() + .map(platform::Process::survivor) + .collect(); + for process in &before.processes { + if let Err(error) = platform::signal(process, libc::SIGKILL) { + if !missing_process(&error) { + return Err(error); + } + } + } + let after = scan(&known)?; + ProcessOutcome { + outcome: after.outcome(true), + processes: after + .processes + .iter() + .map(platform::Process::survivor) + .collect(), + } + }; + publish(&dir.join("cleanup.json"), &proof)?; + return Ok(CleanupAck::Accepted); + } + } + request(dir, "cleanup.req")?; + Ok(CleanupAck::Accepted) +} + +fn request(dir: &Path, name: &str) -> io::Result { + let _gate = start_gate(dir)?; + let marker = OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(dir.join(name)); + match marker { + Ok(file) => { + file.sync_all()?; + File::open(dir)?.sync_all()?; + } + Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {} + Err(error) => return Err(error), + } + if let Ok(identity) = read_json::(&dir.join("wrapper.json")) { + if identity.node == platform::node()? && platform::alive(&identity)? { + match platform::process(identity.pid) { + Ok(process) if process.starttime == identity.starttime => { + match platform::signal(&process, libc::SIGUSR1) { + Ok(()) => return Ok(true), + Err(error) + if error.raw_os_error() == Some(libc::ESRCH) + || error.kind() == io::ErrorKind::NotFound => {} + Err(error) => return Err(error), + } + } + Ok(_) => {} + Err(error) + if error.raw_os_error() == Some(libc::ESRCH) + || error.kind() == io::ErrorKind::NotFound => {} + Err(error) => return Err(error), + } + } + } + Ok(false) +} + +pub(crate) fn read_error(error: io::Error) -> RunState { + if error.kind() == io::ErrorKind::InvalidData { + RunState::InvalidData { + detail: error.to_string(), + } + } else { + RunState::Unreachable { + cause: error.to_string(), + } + } +} + +pub fn started_at(dir: &Path) -> Option { + fs::metadata(dir.join("started")) + .ok()? + .modified() + .ok()? + .duration_since(std::time::UNIX_EPOCH) + .ok()? + .as_millis() + .try_into() + .ok() +} + +pub fn state(dir: &Path) -> io::Result { + let first = receipt(dir); + let identity = read_json::(&dir.join("wrapper.json")); + let alive = match &identity { + Ok(identity) => platform::alive(identity), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false), + Err(_) => Ok(false), + }; + let second = receipt(dir); + let receipt = match second { + Ok(None) => first, + other => other, + }; + match receipt { + Ok(Some(receipt)) => { + if receipt.reason == ExitReason::Cancelled && matches!(alive, Ok(false)) { + if let Ok(identity) = &identity { + if identity.node == platform::node()? { + cleanup(dir)?; + } + } + } + return Ok(RunState::Exited { receipt }); + } + Err(error) => return Ok(read_error(error)), + Ok(None) => {} + } + if alive? { + return Ok(RunState::Running); + } + if dir.join("started").try_exists()? { + if let Ok(identity) = identity { + if identity.node == platform::node()? { + if identity.boot_id != platform::boot_id()? { + return Ok(RunState::Lost { + reason: "host rebooted".into(), + }); + } + if !dir.join("cancel.sh").try_exists()? { + let tag = fs::read_to_string(dir.join("started"))?; + if !tag.trim().is_empty() { + let scan = platform::scan(Some(&identity), tag.trim(), false)?; + if scan.processes.is_empty() && scan.unreadable.is_empty() { + return Ok(RunState::Lost { + reason: + "its supervisor died; no run process remains that orx can see" + .into(), + }); + } + } + } + } + } + return Ok(RunState::Unreconciled { + detail: "wrapper gone after started; containment unverifiable".into(), + }); + } + if dir.join("launch.json").try_exists()? { + return Ok(RunState::Starting); + } + Ok(RunState::Missing) +} + +pub fn cancel(dir: &Path) -> io::Result { + let mutex = crate::run_mutex(dir)?; + let _local = mutex + .lock() + .map_err(|_| io::Error::other("run lock poisoned"))?; + if receipt(dir)?.is_some_and(|receipt| { + receipt.reason != ExitReason::Cancelled || receipt.outcome == CancelOutcome::Verified + }) { + return Ok(CancelAck::NotRunning); + } + let identity = read_json::(&dir.join("wrapper.json")).ok(); + if request(dir, "cancel.req")? { + return Ok(CancelAck::Accepted); + } + if receipt(dir)?.is_some_and(|receipt| { + receipt.reason != ExitReason::Cancelled || receipt.outcome == CancelOutcome::Verified + }) { + return Ok(CancelAck::NotRunning); + } + if !dir.join("started").try_exists()? { + let _gate = start_gate(dir)?; + if let Some(_ownership) = lock(&dir.join("wrapper.lock"))? { + if !dir.join("started").try_exists()? && receipt(dir)?.is_none() { + publish(&dir.join("exit.json"), &cancelled_before_start())?; + } + } + return Ok(CancelAck::Accepted); + } + let identity = identity.ok_or_else(|| io::Error::other("wrapper identity missing"))?; + if identity.node != platform::node()? || identity.boot_id != platform::boot_id()? { + return Ok(CancelAck::Accepted); + } + if let Ok(tag) = fs::read_to_string(dir.join("started")) { + if !tag.trim().is_empty() { + let mut scan = platform::scan(Some(&identity), tag.trim(), false)?; + let known = latest_proof(dir)?.map_or_else(Vec::new, |proof| proof.processes); + scan.include(&known)?; + for process in &scan.processes { + let _ = platform::signal(process, libc::SIGTERM); + } + } + } + Ok(CancelAck::WrapperGone) +} + +pub fn has_live_processes(dir: &Path) -> io::Result { + let identity = match read_json::(&dir.join("wrapper.json")) { + Ok(identity) => identity, + Err(error) if error.kind() == io::ErrorKind::NotFound => { + if dir.join("started").try_exists()? { + return Err(io::Error::other("started run has no wrapper identity")); + } + return Ok(receipt(dir)?.is_none() && dir.join("launch.json").try_exists()?); + } + Err(error) => return Err(error), + }; + if platform::alive(&identity)? { + return Ok(true); + } + if identity.boot_id != platform::boot_id()? { + return Ok(false); + } + let proof = latest_proof(dir)?; + if proof + .as_ref() + .is_some_and(|proof| proof.processes.is_empty() && proof.outcome == CancelOutcome::Verified) + { + return Ok(false); + } + let tag = match fs::read_to_string(dir.join("started")) { + Ok(tag) if !tag.trim().is_empty() => tag, + Ok(_) => return Err(io::Error::new(io::ErrorKind::InvalidData, "empty run tag")), + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(receipt(dir)?.is_none()), + Err(error) => return Err(error), + }; + let mut scan = platform::scan(Some(&identity), tag.trim(), false)?; + let known = proof.map_or_else(Vec::new, |proof| proof.processes); + scan.include(&known)?; + Ok(!scan.processes.is_empty() || !scan.unreadable.is_empty()) +} diff --git a/crates/orx-host/tests/common/mod.rs b/crates/orx-host/tests/common/mod.rs new file mode 100644 index 000000000..e017f0459 --- /dev/null +++ b/crates/orx-host/tests/common/mod.rs @@ -0,0 +1,124 @@ +#![allow(dead_code)] +use orx_host::{nonce, platform, publish, read_json, wrapper}; +use orx_host_proto::{LaunchIntent, ProcessIdentity}; +use std::fs; +use std::path::PathBuf; +use std::process::{Child, Command, Stdio}; +use std::thread; +use std::time::{Duration, Instant}; + +pub struct Directory(pub PathBuf); + +pub struct Group(pub Child); +impl Drop for Group { + fn drop(&mut self) { + unsafe { + libc::kill(-(self.0.id() as i32), libc::SIGKILL); + } + let _ = self.0.wait(); + } +} + +impl Directory { + pub fn new() -> Self { + let path = PathBuf::from(format!( + "/tmp/orx-host-{}-{}", + std::process::id(), + &nonce().unwrap()[..12] + )); + fs::create_dir(&path).unwrap(); + Self(path) + } +} +impl Drop for Directory { + fn drop(&mut self) { + match fs::remove_dir_all(&self.0) { + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + result => result.unwrap(), + } + } +} + +pub fn until(timeout: Duration, mut condition: impl FnMut() -> bool) { + let start = Instant::now(); + while !condition() { + assert!(start.elapsed() < timeout, "timed out after {timeout:?}"); + thread::sleep(Duration::from_millis(10)); + } +} + +pub struct Run { + pub directory: Directory, + pub children: Vec, + pub extra: Vec, +} +impl Run { + pub fn new(script: &str) -> Self { + let directory = Directory::new(); + fs::write(directory.0.join("run.sh"), script).unwrap(); + publish( + &directory.0.join("launch.json"), + &LaunchIntent { + run: "test".into(), + digest: orx_host::sha(script.as_bytes()), + run_sh: script.into(), + env: Default::default(), + source: None, + cancel_sh: None, + }, + ) + .unwrap(); + Self { + directory, + children: vec![], + extra: vec![], + } + } + pub fn spawn(&mut self) { + self.children.push( + Command::new(env!("CARGO_BIN_EXE_orx-host")) + .env("ORX_TEST_FAST_STOPS", "1") + .arg("wrap") + .arg(&self.directory.0) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::inherit()) + .spawn() + .unwrap(), + ); + } + pub fn ready(&self) { + until(Duration::from_secs(5), || { + fs::read_to_string(self.directory.0.join("started")) + .is_ok_and(|tag| tag.ends_with('\n')) + && read_json::(&self.directory.0.join("wrapper.json")).is_ok() + }); + } + pub fn wait(&mut self) { + for child in &mut self.children { + until(Duration::from_secs(15), || { + child.try_wait().unwrap().is_some() + }); + assert!(child.wait().unwrap().success()); + } + } +} +impl Drop for Run { + fn drop(&mut self) { + let _ = wrapper::cancel(&self.directory.0); + let _ = wrapper::cleanup(&self.directory.0); + let end = Instant::now() + Duration::from_secs(14); + for child in &mut self.children { + while child.try_wait().ok().flatten().is_none() && Instant::now() < end { + thread::sleep(Duration::from_millis(20)); + } + if child.try_wait().ok().flatten().is_none() { + let _ = child.kill(); + } + let _ = child.wait(); + } + for process in &self.extra { + let _ = platform::signal(process, libc::SIGKILL); + } + } +} diff --git a/crates/orx-host/tests/fixtures/slurm-terminal.json b/crates/orx-host/tests/fixtures/slurm-terminal.json new file mode 100644 index 000000000..d1be2fe85 --- /dev/null +++ b/crates/orx-host/tests/fixtures/slurm-terminal.json @@ -0,0 +1 @@ +{"job":"123","state":"PREEMPTED","since":{"secs_since_epoch":1793664000,"nanos_since_epoch":123000000}} diff --git a/crates/orx-host/tests/rpc.rs b/crates/orx-host/tests/rpc.rs new file mode 100644 index 000000000..7a20deb49 --- /dev/null +++ b/crates/orx-host/tests/rpc.rs @@ -0,0 +1,712 @@ +// Separate test crate; commands inherit the terminal environment. +#![allow(clippy::disallowed_methods)] +#![cfg(unix)] +mod common; +use common::{until, Directory, Group}; +use orx_host::{legacy, log, platform, server::Host, sha}; +use orx_host_proto::*; +use std::fs::{self, OpenOptions}; +use std::io::Write; +use std::os::unix::process::CommandExt; +use std::process::{Command, Stdio}; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +fn host(dir: &Directory) -> Host { + Host::new(dir.0.clone(), env!("CARGO_BIN_EXE_orx-host").into()).unwrap() +} + +fn log_info(path: &std::path::Path) -> LogInfo { + let probe = ByteRange { + start: u64::MAX - 1, + end: u64::MAX, + }; + let LogPage::Reset { info: Some(info) } = log::read(path, None, &probe, None).unwrap() else { + panic!("no log at {}", path.display()) + }; + info +} + +#[test] +fn random_log_pages_identity_anchor_and_short_eof() { + let dir = Directory::new(); + let path = dir.0.join("log"); + let bytes: Vec<_> = (0..60_123).map(|n| (n % 251) as u8).collect(); + fs::write(&path, &bytes).unwrap(); + let info = log_info(&path); + for n in 0..100 { + let start = 64 + (n * 7357 % 60_059) as u64; + let end = start + 1000; + let anchor = bytes[start as usize - 64..start as usize] + .try_into() + .unwrap(); + let page = log::read( + &path, + Some(&info.ident), + &ByteRange { start, end }, + Some(&anchor), + ) + .unwrap(); + let LogPage::Data { + bytes: actual, eof, .. + } = page + else { + panic!("unexpected reset"); + }; + assert_eq!( + actual, + bytes[start as usize..end.min(bytes.len() as u64) as usize] + ); + assert_eq!(eof, end >= bytes.len() as u64); + } + let bad_anchor = [0; 64]; + assert!(matches!( + log::read( + &path, + Some(&info.ident), + &ByteRange { + start: 100, + end: 200 + }, + Some(&bad_anchor) + ) + .unwrap(), + LogPage::Reset { .. } + )); + fs::write(dir.0.join("new"), &bytes).unwrap(); + fs::rename(dir.0.join("new"), &path).unwrap(); + assert!(matches!( + log::read( + &path, + Some(&info.ident), + &ByteRange { + start: 100, + end: 200 + }, + None + ) + .unwrap(), + LogPage::Reset { .. } + )); + let info = log_info(&path); + fs::write(&path, b"short").unwrap(); + assert!(matches!( + log::read( + &path, + Some(&info.ident), + &ByteRange { + start: 100, + end: 200 + }, + None + ) + .unwrap(), + LogPage::Reset { .. } + )); + assert!(log::read( + &path, + None, + &ByteRange { + start: 0, + end: MAX_PAGE_LEN + 1 + }, + None + ) + .is_err()); +} + +#[test] +fn small_log_identity_survives_appends_from_empty() { + let dir = Directory::new(); + let path = dir.0.join("log"); + fs::write(&path, b"").unwrap(); + let ident = log_info(&path).ident; + for bytes in [b"first".as_slice(), b"second", &[3; 4096]] { + OpenOptions::new() + .append(true) + .open(&path) + .unwrap() + .write_all(bytes) + .unwrap(); + assert_eq!(log_info(&path).ident, ident); + } +} + +/// A watched run the engine has not seen yet, so whatever the host reports is a change. +fn unseen(run: &str) -> (RunId, Summary) { + let summary = Summary { + started_at: None, + state: RunState::Unreconciled { + detail: "unseen".into(), + }, + log_len: None, + notify_len: 0, + cleanup: None, + }; + (run.into(), summary) +} + +#[test] +fn change_feed_isolates_unreadable_intent() { + let dir = Directory::new(); + let host = host(&dir); + fs::create_dir(dir.0.join("runs/bad")).unwrap(); + fs::write(dir.0.join("runs/bad/launch.json"), "{").unwrap(); + fs::create_dir(dir.0.join("runs/good")).unwrap(); + let Response::Changes { runs } = host.handle(Request::Changes { + watch: vec![unseen("bad"), unseen("good")], + follow_logs: vec![], + wait_ms: 0, + }) else { + panic!() + }; + assert!(matches!( + runs.iter().find(|(run, _)| run == "bad").unwrap().1.state, + RunState::InvalidData { .. } + )); + assert!(runs.iter().any(|(run, _)| run == "good")); +} + +#[test] +fn starting_run_recovery_backs_off_and_preserves_the_staged_script() { + use std::os::unix::fs::PermissionsExt; + let dir = Directory::new(); + let binary = dir.0.join("fake-host"); + fs::write(&binary, "#!/bin/sh\nprintf x >> \"$2/attempts\"\n").unwrap(); + fs::set_permissions(&binary, fs::Permissions::from_mode(0o700)).unwrap(); + let host = Host::new(dir.0.clone(), binary).unwrap(); + let intent = LaunchIntent { + run: "retry".into(), + digest: sha(b"true\n"), + run_sh: "true\n".into(), + env: Default::default(), + source: None, + cancel_sh: None, + }; + assert!(matches!( + host.handle(Request::Launch(intent.clone())), + Response::Launch { .. } + )); + let run = dir.0.join("runs/retry"); + until(Duration::from_secs(2), || { + fs::read(run.join("attempts")).is_ok_and(|bytes| bytes == b"x") + }); + let script = fs::metadata(run.join("run.sh")) + .unwrap() + .modified() + .unwrap(); + for _ in 0..5 { + assert!(matches!( + host.handle(Request::Launch(intent.clone())), + Response::Launch { .. } + )); + } + assert_eq!(fs::read(run.join("attempts")).unwrap(), b"x"); + assert!(!run.join("started").exists()); + std::thread::sleep(Duration::from_millis(1050)); + host.handle(Request::Launch(intent)); + until(Duration::from_secs(2), || { + fs::read(run.join("attempts")).is_ok_and(|bytes| bytes == b"xx") + }); + assert_eq!( + fs::metadata(run.join("run.sh")) + .unwrap() + .modified() + .unwrap(), + script + ); +} + +#[test] +fn change_feed_returns_on_change_timeout_and_ignores_unfollowed_log_growth() { + let dir = Directory::new(); + let host = Arc::new(host(&dir)); + let request = |watch| Request::Changes { + watch, + follow_logs: vec![], + wait_ms: 0, + }; + assert_eq!( + host.handle(request(vec![])), + Response::Changes { runs: vec![] } + ); + fs::create_dir(dir.0.join("runs/r1")).unwrap(); + let Response::Changes { runs } = host.handle(request(vec![unseen("r1")])) else { + panic!(); + }; + assert_eq!(runs[0].1.log_len, None); + fs::write(dir.0.join("runs/r1/log"), b"hello").unwrap(); + let start = Instant::now(); + assert_eq!( + host.handle(Request::Changes { + watch: runs.clone(), + follow_logs: vec![], + wait_ms: 40 + }), + Response::Changes { runs: vec![] } + ); + assert!(start.elapsed() >= Duration::from_millis(35)); + let feed = { + let host = host.clone(); + std::thread::spawn(move || { + host.handle(Request::Changes { + watch: runs, + follow_logs: vec![], + wait_ms: 2000, + }) + }) + }; + std::thread::sleep(Duration::from_millis(50)); + fs::write(dir.0.join("runs/r1/notify"), b"done").unwrap(); + assert!( + matches!(feed.join().unwrap(), Response::Changes { runs } if runs[0].1.notify_len == 4) + ); +} + +#[test] +fn blob_retries_are_checked_and_only_verified_blobs_are_published() { + let dir = Directory::new(); + let host = host(&dir); + let bytes = b"a source archive"; + let hash = sha(bytes); + assert_eq!( + host.handle(Request::HasBlob { + sha: hash.clone(), + len: bytes.len() as u64 + }), + Response::HasBlob { present: false } + ); + for (offset, chunk) in [(0, &bytes[..5]), (0, &bytes[..5]), (5, &bytes[5..])] { + assert!(matches!( + host.handle(Request::PutBlob { + sha: hash.clone(), + offset, + bytes: chunk.to_vec() + }), + Response::PutBlob { .. } + )); + } + assert!(matches!( + host.handle(Request::PutBlob { + sha: hash.clone(), + offset: 0, + bytes: b"wrong".to_vec() + }), + Response::Error { + code: ErrorCode::Conflict, + .. + } + )); + assert_eq!( + host.handle(Request::HasBlob { + sha: hash.clone(), + len: 1 + }), + Response::HasBlob { present: false } + ); + assert!(!dir.0.join("sources").join(&hash).exists()); + assert_eq!( + host.handle(Request::HasBlob { + sha: hash.clone(), + len: bytes.len() as u64 + }), + Response::HasBlob { present: true } + ); + assert_eq!(fs::read(dir.0.join("sources").join(&hash)).unwrap(), bytes); + let wrong_hash = sha(b"different"); + host.handle(Request::PutBlob { + sha: wrong_hash.clone(), + offset: 0, + bytes: bytes.to_vec(), + }); + assert_eq!( + host.handle(Request::HasBlob { + sha: wrong_hash.clone(), + len: bytes.len() as u64 + }), + Response::HasBlob { present: false } + ); + assert!(!dir.0.join("sources").join(wrong_hash).exists()); +} + +#[test] +fn legacy_paths_are_validated_and_dir_pages_use_the_same_identity() { + for path in ["/scratch/user/orx", "~/orx/runs/a", "$HOME/.orx/runs/a"] { + assert!(legacy::directory(path).unwrap().is_absolute()); + } + for path in [ + "", + "relative/path", + "/tmp/../etc", + "~/../etc", + "/tmp/a;whoami", + "/tmp/$(id)", + "/tmp/a b", + "/tmp//a", + "/tmp/a/", + ] { + assert!(legacy::directory(path).is_err(), "{path}"); + } + let dir = Directory::new(); + let host = host(&dir); + fs::write(dir.0.join("log"), b"legacy log").unwrap(); + let target = LogTarget::Dir(dir.0.to_str().unwrap().into()); + let request = |ident| Request::ReadLog { + target: target.clone(), + file: LogFile::Log, + ident, + range: ByteRange { start: 0, end: 100 }, + anchor: None, + }; + let Response::ReadLog { + page: + LogPage::Data { + ident, + bytes, + eof: true, + .. + }, + } = host.handle(request(None)) + else { + panic!(); + }; + assert_eq!(bytes, b"legacy log"); + fs::write(dir.0.join("replacement"), b"changed").unwrap(); + fs::rename(dir.0.join("replacement"), dir.0.join("log")).unwrap(); + assert!(matches!( + host.handle(request(Some(ident))), + Response::ReadLog { + page: LogPage::Reset { .. } + } + )); + assert!(matches!( + host.handle(Request::ReadLog { + target: LogTarget::Dir("/tmp/../etc".into()), + file: LogFile::Log, + ident: None, + range: ByteRange { start: 0, end: 1 }, + anchor: None, + }), + Response::Error { + code: ErrorCode::InvalidRequest, + .. + } + )); +} + +#[test] +fn legacy_cancel_terminates_a_real_group_without_rewriting_receipts() { + let dir = Directory::new(); + let mut command = Command::new("/bin/sh"); + command + .arg("-c") + .arg("touch ready; sleep 60 & wait") + .current_dir(&dir.0) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()); + unsafe { + command.pre_exec(|| { + if libc::setsid() == -1 { + Err(std::io::Error::last_os_error()) + } else { + Ok(()) + } + }); + } + let group = Group(command.spawn().unwrap()); + until(Duration::from_secs(3), || dir.0.join("ready").exists()); + fs::write(dir.0.join("pid"), group.0.id().to_string()).unwrap(); + fs::write(dir.0.join("exit_code"), b"").unwrap(); + let before: Vec<_> = fs::read_dir(&dir.0) + .unwrap() + .map(|entry| { + let path = entry.unwrap().path(); + (path.clone(), fs::read(path).unwrap()) + }) + .collect(); + assert!(legacy::inspect(&dir.0).unwrap().receipt_unreadable); + assert_eq!( + legacy::cancel(&dir.0, None, None).unwrap(), + LegacyCancelOutcome::GroupGone + ); + for (path, bytes) in before { + assert_eq!(fs::read(path).unwrap(), bytes); + } + assert!(!platform::process(group.0.id()).is_ok_and(|p| p.live())); +} + +#[test] +fn hello_and_self_verification_match_the_binary() { + let dir = Directory::new(); + let host = host(&dir); + let hash = sha(&fs::read(env!("CARGO_BIN_EXE_orx-host")).unwrap()); + assert!( + matches!(host.handle(Request::Hello { proto: PROTOCOL_VERSION }), Response::Hello { binary_sha, .. } if binary_sha == hash) + ); + assert!(matches!( + host.handle(Request::Hello { proto: 0 }), + Response::Error { + code: ErrorCode::Unsupported, + .. + } + )); + assert!(Command::new(env!("CARGO_BIN_EXE_orx-host")) + .args(["verify-self", &hash]) + .status() + .unwrap() + .success()); + let output = Command::new(env!("CARGO_BIN_EXE_orx-host")) + .args(["verify-self", "wrong"]) + .output() + .unwrap(); + assert!(!output.status.success()); +} + +#[test] +fn source_staging_resumes_and_launch_intent_cannot_be_replaced() { + let dir = Directory::new(); + let source = Directory::new(); + fs::write(source.0.join("input"), b"source data").unwrap(); + let archive = Command::new("tar") + .args(["-cf", "-", "-C"]) + .arg(&source.0) + .arg("input") + .output() + .unwrap(); + assert!(archive.status.success()); + let hash = sha(&archive.stdout); + let host = host(&dir); + let script = "cat repo/input"; + let request = || { + Request::Launch(LaunchIntent { + run: "staged".into(), + digest: sha(script.as_bytes()), + run_sh: script.into(), + env: Default::default(), + source: Some(hash.clone()), + cancel_sh: None, + }) + }; + // An unpinned (or swept) source fails the launch, so the client stages it again. + assert!(matches!( + host.handle(request()), + Response::Error { + code: ErrorCode::NotFound, + .. + } + )); + assert!(!dir.0.join("runs/staged/started").exists()); + host.handle(Request::PutBlob { + sha: hash.clone(), + offset: 0, + bytes: archive.stdout.clone(), + }); + assert_eq!( + host.handle(Request::HasBlob { + sha: hash.clone(), + len: archive.stdout.len() as u64 + }), + Response::HasBlob { present: true } + ); + assert_eq!( + host.handle(Request::PinSource { + run: "staged".into(), + sha: hash.clone(), + }), + Response::PinSource { pinned: true } + ); + assert!(matches!(host.handle(request()), Response::Launch { .. })); + until(Duration::from_secs(5), || { + dir.0.join("runs/staged/exit.json").exists() + }); + assert_eq!( + fs::read(dir.0.join("runs/staged/log")).unwrap(), + b"source data" + ); + assert!(matches!( + host.handle(request()), + Response::Launch { + summary: Summary { + started_at: Some(started_at), + state: RunState::Exited { .. }, + .. + } + } if Some(started_at) == orx_host::wrapper::started_at(&dir.0.join("runs/staged")) + )); + assert!(matches!( + host.handle(Request::Launch(LaunchIntent { + run: "staged".into(), + digest: sha(b"other"), + run_sh: "exit 99".into(), + env: Default::default(), + source: Some(hash), + cancel_sh: None, + })), + Response::Error { + code: ErrorCode::Conflict, + .. + } + )); + assert_eq!( + fs::read_to_string(dir.0.join("runs/staged/run.sh")).unwrap(), + script + ); +} + +#[test] +fn legacy_pid_files_cannot_overflow_into_a_different_signal_target() { + let dir = Directory::new(); + for pid in ["0", "1", "4294967295", "not-a-pid"] { + fs::write(dir.0.join("pid"), pid).unwrap(); + assert_eq!(legacy::inspect(&dir.0).unwrap().pid, None); + assert_eq!( + legacy::cancel(&dir.0, None, None).unwrap(), + LegacyCancelOutcome::GroupGone + ); + } +} + +#[test] +fn legacy_inspection_keeps_a_zombie_leader_live_while_its_group_runs() { + let dir = Directory::new(); + let child = Command::new("/bin/sh") + .args(["-c", "sleep 60 & exit 0"]) + .process_group(0) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .unwrap(); + let group = Group(child); + let pid = group.0.id(); + fs::write(dir.0.join("pid"), pid.to_string()).unwrap(); + until(Duration::from_secs(3), || { + let mut info = unsafe { std::mem::zeroed::() }; + let result = unsafe { + libc::waitid( + libc::P_PID, + pid, + &mut info, + libc::WEXITED | libc::WNOHANG | libc::WNOWAIT, + ) + }; + assert_eq!(result, 0); + unsafe { info.si_pid() != 0 } + }); + assert!(legacy::inspect(&dir.0).unwrap().alive); + assert_eq!( + legacy::cancel(&dir.0, None, None).unwrap(), + LegacyCancelOutcome::GroupGone + ); + assert!(!legacy::inspect(&dir.0).unwrap().alive); +} + +#[test] +fn receipt_read_errors_keep_their_type_and_recover() { + let root = Directory::new(); + let host = host(&root); + let dir = root.0.join("runs/errors"); + fs::create_dir(&dir).unwrap(); + let path = dir.join("exit.json"); + for bytes in [b"{".as_slice(), br#"{"reason":"future"}"#] { + fs::write(&path, bytes).unwrap(); + assert!(matches!( + orx_host::wrapper::state(&dir).unwrap(), + RunState::InvalidData { .. } + )); + } + fs::remove_file(&path).unwrap(); + fs::create_dir(&path).unwrap(); + assert!(matches!( + orx_host::wrapper::state(&dir).unwrap(), + RunState::Unreachable { .. } + )); + let Response::Changes { runs } = host.handle(Request::Changes { + watch: vec![unseen("errors")], + follow_logs: vec![], + wait_ms: 0, + }) else { + panic!() + }; + assert!(matches!(runs[0].1.state, RunState::Unreachable { .. })); + fs::remove_dir(&path).unwrap(); + let receipt = ExitReceipt { + finished_at: None, + code: Some(0), + signal: None, + reason: ExitReason::Exited, + processes: vec![], + outcome: CancelOutcome::Verified, + }; + orx_host::publish(&path, &receipt).unwrap(); + assert_eq!( + orx_host::wrapper::state(&dir).unwrap(), + RunState::Exited { receipt } + ); +} + +#[test] +fn matching_launch_key_adopts_the_accepted_intent_during_staging() { + let root = Directory::new(); + let host = host(&root); + let dir = root.0.join("runs/adopt"); + fs::create_dir(&dir).unwrap(); + let accepted = LaunchIntent { + run: "adopt".into(), + digest: sha(b"accepted"), + run_sh: "printf '%s' \"$TOKEN\"".into(), + env: [("TOKEN".into(), "accepted".into())].into(), + source: None, + cancel_sh: Some("true".into()), + }; + orx_host::publish(&dir.join("launch.json"), &accepted).unwrap(); + let mut retry = accepted.clone(); + retry.run_sh = "touch duplicate".into(); + retry.env.insert("TOKEN".into(), "changed".into()); + retry.cancel_sh = Some("false".into()); + retry.source = Some(sha(b"different source")); + assert!(matches!( + host.handle(Request::Launch(retry)), + Response::Launch { .. } + )); + until(Duration::from_secs(5), || dir.join("exit.json").exists()); + assert_eq!(fs::read(dir.join("log")).unwrap(), b"accepted"); + assert_eq!( + orx_host::read_json::(&dir.join("launch.json")).unwrap(), + accepted + ); + assert_eq!(fs::read_to_string(dir.join("cancel.sh")).unwrap(), "true"); + assert!(!dir.join("duplicate").exists()); +} + +#[test] +fn source_pinning_respects_cross_process_launch_ownership() { + let root = Directory::new(); + let host = host(&root); + let bytes = vec![42; 2 << 20]; + let sha = sha(&bytes); + fs::write(root.0.join("sources").join(&sha), &bytes).unwrap(); + let dir = root.0.join("runs/pin-lock"); + fs::create_dir(&dir).unwrap(); + let mut owner = Group(Command::new("python3").arg("-c").arg( + "import fcntl,pathlib,sys,time; d=pathlib.Path(sys.argv[1]); f=open(d/'launch.lock','w'); fcntl.lockf(f,fcntl.LOCK_EX); (d/'locked').touch();\nwhile not (d/'release').exists(): time.sleep(.01)" + ).arg(&dir).process_group(0).spawn().unwrap()); + until(Duration::from_secs(3), || dir.join("locked").exists()); + let pin = || Request::PinSource { + run: "pin-lock".into(), + sha: sha.clone(), + }; + assert!(matches!( + host.handle(pin()), + Response::Error { + code: ErrorCode::Busy, + .. + } + )); + assert!(!dir.join("source.tar").exists()); + fs::write(dir.join("release"), "").unwrap(); + assert!(owner.0.wait().unwrap().success()); + assert_eq!(host.handle(pin()), Response::PinSource { pinned: true }); + assert_eq!(fs::read(dir.join("source.tar")).unwrap(), bytes); +} diff --git a/crates/orx-host/tests/ssh.rs b/crates/orx-host/tests/ssh.rs new file mode 100644 index 000000000..f6af0cf79 --- /dev/null +++ b/crates/orx-host/tests/ssh.rs @@ -0,0 +1,997 @@ +// Separate test crate; commands inherit the terminal environment. +#![allow(clippy::disallowed_methods)] +#![cfg(unix)] +mod common; +use common::until; +use orx_host::{platform, read_json, wrapper}; +use orx_host_proto::*; +use orx_test_support::Sshd; +use std::collections::BTreeMap; +use std::fs::{self, File}; +use std::io::BufReader; +use std::os::unix::fs::PermissionsExt; +use std::os::unix::process::CommandExt; +use std::path::PathBuf; +use std::process::{Child, ChildStdin, Command, Stdio}; +use std::sync::mpsc::{self, Receiver}; +use std::thread::{self, JoinHandle}; +use std::time::{Duration, Instant}; + +struct Remote { + server: Sshd, + child: Child, + input: Option, + replies: Receiver>>, + reader: Option>, + next_id: u64, +} + +impl Remote { + fn new() -> Self { + let server = Sshd::start().unwrap(); + let bin = server.home().join("bin"); + fs::create_dir(&bin).unwrap(); + let stderr = File::create(server.home().join("serve.stderr")).unwrap(); + let command = format!( + "ORX_TEST_FAST_STOPS=1 PATH='{}':\"$PATH\" exec '{}' serve --root '{}'", + bin.display(), + env!("CARGO_BIN_EXE_orx-host"), + server.home().join("host").display() + ); + let mut child = Command::new("ssh") + .args(server.ssh_args()) + .arg(command) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(stderr) + .spawn() + .unwrap(); + let input = child.stdin.take(); + let mut stdout = BufReader::new(child.stdout.take().unwrap()); + let (tx, replies) = mpsc::channel(); + let reader = thread::spawn(move || loop { + match read_frame::>(&mut stdout) { + Ok(Some(reply)) => { + if tx.send(Ok(reply)).is_err() { + break; + } + } + Ok(None) => break, + Err(error) => { + let _ = tx.send(Err(error)); + break; + } + } + }); + let mut remote = Self { + server, + child, + input, + replies, + reader: Some(reader), + next_id: 1, + }; + assert!(matches!( + remote.request(Request::Hello { + proto: PROTOCOL_VERSION + }), + Response::Hello { .. } + )); + remote + } + fn root(&self) -> PathBuf { + self.server.home().join("host") + } + fn send(&mut self, body: Request) -> u64 { + let id = self.next_id; + self.next_id += 1; + write_frame(self.input.as_mut().unwrap(), &Message { id, body }).unwrap(); + id + } + fn receive(&self) -> Message { + self.replies + .recv_timeout(Duration::from_secs(40)) + .unwrap_or_else(|error| { + panic!( + "{error}: {}", + fs::read_to_string(self.server.home().join("serve.stderr")).unwrap() + ) + }) + .unwrap() + } + fn request(&mut self, body: Request) -> Response { + let id = self.send(body); + let reply = self.receive(); + assert_eq!(reply.id, id); + assert!( + !matches!(reply.body, Response::Error { .. }), + "{:?}", + reply.body + ); + reply.body + } + fn shim(&self, name: &str, script: &str) { + let path = self.server.home().join("bin").join(name); + fs::write(&path, format!("#!/bin/sh\n{script}\n")).unwrap(); + fs::set_permissions(path, fs::Permissions::from_mode(0o700)).unwrap(); + } + fn launch(&mut self, run: &str, script: &str) -> Summary { + let Response::Launch { summary } = self.request(Request::Launch(LaunchIntent { + run: run.into(), + digest: orx_host::sha(script.as_bytes()), + run_sh: script.into(), + env: BTreeMap::new(), + source: None, + cancel_sh: None, + })) else { + panic!(); + }; + summary + } + fn finish(&mut self, run: &str, mut summary: Summary) -> ExitReceipt { + let deadline = Instant::now() + Duration::from_secs(20); + loop { + if let RunState::Exited { receipt } = summary.state { + return receipt; + } + assert!(Instant::now() < deadline, "{summary:?}"); + let Response::Changes { runs } = self.request(Request::Changes { + watch: vec![(run.into(), summary.clone())], + follow_logs: vec![run.into()], + wait_ms: 2000, + }) else { + panic!(); + }; + if let Some((_, changed)) = runs.into_iter().next() { + summary = changed; + } + } + } +} +impl Drop for Remote { + fn drop(&mut self) { + if let Ok(runs) = fs::read_dir(self.root().join("runs")) { + for run in runs.flatten() { + if let Ok(identity) = read_json::(&run.path().join("wrapper.json")) + { + if platform::alive(&identity).unwrap_or(false) { + let _ = wrapper::cancel(&run.path()); + let _ = wrapper::cleanup(&run.path()); + let deadline = Instant::now() + Duration::from_secs(5); + while platform::alive(&identity).unwrap_or(false) + && Instant::now() < deadline + { + thread::sleep(Duration::from_millis(20)); + } + } + } + } + } + self.input = None; + let end = Instant::now() + Duration::from_secs(3); + while self.child.try_wait().unwrap().is_none() && Instant::now() < end { + thread::sleep(Duration::from_millis(10)); + } + if self.child.try_wait().unwrap().is_none() { + let _ = self.child.kill(); + } + let _ = self.child.wait(); + if let Some(reader) = self.reader.take() { + reader.join().unwrap(); + } + } +} + +#[test] +fn run_feed_paged_logs_and_double_fork_cancel_over_real_ssh() { + let mut remote = Remote::new(); + let script = r#"printf 'first\n' +python3 - <<'PY' +import os,time +if os.fork() == 0: + os.setsid() + if os.fork() != 0: os._exit(0) + with open('escaped.pid.tmp','w') as f: f.write(str(os.getpid())) + os.rename('escaped.pid.tmp','escaped.pid') + while True: time.sleep(1) +while not os.path.exists('escaped.pid'): time.sleep(0.01) +PY +printf 'second\n' +touch ready +sleep 60 +"#; + let summary = remote.launch("run1", script); + until(Duration::from_secs(5), || { + remote.root().join("runs/run1/ready").exists() + }); + let pid: u32 = fs::read_to_string(remote.root().join("runs/run1/escaped.pid")) + .unwrap() + .parse() + .unwrap(); + let process = platform::process(pid).unwrap(); + let Response::Changes { runs } = remote.request(Request::Changes { + watch: vec![("run1".into(), summary)], + follow_logs: vec!["run1".into()], + wait_ms: 1000, + }) else { + panic!(); + }; + assert_eq!(runs.len(), 1); + assert!(matches!(runs[0].1.state, RunState::Running)); + assert_eq!(runs[0].1.log_len, Some(13)); + let Response::ReadLog { + page: LogPage::Reset { info: Some(info) }, + } = remote.request(Request::ReadLog { + target: LogTarget::Run("run1".into()), + file: LogFile::Log, + ident: None, + range: ByteRange { + start: u64::MAX - 1, + end: u64::MAX, + }, + anchor: None, + }) + else { + panic!(); + }; + let mut actual = vec![]; + for start in (0..info.len).step_by(4) { + let Response::ReadLog { + page: LogPage::Data { bytes, .. }, + } = remote.request(Request::ReadLog { + target: LogTarget::Run("run1".into()), + file: LogFile::Log, + ident: Some(info.ident.clone()), + range: ByteRange { + start, + end: start + 4, + }, + anchor: None, + }) + else { + panic!(); + }; + actual.extend(bytes); + } + assert_eq!(actual, b"first\nsecond\n"); + assert_eq!( + remote.request(Request::Cancel { run: "run1".into() }), + Response::Cancel { + outcome: CancelAck::Accepted + } + ); + let receipt = remote.finish("run1", runs[0].1.clone()); + assert_eq!(receipt.reason, ExitReason::Cancelled); + assert!(receipt.processes.is_empty()); + assert_eq!(receipt.outcome, CancelOutcome::Verified); + assert!(!platform::process(pid).is_ok_and(|p| p.starttime == process.starttime && p.live())); +} + +#[test] +fn entire_256_mib_log_is_identical_in_shuffled_random_access_pages_over_ssh() { + let mut remote = Remote::new(); + let script = "python3 - <<'PY'\nimport sys\nblock=bytearray(bytes(range(256))*4096)\nfor i in range(256):\n block[:8]=i.to_bytes(8,'little')\n sys.stdout.buffer.write(block)\nPY\n"; + let summary = remote.launch("large", script); + assert_eq!(remote.finish("large", summary).code, Some(0)); + let Response::ReadLog { + page: LogPage::Reset { info: Some(info) }, + } = remote.request(Request::ReadLog { + target: LogTarget::Run("large".into()), + file: LogFile::Log, + ident: None, + range: ByteRange { + start: u64::MAX - 1, + end: u64::MAX, + }, + anchor: None, + }) + else { + panic!(); + }; + assert_eq!(info.len, 256 * 1024 * 1024); + let mut pages: Vec = (0..256).collect(); + let mut seed = 0x12345678u64; + for n in (1..pages.len()).rev() { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + pages.swap(n, seed as usize % (n + 1)); + } + let mut expected: Vec = (0..MAX_PAGE_LEN).map(|offset| offset as u8).collect(); + for batch in pages.chunks(4) { + let mut pending = Vec::new(); + for &page in batch { + let start = page * MAX_PAGE_LEN; + let id = remote.send(Request::ReadLog { + target: LogTarget::Run("large".into()), + file: LogFile::Log, + ident: Some(info.ident.clone()), + range: ByteRange { + start, + end: start + MAX_PAGE_LEN, + }, + anchor: if start >= 64 { + Some(std::array::from_fn(|i| (start - 64 + i as u64) as u8)) + } else { + None + }, + }); + pending.push((id, page)); + } + while !pending.is_empty() { + let response = remote.receive(); + let index = pending + .iter() + .position(|(id, _)| *id == response.id) + .unwrap(); + let (_, page) = pending.swap_remove(index); + let Response::ReadLog { + page: LogPage::Data { + bytes, eof, start, .. + }, + } = response.body + else { + panic!("page {page}"); + }; + assert_eq!(start, page * MAX_PAGE_LEN); + assert_eq!(bytes.len() as u64, MAX_PAGE_LEN); + expected[..8].copy_from_slice(&page.to_le_bytes()); + assert!(bytes == expected, "page {page}"); + assert_eq!(eof, page == 255); + } + } + let start = info.len - 17; + assert!( + matches!(remote.request(Request::ReadLog { target: LogTarget::Run("large".into()), file: LogFile::Log, ident: Some(info.ident), range: ByteRange { start, end: start + MAX_PAGE_LEN }, anchor: None }), Response::ReadLog { page: LogPage::Data { bytes, eof: true, .. } } if bytes.len() == 17) + ); +} + +#[test] +fn control_lane_multiplexes_with_feed_and_exec_is_bounded_over_ssh() { + let mut remote = Remote::new(); + let feed = remote.send(Request::Changes { + watch: vec![], + follow_logs: vec![], + wait_ms: 500, + }); + let hello = remote.send(Request::Hello { + proto: PROTOCOL_VERSION, + }); + let reply = remote.receive(); + assert_eq!(reply.id, hello); + assert!(matches!(reply.body, Response::Hello { .. })); + assert_eq!(remote.receive().id, feed); + let Response::Exec { result } = remote.request(Request::Exec { + command: "cat; head -c 300000 /dev/zero; head -c 20000 /dev/zero >&2".into(), + stdin: b"input".to_vec(), + timeout_ms: 2000, + }) else { + panic!(); + }; + assert_eq!(result.code, Some(0)); + assert_eq!(result.stdout.len(), 256 * 1024); + assert_eq!(result.stderr.len(), 16 * 1024); + assert!(result.stdout.starts_with(b"input")); + assert!(result.stdout_truncated && result.stderr_truncated); + let Response::Exec { result } = remote.request(Request::Exec { + command: "sleep 60 & wait".into(), + stdin: vec![], + timeout_ms: 50, + }) else { + panic!(); + }; + assert!(result.timed_out); +} + +#[test] +fn eof_stops_feed_and_exec_without_leaving_command_children() { + let mut remote = Remote::new(); + let marker = remote.server.home().join("exec.pid"); + remote.send(Request::Exec { + command: format!("echo $$ > '{}'; sleep 60 & wait", marker.display()), + stdin: vec![], + timeout_ms: 60_000, + }); + remote.send(Request::Changes { + watch: vec![], + follow_logs: vec![], + wait_ms: 30_000, + }); + until(Duration::from_secs(3), || { + fs::read_to_string(&marker).is_ok_and(|text| text.trim().parse::().is_ok()) + }); + let pid = fs::read_to_string(marker).unwrap().trim().parse().unwrap(); + let identity = platform::process(pid).unwrap(); + let start = Instant::now(); + remote.input = None; + until(Duration::from_secs(3), || { + remote.child.try_wait().unwrap().is_some() + }); + assert!(start.elapsed() < Duration::from_secs(3)); + assert!(!platform::process(pid).is_ok_and(|p| p.starttime == identity.starttime && p.live())); +} + +#[test] +fn fake_slurm_uses_receipts_and_keeps_unknown_jobs_unreconciled() { + let mut remote = Remote::new(); + remote.shim("sbatch", "cat >/dev/null; printf '123;cluster\\n'"); + remote.shim("squeue", "exit 0"); + remote.shim("sacct", "printf '123|job|COMPLETED|0:0|\\n'"); + let intent = LaunchIntent { + run: "job".into(), + digest: orx_host::sha(b"true"), + run_sh: "true".into(), + env: Default::default(), + source: None, + cancel_sh: None, + }; + assert_eq!( + remote.request(Request::SlurmSubmit { + intent, + directives: "#SBATCH --job-name=job\n".into() + }), + Response::SlurmSubmit { job: "123".into() } + ); + let Response::SlurmQueue { jobs } = remote.request(Request::SlurmQueue { + names: vec!["job".into()], + legacy: Vec::new(), + }) else { + panic!(); + }; + assert!(matches!( + jobs[0].summary.state, + RunState::Unreconciled { .. } + )); + remote.request(Request::Changes { + watch: vec![], + follow_logs: vec![], + wait_ms: 0, + }); + assert!(!remote.root().join("runs/job/started").exists()); + let receipt = ExitReceipt { + finished_at: None, + code: Some(0), + signal: None, + reason: ExitReason::Exited, + processes: vec![], + outcome: CancelOutcome::Verified, + }; + orx_host::publish(&remote.root().join("runs/job/exit.json"), &receipt).unwrap(); + remote.shim("squeue", "echo 'controller down' >&2; exit 1"); + let Response::SlurmQueue { jobs, .. } = remote.request(Request::SlurmQueue { + names: vec!["job".into()], + legacy: Vec::new(), + }) else { + panic!(); + }; + assert_eq!(jobs[0].summary.state, RunState::Exited { receipt }); + remote.shim("sacct", "exit 1"); + let Response::SlurmQueue { jobs } = remote.request(Request::SlurmQueue { + names: vec!["unknown".into()], + legacy: Vec::new(), + }) else { + panic!(); + }; + assert_eq!( + jobs[0].summary.state, + RunState::Unreconciled { + detail: "scheduler unanswered: controller down".into() + } + ); +} + +#[test] +fn slurm_submit_resumes_staging_cut_short_after_the_batch_script() { + let mut remote = Remote::new(); + remote.shim("sbatch", "cat >/dev/null; printf '123;cluster\\n'"); + let submit = || Request::SlurmSubmit { + intent: LaunchIntent { + run: "job".into(), + digest: orx_host::sha(b"true"), + run_sh: "true".into(), + env: Default::default(), + source: None, + cancel_sh: None, + }, + directives: "#SBATCH --job-name=job\n".into(), + }; + let submitted = Response::SlurmSubmit { job: "123".into() }; + assert_eq!(remote.request(submit()), submitted); + let dir = remote.root().join("runs/job"); + for interrupted in [ + &["slurm.job", "run.sh"][..], + &["slurm.job", "run.sh", "launch.json"][..], + ] { + for staged in interrupted { + fs::remove_file(dir.join(staged)).unwrap(); + } + assert_eq!(remote.request(submit()), submitted); + assert!(dir.join("run.sh").exists()); + } + fs::remove_file(dir.join("launch.json")).unwrap(); + let id = remote.send(submit()); + let reply = remote.receive(); + assert_eq!(reply.id, id); + assert!(matches!( + reply.body, + Response::Error { + code: ErrorCode::Io, + .. + } + )); + assert!(dir.join("job.sbatch").exists()); + assert_eq!(fs::read_to_string(dir.join("slurm.job")).unwrap(), "123"); +} + +#[test] +fn legacy_container_cancel_checks_generation_and_both_kill_results() { + let mut remote = Remote::new(); + let dir = remote.server.home().join("legacy"); + fs::create_dir(&dir).unwrap(); + fs::write(dir.join("pid"), "99999999").unwrap(); + let container = ContainerRun { + reference: "fixture".into(), + id: "abc123".into(), + started_at: "generation".into(), + run_dir: "/tmp/container-run".into(), + }; + let exec_marker = remote.server.home().join("docker-exec"); + remote.shim("docker", &format!("if [ \"$1\" = container ]; then printf 'abc123|generation|running\\n'; else printf '%s' \"$*\" > '{}'; fi", exec_marker.display())); + let request = |container| Request::CancelLegacy { + dir: dir.to_str().unwrap().into(), + container: Some(container), + }; + assert_eq!( + remote.request(request(container.clone())), + Response::CancelLegacy { + outcome: LegacyCancelOutcome::GroupGone + } + ); + let called = fs::read_to_string(&exec_marker).unwrap(); + assert!( + called.contains("identity") + && called.contains("kill -KILL") + && called.contains("/tmp/container-run") + ); + fs::remove_file(&exec_marker).unwrap(); + remote.shim("docker", "printf 'abc123|new-generation|running\\n'"); + assert_eq!( + remote.request(request(container.clone())), + Response::CancelLegacy { + outcome: LegacyCancelOutcome::GroupGone + } + ); + assert!(!exec_marker.exists()); + let host_group = common::Group( + Command::new("sleep") + .arg("60") + .process_group(0) + .spawn() + .unwrap(), + ); + fs::write(dir.join("pid"), host_group.0.id().to_string()).unwrap(); + remote.shim("docker", "printf 'abc123|generation|paused\\n'"); + let id = remote.send(request(container.clone())); + let response = remote.receive(); + assert_eq!(response.id, id); + assert!(matches!(response.body, Response::Error { message, .. } + if message == "Container 'fixture' is paused. Unpause it to complete cancellation.")); + remote.shim("docker", "if [ \"$1\" = container ]; then printf 'abc123|generation|running\\n'; else echo 'Process identity changed; refusing to signal it' >&2; exit 1; fi"); + let id = remote.send(request(container)); + let response = remote.receive(); + assert_eq!(response.id, id); + assert!(matches!(response.body, Response::Error { message, .. } + if message == "Process identity changed; refusing to signal it")); + assert!(platform::process(host_group.0.id()).unwrap().live()); + assert_eq!( + fs::read_to_string(dir.join("pid")).unwrap(), + host_group.0.id().to_string() + ); + fs::write(dir.join("pid"), "99999999").unwrap(); + drop(host_group); + assert_eq!(fs::read_dir(&dir).unwrap().count(), 1); + let quoted_dir = remote.server.home().join("container's run"); + fs::create_dir("ed_dir).unwrap(); + let container = ContainerRun { + reference: "fixture".into(), + id: "abc123".into(), + started_at: "generation".into(), + run_dir: quoted_dir.to_str().unwrap().into(), + }; + remote.shim("docker", "if [ \"$1\" = container ]; then printf 'abc123|generation|running\\n'; else shift 3; exec \"$@\"; fi"); + assert_eq!( + remote.request(request(container)), + Response::CancelLegacy { + outcome: LegacyCancelOutcome::GroupGone + } + ); + assert!(quoted_dir.join("cancel").exists()); +} + +#[test] +fn completed_run_reports_lingering_and_cleanup_through_the_feed_over_ssh() { + let mut remote = Remote::new(); + let summary = remote.launch("daemon", r#"python3 - <<'PY' +import os, sys, time +if os.fork() == 0: + os.setsid() + code = "import os,signal,time; signal.signal(signal.SIGTERM,signal.SIG_IGN); f=open('daemon.pid.tmp','w'); f.write(str(os.getpid())); f.close(); os.rename('daemon.pid.tmp','daemon.pid'); time.sleep(60)" + os.execv(sys.executable, [sys.executable, '-c', code]) +while not os.path.exists('daemon.pid'): time.sleep(0.01) +PY +exit 0 +"#); + let receipt = remote.finish("daemon", summary); + let pid = fs::read_to_string(remote.root().join("runs/daemon/daemon.pid")) + .unwrap() + .parse() + .unwrap(); + assert!(receipt.processes.iter().any(|process| process.pid == pid)); + assert_eq!(receipt.reason, ExitReason::Exited); + assert_eq!( + remote.request(Request::Cleanup { + run: "daemon".into() + }), + Response::Cleanup { + outcome: CleanupAck::Accepted + } + ); + let mut watch = Summary { + started_at: None, + state: RunState::Exited { receipt }, + log_len: None, + notify_len: 0, + cleanup: None, + }; + let deadline = Instant::now() + Duration::from_secs(5); + loop { + assert!(Instant::now() < deadline); + let Response::Changes { runs } = remote.request(Request::Changes { + watch: vec![("daemon".into(), watch.clone())], + follow_logs: vec![], + wait_ms: 1000, + }) else { + panic!(); + }; + if let Some((_, changed)) = runs.into_iter().next() { + watch = changed; + } + if watch.cleanup.is_some() { + break; + } + } + assert_eq!( + watch.cleanup.as_ref().unwrap().outcome, + CancelOutcome::Verified + ); + assert!(matches!( + watch.state, + RunState::Exited { + receipt: ExitReceipt { + code: Some(0), + reason: ExitReason::Exited, + .. + } + } + )); + let identity: ProcessIdentity = + read_json(&remote.root().join("runs/daemon/wrapper.json")).unwrap(); + until(Duration::from_secs(3), || { + !platform::alive(&identity).unwrap() + }); + assert!(!platform::process(pid).is_ok_and(|process| process.live())); +} + +#[test] +fn slurm_accounting_uses_recorded_ids_and_an_explicit_history_window() { + let mut remote = Remote::new(); + remote.shim( + "sbatch", + "printf '%s' \"$*\" > \"$HOME/sbatch-args\"; cat >/dev/null; printf '123\\n'", + ); + remote.shim("squeue", "exit 0"); + remote.shim( + "sacct", + r#"printf '%s\n' "$*" >> "$HOME/sacct-args" +case " $* " in +*' --jobs=123 '*) printf '123|historical|PREEMPTED|1:0\n';; +*' --name=unrecorded '*) printf '456|unrecorded|NODE_FAIL|1:0\n';; +esac"#, + ); + remote.request(Request::SlurmSubmit { + intent: LaunchIntent { + run: "historical".into(), + digest: orx_host::sha(b"true"), + run_sh: "true".into(), + env: Default::default(), + source: None, + cancel_sh: None, + }, + directives: String::new(), + }); + let launch = remote.root().join("runs/historical/launch.json"); + let accepted = std::time::UNIX_EPOCH + Duration::from_secs(1_577_934_245); + File::options() + .write(true) + .open(&launch) + .unwrap() + .set_times(fs::FileTimes::new().set_modified(accepted)) + .unwrap(); + assert!(fs::read_to_string(remote.server.home().join("sbatch-args")) + .unwrap() + .contains("--no-requeue")); + let query = || Request::SlurmQueue { + names: vec!["historical".into()], + legacy: vec![], + }; + let Response::SlurmQueue { jobs, .. } = remote.request(query()) else { + panic!() + }; + assert_eq!((&*jobs[0].job, &*jobs[0].state), ("123", "PREEMPTED")); + let arguments = fs::read_to_string(remote.server.home().join("sacct-args")).unwrap(); + let start = arguments + .split_whitespace() + .find_map(|arg| arg.strip_prefix("--starttime=")) + .unwrap(); + let timestamp = Command::new("python3").args([ + "-c", "import datetime,sys; print(int(datetime.datetime.strptime(sys.argv[1], '%Y-%m-%dT%H:%M:%S').timestamp()))", start, + ]).output().unwrap(); + assert!(timestamp.status.success()); + assert_eq!( + String::from_utf8(timestamp.stdout).unwrap().trim(), + "1577934245" + ); + + assert!(matches!( + jobs[0].summary.state, + RunState::Unreconciled { .. } + )); + let Response::SlurmQueue { jobs, .. } = remote.request(Request::SlurmQueue { + names: vec!["unrecorded".into()], + legacy: vec![], + }) else { + panic!() + }; + assert_eq!((&*jobs[0].job, &*jobs[0].state), ("456", "NODE_FAIL")); + remote.shim("sacct", "exit 1"); + thread::sleep(Duration::from_millis(150)); + let Response::SlurmQueue { jobs, .. } = remote.request(query()) else { + panic!() + }; + assert_eq!((&*jobs[0].job, &*jobs[0].state), ("123", "PREEMPTED")); + assert!( + matches!(&jobs[0].summary.state, RunState::Failed { reason } if reason == "scheduler PREEMPTED; no receipt") + ); + let retained = remote.root().join("runs/historical/slurm-terminal.json"); + let bytes = fs::read(&retained).unwrap(); + let command = format!( + "ORX_TEST_FAST_STOPS=1 PATH='{}':\"$PATH\" exec '{}' serve --root '{}'", + remote.server.home().join("bin").display(), + env!("CARGO_BIN_EXE_orx-host"), + remote.root().display(), + ); + let mut replacement = Command::new("ssh") + .args(remote.server.ssh_args()) + .arg(command) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .spawn() + .unwrap(); + write_frame( + replacement.stdin.as_mut().unwrap(), + &Message { + id: 1, + body: query(), + }, + ) + .unwrap(); + let reply: Message = + read_frame(&mut BufReader::new(replacement.stdout.take().unwrap())) + .unwrap() + .unwrap(); + let Response::SlurmQueue { jobs } = reply.body else { + panic!() + }; + assert_eq!((&*jobs[0].job, &*jobs[0].state), ("123", "PREEMPTED")); + assert!( + matches!(&jobs[0].summary.state, RunState::Failed { reason } if reason == "scheduler PREEMPTED; no receipt") + ); + replacement.stdin.take(); + assert!(replacement.wait().unwrap().success()); + assert_eq!(fs::read(&retained).unwrap(), bytes); + remote.shim("squeue", "printf '123|historical|RUNNING\\n'"); + remote.request(query()); + assert!(!retained.exists()); + remote.shim("squeue", "exit 0"); + let Response::SlurmQueue { jobs, .. } = remote.request(query()) else { + panic!() + }; + assert_eq!(jobs[0].state, "UNKNOWN"); +} + +#[test] +fn queued_slurm_intent_keeps_its_original_executable_and_directives() { + let mut remote = Remote::new(); + remote.shim("sbatch", "cat > \"$HOME/accepted-batch\"; printf '123\\n'"); + let intent = LaunchIntent { + run: "pinned".into(), + digest: orx_host::sha(b"true"), + run_sh: "true".into(), + env: Default::default(), + source: None, + cancel_sh: None, + }; + remote.request(Request::SlurmSubmit { + intent: intent.clone(), + directives: "#SBATCH --mem=1G\n".into(), + }); + let dir = remote.root().join("runs/pinned"); + let batch = fs::read_to_string(dir.join("job.sbatch")) + .unwrap() + .replace(env!("CARGO_BIN_EXE_orx-host"), "/queued/orx-host-original"); + fs::write(dir.join("job.sbatch"), &batch).unwrap(); + let mut retry = intent; + retry.run_sh = "false".into(); + retry.env.insert("CHANGED".into(), "value".into()); + remote.request(Request::SlurmSubmit { + intent: retry.clone(), + directives: "invalid regenerated directives".into(), + }); + assert_eq!(fs::read_to_string(dir.join("job.sbatch")).unwrap(), batch); + assert!(batch.contains("/queued/orx-host-original")); + assert_eq!(fs::read(dir.join("run.sh")).unwrap(), b"true"); + retry.digest = orx_host::sha(b"other"); + let id = remote.send(Request::SlurmSubmit { + intent: retry, + directives: String::new(), + }); + let response = remote.receive(); + assert_eq!(response.id, id); + assert!(matches!( + response.body, + Response::Error { + code: ErrorCode::Conflict, + .. + } + )); +} + +#[test] +fn cancelled_slurm_receipts_keep_querying_until_scheduler_proves_teardown() { + let mut remote = Remote::new(); + remote.shim( + "squeue", + "echo query >> \"$HOME/queries\"; printf '123|survivor|RUNNING\\n'", + ); + remote.shim("sacct", "exit 1"); + let dir = remote.root().join("runs/survivor"); + fs::create_dir_all(&dir).unwrap(); + fs::write(dir.join("slurm.job"), "123\n").unwrap(); + fs::write(dir.join("job.sbatch"), "batch").unwrap(); + fs::write(dir.join("started"), "survivor:tag\n").unwrap(); + let mut identity = platform::identity(std::process::id()).unwrap(); + identity.node = "compute-node".into(); + orx_host::publish(&dir.join("wrapper.json"), &identity).unwrap(); + orx_host::publish( + &dir.join("exit.json"), + &ExitReceipt { + finished_at: None, + code: None, + signal: None, + reason: ExitReason::Cancelled, + processes: vec![Survivor { + pid: 123456, + starttime: 1, + state: "D".into(), + }], + outcome: CancelOutcome::Survivors, + }, + ) + .unwrap(); + let bytes = fs::read(dir.join("exit.json")).unwrap(); + let query = || Request::SlurmQueue { + names: vec!["survivor".into()], + legacy: vec![], + }; + for _ in 0..2 { + let Response::SlurmQueue { jobs } = remote.request(query()) else { + panic!() + }; + assert_eq!(jobs[0].state, "RUNNING"); + assert!(jobs[0].summary.cleanup.is_none()); + } + assert_eq!( + fs::read_to_string(remote.server.home().join("queries")) + .unwrap() + .lines() + .count(), + 2 + ); + for (queue, accounting, settled) in [ + ("exit 1", "exit 0", false), + ("exit 0", "exit 1", false), + ("printf 'malformed\\n'", "exit 0", false), + ("exit 0", "printf 'malformed\\n'", false), + ("printf '123|survivor|UNKNOWN\\n'", "exit 0", false), + ("exit 0", "exit 0", true), + ("printf '123|survivor|COMPLETING\\n'", "exit 0", false), + ("printf '123|survivor|CANCELLED\\n'", "exit 1", true), + ("exit 1", "exit 1", true), + ] { + let _ = fs::remove_file(dir.join("cleanup.json")); + remote.shim("squeue", queue); + remote.shim("sacct", accounting); + let Response::SlurmQueue { jobs } = remote.request(query()) else { + panic!() + }; + assert_eq!( + jobs[0].summary.cleanup.is_some(), + settled, + "{queue} / {accounting}" + ); + if settled { + let proof = jobs[0].summary.cleanup.as_ref().unwrap(); + assert!(proof.processes.is_empty()); + assert_eq!(proof.outcome, CancelOutcome::Verified); + assert_eq!(wrapper::cleanup_result(&dir).unwrap().as_ref(), Some(proof)); + } + assert_eq!(fs::read(dir.join("exit.json")).unwrap(), bytes); + } + remote.shim("squeue", "exit 99"); + let Response::SlurmQueue { jobs } = remote.request(query()) else { + panic!() + }; + assert_eq!(jobs[0].state, "RECEIPT"); +} + +#[test] +fn malformed_slurm_ids_skip_only_the_affected_rows() { + let mut remote = Remote::new(); + remote.shim( + "squeue", + "printf '%s\\n' \"$*\" >> \"$HOME/queries\"; printf '123|healthy|RUNNING\\n'", + ); + remote.shim("sacct", "exit 0"); + for (run, job) in [("healthy", "123"), ("empty", ""), ("malformed", "bad;456")] { + let dir = remote.root().join("runs").join(run); + fs::create_dir_all(&dir).unwrap(); + fs::write(dir.join("slurm.job"), job).unwrap(); + } + let legacy_dir = remote.server.home().join("legacy"); + fs::create_dir(&legacy_dir).unwrap(); + let legacy = SlurmLegacyRun { + run: "legacy".into(), + job: "not-a-job".into(), + dir: legacy_dir.to_string_lossy().into_owned(), + }; + let names = vec![ + "empty".into(), + "malformed".into(), + "legacy".into(), + "healthy".into(), + ]; + let Response::SlurmQueue { jobs } = remote.request(Request::SlurmQueue { + names, + legacy: vec![legacy.clone()], + }) else { + panic!() + }; + assert_eq!(jobs.len(), 1); + assert_eq!(jobs[0].run, "healthy"); + assert_eq!(jobs[0].state, "RUNNING"); + let arguments = fs::read_to_string(remote.server.home().join("queries")).unwrap(); + assert_eq!(arguments.lines().count(), 1); + assert!(arguments.contains("--jobs=123")); + assert!(!arguments.contains("--name=")); + let Response::SlurmQueue { jobs } = remote.request(Request::SlurmQueue { + names: vec!["empty".into(), "malformed".into(), "legacy".into()], + legacy: vec![legacy], + }) else { + panic!() + }; + assert!(jobs.is_empty()); + assert_eq!( + fs::read_to_string(remote.server.home().join("queries")).unwrap(), + arguments + ); +} diff --git a/crates/orx-host/tests/wrapper.rs b/crates/orx-host/tests/wrapper.rs new file mode 100644 index 000000000..3384ff1fb --- /dev/null +++ b/crates/orx-host/tests/wrapper.rs @@ -0,0 +1,1033 @@ +// Separate test crate; commands inherit the terminal environment. +#![allow(clippy::disallowed_methods)] +#![cfg(unix)] +mod common; +use common::{until, Directory, Run}; +use orx_host::{platform, publish, read_json, wrapper}; +use orx_host_proto::*; +use std::fs; +use std::os::unix::process::CommandExt; +use std::process::Command; +use std::time::Duration; + +// An unreadable environment makes every concurrent same-UID scan incomplete. +static CANCELLATIONS: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +#[test] +fn cancellation_before_started_never_spawns_the_payload() { + let mut run = Run::new("touch should-not-run\n"); + assert_eq!( + wrapper::cancel(&run.directory.0).unwrap(), + CancelAck::Accepted + ); + run.spawn(); + run.wait(); + assert!(!run.directory.0.join("started").exists()); + assert!(!run.directory.0.join("should-not-run").exists()); + let receipt = wrapper::receipt(&run.directory.0).unwrap().unwrap(); + assert_eq!(receipt.reason, ExitReason::Cancelled); + assert_eq!(receipt.outcome, CancelOutcome::Verified); + assert!(receipt.processes.is_empty()); + + let mut run = Run::new("touch should-not-run\n"); + fs::write(run.directory.0.join("cancel.req"), "").unwrap(); + run.spawn(); + run.wait(); + assert!(!run.directory.0.join("started").exists()); + assert!(!run.directory.0.join("should-not-run").exists()); + assert_eq!( + wrapper::receipt(&run.directory.0).unwrap().unwrap().outcome, + CancelOutcome::Verified + ); +} + +#[test] +fn process_group_leader_can_be_a_wrapper() { + let mut run = Run::new("printf completed\n"); + run.children.push( + Command::new(env!("CARGO_BIN_EXE_orx-host")) + .args(["wrap", run.directory.0.to_str().unwrap()]) + .process_group(0) + .spawn() + .unwrap(), + ); + run.wait(); + assert_eq!( + wrapper::receipt(&run.directory.0).unwrap().unwrap().code, + Some(0) + ); +} + +#[test] +fn term_is_delivered_once_and_checkpoint_completion_returns_before_the_grace_deadline() { + let _serial = CANCELLATIONS.lock().unwrap(); + let mut run = Run::new( + r#"exec python3 - <<'PY' +import signal, time +def checkpoint(signum, frame): + with open('signals', 'a') as f: f.write('TERM\n') + time.sleep(0.35) + raise SystemExit(0) +signal.signal(signal.SIGTERM, checkpoint) +open('ready', 'w').close() +while True: time.sleep(1) +PY +"#, + ); + run.children.push( + Command::new(env!("CARGO_BIN_EXE_orx-host")) + .env("ORX_TEST_FAST_STOPS", "0") + .args(["wrap", run.directory.0.to_str().unwrap()]) + .spawn() + .unwrap(), + ); + run.ready(); + until(Duration::from_secs(3), || { + run.directory.0.join("ready").exists() + }); + let start = std::time::Instant::now(); + assert_eq!( + wrapper::cancel(&run.directory.0).unwrap(), + CancelAck::Accepted + ); + run.wait(); + assert!( + start.elapsed() < Duration::from_secs(3), + "cancel took {:?}", + start.elapsed() + ); + assert_eq!( + fs::read_to_string(run.directory.0.join("signals")).unwrap(), + "TERM\n" + ); + let receipt = wrapper::receipt(&run.directory.0).unwrap().unwrap(); + assert_eq!(receipt.code, Some(0)); + assert_eq!(receipt.outcome, CancelOutcome::Verified); +} + +#[test] +fn transient_request_and_receipt_errors_keep_the_wrapper_and_lock_alive() { + let mut run = Run::new("touch ready\nwhile [ ! -f release ]; do sleep 0.01; done\nexit 7\n"); + run.spawn(); + run.ready(); + until(Duration::from_secs(3), || { + run.directory.0.join("ready").exists() + }); + let cancel = run.directory.0.join("cancel.req"); + std::os::unix::fs::symlink("cancel.req", &cancel).unwrap(); + let identity: ProcessIdentity = read_json(&run.directory.0.join("wrapper.json")).unwrap(); + platform::signal(&platform::process(identity.pid).unwrap(), libc::SIGUSR1).unwrap(); + std::thread::sleep(Duration::from_millis(150)); + let alive = platform::alive(&identity).unwrap(); + let locked = orx_host::lock(&run.directory.0.join("wrapper.lock")) + .unwrap() + .is_none(); + fs::remove_file(cancel).unwrap(); + assert!(alive && locked); + let receipt_path = run.directory.0.join("exit.json"); + fs::create_dir(&receipt_path).unwrap(); + fs::write(run.directory.0.join("release"), "").unwrap(); + std::thread::sleep(Duration::from_millis(250)); + let alive = platform::alive(&identity).unwrap(); + let locked = orx_host::lock(&run.directory.0.join("wrapper.lock")) + .unwrap() + .is_none(); + fs::remove_dir(receipt_path).unwrap(); + assert!(alive && locked); + run.wait(); + let receipt = wrapper::receipt(&run.directory.0).unwrap().unwrap(); + assert_eq!(receipt.code, Some(7)); + assert_eq!(receipt.reason, ExitReason::Exited); + assert!(!fs::read_dir(&run.directory.0).unwrap().any(|entry| entry + .unwrap() + .file_name() + .to_string_lossy() + .contains(".tmp-"))); +} + +#[test] +fn deleting_the_run_directory_ends_retries_without_signalling_the_payload() { + let mut run = Run::new("echo $$ > payload.pid\nexec sleep 60\n"); + let diagnostics = fs::File::create(run.directory.0.join("wrapper.log")).unwrap(); + run.children.push( + Command::new(env!("CARGO_BIN_EXE_orx-host")) + .env("ORX_TEST_FAST_STOPS", "1") + .arg("wrap") + .arg(&run.directory.0) + .stderr(diagnostics.try_clone().unwrap()) + .spawn() + .unwrap(), + ); + run.ready(); + until(Duration::from_secs(3), || { + fs::read_to_string(run.directory.0.join("payload.pid")) + .is_ok_and(|pid| pid.trim().parse::().is_ok()) + }); + let pid = fs::read_to_string(run.directory.0.join("payload.pid")) + .unwrap() + .trim() + .parse() + .unwrap(); + let payload = platform::process(pid).unwrap(); + run.extra.push(payload.clone()); + std::os::unix::fs::symlink("cancel.req", run.directory.0.join("cancel.req")).unwrap(); + let identity: ProcessIdentity = read_json(&run.directory.0.join("wrapper.json")).unwrap(); + platform::signal(&platform::process(identity.pid).unwrap(), libc::SIGUSR1).unwrap(); + until(Duration::from_secs(3), || { + diagnostics.metadata().unwrap().len() > 0 + }); + fs::remove_dir_all(&run.directory.0).unwrap(); + until(Duration::from_secs(2), || { + run.children[0].try_wait().unwrap().is_some() + }); + run.children[0].wait().unwrap(); + assert!(!platform::alive(&identity).unwrap()); + let current = platform::process(pid).unwrap(); + assert_eq!(current.starttime, payload.starttime); + assert!(current.live()); +} + +#[test] +fn duplicate_wrapper_loser_writes_nothing() { + let mut run = Run::new("printf once >> count\nwhile [ ! -f release ]; do sleep 0.01; done\n"); + run.spawn(); + run.ready(); + let identity = fs::read(run.directory.0.join("wrapper.json")).unwrap(); + let started = fs::read(run.directory.0.join("started")).unwrap(); + run.spawn(); + until(Duration::from_secs(2), || { + run.children[1].try_wait().unwrap().is_some() + }); + assert_eq!( + fs::read(run.directory.0.join("wrapper.json")).unwrap(), + identity + ); + assert_eq!(fs::read(run.directory.0.join("started")).unwrap(), started); + fs::write(run.directory.0.join("release"), "").unwrap(); + run.wait(); + assert_eq!( + fs::read_to_string(run.directory.0.join("count")).unwrap(), + "once" + ); + let before = fs::read_dir(&run.directory.0).unwrap().count(); + run.spawn(); + run.wait(); + assert_eq!(fs::read_dir(&run.directory.0).unwrap().count(), before); + let receipt = wrapper::receipt(&run.directory.0).unwrap().unwrap(); + assert_eq!(receipt.code, Some(0)); +} + +#[test] +fn crash_windows_never_reexecute_after_started() { + let _serial = CANCELLATIONS.lock().unwrap(); + let mut run = Run::new("printf once >> count\n"); + assert_eq!( + wrapper::state(&run.directory.0).unwrap(), + RunState::Starting + ); + let mut forged = platform::identity(std::process::id()).unwrap(); + forged.starttime += 1; + publish(&run.directory.0.join("wrapper.json"), &forged).unwrap(); + assert_eq!( + wrapper::state(&run.directory.0).unwrap(), + RunState::Starting + ); + run.spawn(); + run.wait(); + fs::remove_file(run.directory.0.join("exit.json")).unwrap(); + until(Duration::from_secs(5), || { + matches!( + wrapper::state(&run.directory.0).unwrap(), + RunState::Lost { .. } + ) + }); + run.spawn(); + run.wait(); + assert_eq!( + fs::read_to_string(run.directory.0.join("count")).unwrap(), + "once" + ); + assert!(!run.directory.0.join("exit.json").exists()); +} + +#[test] +fn malformed_receipts_remain_unreconciled() { + let dir = Directory::new(); + for bytes in ["", "{", "{}", "null", "{\"code\":"] { + fs::write(dir.0.join("exit.json"), bytes).unwrap(); + assert!(matches!( + wrapper::state(&dir.0).unwrap(), + RunState::InvalidData { .. } + )); + } +} + +#[test] +fn wrapper_gone_with_a_complete_empty_tag_scan_is_lost() { + let _serial = CANCELLATIONS.lock().unwrap(); + let dir = Directory::new(); + fs::write(dir.0.join("started"), "test:nonexistent").unwrap(); + let mut identity = platform::identity(std::process::id()).unwrap(); + identity.starttime += 1; + publish(&dir.0.join("wrapper.json"), &identity).unwrap(); + assert_eq!(wrapper::cancel(&dir.0).unwrap(), CancelAck::WrapperGone); + until(Duration::from_secs(5), || { + matches!(wrapper::state(&dir.0).unwrap(), RunState::Lost { .. }) + }); +} + +#[test] +fn payload_exiting_during_cancel_publishes_one_receipt() { + let _serial = CANCELLATIONS.lock().unwrap(); + let mut run = Run::new("touch ready\ntrap 'exit 0' TERM\nwhile :; do sleep 0.1; done\n"); + run.spawn(); + run.ready(); + until(Duration::from_secs(3), || { + run.directory.0.join("ready").exists() + }); + assert_eq!( + wrapper::cancel(&run.directory.0).unwrap(), + CancelAck::Accepted + ); + assert_eq!( + wrapper::cancel(&run.directory.0).unwrap(), + CancelAck::Accepted + ); + run.wait(); + let receipt = wrapper::receipt(&run.directory.0).unwrap().unwrap(); + assert_eq!(receipt.reason, ExitReason::Cancelled); + assert!(receipt.processes.is_empty()); + assert_eq!(receipt.outcome, CancelOutcome::Verified); + let bytes = fs::read(run.directory.0.join("exit.json")).unwrap(); + assert_eq!( + wrapper::cancel(&run.directory.0).unwrap(), + if receipt.outcome == CancelOutcome::Verified { + CancelAck::NotRunning + } else { + CancelAck::WrapperGone + } + ); + run.spawn(); + run.wait(); + assert_eq!(fs::read(run.directory.0.join("exit.json")).unwrap(), bytes); + assert_eq!( + fs::read_dir(&run.directory.0) + .unwrap() + .filter(|entry| entry + .as_ref() + .unwrap() + .file_name() + .to_string_lossy() + .contains("tmp-")) + .count(), + 0 + ); +} + +#[test] +fn detached_double_fork_and_nohup_children_are_killed() { + let _serial = CANCELLATIONS.lock().unwrap(); + let mut run = Run::new( + r#"python3 - <<'PY' +import os, time +if os.fork() == 0: + os.setsid() + if os.fork() != 0: os._exit(0) + with open('escaped.pid.tmp', 'w') as f: f.write(str(os.getpid())) + os.rename('escaped.pid.tmp', 'escaped.pid') + while True: time.sleep(1) +while not os.path.exists('escaped.pid'): time.sleep(0.01) +PY +nohup sleep 60 >/dev/null 2>&1 & +echo $! > nohup.pid +touch ready +sleep 60 +"#, + ); + run.spawn(); + run.ready(); + until(Duration::from_secs(5), || { + run.directory.0.join("ready").exists() + }); + for file in ["escaped.pid", "nohup.pid"] { + let pid: u32 = fs::read_to_string(run.directory.0.join(file)) + .unwrap() + .trim() + .parse() + .unwrap(); + run.extra.push(platform::process(pid).unwrap()); + } + assert_eq!( + wrapper::cancel(&run.directory.0).unwrap(), + CancelAck::Accepted + ); + run.wait(); + for process in &run.extra { + assert!(!platform::process(process.pid) + .is_ok_and(|found| found.starttime == process.starttime && found.live())); + } + let receipt: ExitReceipt = read_json(&run.directory.0.join("exit.json")).unwrap(); + assert_eq!(receipt.outcome, CancelOutcome::Verified); + assert_eq!(receipt.reason, ExitReason::Cancelled); +} + +#[cfg(feature = "test-hooks")] +#[test] +fn real_crashes_before_and_after_exactly_once_marker() { + use std::process::Command; + for point in [ + "wrapper_locked", + "wrapper_identity", + "wrapper_started", + "wrapper_spawned", + "wrapper_before_receipt", + "wrapper_receipt", + ] { + let mut run = Run::new("printf once >> count\n"); + let status = Command::new(env!("CARGO_BIN_EXE_orx-host")) + .arg("wrap") + .arg(&run.directory.0) + .env("ORX_TEST_CRASH_AT", point) + .status() + .unwrap(); + assert!(!status.success()); + let started = run.directory.0.join("started").exists(); + run.spawn(); + run.wait(); + let count = fs::read_to_string(run.directory.0.join("count")).unwrap_or_default(); + assert!( + count == "once" || (started && count.is_empty()), + "{point}: {count}" + ); + } +} + +#[cfg(target_os = "linux")] +#[test] +fn an_older_nondumpable_same_uid_process_does_not_block_verified_cancellation() { + let _serial = CANCELLATIONS.lock().unwrap(); + let dir = Directory::new(); + let old = common::Group(Command::new("python3") + .arg("-c") + .arg("import ctypes,time; assert ctypes.CDLL(None).prctl(4,0,0,0,0)==0; open('ready','w').close(); time.sleep(60)") + .current_dir(&dir.0).process_group(0).spawn().unwrap()); + until(Duration::from_secs(3), || dir.0.join("ready").exists()); + let predecessor = platform::process(old.0.id()).unwrap(); + assert_eq!(predecessor.uid, unsafe { libc::getuid() }); + assert!(platform::scan(None, "", true) + .unwrap() + .unreadable + .contains(&predecessor.pid)); + std::thread::sleep(Duration::from_millis(30)); + let mut run = Run::new("touch ready; exec sleep 60\n"); + run.spawn(); + run.ready(); + let identity: ProcessIdentity = read_json(&run.directory.0.join("wrapper.json")).unwrap(); + assert!(predecessor.starttime < identity.starttime); + until(Duration::from_secs(3), || { + run.directory.0.join("ready").exists() + }); + assert_eq!( + wrapper::cancel(&run.directory.0).unwrap(), + CancelAck::Accepted + ); + run.wait(); + assert_eq!( + wrapper::receipt(&run.directory.0).unwrap().unwrap().outcome, + CancelOutcome::Verified + ); + assert!(platform::process(predecessor.pid).unwrap().live()); +} + +#[cfg(target_os = "linux")] +#[test] +fn unreadable_environment_requires_a_fresh_scan_after_proven_death() { + let _serial = CANCELLATIONS.lock().unwrap(); + let mut run = Run::new("touch ready; exec sleep 60"); + run.spawn(); + run.ready(); + let identity: ProcessIdentity = read_json(&run.directory.0.join("wrapper.json")).unwrap(); + std::thread::sleep(Duration::from_millis(30)); + let mut unreadable = common::Group(Command::new("python3") + .arg("-c") + .arg("import ctypes,time; assert ctypes.CDLL(None).prctl(4,0,0,0,0)==0; open('unreadable-ready','w').close(); time.sleep(60)") + .current_dir(&run.directory.0).process_group(0).spawn().unwrap()); + until(Duration::from_secs(3), || { + run.directory.0.join("unreadable-ready").exists() + }); + let process = platform::process(unreadable.0.id()).unwrap(); + assert_eq!(process.uid, unsafe { libc::getuid() }); + assert!(process.starttime >= identity.starttime); + let tag = fs::read_to_string(run.directory.0.join("started")).unwrap(); + let scan = platform::scan(Some(&identity), tag.trim(), true).unwrap(); + assert!(scan.unreadable.contains(&process.pid)); + assert!(!scan.complete); + assert_eq!( + wrapper::cancel(&run.directory.0).unwrap(), + CancelAck::Accepted + ); + run.wait(); + let receipt = wrapper::receipt(&run.directory.0).unwrap().unwrap(); + assert!( + matches!(receipt.outcome, CancelOutcome::Unverifiable { unreadable } if unreadable.contains(&process.pid)) + ); + assert!(platform::process(process.pid).unwrap().live()); + let bytes = fs::read(run.directory.0.join("exit.json")).unwrap(); + assert_eq!( + wrapper::cleanup(&run.directory.0).unwrap(), + CleanupAck::Accepted + ); + assert!( + matches!(wrapper::cleanup_result(&run.directory.0).unwrap().unwrap().outcome, + CancelOutcome::Unverifiable { unreadable } if unreadable.contains(&process.pid)) + ); + unreadable.0.kill().unwrap(); + unreadable.0.wait().unwrap(); + assert!(platform::process(process.pid).is_err()); + assert_eq!( + wrapper::cleanup(&run.directory.0).unwrap(), + CleanupAck::Accepted + ); + let proof = wrapper::cleanup_result(&run.directory.0).unwrap().unwrap(); + assert!(proof.processes.is_empty()); + assert_eq!(proof.outcome, CancelOutcome::Verified); + assert_eq!(fs::read(run.directory.0.join("exit.json")).unwrap(), bytes); +} + +#[test] +fn reboot_only_loses_a_run_after_the_exactly_once_marker() { + let run = Run::new("printf once >> count\n"); + let mut identity = platform::identity(std::process::id()).unwrap(); + identity.boot_id.push_str("-previous-boot"); + publish(&run.directory.0.join("wrapper.json"), &identity).unwrap(); + assert_eq!( + wrapper::state(&run.directory.0).unwrap(), + RunState::Starting + ); + fs::write(run.directory.0.join("started"), "test:old-tag").unwrap(); + assert_eq!( + wrapper::state(&run.directory.0).unwrap(), + RunState::Lost { + reason: "host rebooted".into() + } + ); +} + +#[test] +fn killed_wrapper_with_scrubbed_orphan_remains_unreconciled() { + let _serial = CANCELLATIONS.lock().unwrap(); + let mut run = Run::new( + r#"python3 - <<'PY' +import os, sys, time +if os.fork() == 0: + os.setsid() + if os.fork() != 0: os._exit(0) + code = "import os,time; f=open('escaped.pid.tmp','w'); f.write(str(os.getpid())); f.close(); os.rename('escaped.pid.tmp','escaped.pid'); time.sleep(60)" + os.execve(sys.executable, [sys.executable, '-c', code], {}) +while True: time.sleep(1) +PY +"#, + ); + run.spawn(); + run.ready(); + until(Duration::from_secs(5), || { + run.directory.0.join("escaped.pid").exists() + }); + let pid = fs::read_to_string(run.directory.0.join("escaped.pid")) + .unwrap() + .trim() + .parse() + .unwrap(); + let escaped = platform::process(pid).unwrap(); + run.extra.push(escaped.clone()); + let identity: ProcessIdentity = read_json(&run.directory.0.join("wrapper.json")).unwrap(); + let tag = fs::read_to_string(run.directory.0.join("started")).unwrap(); + run.extra.extend( + platform::scan(Some(&identity), tag.trim(), false) + .unwrap() + .processes, + ); + run.children[0].kill().unwrap(); + assert!(!run.children[0].wait().unwrap().success()); + assert!(matches!( + wrapper::state(&run.directory.0).unwrap(), + RunState::Unreconciled { .. } + )); + assert_eq!( + wrapper::cancel(&run.directory.0).unwrap(), + CancelAck::WrapperGone + ); + assert!(platform::process(pid) + .is_ok_and(|process| process.starttime == escaped.starttime && process.live())); + assert!(!run.directory.0.join("exit.json").exists()); +} + +#[test] +fn direct_exit_is_published_before_lingering_daemon_cleanup() { + let _serial = CANCELLATIONS.lock().unwrap(); + let mut run = Run::new( + r#"python3 - <<'PY' +import os, sys, time +if os.fork() == 0: + os.setsid() + code = "import os,signal,time; signal.signal(signal.SIGTERM,signal.SIG_IGN); f=open('daemon.pid.tmp','w'); f.write(str(os.getpid())); f.close(); os.rename('daemon.pid.tmp','daemon.pid'); time.sleep(60)" + os.execv(sys.executable, [sys.executable, '-c', code]) +while not os.path.exists('daemon.pid'): time.sleep(0.01) +PY +exit 23 +"#, + ); + run.spawn(); + until(Duration::from_secs(3), || { + run.directory.0.join("exit.json").exists() + }); + let pid = fs::read_to_string(run.directory.0.join("daemon.pid")) + .unwrap() + .parse() + .unwrap(); + let daemon = platform::process(pid).unwrap(); + run.extra.push(daemon.clone()); + let receipt = wrapper::receipt(&run.directory.0).unwrap().unwrap(); + assert_eq!( + (receipt.code, receipt.reason), + (Some(23), ExitReason::Exited) + ); + assert!(receipt.processes.iter().any(|process| process.pid == pid)); + assert!(run.children[0].try_wait().unwrap().is_none()); + assert!(matches!( + wrapper::state(&run.directory.0).unwrap(), + RunState::Exited { .. } + )); + let bytes = fs::read(run.directory.0.join("exit.json")).unwrap(); + assert_eq!( + wrapper::cleanup(&run.directory.0).unwrap(), + CleanupAck::Accepted + ); + run.wait(); + let outcome = wrapper::cleanup_result(&run.directory.0).unwrap().unwrap(); + assert_eq!(outcome.outcome, CancelOutcome::Verified); + assert!(!platform::process(pid) + .is_ok_and(|process| process.starttime == daemon.starttime && process.live())); + assert_eq!(fs::read(run.directory.0.join("exit.json")).unwrap(), bytes); +} + +#[test] +fn natural_daemon_exit_reaps_and_resolves_lingering_without_changing_the_result() { + let mut run = Run::new("bash -c 'echo $$ > daemon.pid; touch ready; while [ ! -f release ]; do sleep 0.05; done' &\nwhile [ ! -f ready ]; do sleep 0.01; done\nexit 0\n"); + run.spawn(); + until(Duration::from_secs(3), || { + run.directory.0.join("exit.json").exists() + }); + let pid = fs::read_to_string(run.directory.0.join("daemon.pid")) + .unwrap() + .trim() + .parse() + .unwrap(); + run.extra.push(platform::process(pid).unwrap()); + let receipt = fs::read(run.directory.0.join("exit.json")).unwrap(); + assert!(!wrapper::receipt(&run.directory.0) + .unwrap() + .unwrap() + .processes + .is_empty()); + fs::write(run.directory.0.join("release"), "").unwrap(); + run.wait(); + assert_eq!( + fs::read(run.directory.0.join("exit.json")).unwrap(), + receipt + ); + assert!(wrapper::cleanup_result(&run.directory.0).unwrap().is_some()); +} + +#[test] +fn a_timed_out_hook_retries_before_the_receipt_then_recovers() { + let _serial = CANCELLATIONS.lock().unwrap(); + let mut run = Run::new("touch ready; sleep 60\n"); + fs::write( + run.directory.0.join("cancel.sh"), + "echo attempt >> hook-called; [ -f hook-recovered ] || sleep 60\n", + ) + .unwrap(); + run.spawn(); + run.ready(); + until(Duration::from_secs(3), || { + run.directory.0.join("ready").exists() + }); + let start = std::time::Instant::now(); + assert_eq!( + wrapper::cancel(&run.directory.0).unwrap(), + CancelAck::Accepted + ); + until(Duration::from_secs(3), || { + fs::read(run.directory.0.join("hook-called")).is_ok_and(|bytes| bytes.len() >= 16) + }); + assert!(!run.directory.0.join("exit.json").exists()); + assert!(run.children[0].try_wait().unwrap().is_none()); + fs::write(run.directory.0.join("hook-recovered"), "").unwrap(); + run.wait(); + assert!(start.elapsed() < Duration::from_secs(3)); + let receipt = wrapper::receipt(&run.directory.0).unwrap().unwrap(); + assert_eq!(receipt.reason, ExitReason::Cancelled); + assert!(matches!( + receipt.outcome, + CancelOutcome::Unverifiable { .. } + )); +} + +#[test] +fn a_hook_prevents_lingering_from_upgrading_to_verified() { + let _serial = CANCELLATIONS.lock().unwrap(); + let mut run = Run::new("bash -c 'touch ready; while [ ! -f release ]; do sleep .01; done' &\nwhile [ ! -f ready ]; do sleep .01; done\n"); + fs::write(run.directory.0.join("cancel.sh"), "true").unwrap(); + run.spawn(); + until(Duration::from_secs(3), || { + run.directory.0.join("exit.json").exists() + }); + let receipt = fs::read(run.directory.0.join("exit.json")).unwrap(); + assert_ne!( + wrapper::receipt(&run.directory.0).unwrap().unwrap().outcome, + CancelOutcome::Verified + ); + fs::write(run.directory.0.join("release"), "").unwrap(); + run.wait(); + let cleanup = wrapper::cleanup_result(&run.directory.0).unwrap().unwrap(); + assert!(cleanup.processes.is_empty()); + assert!(matches!( + cleanup.outcome, + CancelOutcome::Unverifiable { .. } + )); + assert_eq!( + fs::read(run.directory.0.join("exit.json")).unwrap(), + receipt + ); + assert_ne!( + wrapper::cleanup(&run.directory.0).ok(), + Some(CleanupAck::NothingLingering) + ); +} + +#[test] +fn an_empty_unverifiable_receipt_does_not_skip_cleanup() { + let run = Run::new("true"); + publish( + &run.directory.0.join("exit.json"), + &ExitReceipt { + finished_at: None, + code: Some(0), + signal: None, + reason: ExitReason::Exited, + processes: vec![], + outcome: CancelOutcome::Unverifiable { unreadable: vec![] }, + }, + ) + .unwrap(); + assert_ne!( + wrapper::cleanup(&run.directory.0).ok(), + Some(CleanupAck::NothingLingering) + ); +} + +#[test] +fn slurm_wrapper_releases_the_allocation_after_the_receipt() { + let mut run = Run::new("bash -c 'echo $$ > daemon.pid; touch ready; while [ ! -f release ]; do sleep .01; done' &\nwhile [ ! -f ready ]; do sleep .01; done\n"); + run.children.push( + Command::new(env!("CARGO_BIN_EXE_orx-host")) + .env("SLURM_JOB_ID", "123") + .arg("wrap") + .arg(&run.directory.0) + .spawn() + .unwrap(), + ); + until(Duration::from_secs(3), || { + run.directory.0.join("exit.json").exists() + }); + let pid = fs::read_to_string(run.directory.0.join("daemon.pid")) + .unwrap() + .trim() + .parse() + .unwrap(); + run.extra.push(platform::process(pid).unwrap()); + run.wait(); + assert!(!wrapper::receipt(&run.directory.0) + .unwrap() + .unwrap() + .processes + .is_empty()); + fs::write(run.directory.0.join("release"), "").unwrap(); +} + +#[test] +fn node_or_boot_mismatch_never_authorizes_a_fallback_signal() { + for foreign_node in [true, false] { + let run = Run::new("sleep 60\n"); + let mut worker = Command::new("sleep").arg("60").spawn().unwrap(); + let mut identity = platform::identity(worker.id()).unwrap(); + if foreign_node { + identity.node.push_str("-elsewhere"); + } else { + identity.boot_id.push_str("-old"); + } + publish(&run.directory.0.join("wrapper.json"), &identity).unwrap(); + fs::write(run.directory.0.join("started"), "scope-test").unwrap(); + assert_eq!( + wrapper::cancel(&run.directory.0).unwrap(), + CancelAck::Accepted + ); + assert!(worker.try_wait().unwrap().is_none()); + assert!(run.directory.0.join("cancel.req").exists()); + if foreign_node { + assert_eq!( + wrapper::state(&run.directory.0).unwrap_err().kind(), + std::io::ErrorKind::NotConnected + ); + assert!(wrapper::has_live_processes(&run.directory.0).is_err()); + } else { + assert!(matches!( + wrapper::state(&run.directory.0).unwrap(), + RunState::Lost { .. } + )); + assert!(!wrapper::has_live_processes(&run.directory.0).unwrap()); + } + worker.kill().unwrap(); + worker.wait().unwrap(); + } +} + +#[test] +fn missing_log_can_appear_after_a_lookup() { + let dir = Directory::new(); + let path = dir.0.join("log"); + let range = ByteRange { start: 0, end: 100 }; + assert!(matches!( + orx_host::log::read(&path, None, &range, None).unwrap(), + LogPage::Reset { info: None } + )); + fs::write(&path, b"Traceback\n").unwrap(); + let LogPage::Data { bytes, .. } = orx_host::log::read(&path, None, &range, None).unwrap() + else { + panic!("log missing"); + }; + assert_eq!(bytes, b"Traceback\n"); +} + +#[test] +fn wrapper_receipt_records_completion_time() { + let before = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_millis() as i64; + let mut run = Run::new("exit 3\n"); + run.spawn(); + run.wait(); + let receipt = wrapper::receipt(&run.directory.0).unwrap().unwrap(); + let after = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_millis() as i64; + assert_eq!(receipt.code, Some(3)); + assert!((before..=after).contains(&receipt.finished_at.unwrap())); +} + +#[test] +fn cancellation_waits_for_a_slow_survivor_inside_the_kill_window() { + let _serial = CANCELLATIONS.lock().unwrap(); + let mut run = Run::new("touch ready; exec sleep 60"); + let hold = run.directory.0.join("hold"); + fs::write(&hold, "once").unwrap(); + run.children.push( + Command::new(env!("CARGO_BIN_EXE_orx-host")) + .env("ORX_TEST_FAST_STOPS", "1") + .env("ORX_TEST_DEFER_SIGNALS", &hold) + .arg("wrap") + .arg(&run.directory.0) + .spawn() + .unwrap(), + ); + until(Duration::from_secs(5), || { + run.directory.0.join("ready").exists() + }); + wrapper::cancel(&run.directory.0).unwrap(); + run.wait(); + let receipt = wrapper::receipt(&run.directory.0).unwrap().unwrap(); + assert_eq!(receipt.reason, ExitReason::Cancelled); + assert!(receipt.processes.is_empty()); + assert_eq!(receipt.outcome, CancelOutcome::Verified); +} + +#[test] +fn survivors_after_the_window_are_rekilled_and_the_proof_is_renewed() { + let _serial = CANCELLATIONS.lock().unwrap(); + for slurm in [false, true] { + let mut run = Run::new("touch ready; exec sleep 60"); + let hold = run.directory.0.join("hold"); + fs::write(&hold, "hold").unwrap(); + let mut command = Command::new(env!("CARGO_BIN_EXE_orx-host")); + command + .env("ORX_TEST_FAST_STOPS", "1") + .env("ORX_TEST_DEFER_SIGNALS", &hold) + .arg("wrap") + .arg(&run.directory.0); + if slurm { + command.env("SLURM_JOB_ID", "123"); + } + run.children.push(command.spawn().unwrap()); + until(Duration::from_secs(5), || { + run.directory.0.join("ready").exists() + }); + wrapper::cancel(&run.directory.0).unwrap(); + until(Duration::from_secs(5), || { + run.directory.0.join("exit.json").exists() + }); + let bytes = fs::read(run.directory.0.join("exit.json")).unwrap(); + let receipt = wrapper::receipt(&run.directory.0).unwrap().unwrap(); + assert_eq!(receipt.outcome, CancelOutcome::Survivors); + assert!(!receipt.processes.is_empty()); + if slurm { + for survivor in receipt.processes { + run.extra.push(platform::process(survivor.pid).unwrap()); + } + run.wait(); + assert!(!run.directory.0.join("cleanup.json").exists()); + } else { + until(Duration::from_secs(5), || { + wrapper::cleanup_result(&run.directory.0).unwrap().is_some() + }); + assert!(!wrapper::cleanup_result(&run.directory.0) + .unwrap() + .unwrap() + .processes + .is_empty()); + fs::remove_file(hold).unwrap(); + run.wait(); + let proof = wrapper::cleanup_result(&run.directory.0).unwrap().unwrap(); + assert!(proof.processes.is_empty()); + assert_eq!(proof.outcome, CancelOutcome::Verified); + } + assert_eq!(fs::read(run.directory.0.join("exit.json")).unwrap(), bytes); + } +} + +#[test] +fn a_dead_wrapper_reterms_receipted_survivors_even_after_their_tag_is_gone() { + let run = Run::new("true"); + let mut worker = common::Group( + Command::new("sleep") + .arg("60") + .process_group(0) + .spawn() + .unwrap(), + ); + let survivor = platform::process(worker.0.id()).unwrap().survivor(); + let mut identity = platform::identity(std::process::id()).unwrap(); + identity.starttime += 1; + publish(&run.directory.0.join("wrapper.json"), &identity).unwrap(); + fs::write(run.directory.0.join("started"), "test:no-matching-tag").unwrap(); + publish( + &run.directory.0.join("exit.json"), + &ExitReceipt { + code: None, + signal: None, + reason: ExitReason::Cancelled, + finished_at: None, + processes: vec![survivor], + outcome: CancelOutcome::Survivors, + }, + ) + .unwrap(); + assert_eq!( + wrapper::cancel(&run.directory.0).unwrap(), + CancelAck::WrapperGone + ); + until(Duration::from_secs(5), || { + worker.0.try_wait().unwrap().is_some() + }); +} + +#[test] +fn cancellation_never_replaces_a_receipt_even_without_started() { + let run = Run::new("true"); + publish( + &run.directory.0.join("exit.json"), + &ExitReceipt { + finished_at: Some(1234), + code: None, + signal: None, + reason: ExitReason::Cancelled, + processes: vec![Survivor { + pid: 123456, + starttime: 1, + state: "D".into(), + }], + outcome: CancelOutcome::Survivors, + }, + ) + .unwrap(); + let bytes = fs::read(run.directory.0.join("exit.json")).unwrap(); + assert_eq!( + wrapper::cancel(&run.directory.0).unwrap(), + CancelAck::Accepted + ); + assert_eq!(fs::read(run.directory.0.join("exit.json")).unwrap(), bytes); +} + +#[test] +fn dead_wrapper_cleanup_renews_proof_without_changing_the_receipt() { + let _serial = CANCELLATIONS.lock().unwrap(); + for reboot in [false, true] { + let run = Run::new("true"); + let mut worker = common::Group( + Command::new("sleep") + .arg("60") + .process_group(0) + .spawn() + .unwrap(), + ); + let process = platform::process(worker.0.id()).unwrap(); + let mut identity = platform::identity(std::process::id()).unwrap(); + identity.starttime += 1; + if reboot { + identity.boot_id.push_str("-previous-boot"); + } + publish(&run.directory.0.join("wrapper.json"), &identity).unwrap(); + fs::write(run.directory.0.join("started"), "test:no-matching-tag").unwrap(); + publish( + &run.directory.0.join("exit.json"), + &ExitReceipt { + finished_at: Some(1234), + code: None, + signal: None, + reason: ExitReason::Cancelled, + processes: vec![process.survivor()], + outcome: CancelOutcome::Survivors, + }, + ) + .unwrap(); + let bytes = fs::read(run.directory.0.join("exit.json")).unwrap(); + if reboot { + assert_eq!( + wrapper::cleanup(&run.directory.0).unwrap(), + CleanupAck::Accepted + ); + assert!(platform::process(process.pid).unwrap().live()); + } else { + until(Duration::from_secs(3), || { + assert!(matches!( + wrapper::state(&run.directory.0).unwrap(), + RunState::Exited { .. } + )); + wrapper::cleanup_result(&run.directory.0) + .unwrap() + .is_some_and(|proof| proof.outcome == CancelOutcome::Verified) + }); + assert!(worker.0.try_wait().unwrap().is_some()); + } + let proof = wrapper::cleanup_result(&run.directory.0).unwrap().unwrap(); + assert!(proof.processes.is_empty()); + assert_eq!(proof.outcome, CancelOutcome::Verified); + assert_eq!( + wrapper::cleanup(&run.directory.0).unwrap(), + CleanupAck::NothingLingering + ); + assert_eq!(fs::read(run.directory.0.join("exit.json")).unwrap(), bytes); + } +} diff --git a/docs/runner-stress.md b/docs/runner-stress.md new file mode 100644 index 000000000..a05f1e839 --- /dev/null +++ b/docs/runner-stress.md @@ -0,0 +1,364 @@ +# Runner stress: local chaos and sage release gate + +Run Tier 2 locally before an RC; run Tier 3 on **two disposable Linux sage boxes, +four GPUs each**. Save the RC version, seed, elapsed time, run IDs, server logs, +receipts and measurements with the release results. Failures block the RC. + +## Tier 2: real SSH, seeded faults (stable Rust) + +Prerequisites: Rust stable, OpenSSH client/server, bash, Python 3. On Ubuntu: +`sudo apt-get install -y openssh-server python3; sudo mkdir -p /run/sshd`. +On macOS the harness uses `/usr/sbin/sshd`; no Remote Login service is needed. +The harness supplies isolated keys, homes, sshd listeners and proxies. + +From the repository root: + +```sh +env -u CLAUDE_CONFIG_DIR -u CODEX_HOME cargo test --locked --bin orx -- --ignored chaos --nocapture +``` + +Default: 32 concurrent runs, at least 120 seconds of faults, then at most 60 +seconds to drain. Each seeded hold lasts 1–60 seconds, so the final hold can +overrun the requested duration by 59 seconds. Assertions run every second. +`CHAOS_SEED` accepts a decimal u64 or the printed `u64:seconds:runs` replay seed. +The composite seed overrides duration/run-count environment variables, so it alone +reproduces the launch scripts, fault order and clock jumps; OS scheduling remains real. +Replay with `CHAOS_SEED=8030613221891662191:120:32` before the command. Scale to the +200-run, six-hour soak: + +```sh +CHAOS_SEED=8030613221891662191 CHAOS_RUNS=200 CHAOS_DURATION=21600 env -u CLAUDE_CONFIG_DIR -u CODEX_HOME cargo test --locked --bin orx -- --ignored chaos --nocapture +``` + +The scheduler shuffles complete cycles of black-hole, pause, latency, bandwidth, +connection reset/refusal, sshd restart, engine SIGKILL/restart and independent +wall/monotonic clock jumps. Payloads exit nonzero, SIGKILL themselves, double-fork +through setsid and leave daemons, pin every CPU core, or produce fast 2–8 MiB +logs. The worker runs the production Runtime, SSH transport, host program and log collector. The rejected-key +alias has a run in the same Runtime and its real sshd authentication counter is +checked throughout holds, across engine restarts and clock jumps. A prelude +kills engines at the intent/fence/response/handle hooks and swaps a wrapper boot +ID after killing its wrapper and payload, requiring Lost with one notice. +SQLite captures every phase transition, including transitions between assertions; +checks enforce monotonic phase, immutable terminal phase, one terminal notice, +one payload start and stable `started`, at most two SSH clients per host, no +post-failure auth, a kept-log manifest for every terminal run with an exit receipt, +and byte equality for every collected range. A host live and continuously reachable for 35 seconds must reconcile receipts older than 35 seconds. +After the final clean reconnect, each run must reconcile within 60 seconds of that reconnect +or its receipt's publication, whichever is later. Payloads keep their natural lifetimes; +the drain is bounded by their known maximum lifetime plus 60 seconds. This is opt-in; ordinary tests include +all chaos code in CI but leave its two tests ignored. Seeded frame, receipt +and bootstrap-stub properties run in the ordinary suite. + +## Tier 3: sage boxes, per RC + +Prerequisites on each box: cgroup v2 and systemd, root/sudo, `stress-ng`, `iproute2`, +Python 3, sysstat, NVIDIA driver and `nvidia-smi`. Keep a console or separate management +route available for the network and reboot cases. Use isolated test accounts, +no valuable workloads, and an RC `orx` on the laptop. Register each SSH alias in +Compute; Connect successfully. Create a local project, then use the commands +below to create 32 experiments. Set `PROJECT` to that project's ID and `HOST` +to the sage SSH alias. +Use the same project on both boxes, in separate rounds. + +```sh +# On each sage box: +sudo apt-get install -y stress-ng iproute2 python3 sysstat +stat -fc %T /sys/fs/cgroup # cgroup2fs +nvidia-smi -L # four GPUs +# On the laptop, in the experiment checkout (include stress.sh in its source): +export HOST=sage-a PROJECT=replace-with-project-id +cat > stress.sh <<'SH' +printf 'started %s\n' "$(date -Is)" +stress-ng --cpu 1 --cpu-load 10 --timeout 10m +printf 'finished %s\n' "$(date -Is)" +SH +orx create-experiment "$PROJECT" --baseline --title 'Stress root' --run-command 'bash stress.sh' > stress-root.txt +ROOT_EXP=$(awk '$1 == "id:" {print $2}' stress-root.txt) +: > experiments.txt +for i in $(seq 1 32); do + orx create-experiment "$PROJECT" --parent "$ROOT_EXP" --title "Stress $i" --run-command 'bash stress.sh' | + awk '$1 == "id:" {print $2}' >> experiments.txt +done +test "$(wc -l < experiments.txt)" -eq 32 +while IFS= read -r exp; do orx exp run "$exp" --force --backend ssh --host "$HOST" --no-container; done < experiments.txt +orx runs "$PROJECT" +``` + +**(a) 32 concurrent runs.** Repeat on sage-b. While all 32 are running, sample +below once per second for a minute (run in a separate foreground terminal). +For idle-host overhead, repeat with `sleep 600` payloads, and keep Compute closed. + +```sh +# On the sage box; RSS is KiB, ps %CPU is lifetime average (also record interval CPU): +ps -eo pid,ppid,rss,pcpu,args | grep '[/]orx-host-.* \(serve\|wrap\)' +# Binary names contain a digest, so use full command matching for interval samples: +pids=$(pgrep -d, -f '/orx-host-[^ ]+ (serve|wrap)') +pidstat -u -r -p "$pids" 1 60 +``` + +Pass: every wrapper RSS <2048 KiB, `serve` interval CPU <0.5% of one core, +≤2 laptop SSH clients for this alias, no duplicate starts, all results correct. +In the app, inspect run status and logs. CLI launches have no subscribed chat; +for the notice check, launch from a chat and require exactly one completion in +that subscribed chat. +`orx runs "$PROJECT"` and `orx logs RUN_ID` must agree with the app and remote log. + +**(b) OOM, payload then wrapper.** On the box, create a limited cgroup using +systemd (the test account needs noninteractive sudo for the cgroup move): + +```sh +sudo systemd-run --unit=orx-payload-limit -p Delegate=yes \ + -p MemoryMax=96M -p MemorySwapMax=0 -p OOMPolicy=continue sleep infinity +``` + +Replace stress.sh with the following and set the experiment command to +`exec bash stress.sh`, so Python becomes the wrapper's direct child. Rerun it: + +```sh +cg=$(systemctl show orx-payload-limit -p ControlGroup --value) +printf '%s\n' "$$" | sudo -n tee "/sys/fs/cgroup$cg/cgroup.procs" >/dev/null +exec python3 -c 'x=bytearray(512*1024*1024)' +``` + +Pass: Failed with SIGKILL in exit.json and a matching kernel cgroup OOM record. +Then `sudo systemctl stop orx-payload-limit` on the box. +For the wrapper, start `sleep 20`, select its PID from that run's wrapper.json, +then on the box move just that wrapper into a memory-limited cgroup: + +```sh +WRAPPER_PID=replace-with-wrapper-pid +sudo systemd-run --unit=orx-wrapper-oom \ + -p Delegate=yes \ + sh -c ' + base=/sys/fs/cgroup$(awk -F: '\''$1=="0" {print $3}'\'' /proc/self/cgroup) + mkdir "$base/supervisor" + echo $$ > "$base/supervisor/cgroup.procs" + echo +memory > "$base/cgroup.subtree_control" + mkdir "$base/victim" + echo 4096 > "$base/victim/memory.max" + echo 0 > "$base/victim/memory.swap.max" + echo "$1" > "$base/victim/cgroup.procs" + # Existing pages retain their old charge; the next receipt write must fault new pages. + sleep 60 + # Keep this unit alive until the kernel OOM record has been inspected. + while :; do sleep 60; done + ' sh "$WRAPPER_PID" +``` + +Confirm the wrapper actually died and the kernel logged the cgroup OOM +(`sudo journalctl -k --since '-5 min' | grep -i oom`); match the wrapper PID +and victim cgroup. A unit stop or SIGKILL without this record is not an OOM pass. +Only after recording it, run `sudo systemctl stop orx-wrapper-oom`. Pass: Running + +Unreconciled, no respawn, no fabricated Lost/verified cancel. Abandon after +recording evidence; explicitly kill the disposable payload and descendants. + +**(c) One hour of loss/latency.** On the box, choose the interface used by the +laptop route. These commands impair that interface, including SSH. + +```sh +export IFACE=eth0 +sudo systemd-run --unit=orx-netem sh -c ' + trap '\''tc qdisc del dev "$1" root 2>/dev/null || true'\'' EXIT HUP INT TERM + tc qdisc replace dev "$1" root netem delay 2000ms loss 30% + sleep 3600 + tc qdisc del dev "$1" root + trap - EXIT HUP INT TERM +' sh "$IFACE" +``` + +Pass: contact becomes Unreachable without terminalizing live work; after the +route returns, completed runs reconcile and logs match remote bytes. No extra +payload starts, no missing/duplicate completion notices. Check both long-running +and already-finished runs. Remove the qdisc from the console if disconnected. + +**(d) Laptop sleep.** Start ten-minute runs, close the lid/suspend the laptop +for eight hours, then wake with the app open. Pass: correct phases and complete +logs within 60 seconds without a click; one completion per subscribed chat. + +**(e) Host reboot.** Start long runs and, from the box's console: + +```sh +sudo systemctl reboot +``` + +Pass: each interrupted run is Lost with reason `host rebooted`, exactly one +terminal notice, no relaunch. New runs still work after the host returns. + +**(f) Hung GPU probe.** Open Compute with a live run; stop only an actual +nvidia-smi child of the host `serve` process (check PPID/args first): + +```sh +ps -eo pid,ppid,args | grep '[n]vidia-smi' +PROBE_PID=replace-with-confirmed-probe-pid +kill -STOP "$PROBE_PID" +sleep 10 +kill -KILL "$PROBE_PID" 2>/dev/null || true +``` + +If sampling is too quick, use a private shim in the test account's noninteractive +SSH PATH. On the sage box (bash test account; back up its existing .bashrc): + +```sh +cp ~/.bashrc ~/.bashrc.orx-stress-backup +mkdir -p ~/.orx-stress-bin +printf '#!/bin/sh\nkill -STOP $$\n' > ~/.orx-stress-bin/nvidia-smi +chmod +x ~/.orx-stress-bin/nvidia-smi +{ printf 'export PATH="$HOME/.orx-stress-bin:$PATH"\n'; cat ~/.bashrc.orx-stress-backup; } > ~/.bashrc +``` + +From the laptop, `ssh "$HOST" 'command -v nvidia-smi'` must print the shim path. +Close the test account's SSH master and Connect once in the app, then open +Compute. Pass: probe times out within five seconds; payload, feed, logs and +completion remain responsive. Restore on the box and reconnect: + +```sh +mv ~/.bashrc.orx-stress-backup ~/.bashrc +rm -rf ~/.orx-stress-bin +``` + +**(g) Real password + TOTP.** Use a dedicated sshd/account with PAM password and +TOTP configured by the box administrator; the harness key fixtures do not cover +this. Disable usable keys for its alias. Tail `sudo journalctl -fu ssh` (or sshd) +in a console. Submit, leave untouched for 30 minutes, restart the app, then +Connect once and answer password/TOTP. Kill the master and wait another 30 +minutes, including laptop sleep/wake. Pass: NeedsAuth and zero background +attempts after the initial failure; one explicit Connect restores the feed; +master loss returns to NeedsAuth without a password/TOTP retry storm. Count +login connections, not public-key probes or individual MFA factors. + +**(h) Resource overload matrix.** Use a dedicated test account and a root console +outside its slice. Run each row separately with 32 active experiments; retain +`journalctl -u orx-...` and kernel logs. PyTorch with CUDA must already be installed +for the GPU row. The pressure services run as the test user in its slice: + +```sh +# Root management console on the sage box; use the account behind $HOST. +TEST_USER=orx-stress +TEST_UID=$(id -u "$TEST_USER") +SLICE=user-$TEST_UID.slice +``` + +For **each row**, sample the app's live logs and Compute view throughout pressure. +On the laptop, count clients and time a request through the existing engine: + +```sh +ps -axo comm=,args= | awk -v host="$HOST" '$1 ~ /ssh$/ && index($0,host) {print}' +timeout 35s orx compute test ssh --host "$HOST" +orx runs "$PROJECT" +``` + +Use GNU `timeout` on the Linux observing laptop; on macOS use the app's request +network timing. Pass for every row: ≤2 SSH clients for the alias; `serve` answers +within its 35-second deadline; no Done without a readable exit.json; an uncertain +outcome is Failed with evidence or Unreconciled, never fabricated success or Lost. +After pressure lifts, existing runs and logs reconcile within 60 seconds without +a new launch or duplicate start; evidence-backed terminal runs have one notice +per subscribed chat. A pressure-induced wrapper death must stay Unreconciled. + +| Pressure | Additional evidence and pass rule | +| --- | --- | +| CPU + RAM | CPU saturation and cgroup memory pressure are real; SSH and `serve` meet the common deadline. OOM victims agree with receipts/kernel logs. | +| Disk full | Run-root `df` has zero available bytes, receipt publication encounters ENOSPC, and no completion is invented; after freeing space the original receipt and exact log appear. | +| Tasks + file descriptors | The slice reaches its task limit and the hog reaches EMFILE; the existing connection survives, no reconnect/fork storm, recovery after restoring limits. | +| Four GPUs | All four GPUs report sustained utilization; CPU-side transport, status and receipt collection meet the common deadline even if GPU telemetry times out. | + +CPU and RAM (the unit's 90% memory limit keeps pressure inside the test slice): + +```sh +sudo systemd-run --unit=orx-cpu-memory --uid="$TEST_USER" --slice="$SLICE" \ + -p MemoryMax=90% -p MemorySwapMax=0 -p OOMPolicy=continue \ + stress-ng --cpu 0 --vm 2 --vm-bytes 90% --timeout 120s +sudo systemctl status orx-cpu-memory +sudo journalctl -k --since '-5 min' | grep -i oom +``` + +Disk full: reserve at least 5 GiB on the backing filesystem and use a fresh +dedicated filesystem so this cannot fill other users' filesystems. Configure its parent as the SSH remote root **before** launching this +round (from the laptop: `orx compute configure ssh --host "$HOST" --remote-root +/mnt/orx-stress`). Start `sleep 20` runs before starting the fill service. + +```sh +sudo truncate -s 4G /var/tmp/orx-stress.img +sudo mkfs.ext4 -F /var/tmp/orx-stress.img +sudo mkdir -p /mnt/orx-stress +sudo mount -o loop /var/tmp/orx-stress.img /mnt/orx-stress +sudo chown "$TEST_USER" /mnt/orx-stress +# Connect and start runs now; they create /mnt/orx-stress/engine/runs. +sudo systemd-run --unit=orx-disk-full --uid="$TEST_USER" --slice="$SLICE" sh -c ' + fill=/mnt/orx-stress/engine/.pressure-fill + trap '\''rm -f "$fill"'\'' EXIT HUP INT TERM + free=$(df -B1 --output=avail /mnt/orx-stress | tail -n 1) + fallocate -l "$((free - 1048576))" "$fill" + dd if=/dev/zero of="$fill" bs=4096 oflag=append conv=notrunc status=none || true + df -B1 /mnt/orx-stress + sleep 90 + rm -f "$fill" +' +# After recovery and evidence collection, reset the host's remote root on the laptop: +# orx compute configure ssh --host "$HOST" --clear remote-root +# Then on the box: +sudo umount /mnt/orx-stress +sudo rm /var/tmp/orx-stress.img +``` + +Tasks and descriptors: keep the root console outside the constrained slice so +restoring the limit cannot itself need a slot in that slice. Start the service +before lowering TasksMax. Its file descriptors are intentionally held open. + +```sh +cat > /tmp/orx-fd-tasks.py <<'PY' +import os, resource, threading, time +resource.setrlimit(resource.RLIMIT_NOFILE, (4096, 4096)) +fds = [] +try: + while True: + fds.append(os.open('/dev/null', os.O_RDONLY)) +except OSError as error: + print('fd pressure:', error, 'open=', len(fds), flush=True) +time.sleep(5) +try: + while True: + threading.Thread(target=time.sleep, args=(120,), daemon=True).start() +except RuntimeError as error: + print('task pressure:', error, flush=True) +time.sleep(120) +PY +sudo systemd-run --unit=orx-fd-tasks --uid="$TEST_USER" --slice="$SLICE" python3 /tmp/orx-fd-tasks.py +TASKS_BEFORE=$(systemctl show "$SLICE" -p TasksMax --value) +TASKS_NOW=$(systemctl show "$SLICE" -p TasksCurrent --value) +sudo systemctl set-property --runtime "$SLICE" TasksMax="$((TASKS_NOW + 8))" +sleep 120 +sudo systemctl set-property --runtime "$SLICE" TasksMax="$TASKS_BEFORE" +sudo systemctl stop orx-fd-tasks +sudo journalctl -u orx-fd-tasks --no-pager +rm /tmp/orx-fd-tasks.py +``` + +Four-GPU matmul (use the Python environment containing CUDA PyTorch): + +```sh +cat > /tmp/orx-gpu-pressure.py <<'PY' +import subprocess, sys, torch +assert torch.cuda.device_count() >= 4 +worker = ''' +import sys,time,torch +torch.cuda.set_device(int(sys.argv[1])) +a=torch.randn((8192,8192),device='cuda',dtype=torch.float16) +b=torch.randn_like(a); c=torch.empty_like(a) +end=time.monotonic()+120 +while time.monotonic() or --target `) + } + if (!selected.length) selected.push(...targets.filter(target => process.platform === 'darwin' || !target.includes('darwin'))) + const darwinTargets = selected.filter(target => target.includes('apple-darwin')) + const missingDarwinTarget = targets.find(target => target.includes('apple-darwin') && !selected.includes(target)) + if (darwinTargets.length && missingDarwinTarget) { + throw new Error('Universal Darwin orx-host requires both --target aarch64-apple-darwin and --target x86_64-apple-darwin') + } + const installed = spawnSync('rustup', ['target', 'list', '--installed'], { encoding: 'utf8' }) + if (installed.status !== 0) throw new Error('Missing rustup; install Rust from https://rustup.rs') + const darwin = [] + const zigbuild = spawnSync('cargo', ['zigbuild', '--help'], { stdio: 'ignore' }).status === 0 + for (const target of selected) { + if (!installed.stdout.split(/\s+/).includes(target)) throw new Error(`Missing Rust target ${target}; install with: rustup target add ${target}`) + const musl = target.endsWith('linux-musl') + if (musl && !zigbuild) throw new Error('Missing cargo-zigbuild; install with: cargo install --locked cargo-zigbuild') + if (musl && spawnSync('zig', ['version'], { stdio: 'ignore' }).status !== 0) throw new Error('Missing Zig; install Zig and put zig on PATH (https://ziglang.org/download/)') + const result = spawnSync('cargo', [musl ? 'zigbuild' : 'build', '-p', 'orx-host', '--profile', 'host', '--locked', '--target', target, '--target-dir', join(root, 'target')], { cwd: root, stdio: 'inherit' }) + if (result.status !== 0) throw new Error(`orx-host build failed for ${target}; check the compiler/linker diagnostics above`) + const source = join(root, 'target', target, 'host/orx-host') + if (target.includes('apple-darwin')) darwin.push(source) + else writeArtifact(source, `orx-host-linux-${target.split('-')[0]}`, output) + } + if (darwin.length) { + const universal = join(root, 'target/orx-host-darwin-universal') + const result = spawnSync('lipo', ['-create', ...darwin, '-output', universal], { stdio: 'inherit' }) + if (result.error?.code === 'ENOENT') throw new Error('Missing lipo; install Apple command-line tools with: xcode-select --install') + if (result.status !== 0) throw new Error('Failed to combine Darwin orx-host binaries with lipo') + writeArtifact(universal, 'orx-host-darwin-universal', output) + } +} catch (error) { + console.error(error.message) + process.exitCode = 1 +} + +function writeArtifact(source, name, output) { + const bytes = readFileSync(source) + if (!bytes.length || bytes.length > 4 * 1024 * 1024) throw new Error(`${name} must be between 1 byte and 4 MiB`) + mkdirSync(output, { recursive: true }) + copyFileSync(source, join(output, name)) + console.log(`${name}: ${bytes.length} bytes`) +} diff --git a/scripts/build-host.test.mjs b/scripts/build-host.test.mjs new file mode 100644 index 000000000..2efcf8517 --- /dev/null +++ b/scripts/build-host.test.mjs @@ -0,0 +1,52 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { execFileSync } from 'node:child_process' +import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, readdirSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join, resolve } from 'node:path' + +const script = resolve('scripts/build-host.mjs') + +test('host builder validates prerequisites and Darwin targets without checksum sidecars', { skip: process.platform === 'win32' }, () => { + const root = mkdtempSync(join(tmpdir(), 'orx-build-host-')) + try { + const bin = join(root, 'bin') + mkdirSync(bin) + const shim = name => `#!${process.execPath}\n${name}\n` + writeFileSync(join(bin, 'rustup'), shim(`console.log(process.env.INSTALLED_TARGETS || '')`), { mode: 0o755 }) + writeFileSync(join(bin, 'zig'), shim('process.exit(0)'), { mode: 0o755 }) + writeFileSync(join(bin, 'lipo'), shim(` +const fs = require('node:fs'), args = process.argv.slice(2), split = args.indexOf('-output'); +fs.writeFileSync(args[split + 1], Buffer.concat(args.slice(1, split).map(source => fs.readFileSync(source)))); +`), { mode: 0o755 }) + writeFileSync(join(bin, 'cargo'), shim(` +const fs = require('node:fs'), path = require('node:path'), args = process.argv.slice(2); +if (args.includes('--help')) process.exit(process.env.NO_ZIGBUILD ? 1 : 0); +const target = args[args.indexOf('--target') + 1]; +const dir = path.join(args[args.indexOf('--target-dir') + 1], target, 'host'); +fs.mkdirSync(dir, {recursive:true}); +fs.writeFileSync(path.join(dir, 'orx-host'), 'native stand-in'); +`), { mode: 0o755 }) + // Run a copy so the fake cargo outputs cannot replace real build products. + mkdirSync(join(root, 'scripts')) + const copy = join(root, 'scripts/build-host.mjs') + writeFileSync(copy, readFileSync(script)) + const target = 'x86_64-unknown-linux-musl' + const env = { ...process.env, PATH: `${bin}:${process.env.PATH}`, INSTALLED_TARGETS: target } + const run = (overrides, args = ['--target', target]) => execFileSync(process.execPath, [copy, ...args], { env: { ...env, ...overrides }, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }) + assert.throws(() => run({ INSTALLED_TARGETS: '' }), /rustup target add x86_64-unknown-linux-musl/) + assert.throws(() => run({ NO_ZIGBUILD: '1' }), /cargo install --locked cargo-zigbuild/) + assert.match(run({}), /orx-host-linux-x86_64: 15 bytes/) + const bytes = readFileSync(join(root, 'target/host-binaries/orx-host-linux-x86_64')) + assert.equal(bytes.toString(), 'native stand-in') + for (const darwin of ['aarch64-apple-darwin', 'x86_64-apple-darwin']) { + assert.throws(() => run({}, ['--target', darwin]), /requires both --target aarch64-apple-darwin and --target x86_64-apple-darwin/) + } + assert.match(run({ INSTALLED_TARGETS: 'aarch64-apple-darwin x86_64-apple-darwin' }, ['--target', 'aarch64-apple-darwin', '--target', 'x86_64-apple-darwin']), /orx-host-darwin-universal: 30 bytes/) + const universal = readFileSync(join(root, 'target/host-binaries/orx-host-darwin-universal')) + assert.equal(universal.toString(), 'native stand-innative stand-in') + assert.deepEqual(readdirSync(join(root, 'target/host-binaries')).sort(), ['orx-host-darwin-universal', 'orx-host-linux-x86_64']) + } finally { + rmSync(root, { recursive: true, force: true }) + } +}) diff --git a/scripts/ci-changes.mjs b/scripts/ci-changes.mjs index 7790ab8ad..b26ba7391 100644 --- a/scripts/ci-changes.mjs +++ b/scripts/ci-changes.mjs @@ -11,10 +11,10 @@ export function classifyChanges(paths) { const rust = () => Object.assign(checks, { rust: true, windows: true, linux: true, macos: true }) for (const path of paths) { if (['src/local/acp/zcode-runtime.cjs', 'src/commands/app.rs', 'agent-skills/orx-figures/assets/orx-chart.html'].includes(path)) checks.javascript = true - if (path.startsWith('.github/workflows/') || path.startsWith('.github/actions/') || path === '.github/build-setup.yml' || path.startsWith('.cargo/') || /^scripts\/ci-/.test(path)) return all() + if (path.startsWith('.github/workflows/') || path.startsWith('.github/actions/') || path === '.github/build-setup.yml' || path.startsWith('.cargo/') || /^scripts\/(?:ci-|build-host(?:\.test)?\.mjs$)/.test(path)) return all() if (/^ui\/(README\.md|project\.inlang\/README\.md)$/.test(path)) continue if (path.startsWith('ui/')) checks.frontend = true - else if (/^(src\/|tests\/|agent-skills\/|demo\/|Cargo\.(toml|lock)$|build\.rs$|SKILL\.md$|SYSTEM_PROMPT\.md$)/.test(path)) { + else if (/^(src\/|crates\/|tests\/|agent-skills\/|demo\/|Cargo\.(toml|lock)$|build\.rs$|SKILL\.md$|SYSTEM_PROMPT\.md$)/.test(path)) { rust() if (path.startsWith('agent-skills/orx-figures/assets/')) checks.chart = true } diff --git a/scripts/ci-changes.test.mjs b/scripts/ci-changes.test.mjs index e4ca72118..2974b1a01 100644 --- a/scripts/ci-changes.test.mjs +++ b/scripts/ci-changes.test.mjs @@ -13,7 +13,7 @@ test('frontend changes do not select Rust', () => { assert.deepEqual(enabled(['ui/src/App.tsx', 'ui/pnpm-lock.yaml']), ['frontend']) }) test('Rust and embedded resources select all existing Rust platforms', () => { - for (const path of ['src/main.rs', 'tests/compute_cli.rs', 'Cargo.lock', 'build.rs', 'agent-skills/orx-compute/SKILL.md', 'demo/nanochat/base/file.txt', 'SYSTEM_PROMPT.md', 'SKILL.md']) { + for (const path of ['src/main.rs', 'crates/orx-host/src/main.rs', 'tests/compute_cli.rs', 'Cargo.lock', 'build.rs', 'agent-skills/orx-compute/SKILL.md', 'demo/nanochat/base/file.txt', 'SYSTEM_PROMPT.md', 'SKILL.md']) { assert.deepEqual(enabled([path]), ['rust', 'windows', 'linux', 'macos'], path) } }) @@ -28,7 +28,7 @@ test('helper tests are independent and combine with other changes', () => { }) test('docs skip builds, workflow changes and unknown files select all', () => { assert.deepEqual(enabled(['README.md', 'docs/linux.md', 'LICENSE', '.github/readme-assets/banner.png', 'macos/DISTRIBUTION.md', 'windows/README.md', 'ui/README.md']), []) - for (const path of ['.github/workflows/ci.yml', 'scripts/ci-changes.mjs', '.cargo/config.toml', 'new-build-input']) assert.equal(enabled([path]).length, 9) + for (const path of ['.github/workflows/ci.yml', 'scripts/ci-changes.mjs', '.cargo/config.toml', 'scripts/build-host.mjs', 'scripts/build-host.test.mjs', 'new-build-input']) assert.equal(enabled([path]).length, 9) }) test('embedded chart changes also run chart tests', () => { assert.equal(classifyChanges(['agent-skills/orx-figures/assets/orx_chart.py']).chart, true) diff --git a/scripts/ci-workflows.test.mjs b/scripts/ci-workflows.test.mjs index 3bf092452..3e6450fce 100644 --- a/scripts/ci-workflows.test.mjs +++ b/scripts/ci-workflows.test.mjs @@ -252,3 +252,47 @@ test('ARM PR lanes preserve desktop lint and linking; other validation remains c } } }) + +test('release and canary host artifacts reach every source build', () => { + const builder = workflow('build-host') + assert.match(builder, /runs-on: macos-14/) + assert.match(builder, /actions\/checkout@v6/) + assert.match(builder, /actions\/upload-artifact@v7/) + assert.match(builder, /mlugg\/setup-zig@[a-f0-9]{40}/) + for (const target of ['x86_64-unknown-linux-musl', 'aarch64-unknown-linux-musl', 'x86_64-apple-darwin', 'aarch64-apple-darwin']) assert.ok(builder.includes(target)) + assert.match(builder, /run: node scripts\/build-host\.mjs/) + assert.match(builder, /name: release-host\n\s+path: target\/host-binaries/) + for (const source of [release, canary]) { + const job = source.split('\n build-host:')[1].split(/\n [a-z]/)[0] + assert.match(job, /uses: \.\/\.github\/workflows\/build-host.yml/) + assert.match(job, /source-sha:/) + } + const local = release.split('\n build-local-artifacts:')[1].split('\n custom-sign-macos-cli:')[0] + assert.match(local, /- build-host/) + assert.match(local, /Build artifacts\n\s+env:\n\s+ORX_EMBED_HOST_DIR:/) + assert.match(local, /name: release-host\n\s+path: target\/host-binaries/) + for (const job of ['ci', 'macos-build', 'linux', 'windows']) { + const section = canary.split(`\n ${job}:`)[1].split(/\n [a-z]/)[0] + assert.match(section, /needs: \[[^\n]*build-host\]/) + if (job !== 'ci') { + assert.match(section, /name: release-host\n\s+path: target\/host-binaries/) + assert.match(section, /ORX_EMBED_HOST_DIR:/) + } + } + assert.match(ci, /Packaged binary bootstraps SSH host without a binary directory\n\s+if: inputs.release && github.event_name != 'pull_request'/) + assert.match(ci, /ORX_PACKAGED_BINARY: \$\{\{ github.workspace \}\}\/target\/release\/orx/) + assert.match(ci, /env -u ORX_HOST_BIN_DIR cargo test --locked --test packaged_host -- --ignored --nocapture/) + for (const name of ['Verify embedded host lookup', 'Optimized source builds disable production telemetry', 'Packaged binary bootstraps SSH host without a binary directory']) { + const step = ci.split(` - name: ${name}\n`)[1].split(' - name:')[0] + assert.match(step, /ORX_EMBED_HOST_DIR:/) + } + assert.match(ci, /Download release hosts\n\s+if: inputs.release && github.event_name != 'pull_request'/) + for (const platform of ['macos', 'linux']) { + const source = workflow(`release-${platform}-app`) + assert.match(source, /ORX_EMBED_HOST_DIR:/) + const download = source.split(' - name: Download release hosts')[1].split(' - name:')[0] + assert.match(download, /actions\/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c/) + assert.match(source, /name: release-host\n\s+path: target\/host-binaries\n\s+run-id: \$\{\{ needs.check.outputs.release-run-id \}\}/) + } + assert.match(workflow('release-windows-app'), /Take orx.exe from the release/) +}) diff --git a/src/commands/app.rs b/src/commands/app.rs index eaef55c93..c8d386021 100644 --- a/src/commands/app.rs +++ b/src/commands/app.rs @@ -178,6 +178,36 @@ fn desktop_entry(appimage: &str, icon: &str) -> String { .collect() } +#[cfg_attr(not(desktop_app), allow(dead_code))] +#[derive(Debug, PartialEq)] +enum CloseAction { + Background, + Quit, + ConfirmQuit, +} + +/// A busy engine keeps running windowless after a close, and asks before an explicit Quit. +#[cfg_attr(not(desktop_app), allow(dead_code))] +fn close_action(explicit_quit: bool, busy: bool) -> CloseAction { + match (explicit_quit, busy) { + (_, false) => CloseAction::Quit, + (true, true) => CloseAction::ConfirmQuit, + (false, true) => CloseAction::Background, + } +} + +static WINDOWLESS: std::sync::LazyLock> = + std::sync::LazyLock::new(|| tokio::sync::watch::channel(false).0); + +pub(crate) fn windowless() -> bool { + *WINDOWLESS.borrow() +} + +#[cfg_attr(not(target_os = "macos"), allow(dead_code))] +fn native_quit_needs_confirmation(runs_busy: bool, system_reason: Option) -> bool { + runs_busy && system_reason.is_none() +} + #[cfg(desktop_app)] const APP_PORT: u16 = 4792; @@ -228,6 +258,29 @@ pub async fn run() { return; } }; + let discovered = match crate::commands::remote_host::canonical_data_dir() { + Ok(data_dir) => crate::commands::remote_host::ServerDescriptor::live(&data_dir).await, + Err(error) => Err(error), + }; + match discovered { + Ok(Some(server)) => { + #[cfg(target_os = "macos")] + imp::run_event_loop(server.port, true); + #[cfg(not(target_os = "macos"))] + imp::run_event_loop( + server.port, + true, + focus_requests, + link.as_deref().and_then(link_path), + ); + return; + } + Ok(None) => {} + Err(error) => { + crate::show_error_dialog(&error.to_string()); + return; + } + } // After an update relaunch, keep the previous port. Otherwise a fixed port, // since the window's localStorage is keyed by origin, falling back to an // ephemeral one when a terminal `orx up` or another app holds it. @@ -820,12 +873,17 @@ mod imp { enum UserEvent { ServerReady, + EngineBusy(bool), LoadTimedOut, SyncZoom, Zoom(ZoomAction), #[cfg(target_os = "macos")] Menu(MenuId), #[cfg(target_os = "macos")] + QuitRequested, + #[cfg(target_os = "macos")] + NativeQuitRequested, + #[cfg(target_os = "macos")] MenuSpec(Vec), #[cfg(target_os = "macos")] MenuState(HashMap), @@ -882,6 +940,10 @@ mod imp { #[cfg(target_os = "linux")] gtk::glib::set_prgname(Some("OpenResearch")); let event_loop = EventLoopBuilder::::with_user_event().build(); + #[cfg(target_os = "macos")] + if !external_server { + intercept_native_quit(event_loop.create_proxy()); + } // Dashboard server on background workers (we're inside main's runtime). if !external_server { @@ -890,6 +952,7 @@ mod imp { port, remote: None, no_browser: true, + headless: false, no_agent: false, model: None, remote_host: false, @@ -907,6 +970,32 @@ mod imp { }); } + if !external_server { + let lifecycle = event_loop.create_proxy(); + let mut visibility = super::WINDOWLESS.subscribe(); + tokio::spawn(async move { + loop { + while !*visibility.borrow_and_update() { + if visibility.changed().await.is_err() { + return; + } + let _ = lifecycle.send_event(UserEvent::EngineBusy(true)); + } + let busy = crate::commands::up::api_v2::busy().unwrap_or(true); + if lifecycle.send_event(UserEvent::EngineBusy(busy)).is_err() { + return; + } + tokio::select! { + _ = tokio::time::sleep(Duration::from_secs(10)) => {} + result = visibility.changed() => { + if result.is_err() { return; } + let _ = lifecycle.send_event(UserEvent::EngineBusy(true)); + } + } + } + }); + } + let ready = event_loop.create_proxy(); tokio::spawn(async move { while tokio::net::TcpStream::connect(( @@ -950,6 +1039,7 @@ mod imp { _ => None, }; let event = match action { + _ if event.id.as_ref() == "app.quit" => UserEvent::QuitRequested, Some(action) => UserEvent::Zoom(action), None => UserEvent::Menu(event.id), }; @@ -1076,7 +1166,10 @@ mod imp { } #[cfg(any(windows, target_os = "macos"))] let _ = proxy.send_event(UserEvent::SyncWindowState); - if super::is_dashboard_url(&url, &origin) && !shown.replace(true) { + if super::is_dashboard_url(&url, &origin) + && !super::windowless() + && !shown.replace(true) + { window.set_visible(true); window.set_focus(); } @@ -1224,6 +1317,8 @@ mod imp { #[cfg(target_os = "macos")] align_traffic_lights(&window, zoom_percent); let mut quit = Quit::No; + let mut idle = crate::commands::up::api_v2::Idle::default(); + let started = Instant::now(); let mut links = DeepLinks { server_ready: false, page_ready, @@ -1258,12 +1353,21 @@ mod imp { } Quit::ShuttingDown => *control_flow = ControlFlow::Exit, }, + Event::UserEvent(UserEvent::EngineBusy(value)) if matches!(quit, Quit::No) => { + if idle.should_exit(started.elapsed(), !super::windowless() || value) { + begin_quit(&mut quit, &window, &webview, control_flow); + } + } Event::UserEvent(UserEvent::ServerReady) if matches!(quit, Quit::No) => { + if super::windowless() { + links.server_ready = true; + return; + } let _ = webview.load_url(&format!("{origin}{}", links.on_server_ready())); } // A window that never appears is worse than a blank one. Event::UserEvent(UserEvent::LoadTimedOut) - if matches!(quit, Quit::No) && !shown.replace(true) => + if matches!(quit, Quit::No) && !super::windowless() && !shown.replace(true) => { eprintln!("openresearch app: the dashboard has not finished loading; showing the window anyway"); window.set_visible(true); @@ -1271,7 +1375,7 @@ mod imp { } #[cfg(windows)] Event::UserEvent(UserEvent::Close) => { - begin_quit(&mut quit, &window, &webview, control_flow); + close_window(false, external_server, &mut quit, &window, &webview, control_flow); } #[cfg(windows)] Event::UserEvent(UserEvent::SyncWindowState) => { @@ -1303,12 +1407,18 @@ mod imp { } } #[cfg(target_os = "macos")] - Event::UserEvent(UserEvent::Menu(id)) if id.as_ref() == "app.quit" => { - begin_quit(&mut quit, &window, &webview, control_flow); + Event::UserEvent(UserEvent::NativeQuitRequested) => { + let confirmed = !matches!(quit, Quit::No) || confirm_quit(&window); + NSApplication::sharedApplication(MainThreadMarker::new().unwrap()) + .replyToApplicationShouldTerminate(confirmed); + } + #[cfg(target_os = "macos")] + Event::UserEvent(UserEvent::QuitRequested) => { + close_window(true, external_server, &mut quit, &window, &webview, control_flow); } #[cfg(target_os = "macos")] Event::UserEvent(UserEvent::Menu(id)) if id.as_ref() == "window.close" => { - NSApplication::sharedApplication(MainThreadMarker::new().unwrap()).hide(None); + close_window(false, external_server, &mut quit, &window, &webview, control_flow); } #[cfg(target_os = "macos")] Event::UserEvent(UserEvent::MenuSpec(spec)) => match build_menu(&spec) { @@ -1368,6 +1478,11 @@ mod imp { // Even before the page loads: a launch that brings nothing up looks // like a broken app. While quitting it must stay hidden. Event::UserEvent(UserEvent::Focus(link)) if matches!(quit, Quit::No) => { + if super::WINDOWLESS.send_replace(false) { + shown.set(false); + links.reopen(&webview, &origin, link.as_deref().and_then(super::link_path)); + return; + } if let Some(path) = link.as_deref().and_then(super::link_path) { links.open(path, &webview, &origin); } @@ -1380,23 +1495,20 @@ mod imp { event: WindowEvent::CloseRequested, .. } => { - #[cfg(target_os = "macos")] - if external_server { - begin_quit(&mut quit, &window, &webview, control_flow); - } else { - // AppKit switches Spaces when hiding the app, unlike ordering out its window. - NSApplication::sharedApplication(MainThreadMarker::new().unwrap()).hide(None); - } - #[cfg(not(target_os = "macos"))] - begin_quit(&mut quit, &window, &webview, control_flow); + close_window(false, external_server, &mut quit, &window, &webview, control_flow); } #[cfg(target_os = "macos")] - Event::Reopen { .. } => { + Event::Reopen { .. } if matches!(quit, Quit::No) => { + if super::WINDOWLESS.send_replace(false) { + shown.set(false); + links.reopen(&webview, &origin, None); + return; + } shown.set(true); window.set_visible(true); window.set_focus(); } - Event::UserEvent(UserEvent::PageReady) if matches!(quit, Quit::No) => { + Event::UserEvent(UserEvent::PageReady) if matches!(quit, Quit::No) && !super::windowless() => { links.on_page_ready(&webview); } #[cfg(target_os = "macos")] @@ -1410,7 +1522,12 @@ mod imp { let Some(path) = urls.iter().find_map(super::deep_link_path) else { return; }; - links.open(path, &webview, &origin); + if super::WINDOWLESS.send_replace(false) { + shown.set(false); + links.reopen(&webview, &origin, Some(path)); + } else { + links.open(path, &webview, &origin); + } } _ => {} }) @@ -1436,6 +1553,17 @@ mod imp { } } + fn reopen(&mut self, webview: &WebView, origin: &str, path: Option) { + self.page_ready.set(false); + if let Some(path) = path { + self.pending = Some(path); + } + if self.server_ready { + let path = self.pending.take().unwrap_or_else(|| "/".to_string()); + let _ = webview.load_url(&format!("{origin}{path}")); + } + } + fn open(&mut self, path: String, webview: &WebView, origin: &str) { if self.page_ready.get() { open_in_page(webview, &path); @@ -1461,6 +1589,151 @@ mod imp { )); } + #[cfg(target_os = "macos")] + thread_local! { + static QUIT_PROXY: RefCell>> = const { RefCell::new(None) }; + } + + #[cfg(target_os = "macos")] + fn intercept_native_quit(proxy: tao::event_loop::EventLoopProxy) { + QUIT_PROXY.with(|slot| *slot.borrow_mut() = Some(proxy)); + let app = NSApplication::sharedApplication(MainThreadMarker::new().unwrap()); + unsafe { + let delegate: *mut AnyObject = objc2::msg_send![&*app, delegate]; + let Some(delegate) = delegate.as_ref() else { + return; + }; + let class: *const AnyClass = delegate.class(); + type ShouldTerminate = + unsafe extern "C-unwind" fn( + &AnyObject, + Sel, + &AnyObject, + ) + -> objc2_app_kit::NSApplicationTerminateReply; + let handler: ShouldTerminate = native_quit_requested; + objc2::ffi::class_addMethod( + class.cast_mut(), + objc2::sel!(applicationShouldTerminate:), + std::mem::transmute::(handler), + c"Q@:@".as_ptr(), + ); + // AppKit caches optional methods when the delegate is assigned. + let _: () = objc2::msg_send![&*app, setDelegate: delegate]; + } + } + + #[cfg(target_os = "macos")] + unsafe extern "C-unwind" fn native_quit_requested( + _delegate: &AnyObject, + _selector: Sel, + _app: &AnyObject, + ) -> objc2_app_kit::NSApplicationTerminateReply { + use objc2_app_kit::NSApplicationTerminateReply; + use objc2_foundation::NSAppleEventManager; + + let reason = NSAppleEventManager::sharedAppleEventManager() + .currentAppleEvent() + .and_then(|event| { + // AEKeyword is u32; the generated binding otherwise requires CoreServices. + let reason: Option> = unsafe { + objc2::msg_send![&*event, paramDescriptorForKeyword: u32::from_be_bytes(*b"why?")] + }; + reason + }) + .map(|reason| reason.enumCodeValue()); + let busy = reason.is_none() && crate::commands::up::api_v2::runs_busy().unwrap_or(true); + if !super::native_quit_needs_confirmation(busy, reason) { + return NSApplicationTerminateReply::TerminateNow; + } + let sent = QUIT_PROXY.with(|slot| { + slot.borrow() + .as_ref() + .is_some_and(|proxy| proxy.send_event(UserEvent::NativeQuitRequested).is_ok()) + }); + if sent { + NSApplicationTerminateReply::TerminateLater + } else { + NSApplicationTerminateReply::TerminateNow + } + } + + fn close_window( + explicit_quit: bool, + external_server: bool, + quit: &mut Quit, + window: &Window, + webview: &WebView, + control_flow: &mut ControlFlow, + ) { + if !matches!(quit, Quit::No) { + return; + } + if external_server { + begin_quit(quit, window, webview, control_flow); + return; + } + let busy = if explicit_quit { + crate::commands::up::api_v2::runs_busy().unwrap_or(true) + } else { + crate::commands::up::api_v2::busy().unwrap_or(true) + }; + match super::close_action(explicit_quit, busy) { + super::CloseAction::Background => { + super::WINDOWLESS.send_replace(true); + window.set_visible(false); + let _ = webview.load_url("about:blank"); + } + super::CloseAction::ConfirmQuit => { + if confirm_quit(window) { + begin_quit(quit, window, webview, control_flow); + } + } + super::CloseAction::Quit => begin_quit(quit, window, webview, control_flow), + } + } + + fn confirm_quit(window: &Window) -> bool { + #[cfg(target_os = "macos")] + let _ = window; + let title = "Quit OpenResearch?"; + let description = "Runs will continue on their hosts. Results will be collected the next time OpenResearch opens."; + #[cfg(not(target_os = "linux"))] + let confirmed = { + let dialog = rfd::MessageDialog::new() + .set_title(title) + .set_description(description) + .set_buttons(rfd::MessageButtons::OkCancelCustom( + "Quit".into(), + "Cancel".into(), + )); + #[cfg(windows)] + let dialog = dialog.set_parent(window); + dialog.show() == rfd::MessageDialogResult::Custom("Quit".into()) + }; + #[cfg(target_os = "linux")] + let confirmed = { + use gtk::prelude::*; + use tao::platform::unix::WindowExtUnix; + + let dialog = gtk::MessageDialog::builder() + .transient_for(window.gtk_window()) + .modal(true) + .text(title) + .secondary_text(description) + .build(); + dialog.add_buttons(&[ + ("Cancel", gtk::ResponseType::Cancel), + ("Quit", gtk::ResponseType::Accept), + ]); + dialog.set_default_response(gtk::ResponseType::Cancel); + let confirmed = dialog.run() == gtk::ResponseType::Accept; + dialog.close(); + confirmed + }; + confirmed + } + fn begin_quit( quit: &mut Quit, window: &Window, @@ -1871,6 +2144,41 @@ mod tests { use std::ffi::{OsStr, OsString}; use std::path::Path; + #[test] + fn close_and_quit_matrix() { + use super::{close_action, CloseAction}; + + assert_eq!(close_action(false, false), CloseAction::Quit); + assert_eq!(close_action(true, false), CloseAction::Quit); + assert_eq!(close_action(false, true), CloseAction::Background); + assert_eq!(close_action(true, true), CloseAction::ConfirmQuit); + } + + #[test] + fn native_quit_never_defers_system_termination_or_idle_quit() { + for busy in [false, true] { + assert_eq!(super::native_quit_needs_confirmation(busy, None), busy); + for reason in [*b"quia", *b"shut", *b"rest", *b"rlgo"] { + assert!(!super::native_quit_needs_confirmation( + busy, + Some(u32::from_be_bytes(reason)) + )); + } + } + } + + #[test] + fn new_work_resets_windowless_idle_exit() { + let mut idle = crate::commands::up::api_v2::Idle::default(); + let secs = std::time::Duration::from_secs; + + assert!(!idle.should_exit(secs(0), false)); + assert!(!idle.should_exit(secs(599), true)); + assert!(!idle.should_exit(secs(600), false)); + assert!(!idle.should_exit(secs(1199), false)); + assert!(idle.should_exit(secs(1200), false)); + } + #[test] fn the_desktop_entry_launches_the_appimage_wherever_it_is() { let entry = desktop_entry( diff --git a/src/commands/compute.rs b/src/commands/compute.rs index 57fa75e12..5ff5bbe33 100644 --- a/src/commands/compute.rs +++ b/src/commands/compute.rs @@ -275,9 +275,6 @@ pub struct ConfigureArgs { pub struct ConnectArgs { #[command(flatten)] check: CheckArgs, - /// Idle lifetime for a new SSH master, in seconds (default: 86400; 0 means indefinite). - #[arg(long)] - persist: Option, } #[derive(Debug, Args)] @@ -467,23 +464,22 @@ async fn run_command(command: ComputeCommand, json_output: bool) -> Result<()> { } if let ComputeCommand::Connect(ref args) = command { validate_check(&args.check)?; - if args.persist.is_some() - && (!cfg!(unix) || !matches!(args.check.backend, Backend::Ssh | Backend::Slurm)) - { - return Err(anyhow!("--persist requires SSH or Slurm on Unix.")); - } if json_output { return Err(anyhow!( "connect is interactive; use test --json for machine-readable checks." )); } - connect(&args.check, args.persist).await?; + if !matches!(args.check.backend, Backend::Ssh | Backend::Slurm) { + connect(&args.check).await?; + } } let is_check = matches!( command, ComputeCommand::Test(_) | ComputeCommand::Connect(_) ); let value = match command { + ComputeCommand::Test(args) => check(&args, "test").await?, + ComputeCommand::Connect(ConnectArgs { check: args }) => check(&args, "connect").await?, ComputeCommand::Catalog(a) => return catalog(a, json_output).await, ComputeCommand::Status => settings::status().await?, ComputeCommand::Show { backend } => settings::show(backend.name()).await?, @@ -497,16 +493,6 @@ async fn run_command(command: ComputeCommand, json_output: bool) -> Result<()> { let backend = args.backend.name(); settings::configure(backend, (*args).body()?).await? } - ComputeCommand::Test(args) | ComputeCommand::Connect(ConnectArgs { check: args, .. }) => { - settings::check( - args.backend.name(), - args.host, - args.container, - args.no_container, - args.address, - ) - .await? - } ComputeCommand::SshConfig { command } => match command { SshConfigCommand::Show => settings::read_ssh_config().await?, SshConfigCommand::Set { @@ -553,6 +539,29 @@ async fn run_command(command: ComputeCommand, json_output: bool) -> Result<()> { Ok(()) } +/// Checks run in the server, which owns SSH connections and relays their login prompts. +async fn check(args: &CheckArgs, action: &str) -> Result { + let body = json!({"backend":args.backend.name(), "host":args.host, "container":args.container, "noContainer":args.no_container, "address":args.address}); + let client = crate::plane::local_plane::ApiClient::discover().await?; + if action == "connect" && matches!(args.backend, Backend::Ssh | Backend::Slurm) { + use std::io::IsTerminal as _; + if !std::io::stdin().is_terminal() { + return Err(anyhow!("connect requires a terminal for login/MFA. Use configure with --credentials-file - for unattended credential setup.")); + } + let prompt: crate::engine::transport::Prompt = std::sync::Arc::new(|question| { + Box::pin(async move { Ok(Some(secret_prompt(&question).await?)) }) + }); + return client.connect(body, prompt).await; + } + client + .json( + reqwest::Method::POST, + &format!("compute/{action}"), + Some(&body), + ) + .await +} + fn validate_check(args: &CheckArgs) -> Result<()> { let name = args.backend.name(); if args.host.is_some() && !matches!(name, "ssh" | "slurm") { @@ -619,74 +628,12 @@ fn instructions_write(path: &std::path::Path, content: &str, expected: &str) -> instructions_read(path) } -async fn connect(args: &CheckArgs, persist: Option) -> Result<()> { +async fn connect(args: &CheckArgs) -> Result<()> { use std::io::IsTerminal; if !std::io::stdin().is_terminal() { return Err(anyhow!("connect requires a terminal for login/MFA. Use configure with --credentials-file - for unattended credential setup.")); } match args.backend { - Backend::Ssh | Backend::Slurm => { - let host = match &args.host { - Some(host) => Some(host.clone()), - None => match args.backend { - Backend::Ssh => crate::config::ssh_settings()?.default_host, - _ => { - crate::jobs::slurm::load_settings()? - .unwrap_or_default() - .host - } - }, - } - .ok_or_else(|| anyhow!("Pass --host or configure a default host."))?; - let target = crate::jobs::ssh::SshTarget::alias(&host); - #[cfg(unix)] - if !crate::jobs::ssh::service::healthy(&target).await { - let connection = crate::jobs::ssh::interactive_args(&target, persist, None).await?; - interactive_command("ssh", &connection.args).await?; - if let Some(warning) = crate::jobs::ssh::setup_connection_sharing(&target).await { - eprintln!("orx: warning: {warning}"); - } - } - #[cfg(windows)] - { - let _ = persist; - use crate::jobs::ssh::service; - let start = service::request(&target, json!({"op":"connect_start"})).await?; - let attempt = start["attempt"] - .as_str() - .ok_or_else(|| anyhow!("Missing SSH login attempt"))?; - let result = async { - loop { - let status = service::request( - &target, - json!({"op":"connect_status", "attempt":attempt}), - ) - .await?; - if status["done"] == true { - if let Some(error) = status["error"].as_str() { - return Err(anyhow!(error.to_owned())); - } - return Ok(()); - } - if let Some(prompt) = status["prompt"].as_str() { - let answer = secret_prompt(prompt).await?; - service::request( - &target, - json!({"op":"connect_answer", "attempt":attempt, "answer":answer}), - ) - .await?; - } - tokio::time::sleep(std::time::Duration::from_millis(150)).await; - } - } - .await; - let _ = - service::request(&target, json!({"op":"connect_cancel", "attempt":attempt})) - .await; - result?; - } - crate::jobs::ssh::service::attach(&target).await?; - } Backend::Hf => { interactive_command("hf", &["auth".into(), "login".into()]).await?; use crate::jobs::huggingface::{resolve_token_with_source, TokenSource}; @@ -722,7 +669,7 @@ async fn connect(args: &CheckArgs, persist: Option) -> Result<()> { Environment. Check them with `orx compute test vercel`." ); } - Backend::Local | Backend::Ray | Backend::K8s => {} + Backend::Local | Backend::Ray | Backend::K8s | Backend::Ssh | Backend::Slurm => {} } Ok(()) } diff --git a/src/commands/exp.rs b/src/commands/exp.rs index 7816d3d52..c2ce9314f 100644 --- a/src/commands/exp.rs +++ b/src/commands/exp.rs @@ -3,7 +3,7 @@ //! orx exp status inspect status, run command, latest run //! orx exp run … launch a local orx-supervised run //! orx exp cancel cancel the in-flight run -//! orx exp wake resume this agent when the run succeeds or fails +//! orx exp wake send this chat the run's result when it finishes //! orx exp archive --ancestors|--only|--descendants hide the chosen scope //! orx exp unarchive --ancestors|--only|--descendants restore the same nodes //! orx exp move --parent |--baseline re-parent a subtree @@ -20,6 +20,12 @@ use crate::store::Store; use crate::ExpCommand; pub async fn run(args: crate::ExpArgs) -> Result<()> { + if let ExpCommand::Abandon { run } = &args.command { + return crate::plane::local_plane::ApiClient::discover() + .await? + .abandon(run) + .await; + } // `exp wait` opens its store itself: a transiently locked orx.db is // retried inside the wait timeout rather than dying at startup. if let ExpCommand::Wait { @@ -67,9 +73,21 @@ pub async fn run(args: crate::ExpArgs) -> Result<()> { .launch(run_args) .await } - ExpCommand::Cancel { exp_id } => resolve_experiment(store, &exp_id)?.cancel().await, + ExpCommand::Cancel { exp_id, run } => match exp_id { + Some(exp_id) => { + resolve_experiment(store, &exp_id)? + .cancel(run.as_deref()) + .await + } + None => { + crate::plane::local_plane::ApiClient::discover() + .await? + .cancel(None, run.as_deref()) + .await + } + }, ExpCommand::Wake { exp_id } => wake(&store, &exp_id), - ExpCommand::Wait { .. } => unreachable!("handled above"), + ExpCommand::Wait { .. } | ExpCommand::Abandon { .. } => unreachable!("handled above"), } } @@ -142,33 +160,36 @@ fn wake(store: &Store, exp_id: &str) -> Result<()> { .latest_run_for_experiment(exp_id)? .ok_or_else(|| anyhow!("Experiment {exp_id} has no runs to wake for."))?; if run.status == "cancelled" { - store.remove_run_wakeup(&run.id, &session_id)?; println!("Run {} was cancelled; no wake-up scheduled.", run.id); return Ok(()); } - match store.register_run_wakeup(&run.id, &session_id)? { - crate::store::RunWakeupRegistration::Scheduled => { - println!("Wake-up scheduled for run {}.", run.id); - } - crate::store::RunWakeupRegistration::AlreadyPending => { - println!("Wake-up already scheduled for run {}.", run.id); - } - crate::store::RunWakeupRegistration::AlreadyDelivered => { - println!("Run {} already delivered its wake-up.", run.id); - } + let now = crate::store::now_ms(); + store.subscribe_run(&run.id, &session_id, now)?; + if !crate::local::is_terminal(&run.status) { + println!("Wake-up scheduled for run {}.", run.id); + return Ok(()); + } + let body = store.terminal_notice_body(&run)?; + let terminal = crate::store::TERMINAL; + if store.insert_run_notice(&run.id, &session_id, terminal, terminal, &body, now)? { + println!( + "Run {} already finished; its result is queued for this chat.", + run.id + ); + } else { + println!("Run {} already delivered its result to this chat.", run.id); } Ok(()) } -/// `orx exp wait …` — block on run state, for agents driving a research loop. +/// `orx exp wait …` — block on run state, one server event stream at a time. /// /// Two modes, picked by argument: -/// - `` — level trigger: poll the experiment's latest run until it reaches a terminal state (done/failed/cancelled). -/// - `--project` — edge trigger: snapshot every run in the project and return when the first run *completes* — i.e. transitions into a terminal state (done/failed/cancelled). This is the "a slot just freed" signal a budget-saturation loop wants; run starts and queued→running transitions are intentionally ignored. +/// - `` — level trigger: wait until the experiment's latest run reaches a terminal state (done/failed/cancelled). +/// - `--project` — edge trigger: snapshot every run in the project and return when the first run *completes* — i.e. transitions into a terminal state (done/failed/cancelled). A cancelled result can still report surviving processes; run starts and queued→running transitions are intentionally ignored. /// -/// Polls every `--interval` seconds (default 5), gives up after `--timeout` -/// seconds (default 1800) with a non-zero exit so callers can branch on it. The -/// Polling reads only the local run store. +/// Gives up after `--timeout` seconds (default 1800) with a non-zero exit so callers can +/// branch on it. async fn wait( exp_id: Option, project: Option, @@ -196,7 +217,7 @@ async fn wait( deadline, ) .await?; - plane.wait_experiment(interval, deadline).await + plane.wait(deadline).await } (None, Some(project_id)) => { let plane = crate::plane::local_plane::retry_on_db_lock( @@ -210,27 +231,13 @@ async fn wait( deadline, ) .await?; - plane.wait_project(interval, deadline).await + plane.wait(deadline).await } } } -// --- job-launch helpers shared with the src/local/* backends ----------------- - -/// Default docker image per flavor family: plain python for CPU flavors, a -/// CUDA-ready pytorch image for GPU flavors. Override with --image. -pub(crate) fn default_hf_image(flavor: &str) -> String { - if flavor.starts_with("cpu") { - "python:3.12".to_string() - } else { - "pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime".to_string() - } -} - const SUPERVISOR_LOG_MAX_BYTES: u64 = 1024 * 1024; -/// Spawn `orx supervise ` fully detached (own process group, stderr to a log), -/// so it outlives this command and any SSH session that launched it. pub(crate) fn spawn_detached_supervise(run_id: &str) -> Result<()> { let exe = crate::paths::spawnable_exe().map_err(|e| { anyhow!( @@ -239,7 +246,8 @@ pub(crate) fn spawn_detached_supervise(run_id: &str) -> Result<()> { ) })?; // Supervisor diagnostics (retries, transitions) exist only on stderr; keep them per run. - let path = crate::store::log_path(run_id).with_extension("supervisor.log"); + let path = + crate::store::log_path(&crate::store::data_dir(), run_id).with_extension("supervisor.log"); if std::fs::metadata(&path).is_ok_and(|meta| meta.len() >= SUPERVISOR_LOG_MAX_BYTES) { // Rename rather than truncate: a still-running supervisor keeps writing to its handle. let _ = std::fs::rename(&path, path.with_extension("log.1")); @@ -312,8 +320,6 @@ fn supervise_command( cmd } -/// Names the binary that failed and how to attach a supervisor by hand, since -/// the run stays `starting` without one. fn supervise_spawn_error( exe: &std::path::Path, run_id: &str, @@ -337,7 +343,6 @@ fn supervise_spawn_error( ) } -/// The kernel's own name for this binary when it differs from the spawned path, e.g. `… (deleted)`. fn current_exe_note(exe: &std::path::Path) -> String { std::env::current_exe() .ok() @@ -346,6 +351,18 @@ fn current_exe_note(exe: &std::path::Path) -> String { .unwrap_or_default() } +// --- job-launch helpers shared with the src/local/* backends ----------------- + +/// Default docker image per flavor family: plain python for CPU flavors, a +/// CUDA-ready pytorch image for GPU flavors. Override with --image. +pub(crate) fn default_hf_image(flavor: &str) -> String { + if flavor.starts_with("cpu") { + "python:3.12".to_string() + } else { + "pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime".to_string() + } +} + /// Who asked `orx exp cancel` to stop a run, recorded on the run. pub(crate) fn exp_cancel_reason(chat_session_id: Option<&str>) -> String { match chat_session_id { @@ -354,26 +371,19 @@ pub(crate) fn exp_cancel_reason(chat_session_id: Option<&str>) -> String { } } -/// Persist cancel intent and ensure an orphaned run gets a fresh supervisor. -pub(crate) fn request_local_run_cancel(store: &Store, run_id: &str, reason: &str) -> Result<()> { - let lock_path = crate::store::log_path(run_id).with_extension("cancel.lock"); - request_local_run_cancel_with( - store, - run_id, - reason, - &lock_path, - || {}, - spawn_detached_supervise, - ) +/// Records cancel intent for a run a 0.2.x supervisor owns, under the `cancel.lock` it reads +/// the intent under. +pub(crate) fn request_legacy_run_cancel(store: &Store, run_id: &str, reason: &str) -> Result<()> { + let lock_path = + crate::store::log_path(&crate::store::data_dir(), run_id).with_extension("cancel.lock"); + request_legacy_run_cancel_at(store, run_id, reason, &lock_path) } -fn request_local_run_cancel_with( +fn request_legacy_run_cancel_at( store: &Store, run_id: &str, reason: &str, lock_path: &std::path::Path, - before_lock: impl FnOnce(), - spawn: impl FnOnce(&str) -> Result<()>, ) -> Result<()> { let lock_file = std::fs::OpenOptions::new() .create(true) @@ -381,30 +391,16 @@ fn request_local_run_cancel_with( .write(true) .open(lock_path)?; let mut cancel_lock = fd_lock::RwLock::new(lock_file); - before_lock(); let _cancel_guard = cancel_lock.write()?; store .get_run(run_id)? .ok_or_else(|| anyhow!("Run {run_id} not found in the local store."))?; - let requested = store.request_cancel(run_id, reason)?; - if let Err(spawn_err) = spawn(run_id) { - if requested { - if let Err(rollback_err) = store.withdraw_cancel(run_id) { - return Err(anyhow!( - "Could not recover the supervisor: {spawn_err}; could not restore retryable cancel state: {rollback_err}" - )); - } - } - return Err(spawn_err); - } + store.request_cancel(run_id, reason)?; Ok(()) } #[cfg(test)] mod tests { - use super::*; - use crate::store::StoredRun; - #[test] fn supervise_spawn_error_names_the_binary_and_the_manual_attach() { let message = supervise_spawn_error( @@ -417,6 +413,25 @@ mod tests { assert!(message.ends_with(" supervise run-1` in the background.")); } + #[tokio::test] + async fn wait_validates_both_and_neither_targets_before_opening_the_store() { + assert!( + super::wait(Some("exp".into()), Some("project".into()), Some(1), None) + .await + .unwrap_err() + .to_string() + .contains("either") + ); + assert!(super::wait(None, None, Some(1), None) + .await + .unwrap_err() + .to_string() + .contains("Specify")); + } + + use super::*; + use crate::store::StoredRun; + fn run_fixture() -> StoredRun { StoredRun { id: "run-1".into(), @@ -437,37 +452,6 @@ mod tests { } } - #[test] - fn failed_supervisor_spawn_restores_cancel_retry() { - let dir = - std::env::temp_dir().join(format!("orx-cancel-spawn-test-{}", uuid::Uuid::new_v4())); - let store = Store::open_at(dir.clone()).unwrap(); - let run = run_fixture(); - store.upsert_run(&run).unwrap(); - let lock_path = dir.join("cancel.lock"); - - let result = request_local_run_cancel_with( - &store, - &run.id, - "test", - &lock_path, - || {}, - |_| Err(anyhow!("synthetic spawn failure")), - ); - assert!(result.is_err()); - let stored = store.get_run(&run.id).unwrap().unwrap(); - assert!(!stored.cancel_requested); - // A supervisor that already sent the cancel still ends the run with its requester. - store - .update_status(&run.id, crate::store::RunStatus::Cancelled, Some(1), None) - .unwrap(); - let cancelled = crate::plane::Run::from(&store.get_run(&run.id).unwrap().unwrap()); - assert_eq!(cancelled.failure_detail().as_deref(), Some("reason: test")); - - drop(store); - let _ = std::fs::remove_dir_all(dir); - } - #[test] fn cancel_reason_keeps_the_first_requester_and_shows_only_when_cancelled() { use crate::store::RunStatus; @@ -491,8 +475,7 @@ mod tests { ("run-1", "second"), ("run-done", "first"), ] { - request_local_run_cancel_with(&store, run_id, reason, &lock_path, || {}, |_| Ok(())) - .unwrap(); + request_legacy_run_cancel_at(&store, run_id, reason, &lock_path).unwrap(); } // A backend's submit upsert lands after the cancel request. store.upsert_run(&starting).unwrap(); @@ -516,72 +499,4 @@ mod tests { drop(store); let _ = std::fs::remove_dir_all(dir); } - - #[test] - fn concurrent_spawn_failure_preserves_successful_cancel_intent() { - let dir = std::env::temp_dir().join(format!( - "orx-cancel-concurrency-test-{}", - uuid::Uuid::new_v4() - )); - let store = Store::open_at(dir.clone()).unwrap(); - let run = run_fixture(); - store.upsert_run(&run).unwrap(); - drop(store); - let lock_path = dir.join("cancel.lock"); - let (entered_tx, entered_rx) = std::sync::mpsc::channel(); - let (release_tx, release_rx) = std::sync::mpsc::channel(); - let (attempted_tx, attempted_rx) = std::sync::mpsc::channel(); - let (completed_tx, completed_rx) = std::sync::mpsc::channel(); - - let first_dir = dir.clone(); - let first_lock = lock_path.clone(); - let first = std::thread::spawn(move || { - let store = Store::open_at(first_dir).unwrap(); - request_local_run_cancel_with( - &store, - "run-1", - "first", - &first_lock, - || {}, - |_| { - entered_tx.send(()).unwrap(); - release_rx.recv().unwrap(); - Err(anyhow!("synthetic spawn failure")) - }, - ) - .unwrap_err(); - }); - entered_rx.recv().unwrap(); - - let second_dir = dir.clone(); - let second_lock = lock_path.clone(); - let second = std::thread::spawn(move || { - let store = Store::open_at(second_dir).unwrap(); - request_local_run_cancel_with( - &store, - "run-1", - "second", - &second_lock, - || attempted_tx.send(()).unwrap(), - |_| Ok(()), - ) - .unwrap(); - completed_tx.send(()).unwrap(); - }); - attempted_rx.recv().unwrap(); - let completed_while_locked = completed_rx - .recv_timeout(std::time::Duration::from_millis(250)) - .is_ok(); - release_tx.send(()).unwrap(); - first.join().unwrap(); - second.join().unwrap(); - - let store = Store::open_at(dir.clone()).unwrap(); - assert!(!completed_while_locked); - let run = store.get_run("run-1").unwrap().unwrap(); - assert!(run.cancel_requested); - assert_eq!(run.cancel_reason.as_deref(), Some("second")); - drop(store); - let _ = std::fs::remove_dir_all(dir); - } } diff --git a/src/commands/logs.rs b/src/commands/logs.rs index 0fd829576..b81dc20bc 100644 --- a/src/commands/logs.rs +++ b/src/commands/logs.rs @@ -66,19 +66,60 @@ fn print_compact_summary(path: &std::path::Path, total_bytes: u64, preview: &str Ok(()) } -/// Prints a run's local log path, size, and bounded preview. +/// Prints a run's local log path, size, and bounded preview; follows it through the server +/// with `-f`. pub async fn run(args: crate::LogsArgs) -> Result<()> { crate::local::chat::record_chat_target("runs", &args.run_id); + if args.follow { + return crate::plane::local_plane::ApiClient::discover() + .await? + .logs(&args.run_id, true) + .await; + } resolve_run(Store::open()?, &args.run_id)?; + let ranges = crate::commands::up::api_v2::kept_ranges(&crate::store::data_dir(), &args.run_id)?; + if let Some(tail) = ranges.iter().max_by_key(|range| range.offset) { + let total = ranges + .iter() + .map(|range| range.offset + range.len) + .max() + .unwrap(); + let mut stdout = std::io::stdout(); + writeln!(stdout, "Original log: {total} bytes.")?; + for range in &ranges { + writeln!( + stdout, + "Kept bytes {}..{}: {}", + range.offset, + range.offset + range.len, + range.file.display() + )?; + } + let kept: u64 = ranges.iter().map(|range| range.len).sum(); + if kept < total { + writeln!(stdout, "The middle of the log is not on this computer.")?; + } + let mut file = std::fs::File::open(&tail.file)?; + let bytes = read_preview_suffix(&mut file, tail.len)?; + writeln!(stdout, "Last {PREVIEW_CHARS} characters of the kept tail:")?; + writeln!(stdout, "{}", trailing_char_preview(&bytes))?; + return Ok(()); + } - let (mut file, path, total) = match crate::jobs::ssh::service::logs::open_current(&args.run_id) - { + let log_path = crate::store::log_path(&crate::store::data_dir(), &args.run_id); + let (mut file, path, total) = match crate::jobs::ssh::service::logs::open_current(log_path) { Ok(current) => current, Err(error) if error .downcast_ref::() .is_some_and(|error| error.kind() == std::io::ErrorKind::NotFound) => { + let live = Store::open()? + .get_run(&args.run_id)? + .is_some_and(|run| !crate::local::is_terminal(&run.status)); + if live { + return host_preview(&args.run_id).await; + } eprintln!("[local file] no log captured yet for this run."); return Ok(()); } @@ -89,6 +130,57 @@ pub async fn run(args: crate::LogsArgs) -> Result<()> { print_compact_summary(&path, total, &preview) } +/// A live engine run's log stays on its host until the run finishes. +async fn host_preview(run_id: &str) -> Result<()> { + let client = crate::plane::local_plane::ApiClient::discover().await?; + let page = |start: u64, end: u64| { + let client = client.clone(); + async move { + let page: crate::engine::LogPage = serde_json::from_value( + client + .json( + reqwest::Method::GET, + &format!( + "runs/{}/log?start={start}&end={end}", + urlencoding::encode(run_id) + ), + None, + ) + .await?, + )?; + Ok::<_, crate::error::Error>(page) + } + }; + let total = match page(u64::MAX - 1, u64::MAX).await? { + crate::engine::LogPage::Reset { info: Some(info) } => info.len, + _ => 0, + }; + let bytes = match page(total.saturating_sub(PREVIEW_SUFFIX_BYTES as u64), total).await? { + crate::engine::LogPage::Data { bytes, .. } => bytes, + crate::engine::LogPage::Reset { .. } => Vec::new(), + }; + let preview = trailing_char_preview(&bytes); + let mut stdout = std::io::stdout(); + writeln!( + stdout, + "This run is still running; its log is on the compute host and is kept on this computer when the run finishes." + )?; + writeln!(stdout, "It is {total} bytes so far.")?; + writeln!(stdout)?; + writeln!(stdout, "Here are the last 500 characters of the log:")?; + stdout.write_all(preview.as_bytes())?; + if preview.is_empty() || !preview.ends_with('\n') { + writeln!(stdout)?; + } + writeln!( + stdout, + "Follow it with `{} logs -f {run_id}`. This preview is not proof of absence.", + crate::invocation::orx() + )?; + stdout.flush()?; + Ok(()) +} + #[cfg(test)] mod tests { use super::read_preview_suffix; diff --git a/src/commands/remote_host.rs b/src/commands/remote_host.rs index 98685f65a..1b7e95b40 100644 --- a/src/commands/remote_host.rs +++ b/src/commands/remote_host.rs @@ -11,7 +11,7 @@ use std::process::Stdio; use std::sync::atomic::AtomicBool; #[cfg(unix)] use std::sync::atomic::Ordering; -use std::sync::{Arc, RwLock}; +use std::sync::{Arc, Mutex, RwLock}; use std::time::Duration; use serde::{Deserialize, Serialize}; @@ -153,11 +153,6 @@ fn constant_time_eq(left: &[u8], right: &[u8]) -> bool { == 0 } -pub(crate) enum DashboardLockMode { - Shared, - Exclusive, -} - pub(crate) struct DashboardLock { release: Option>, thread: Option>, @@ -173,7 +168,8 @@ impl Drop for DashboardLock { } impl DashboardLock { - pub(crate) fn acquire(data_dir: &Path, mode: DashboardLockMode) -> Result { + /// The engine lock: exclusive, so one server owns the data directory's runs. + pub(crate) fn acquire(data_dir: &Path) -> Result { let path = shared_path(data_dir, "lock")?; let (ready_tx, ready_rx) = std::sync::mpsc::sync_channel(1); let (release_tx, release_rx) = std::sync::mpsc::channel(); @@ -182,34 +178,15 @@ impl DashboardLock { let mut lock = open_lock(&path).map_err(|error| { anyhow!("Could not open dashboard lock {}: {error}", path.display()) })?; - match mode { - DashboardLockMode::Shared => { - let _guard = lock.try_read().map_err(|error| { - if is_lock_conflict(&error) { - anyhow!( - "A persistent OpenResearch host is already using this database." - ) - } else { - lock_error(&path, error) - } - })?; - ready_tx.send(Ok(())).ok(); - let _ = release_rx.recv(); + let _guard = lock.try_write().map_err(|error| { + if is_lock_conflict(&error) { + anyhow!("Another OpenResearch dashboard is already using this database.") + } else { + lock_error(&path, error) } - DashboardLockMode::Exclusive => { - let _guard = lock.try_write().map_err(|error| { - if is_lock_conflict(&error) { - anyhow!( - "Another OpenResearch dashboard is already using this database." - ) - } else { - lock_error(&path, error) - } - })?; - ready_tx.send(Ok(())).ok(); - let _ = release_rx.recv(); - } - } + })?; + ready_tx.send(Ok(())).ok(); + let _ = release_rx.recv(); Ok(()) })(); if let Err(error) = result { @@ -522,35 +499,32 @@ async fn ensure(expected_instance: Option) -> Result<()> { )); } - let mut start_lock = open_lock(&shared_path(&data_dir, "start.lock")?)?; - let _start_guard = start_lock.write()?; - match live_descriptor(&data_dir).await { - LiveHost::Running(descriptor) => return print_descriptor(&descriptor), - LiveHost::Stopping(_) => wait_for_server_lock_free(&data_dir).await?, - LiveHost::Missing => ensure_server_lock_free(&data_dir)?, - } - let (mut child, log_path) = spawn_detached_host(&data_dir)?; - let started = tokio::time::timeout(START_TIMEOUT, async { - loop { - if let LiveHost::Running(descriptor) = live_descriptor(&data_dir).await { - return Ok(descriptor); - } - if let Some(status) = child.try_wait()? { - return Err(anyhow!( - "The persistent OpenResearch host exited ({status}). See {}.", - log_path.display() - )); + let started = ensure_started( + data_dir.clone(), + START_TIMEOUT, + ServerMode::Persistent, + vec![ + "up".into(), + "--no-browser".into(), + "--remote-host".into(), + "--port".into(), + "0".into(), + ], + move || { + let data_dir = data_dir.clone(); + async move { + match live_descriptor(&data_dir).await { + LiveHost::Running(descriptor) => Ok(Some(descriptor)), + LiveHost::Stopping(_) => { + wait_for_server_lock_free(&data_dir).await?; + Ok(None) + } + LiveHost::Missing => Ok(None), + } } - tokio::time::sleep(Duration::from_millis(100)).await; - } - }) - .await - .map_err(|_| { - anyhow!( - "Timed out starting the persistent OpenResearch host. See {}.", - log_path.display() - ) - })??; + }, + ) + .await?; print_descriptor(&started) } @@ -743,10 +717,100 @@ fn print_descriptor(descriptor: &HostDescriptor) -> Result<()> { Ok(()) } -#[cfg(unix)] -fn spawn_detached_host(data_dir: &Path) -> Result<(std::process::Child, PathBuf)> { +// Startup children must inherit neither the readiness pipe nor its environment capability. +static READY_PIPE: Mutex> = Mutex::new(None); + +pub(crate) fn prepare_readiness_pipe() -> Result<()> { + let Some(pipe) = std::env::var_os("ORX_SERVER_READY_PIPE") else { + return Ok(()); + }; + std::env::remove_var("ORX_SERVER_READY_PIPE"); + #[cfg(unix)] + let file = { + let pipe: usize = pipe.to_string_lossy().parse()?; + use std::os::fd::FromRawFd as _; + let pipe = i32::try_from(pipe)?; + let file = unsafe { File::from_raw_fd(pipe) }; + if unsafe { libc::fcntl(pipe, libc::F_SETFD, libc::FD_CLOEXEC) } == -1 { + return Err(std::io::Error::last_os_error().into()); + } + file + }; + #[cfg(windows)] + let file = OpenOptions::new().write(true).open(pipe)?; + *READY_PIPE.lock().unwrap() = Some(file); + Ok(()) +} + +#[derive(Clone, Copy)] +enum ServerMode { + Persistent, + Headless, +} + +enum Readiness { + #[cfg(unix)] + Pipe(std::io::PipeReader), + #[cfg(windows)] + Named(tokio::net::windows::named_pipe::NamedPipeServer), +} + +impl Readiness { + async fn wait(self) -> std::io::Result<()> { + let byte = match self { + #[cfg(unix)] + Self::Pipe(mut reader) => tokio::task::spawn_blocking(move || { + let mut byte = [0]; + std::io::Read::read_exact(&mut reader, &mut byte)?; + Ok::<_, std::io::Error>(byte) + }) + .await + .map_err(std::io::Error::other)??, + #[cfg(windows)] + Self::Named(mut server) => { + server.connect().await?; + let mut byte = [0]; + server.read_exact(&mut byte).await?; + byte + } + }; + if byte != [1] { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidData, + "Incorrect readiness signal", + )); + } + Ok(()) + } +} + +fn spawn_detached_host( + data_dir: &Path, + args: &[String], + mode: ServerMode, +) -> Result<(std::process::Child, PathBuf, Option)> { + #[cfg(unix)] + if args.iter().any(|arg| arg == "--remote-host") { + ensure_server_lock_free(data_dir)?; + } + #[cfg(unix)] + let readiness = if matches!(mode, ServerMode::Headless) { + Some(std::io::pipe()?) + } else { + None + }; + #[cfg(windows)] + let readiness = if matches!(mode, ServerMode::Headless) { + let path = format!(r"\\.\pipe\orx-ready-{}", uuid::Uuid::new_v4()); + let server = tokio::net::windows::named_pipe::ServerOptions::new() + .first_pipe_instance(true) + .reject_remote_clients(true) + .create(&path)?; + Some((server, path)) + } else { + None + }; let executable = std::env::current_exe()?; - let args = ["up", "--no-browser", "--remote-host", "--port", "0"]; let log_path = runtime_path(data_dir, "log")?; let log = open_runtime_log(&log_path)?; let mut command = crate::process::command(&executable); @@ -755,10 +819,29 @@ fn spawn_detached_host(data_dir: &Path) -> Result<(std::process::Child, PathBuf) .stdin(Stdio::null()) .stdout(Stdio::from(log.try_clone()?)) .stderr(Stdio::from(log)); + if matches!(mode, ServerMode::Headless) { + command.env("ORX_DATA_DIR", data_dir); + } + #[cfg(unix)] + if let Some((_, writer)) = &readiness { + use std::os::fd::AsRawFd as _; + command.env("ORX_SERVER_READY_PIPE", writer.as_raw_fd().to_string()); + } + #[cfg(windows)] + if let Some((_, path)) = &readiness { + command.env("ORX_SERVER_READY_PIPE", path); + } #[cfg(unix)] unsafe { + use std::os::fd::AsRawFd as _; use std::os::unix::process::CommandExt as _; - command.pre_exec(|| { + let ready_fd = readiness.as_ref().map(|(_, writer)| writer.as_raw_fd()); + command.pre_exec(move || { + if let Some(fd) = ready_fd { + if libc::fcntl(fd, libc::F_SETFD, 0) == -1 { + return Err(std::io::Error::last_os_error()); + } + } if libc::setsid() == -1 { Err(std::io::Error::last_os_error()) } else { @@ -766,8 +849,22 @@ fn spawn_detached_host(data_dir: &Path) -> Result<(std::process::Child, PathBuf) } }); } - if let Ok(child) = command.spawn() { - return Ok((child, log_path)); + #[cfg(windows)] + { + use std::os::windows::process::CommandExt as _; + use windows_sys::Win32::System::Threading::{CREATE_NEW_PROCESS_GROUP, DETACHED_PROCESS}; + command.creation_flags(DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP); + } + match command.spawn() { + Ok(child) => { + #[cfg(unix)] + let readiness = readiness.map(|(reader, _)| Readiness::Pipe(reader)); + #[cfg(windows)] + let readiness = readiness.map(|(server, _)| Readiness::Named(server)); + return Ok((child, log_path, readiness)); + } + Err(error) if matches!(mode, ServerMode::Headless) => return Err(error.into()), + Err(_) => {} } let log = open_runtime_log(&log_path)?; let child = crate::process::command("nohup") @@ -778,10 +875,9 @@ fn spawn_detached_host(data_dir: &Path) -> Result<(std::process::Child, PathBuf) .stderr(Stdio::from(log)) .spawn() .map_err(|error| anyhow!("Could not start the persistent OpenResearch host: {error}"))?; - Ok((child, log_path)) + Ok((child, log_path, None)) } -#[cfg(unix)] fn open_runtime_log(path: &Path) -> Result { let mut options = OpenOptions::new(); options.create(true).append(true); @@ -791,6 +887,7 @@ fn open_runtime_log(path: &Path) -> Result { options.mode(0o600).custom_flags(libc::O_NOFOLLOW); } let file = options.open(path)?; + #[cfg(unix)] set_mode(path, 0o600)?; Ok(file) } @@ -879,10 +976,17 @@ fn control_socket_path(data_dir: &Path) -> Result { runtime_path(data_dir, "sock") } -#[cfg(unix)] fn runtime_path(data_dir: &Path, extension: &str) -> Result { + #[cfg(unix)] let root = PathBuf::from(format!("/tmp/orx-{}", effective_uid())); + #[cfg(unix)] ensure_private_dir(&root)?; + #[cfg(not(unix))] + let root = { + let root = data_dir.join("runtime"); + std::fs::create_dir_all(&root)?; + root + }; let lock_key = normalize_lock_key(data_dir)?; let hash = Sha256::digest(lock_key.as_os_str().as_encoded_bytes()); let name = hash @@ -1066,3 +1170,688 @@ mod tests { ); } } + +#[derive(Clone, serde::Serialize, serde::Deserialize)] +pub(crate) struct ServerDescriptor { + pub instance: String, + pub pid: u32, + pub starttime: u64, + pub port: u16, + pub version: String, + pub proto: u32, + pub token: String, +} + +impl ServerDescriptor { + pub fn agent_session(port: Option, token: Option) -> Result> { + match (port, token) { + (None, None) => Ok(None), + (Some(port), Some(token)) if !token.is_empty() => Ok(Some(Self { + instance: String::new(), + pid: 0, + starttime: 0, + port: port.parse()?, + version: String::new(), + proto: 2, + token, + })), + _ => Err(anyhow!( + "Agent server credentials are incomplete. Restart this agent session." + )), + } + } + + pub fn publish(&self, data_dir: &Path) -> Result<()> { + crate::local::git::atomic_write_with_mode( + &runtime_path(data_dir, "server.json")?, + &serde_json::to_vec(self)?, + Some(0o600), + )?; + if let Some(mut file) = READY_PIPE.lock().unwrap().take() { + std::io::Write::write_all(&mut file, &[1])?; + } + Ok(()) + } + + pub(crate) async fn live(data_dir: &Path) -> Result> { + let deadline = tokio::time::Instant::now() + Duration::from_secs(3); + loop { + let path = runtime_path(data_dir, "server.json")?; + let metadata = match std::fs::symlink_metadata(&path) { + Ok(metadata) => metadata, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(error) => return Err(error.into()), + }; + if metadata.file_type().is_symlink() || !metadata.is_file() { + return Err(anyhow!( + "Unsafe server descriptor. Remove it and restart OpenResearch." + )); + } + #[cfg(unix)] + if metadata_uid(&metadata) != effective_uid() || metadata_mode(&metadata) & 0o077 != 0 { + return Err(anyhow!( + "Unsafe server descriptor. Remove it and restart OpenResearch." + )); + } + let mut options = OpenOptions::new(); + options.read(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt as _; + options.custom_flags(libc::O_NOFOLLOW); + } + let mut file = options.open(&path)?; + #[cfg(unix)] + { + let metadata = file.metadata()?; + if metadata_uid(&metadata) != effective_uid() + || metadata_mode(&metadata) & 0o077 != 0 + { + return Err(anyhow!( + "Unsafe server descriptor. Remove it and restart OpenResearch." + )); + } + } + let mut bytes = Vec::new(); + std::io::Read::read_to_end(&mut std::io::Read::take(&mut file, 65537), &mut bytes)?; + let descriptor: Self = match serde_json::from_slice(&bytes) { + Ok(value) => value, + Err(_) => return Ok(None), + }; + if crate::engine::process::identity(descriptor.pid) + .is_none_or(|identity| identity.starttime != descriptor.starttime) + { + return Ok(None); + } + if descriptor.proto != 2 || descriptor.token.is_empty() { + return Err(anyhow!("The running OpenResearch server uses an unsupported discovery protocol. Restart it with this version of orx.")); + } + let nonce = uuid::Uuid::new_v4().to_string(); + let response = crate::net::loopback_client() + .build()? + .get(format!("http://127.0.0.1:{}/api/v2/hello", descriptor.port)) + .query(&[("nonce", &nonce)]) + .timeout(Duration::from_millis(500)) + .send() + .await; + let hello = match response { + Ok(response) if response.status().is_success() => { + response.json::().await.ok() + } + _ => None, + }; + let Some(hello) = hello else { + if tokio::time::Instant::now() >= deadline { + return Err(anyhow!( + "The running OpenResearch server is not ready. Try again shortly." + )); + } + tokio::time::sleep(Duration::from_millis(100)).await; + continue; + }; + let verified = hello["instance"].as_str() == Some(&descriptor.instance) + && hello["proto"] == 2 + && hello["proof"].as_str().is_some_and(|proof| { + use base64::Engine as _; + use hmac::Mac; + let Ok(proof) = base64::engine::general_purpose::STANDARD.decode(proof) else { + return false; + }; + hello_mac(&descriptor.token, &descriptor.instance, &nonce) + .verify_slice(&proof) + .is_ok() + }); + if !verified { + return Err(anyhow!("The running OpenResearch server could not be verified. Restart it before trying again.")); + } + return Ok(Some(descriptor)); + } + } +} + +async fn ensure_started( + data_dir: PathBuf, + timeout: Duration, + mode: ServerMode, + args: Vec, + mut inspect: F, +) -> Result +where + T: Send + 'static, + F: FnMut() -> Fut + Send + 'static, + Fut: std::future::Future>> + Send, +{ + let runtime = tokio::runtime::Handle::current(); + tokio::task::spawn_blocking(move || { + let mut lock = open_lock(&shared_path(&data_dir, "start.lock")?)?; + let _guard = lock.write()?; + runtime.block_on(async { + if let Some(descriptor) = inspect().await? { + return Ok(descriptor); + } + let (mut child, log, readiness) = spawn_detached_host(&data_dir, &args, mode)?; + if let Some(readiness) = readiness { + match tokio::time::timeout(timeout, readiness.wait()).await { + Ok(Ok(())) => { + return inspect() + .await? + .ok_or_else(|| anyhow!("Server published an invalid descriptor")); + } + result => { + let eof = matches!( + &result, + Ok(Err(error)) if error.kind() == std::io::ErrorKind::UnexpectedEof + ); + let status = if eof { + Some(child.wait()?) + } else { + child.try_wait()? + }; + if let Some(status) = status { + return Err(anyhow!( + "OpenResearch server exited ({status}). See {}.", + log.display() + )); + } + + let _ = child.kill(); + let _ = child.wait(); + return match result { + Ok(Err(error)) => Err(anyhow!( + "OpenResearch server readiness failed: {error}. See {}.", + log.display() + )), + _ => Err(anyhow!( + "Timed out starting OpenResearch server. See {}.", + log.display() + )), + }; + } + } + } + tokio::time::timeout(timeout, async { + loop { + if let Some(descriptor) = inspect().await? { + return Ok(descriptor); + } + if let Some(status) = child.try_wait()? { + return Err(anyhow!( + "The persistent OpenResearch host exited ({status}). See {}.", + log.display() + )); + } + tokio::time::sleep(Duration::from_millis(100)).await; + } + }) + .await + .map_err(|_| { + anyhow!( + "Timed out starting the persistent OpenResearch host. See {}.", + log.display() + ) + })? + }) + }) + .await? +} + +pub(crate) async fn discover() -> Result { + if let Some(descriptor) = ServerDescriptor::agent_session( + std::env::var("ORX_UP_PORT").ok(), + std::env::var("ORX_UP_AUTH_TOKEN").ok(), + )? { + return Ok(descriptor); + } + discover_at(canonical_data_dir()?).await +} + +async fn discover_at(data_dir: PathBuf) -> Result { + if let Some(descriptor) = ServerDescriptor::live(&data_dir).await? { + return Ok(descriptor); + } + ensure_started( + data_dir.clone(), + Duration::from_secs(10), + ServerMode::Headless, + vec![ + "up".into(), + "--headless".into(), + "--port".into(), + "0".into(), + ], + move || { + let data_dir = data_dir.clone(); + async move { ServerDescriptor::live(&data_dir).await } + }, + ) + .await +} + +pub(crate) fn hello_proof(token: &str, instance: &str, nonce: &str) -> String { + use base64::Engine as _; + use hmac::Mac; + base64::engine::general_purpose::STANDARD + .encode(hello_mac(token, instance, nonce).finalize().into_bytes()) +} + +fn hello_mac(token: &str, instance: &str, nonce: &str) -> hmac::Hmac { + use hmac::Mac; + let mut mac = hmac::Hmac::::new_from_slice(token.as_bytes()) + .expect("HMAC accepts any key length"); + mac.update(instance.as_bytes()); + mac.update(b"\0"); + mac.update(nonce.as_bytes()); + mac +} + +#[cfg(all(test, unix))] +mod discovery_tests { + use super::*; + + #[test] + fn exits_before_readiness_child() { + if std::env::var_os("ORX_SERVER_READY_PIPE").is_some() { + std::process::exit(7); + } + } + + #[tokio::test] + async fn early_headless_exit_reports_the_child_status() { + let directory = + std::env::temp_dir().join(format!("orx-early-exit-{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&directory).unwrap(); + let result: Result = ensure_started( + directory.clone(), + Duration::from_secs(2), + ServerMode::Headless, + vec![ + "--exact".into(), + "commands::remote_host::discovery_tests::exits_before_readiness_child".into(), + ], + || async { Ok(None) }, + ) + .await; + let error = result.err().unwrap().to_string(); + assert!(error.contains("exited") && error.contains('7'), "{error}"); + assert!(!error.contains("persistent")); + std::fs::remove_dir_all(directory).unwrap(); + } + + #[test] + fn legacy_spawn_child() { + let Some(output) = std::env::var_os("ORX_TEST_LEGACY_SPAWN") else { + return; + }; + let source = if matches!( + crate::store::data_dir_source(), + crate::store::DataDirSource::Env + ) { + "env" + } else { + "not env" + }; + std::fs::write(output, source).unwrap(); + } + + #[test] + fn legacy_spawn_parent() { + let Some(output) = std::env::var_os("ORX_TEST_LEGACY_SPAWN") else { + return; + }; + let output = PathBuf::from(output); + let (mut child, log, readiness) = spawn_detached_host( + output.parent().unwrap(), + &[ + "--exact".into(), + "commands::remote_host::discovery_tests::legacy_spawn_child".into(), + ], + ServerMode::Persistent, + ) + .unwrap(); + assert!(readiness.is_none()); + assert!(child.wait().unwrap().success()); + std::fs::remove_file(log).unwrap(); + } + + #[test] + fn legacy_spawn_does_not_change_data_directory_provenance() { + let directory = + std::env::temp_dir().join(format!("orx-legacy-spawn-{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&directory).unwrap(); + let output = directory.join("source"); + let result = crate::process::command(std::env::current_exe().unwrap()) + .args([ + "--exact", + "commands::remote_host::discovery_tests::legacy_spawn_parent", + "--nocapture", + ]) + .env_remove("ORX_DATA_DIR") + .env("ORX_TEST_LEGACY_SPAWN", &output) + .output() + .unwrap(); + assert!( + result.status.success(), + "{}", + String::from_utf8_lossy(&result.stderr) + ); + assert_eq!(std::fs::read_to_string(output).unwrap(), "not env"); + std::fs::remove_dir_all(directory).unwrap(); + } + + #[tokio::test] + async fn discovery_waits_for_a_live_owner_during_restart_without_spawning() { + let directory = + std::env::temp_dir().join(format!("orx-restart-discovery-{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&directory).unwrap(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let descriptor = ServerDescriptor { + instance: "draining".into(), + pid: std::process::id(), + starttime: crate::engine::process::identity(std::process::id()) + .unwrap() + .starttime, + port: listener.local_addr().unwrap().port(), + version: "test".into(), + proto: 2, + token: "secret".into(), + }; + descriptor.publish(&directory).unwrap(); + let app = axum::Router::new().route( + "/api/v2/hello", + axum::routing::get(|| async { axum::http::StatusCode::SERVICE_UNAVAILABLE }), + ); + let server = tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + let error = discover_at(directory.clone()).await.err().unwrap(); + assert!(error.to_string().contains("not ready")); + assert!(!shared_path(&directory, "start.lock").unwrap().exists()); + server.abort(); + let _ = server.await; + let error = discover_at(directory.clone()).await.err().unwrap(); + assert!(error.to_string().contains("not ready")); + assert!(!shared_path(&directory, "start.lock").unwrap().exists()); + std::fs::remove_file(runtime_path(&directory, "server.json").unwrap()).unwrap(); + std::fs::remove_dir_all(directory).unwrap(); + } + + #[tokio::test] + async fn discovery_succeeds_when_the_live_owner_becomes_ready_within_the_bound() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let directory = + std::env::temp_dir().join(format!("orx-ready-discovery-{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&directory).unwrap(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let descriptor = ServerDescriptor { + instance: "restarting".into(), + pid: std::process::id(), + starttime: crate::engine::process::identity(std::process::id()) + .unwrap() + .starttime, + port: listener.local_addr().unwrap().port(), + version: "test".into(), + proto: 2, + token: "secret".into(), + }; + descriptor.publish(&directory).unwrap(); + let calls = Arc::new(AtomicUsize::new(0)); + let count = calls.clone(); + let app = axum::Router::new().route("/api/v2/hello", axum::routing::get(move |axum::extract::Query(query): axum::extract::Query>| { + let count = count.clone(); + async move { + if count.fetch_add(1, Ordering::SeqCst) == 0 { + return Err(axum::http::StatusCode::SERVICE_UNAVAILABLE); + } + Ok(axum::Json(serde_json::json!({"instance":"restarting", "proto":2, "proof":hello_proof("secret", "restarting", &query["nonce"])}))) + } + })); + let server = tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + let started = tokio::time::Instant::now(); + let found = discover_at(directory.clone()).await.unwrap(); + assert_eq!(found.instance, descriptor.instance); + assert!(started.elapsed() >= Duration::from_millis(100)); + assert!(calls.load(Ordering::SeqCst) >= 2); + assert!(!shared_path(&directory, "start.lock").unwrap().exists()); + server.abort(); + let _ = server.await; + std::fs::remove_dir_all(directory).unwrap(); + } + + #[tokio::test] + async fn discovery_checks_process_identity_and_a_nonce_proof_without_sending_the_token() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let directory = + std::env::temp_dir().join(format!("orx-discovery-proof-{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&directory).unwrap(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let mut descriptor = ServerDescriptor { + instance: "instance".into(), + pid: std::process::id(), + starttime: crate::engine::process::identity(std::process::id()) + .unwrap() + .starttime + + 1, + port: listener.local_addr().unwrap().port(), + version: "test".into(), + proto: 2, + token: "private-token".into(), + }; + let calls = Arc::new(AtomicUsize::new(0)); + let count = calls.clone(); + let app = axum::Router::new().route("/api/v2/hello", axum::routing::get(move |headers: axum::http::HeaderMap, axum::extract::Query(query): axum::extract::Query>| { + let count = count.clone(); + async move { + assert!(!headers.contains_key("authorization")); + count.fetch_add(1, Ordering::SeqCst); + axum::Json(serde_json::json!({"instance":"instance", "proto":2, "proof":hello_proof("private-token", "instance", &query["nonce"])})) + } + })); + let server = tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + descriptor.publish(&directory).unwrap(); + assert!(ServerDescriptor::live(&directory).await.unwrap().is_none()); + assert_eq!(calls.load(Ordering::SeqCst), 0); + descriptor.starttime -= 1; + descriptor.publish(&directory).unwrap(); + assert!(ServerDescriptor::live(&directory).await.unwrap().is_some()); + descriptor.token = "incorrect-token".into(); + descriptor.publish(&directory).unwrap(); + assert!(ServerDescriptor::live(&directory).await.is_err()); + let path = runtime_path(&directory, "server.json").unwrap(); + set_mode(&path, 0o666).unwrap(); + assert!(ServerDescriptor::live(&directory).await.is_err()); + set_mode(&path, 0o600).unwrap(); + let target = directory.join("descriptor"); + std::fs::rename(&path, &target).unwrap(); + std::os::unix::fs::symlink(target, &path).unwrap(); + assert!(ServerDescriptor::live(&directory).await.is_err()); + std::fs::remove_file(path).unwrap(); + server.abort(); + std::fs::remove_dir_all(directory).unwrap(); + } + + #[test] + fn agent_session_credentials_take_precedence_and_must_be_complete() { + let descriptor = + ServerDescriptor::agent_session(Some("1234".into()), Some("agent-token".into())) + .unwrap() + .unwrap(); + assert_eq!(descriptor.port, 1234); + assert_eq!(descriptor.token, "agent-token"); + assert!(ServerDescriptor::agent_session(Some("1234".into()), None).is_err()); + assert!(ServerDescriptor::agent_session(None, None) + .unwrap() + .is_none()); + } + + #[tokio::test] + async fn agent_session_child() { + if std::env::var_os("ORX_TEST_AGENT_DISCOVERY").is_none() { + return; + } + let descriptor = discover().await.unwrap(); + assert_eq!(descriptor.port, 1234); + assert_eq!(descriptor.token, "agent-token"); + assert!(!PathBuf::from(std::env::var("ORX_DATA_DIR").unwrap()).exists()); + } + + #[test] + fn discovery_uses_agent_environment_without_touching_a_descriptor_or_starting_a_server() { + let path = + std::env::temp_dir().join(format!("orx-agent-discovery-{}", uuid::Uuid::new_v4())); + let output = crate::process::command(std::env::current_exe().unwrap()) + .args([ + "--exact", + "commands::remote_host::discovery_tests::agent_session_child", + "--nocapture", + ]) + .env("ORX_TEST_AGENT_DISCOVERY", "1") + .env("ORX_UP_PORT", "1234") + .env("ORX_UP_AUTH_TOKEN", "agent-token") + .env("ORX_DATA_DIR", path) + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + } + + #[tokio::test] + async fn autostart_child() { + let Ok(data_dir) = std::env::var("ORX_DATA_DIR").map(PathBuf::from) else { + return; + }; + if !data_dir.join("autostart-fixture").exists() { + return; + } + prepare_readiness_pipe().unwrap(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let descriptor = ServerDescriptor { + instance: uuid::Uuid::new_v4().to_string(), + pid: std::process::id(), + starttime: crate::engine::process::identity(std::process::id()) + .unwrap() + .starttime, + port: listener.local_addr().unwrap().port(), + version: "test".into(), + proto: 2, + token: "private-test-token".into(), + }; + use std::io::Write; + let mut count = OpenOptions::new() + .create(true) + .append(true) + .open(data_dir.join("spawn-count")) + .unwrap(); + writeln!(count, "started").unwrap(); + let instance = descriptor.instance.clone(); + let token = descriptor.token.clone(); + let app = axum::Router::new().route( + "/api/v2/hello", + axum::routing::get(move |axum::extract::Query(query): axum::extract::Query>| { + let instance = instance.clone(); let token = token.clone(); + async move { axum::Json(serde_json::json!({"instance":instance,"proto":2,"proof":hello_proof(&token, &instance, &query["nonce"])})) } + }), + ); + descriptor.publish(&data_dir).unwrap(); + let _ = tokio::time::timeout( + Duration::from_secs(20), + std::future::IntoFuture::into_future(axum::serve(listener, app)), + ) + .await; + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn concurrent_autostarts_recheck_the_descriptor_under_the_shared_start_lock() { + let data_dir = std::env::temp_dir().join(format!("orx-discover-{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&data_dir).unwrap(); + std::fs::write(data_dir.join("autostart-fixture"), []).unwrap(); + let stale = ServerDescriptor { + instance: "dead".into(), + pid: i32::MAX as u32, + starttime: 0, + port: 1, + version: "test".into(), + proto: 2, + token: "old".into(), + }; + stale.publish(&data_dir).unwrap(); + assert!(ServerDescriptor::live(&data_dir).await.unwrap().is_none()); + let start = |data_dir: PathBuf| { + ensure_started( + data_dir.clone(), + Duration::from_secs(10), + ServerMode::Headless, + vec![ + "--exact".into(), + "commands::remote_host::discovery_tests::autostart_child".into(), + "--nocapture".into(), + ], + move || { + let data_dir = data_dir.clone(); + async move { ServerDescriptor::live(&data_dir).await } + }, + ) + }; + let (left, right) = tokio::join!(start(data_dir.clone()), start(data_dir.clone())); + let left = left.unwrap(); + let right = right.unwrap(); + assert_eq!(left.instance, right.instance); + assert_eq!( + std::fs::read_to_string(data_dir.join("spawn-count")).unwrap(), + "started\n" + ); + unsafe { + libc::kill(left.pid as i32, libc::SIGTERM); + } + let _ = std::fs::remove_file(runtime_path(&data_dir, "server.json").unwrap()); + let _ = std::fs::remove_dir_all(data_dir); + } + + #[tokio::test] + async fn wrong_instance_echo_and_reused_port_refuse_discovery() { + let data_dir = + std::env::temp_dir().join(format!("orx-wrong-server-{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&data_dir).unwrap(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let descriptor = ServerDescriptor { + instance: "expected".into(), + pid: std::process::id(), + starttime: crate::engine::process::identity(std::process::id()) + .unwrap() + .starttime, + port: listener.local_addr().unwrap().port(), + version: "test".into(), + proto: 2, + token: "secret".into(), + }; + descriptor.publish(&data_dir).unwrap(); + let app = axum::Router::new().route( + "/api/v2/hello", + axum::routing::get(|| async { + axum::Json(serde_json::json!({"instance":"different", "proto":2})) + }), + ); + let task = tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + assert!(ServerDescriptor::live(&data_dir).await.is_err()); + task.abort(); + task.await.unwrap_err(); + let listener = tokio::net::TcpListener::bind(("127.0.0.1", descriptor.port)) + .await + .unwrap(); + let task = tokio::spawn(async move { + axum::serve(listener, axum::Router::new()).await.unwrap(); + }); + assert!(ServerDescriptor::live(&data_dir).await.is_err()); + task.abort(); + let _ = std::fs::remove_file(runtime_path(&data_dir, "server.json").unwrap()); + let _ = std::fs::remove_dir_all(data_dir); + } +} diff --git a/src/commands/runs.rs b/src/commands/runs.rs index b66e8d667..29a12e343 100644 --- a/src/commands/runs.rs +++ b/src/commands/runs.rs @@ -37,7 +37,7 @@ pub async fn run(args: crate::RunsArgs) -> Result<()> { .map(|r| { vec![ r.id.clone(), - r.status.clone(), + r.display_status().into(), listing .titles .get(&r.experiment_id) @@ -65,6 +65,12 @@ pub async fn run(args: crate::RunsArgs) -> Result<()> { &rows, ); + for run in &filtered { + if let Some(detail) = run.contact_detail() { + println!("{} {detail}", run.id); + } + } + if !failures.is_empty() { println!(); for (id, detail) in &failures { diff --git a/src/commands/supervise.rs b/src/commands/supervise.rs index 011812f8a..adca3734a 100644 --- a/src/commands/supervise.rs +++ b/src/commands/supervise.rs @@ -22,6 +22,90 @@ use crate::jobs::vercel; use crate::jobs::{is_terminal_stage, stage_to_run_status, BackendDescriptor}; use crate::store::{log_path, now_ms, RunStatus, Store}; +pub(crate) trait RunSink { + fn transport_error(&self, _run: &str, _target: &ssh::SshTarget, _cause: &str) -> Result<()> { + Ok(()) + } + fn finish( + &self, + run: &str, + status: RunStatus, + exit_code: Option, + reason: Option<&str>, + ) -> Result { + let applied = self.update_status(run, status, Some(now_ms()), exit_code)?; + if applied { + if let Some(reason) = reason { + if let Err(error) = self.set_result_markdown(run, reason) { + eprintln!("supervise {run}: could not record failure reason: {error}"); + } + } + } + Ok(applied) + } + fn get_run(&self, run: &str) -> Result>; + fn update_status( + &self, + run: &str, + status: RunStatus, + ended_at: Option, + exit_code: Option, + ) -> Result; + fn set_result_markdown(&self, run: &str, result: &str) -> Result<()>; + fn set_backend_json(&self, run: &str, descriptor: &str) -> Result<()>; + fn queue_finished_remote_cleanup(&self, run: &str) -> Result<()>; +} + +impl RunSink for Store { + fn get_run(&self, run: &str) -> Result> { + self.get_run(run) + } + fn update_status( + &self, + run: &str, + status: RunStatus, + ended_at: Option, + exit_code: Option, + ) -> Result { + self.update_status(run, status, ended_at, exit_code) + } + fn set_result_markdown(&self, run: &str, result: &str) -> Result<()> { + self.set_result_markdown(run, result) + } + fn set_backend_json(&self, run: &str, descriptor: &str) -> Result<()> { + self.set_backend_json(run, descriptor) + } + fn queue_finished_remote_cleanup(&self, run: &str) -> Result<()> { + self.queue_finished_remote_cleanup(run) + } +} + +impl RunSink for std::sync::Mutex { + fn get_run(&self, run: &str) -> Result> { + self.lock().unwrap().get_run(run) + } + fn update_status( + &self, + run: &str, + status: RunStatus, + ended_at: Option, + exit_code: Option, + ) -> Result { + self.lock() + .unwrap() + .update_status(run, status, ended_at, exit_code) + } + fn set_result_markdown(&self, run: &str, result: &str) -> Result<()> { + self.lock().unwrap().set_result_markdown(run, result) + } + fn set_backend_json(&self, run: &str, descriptor: &str) -> Result<()> { + self.lock().unwrap().set_backend_json(run, descriptor) + } + fn queue_finished_remote_cleanup(&self, run: &str) -> Result<()> { + self.lock().unwrap().queue_finished_remote_cleanup(run) + } +} + const POLL_INTERVAL: Duration = Duration::from_secs(5); /// How long a silent log stream is held before re-checking job state. const LOG_IDLE: Duration = Duration::from_secs(30); @@ -42,7 +126,7 @@ fn open_supervisor_lock(path: &std::path::Path) -> Result std::path::PathBuf { - log_path(run_id).with_extension("supervisor.lock") + log_path(&crate::store::data_dir(), run_id).with_extension("supervisor.lock") } /// Whether a live `orx supervise` holds `run_id`'s lock. @@ -51,7 +135,9 @@ pub(crate) fn supervisor_running(run_id: &str) -> bool { } pub(crate) fn uses_shared_ssh(run_id: &str) -> bool { - lock_held(&log_path(run_id).with_extension("supervisor.shared-ssh.lock")) + lock_held( + &log_path(&crate::store::data_dir(), run_id).with_extension("supervisor.shared-ssh.lock"), + ) } fn lock_held(path: &std::path::Path) -> bool { @@ -120,8 +206,9 @@ pub async fn run(args: crate::SuperviseArgs) -> Result<()> { Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => return Ok(()), Err(err) => return Err(err.into()), }; - let mut protocol_lock = - open_supervisor_lock(&log_path(&run_id).with_extension("supervisor.shared-ssh.lock"))?; + let mut protocol_lock = open_supervisor_lock( + &log_path(&crate::store::data_dir(), &run_id).with_extension("supervisor.shared-ssh.lock"), + )?; let _protocol_guard = protocol_lock.try_write()?; let stored = store .get_run(&run_id)? @@ -191,7 +278,7 @@ pub async fn run(args: crate::SuperviseArgs) -> Result<()> { // then report `running`… as `done` (the UI would see no live run at all, // then the whole log at once). The tail task owns the log file; this loop // owns status and cancel intent. - let path = log_path(&run_id); + let path = log_path(&crate::store::data_dir(), &run_id); let (done_tx, done_rx) = tokio::sync::watch::channel(false); let mut log_task = tokio::spawn(tail_logs( token.clone(), @@ -260,7 +347,7 @@ pub async fn run(args: crate::SuperviseArgs) -> Result<()> { /// Local cancel intent from the run row itself. Best-effort — a transient /// db error must not kill supervision. -fn local_cancel_requested(store: &Store, run_id: &str) -> bool { +fn local_cancel_requested(store: &dyn RunSink, run_id: &str) -> bool { store .get_run(run_id) .ok() @@ -269,11 +356,16 @@ fn local_cancel_requested(store: &Store, run_id: &str) -> bool { .unwrap_or(false) } -fn should_report_cancelled(store: &Store, run_id: &str, cancel_sent: bool) -> bool { +fn should_report_cancelled(store: &dyn RunSink, run_id: &str, cancel_sent: bool) -> bool { cancel_sent || local_cancel_requested(store, run_id) } -fn run_status_for_stage(store: &Store, run_id: &str, cancel_sent: bool, stage: &str) -> RunStatus { +fn run_status_for_stage( + store: &dyn RunSink, + run_id: &str, + cancel_sent: bool, + stage: &str, +) -> RunStatus { if stage == "LOST" { return if cancel_sent { RunStatus::Cancelled @@ -330,7 +422,7 @@ async fn tail_logs( seen += 1; log.line(line); }; - let pass = hf::stream_logs(&token, &namespace, &job_id, skip, LOG_IDLE, &mut sink); + let pass = hf::stream_logs(&token, &namespace, &job_id, skip, Some(LOG_IDLE), &mut sink); let Some(result) = log_pass(&mut done, draining, pass).await else { continue; }; @@ -384,7 +476,7 @@ async fn run_k8s( eprintln!("supervise {run_id}: watching k8s job {namespace}/{job_name}"); - let path = log_path(&run_id); + let path = log_path(&crate::store::data_dir(), &run_id); let (done_tx, done_rx) = tokio::sync::watch::channel(false); let mut log_task = tokio::spawn(tail_logs_k8s( context.clone(), @@ -490,7 +582,7 @@ async fn tail_logs_k8s( &namespace, &job_name, &mut resume, - LOG_IDLE, + Some(LOG_IDLE), &mut sink, ); let Some(streamed) = log_pass(&mut done, draining, pass).await else { @@ -539,7 +631,7 @@ async fn run_modal( eprintln!("supervise {run_id}: watching modal sandbox {sandbox_id}"); - let path = log_path(&run_id); + let path = log_path(&crate::store::data_dir(), &run_id); let (done_tx, done_rx) = tokio::sync::watch::channel(false); let mut log_task = tokio::spawn(tail_logs_modal( sandbox_id.clone(), @@ -628,7 +720,7 @@ async fn tail_logs_modal( seen += 1; log.line(line); }; - let pass = modal::stream_logs(&sandbox_id, skip, LOG_IDLE, &mut sink); + let pass = modal::stream_logs(&sandbox_id, skip, Some(LOG_IDLE), &mut sink); let Some(result) = log_pass(&mut done, draining, pass).await else { continue; }; @@ -669,7 +761,7 @@ async fn run_vercel( eprintln!("supervise {run_id}: watching vercel sandbox {name} (process {process_id})"); - let path = log_path(&run_id); + let path = log_path(&crate::store::data_dir(), &run_id); let (done_tx, done_rx) = tokio::sync::watch::channel(false); let mut log_task = tokio::spawn(tail_logs_vercel( name.clone(), @@ -851,6 +943,7 @@ async fn run_ssh( mut descriptor: BackendDescriptor, run_id: String, ) -> Result<()> { + let store = std::sync::Mutex::new(store); let (host, dir) = descriptor.ssh_ref()?; eprintln!("supervise {run_id}: watching ssh job {host}:{dir}"); let target = ssh::SshTarget::alias(host).for_run(&run_id); @@ -871,8 +964,8 @@ async fn run_ssh( /// The ssh two-half loop, shared by every backend whose job is a run dir on a /// box we ssh into (ssh itself, openresearch). Runs until the job is terminal /// and returns the final run status after logs are drained. -async fn watch_ssh_job( - store: &Store, +pub(crate) async fn watch_ssh_job( + store: &(dyn RunSink + Sync), initial_status: RunStatus, target: ssh::SshTarget, dir: String, @@ -881,7 +974,7 @@ async fn watch_ssh_job( sandbox: Option<(&Credentials, &str)>, ) -> Result { let container = descriptor.ssh_container.clone(); - let path = log_path(run_id); + let path = log_path(&crate::store::data_dir(), run_id); let (done_tx, done_rx) = tokio::sync::watch::channel(false); let (log_error_tx, log_error_rx) = tokio::sync::watch::channel(None); let mut log_task = tokio::spawn(tail_logs_ssh( @@ -893,6 +986,14 @@ async fn watch_ssh_job( Some(log_error_tx), )); + struct StopTail(tokio::task::AbortHandle); + impl Drop for StopTail { + fn drop(&mut self) { + self.0.abort(); + } + } + let _tail = StopTail(log_task.abort_handle()); + let mut last_status = initial_status; let mut cancel_sent = descriptor.cancellation_accepted; let mut last_message = None; @@ -918,6 +1019,9 @@ async fn watch_ssh_job( .err() .map(ToString::to_string) .or_else(|| log_error_rx.borrow().clone()); + if let Some(error) = &polling_error { + store.transport_error(run_id, &target, error)?; + } let error = polling_error.map(|err| { let recovery = if descriptor.kind == "ssh_job" { format!( @@ -990,7 +1094,7 @@ async fn watch_ssh_job( } let mut job = job; let mut exit_code = None; - if descriptor.rental_lease.is_some() && is_terminal_stage(&job.stage) { + if is_terminal_stage(&job.stage) { exit_code = ssh::ssh_run( &target, &format!("cat {}/exit_code", ssh::shell_path(&dir)), @@ -1023,24 +1127,19 @@ async fn watch_ssh_job( if !collected { log_task.abort(); } - let applied = store.update_status(run_id, status, Some(now_ms()), exit_code)?; - if applied && matches!(status, RunStatus::Failed | RunStatus::Lost) { - if let Some(msg) = &job.message { - if let Err(err) = store.set_result_markdown( - run_id, - &format!( - "{}: {msg}", - if status == RunStatus::Lost { - "Outcome unavailable" - } else { - "Job failed" - } - ), - ) { - eprintln!("supervise {run_id}: could not record failure reason: {err}"); - } - } - } + let reason = job + .message + .as_ref() + .filter(|_| matches!(status, RunStatus::Failed | RunStatus::Lost)) + .map(|message| { + let prefix = if status == RunStatus::Lost { + "Outcome unavailable" + } else { + "Job failed" + }; + format!("{prefix}: {message}") + }); + store.finish(run_id, status, exit_code, reason.as_deref())?; if descriptor.rental_lease.is_some() && stage != "LOST" && collected @@ -1124,13 +1223,17 @@ async fn tail_logs_ssh( let mut last_error = None; loop { let draining = *done.borrow(); - let result = ssh::service::request( - &target, - serde_json::json!({ - "op":"collect", "run":run_id, "dir":dir, - }), - ) - .await; + let result = if let Some(transport) = &target.transport { + transport.collect(&run_id, &dir).await + } else { + ssh::service::request( + &target, + serde_json::json!({ + "op":"collect", "run":run_id, "dir":dir, + }), + ) + .await + }; match result { Ok(value) => { last_error = None; @@ -1190,8 +1293,25 @@ async fn cancel_ssh( async fn run_openresearch( store: Store, stored: crate::store::StoredRun, + descriptor: BackendDescriptor, + run_id: String, +) -> Result<()> { + run_openresearch_loop( + &std::sync::Mutex::new(store), + stored, + descriptor, + run_id, + None, + ) + .await +} + +pub(crate) async fn run_openresearch_loop( + store: &(dyn RunSink + Sync), + stored: crate::store::StoredRun, mut descriptor: BackendDescriptor, run_id: String, + transport: Option, ) -> Result<()> { let (_org, sandbox_id) = descriptor.openresearch_ref()?; let sandbox_id = sandbox_id.to_string(); @@ -1202,24 +1322,29 @@ async fn run_openresearch( let lifecycle = match crate::config::load_credentials().await { Ok(Some(c)) => c, _ => { - if store.update_status(&run_id, RunStatus::Failed, Some(now_ms()), None)? { - store.set_result_markdown( - &run_id, - &format!( - "The supervisor found no OpenResearch credentials (`orx login`), so it \ - could not manage box {sandbox_id} — the box may still be running; \ - delete it through OpenResearch." - ), - )?; - } + store.finish( + &run_id, + RunStatus::Failed, + None, + Some(&format!( + "The supervisor found no OpenResearch credentials (`orx login`), so it \ + could not manage box {sandbox_id} — the box may still be running; \ + delete it through OpenResearch." + )), + )?; return Err(anyhow!("no credentials for the openresearch backend")); } }; - let mut bootstrap_heartbeat = descriptor - .rental_lease - .as_ref() - .map(crate::jobs::rental::Rental::heartbeat); + let mut bootstrap_heartbeat = + if transport.is_none() || descriptor.openresearch_ssh_target().is_none() { + descriptor + .rental_lease + .as_ref() + .map(crate::jobs::rental::Rental::heartbeat) + } else { + None + }; let dir = openresearch::run_dir(&run_id); // Provisioning: wait for the box unless a restarted supervisor already @@ -1228,38 +1353,52 @@ async fn run_openresearch( Some(target) => target, None => { eprintln!("supervise {run_id}: waiting for box {sandbox_id} to come online"); - let outcome = openresearch::wait_online( - &lifecycle, - &sandbox_id, - openresearch::PROVISION_DEADLINE, - || local_cancel_requested(&store, &run_id), - ) - .await; - let sandbox = match outcome { - Ok(openresearch::WaitOutcome::Online(sandbox)) => sandbox, - Ok(openresearch::WaitOutcome::Cancelled) => { - eprintln!("supervise {run_id}: cancelled during provisioning"); - store.update_status(&run_id, RunStatus::Cancelled, Some(now_ms()), None)?; - teardown_box(&store, &lifecycle, &sandbox_id, &run_id).await; - return Ok(()); - } - Ok(openresearch::WaitOutcome::Failed(reason)) - | Ok(openresearch::WaitOutcome::TimedOut(reason)) => { - if store.update_status(&run_id, RunStatus::Failed, Some(now_ms()), None)? { - store.set_result_markdown( + let sandbox = loop { + let outcome = openresearch::wait_online( + &lifecycle, + &sandbox_id, + openresearch::PROVISION_DEADLINE, + || local_cancel_requested(store, &run_id), + ) + .await; + match outcome { + Ok(openresearch::WaitOutcome::Online(sandbox)) => break sandbox, + Ok(openresearch::WaitOutcome::Cancelled) => { + eprintln!("supervise {run_id}: cancelled during provisioning"); + store.update_status(&run_id, RunStatus::Cancelled, Some(now_ms()), None)?; + teardown_box(store, &lifecycle, &sandbox_id, &run_id).await; + return Ok(()); + } + Ok(openresearch::WaitOutcome::TimedOut(reason)) if transport.is_some() => { + drop(bootstrap_heartbeat.take()); + eprintln!("supervise {run_id}: provisioning unresolved: {reason}"); + tokio::time::sleep(POLL_INTERVAL).await; + } + Err(error) if transport.is_some() => { + drop(bootstrap_heartbeat.take()); + eprintln!("supervise {run_id}: provisioning unavailable: {error}"); + tokio::time::sleep(POLL_INTERVAL).await; + } + Ok(openresearch::WaitOutcome::Failed(reason)) + | Ok(openresearch::WaitOutcome::TimedOut(reason)) => { + store.finish( &run_id, - &format!("Provisioning failed: {reason}"), + RunStatus::Failed, + None, + Some(&format!("Provisioning failed: {reason}")), )?; + return Ok(()); } - return Ok(()); - } - Err(err) => { - if store.update_status(&run_id, RunStatus::Failed, Some(now_ms()), None)? { - store - .set_result_markdown(&run_id, &format!("Provisioning failed: {err}"))?; + Err(err) => { + store.finish( + &run_id, + RunStatus::Failed, + None, + Some(&format!("Provisioning failed: {err}")), + )?; + teardown_box(store, &lifecycle, &sandbox_id, &run_id).await; + return Ok(()); } - teardown_box(&store, &lifecycle, &sandbox_id, &run_id).await; - return Ok(()); } }; descriptor.ssh_host = sandbox.ssh_hostname.clone(); @@ -1272,120 +1411,146 @@ async fn run_openresearch( } }; - let target = target.for_run(&run_id); + let mut target = target.for_run(&run_id); + target.transport = transport + .as_ref() + .map(|factory| factory(&target)) + .transpose()?; // Launch, unless a previous supervisor already did (restart mid-run just // reattaches to the watch loop). An unreachable box reads as fresh here; // the launch retries below absorb that. - let already_launched = loop { - match openresearch::launched(&target, &run_id).await { - Ok(launched) => break launched, - Err(_) if descriptor.rental_lease.is_some() => { - drop(bootstrap_heartbeat.take()); - if local_cancel_requested(&store, &run_id) { - teardown_box(&store, &lifecycle, &sandbox_id, &run_id).await; - store.update_status(&run_id, RunStatus::Cancelled, Some(now_ms()), None)?; - return Ok(()); - } - if openresearch::box_deleted(&lifecycle, &sandbox_id).await { - if store.update_status(&run_id, RunStatus::Lost, Some(now_ms()), None)? { - store.set_result_markdown( + 'bootstrap: loop { + let already_launched = loop { + match openresearch::launched(&target, &run_id).await { + Ok(launched) => break launched, + Err(error) if descriptor.rental_lease.is_some() || transport.is_some() => { + drop(bootstrap_heartbeat.take()); + store.transport_error(&run_id, &target, &error.to_string())?; + if local_cancel_requested(store, &run_id) { + teardown_box(store, &lifecycle, &sandbox_id, &run_id).await; + store.update_status(&run_id, RunStatus::Cancelled, Some(now_ms()), None)?; + return Ok(()); + } + if openresearch::box_deleted(&lifecycle, &sandbox_id).await { + store.finish( &run_id, - "Outcome unavailable: the rental was released before its final outcome was collected.", + RunStatus::Lost, + None, + Some(&crate::plane::LABELS["run_notice_rental_outcome_unavailable"]), )?; + return Ok(()); } - return Ok(()); + tokio::time::sleep(POLL_INTERVAL).await; } - tokio::time::sleep(POLL_INTERVAL).await; + Err(_) => break false, } - Err(_) => break false, - } - }; - if !already_launched { - if bootstrap_heartbeat.is_none() { - bootstrap_heartbeat = descriptor - .rental_lease - .as_ref() - .map(crate::jobs::rental::Rental::heartbeat); - } - let source = match crate::compute::SourceSnapshot::from_run(&stored, &descriptor) { - Ok(source) => source, - Err(error) => { - if store.update_status(&run_id, RunStatus::Failed, Some(now_ms()), None)? { - store.set_result_markdown( + }; + if !already_launched { + if bootstrap_heartbeat.is_none() { + bootstrap_heartbeat = descriptor + .rental_lease + .as_ref() + .map(crate::jobs::rental::Rental::heartbeat); + } + let source = match crate::compute::SourceSnapshot::from_run(&stored, &descriptor) { + Ok(source) => source, + Err(error) => { + store.finish( &run_id, - &format!("The recorded source snapshot could not be loaded: {error}"), + RunStatus::Failed, + None, + Some(&format!( + "The recorded source snapshot could not be loaded: {error}" + )), )?; + teardown_box(store, &lifecycle, &sandbox_id, &run_id).await; + return Ok(()); } - teardown_box(&store, &lifecycle, &sandbox_id, &run_id).await; - return Ok(()); - } - }; - let script = crate::compute::staged_script(&stored.command); - let script = - openresearch::wrap_with_timeout(&script, descriptor.timeout_secs.unwrap_or(4 * 3600)); - let mut env = crate::config::run_env(&run_id); - if let Ok(hf_token) = hf::resolve_token() { - env.entry("HF_TOKEN".to_string()).or_insert(hf_token); - } - // sshd and the org key sync can lag a freshly-online box, so the - // launch retries for ~2 minutes before giving up. - let mut launch_err = None; - for backoff_secs in [0u64, 5, 10, 20, 30, 45] { - if backoff_secs > 0 { - tokio::time::sleep(Duration::from_secs(backoff_secs)).await; - } - if local_cancel_requested(&store, &run_id) { - eprintln!("supervise {run_id}: cancelled before launch"); - store.update_status(&run_id, RunStatus::Cancelled, Some(now_ms()), None)?; - teardown_box(&store, &lifecycle, &sandbox_id, &run_id).await; - return Ok(()); - } - let staged = - ssh::stage_source(&target, &run_id, &source.path, &source.digest, None, None).await; - if let Err(err) = staged { - eprintln!("supervise {run_id}: source staging failed (will retry): {err}"); - launch_err = Some(err); - continue; - } - let launch = if let Some(rental) = &descriptor.rental_lease { - crate::jobs::rental::launch(&target, &run_id, &script, &env, rental).await - } else { - ssh::run_job(&ssh::SshJobSpec { - container: None, - target: target.clone(), - run_id: run_id.clone(), - remote_root: None, - script: script.clone(), - env: env.clone(), - }) - .await - .map(|_| ()) }; - match launch { - Ok(_) => { - launch_err = None; - break; + let script = crate::compute::staged_script(&stored.command); + let script = openresearch::wrap_with_timeout( + &script, + descriptor.timeout_secs.unwrap_or(4 * 3600), + ); + let mut env = crate::config::run_env(&run_id); + if let Ok(hf_token) = hf::resolve_token() { + env.entry("HF_TOKEN".to_string()).or_insert(hf_token); + } + // sshd and the org key sync can lag a freshly-online box, so the + // launch retries for ~2 minutes before giving up. + let mut launch_err = None; + for backoff_secs in [0u64, 5, 10, 20, 30, 45] { + if backoff_secs > 0 { + tokio::time::sleep(Duration::from_secs(backoff_secs)).await; } - Err(err) => { - eprintln!("supervise {run_id}: launch failed (will retry): {err}"); + if local_cancel_requested(store, &run_id) { + eprintln!("supervise {run_id}: cancelled before launch"); + store.update_status(&run_id, RunStatus::Cancelled, Some(now_ms()), None)?; + teardown_box(store, &lifecycle, &sandbox_id, &run_id).await; + return Ok(()); + } + let staged = + ssh::stage_source(&target, &run_id, &source.path, &source.digest, None, None) + .await; + if let Err(err) = staged { + eprintln!("supervise {run_id}: source staging failed (will retry): {err}"); + if transport.is_some() { + drop(bootstrap_heartbeat.take()); + store.transport_error(&run_id, &target, &err.to_string())?; + tokio::time::sleep(POLL_INTERVAL).await; + continue 'bootstrap; + } launch_err = Some(err); + continue; + } + let launch = if let Some(rental) = &descriptor.rental_lease { + crate::jobs::rental::launch(&target, &run_id, &script, &env, rental).await + } else { + ssh::run_job(&ssh::SshJobSpec { + container: None, + target: target.clone(), + run_id: run_id.clone(), + remote_root: None, + script: script.clone(), + env: env.clone(), + }) + .await + .map(|_| ()) + }; + match launch { + Ok(_) => { + launch_err = None; + break; + } + Err(err) => { + eprintln!("supervise {run_id}: launch failed (will retry): {err}"); + if transport.is_some() { + drop(bootstrap_heartbeat.take()); + store.transport_error(&run_id, &target, &err.to_string())?; + tokio::time::sleep(POLL_INTERVAL).await; + continue 'bootstrap; + } + launch_err = Some(err); + } } } - } - if let Some(err) = launch_err.filter(|_| descriptor.rental_lease.is_none()) { - if store.update_status(&run_id, RunStatus::Failed, Some(now_ms()), None)? { - store.set_result_markdown( + if let Some(err) = launch_err.filter(|_| descriptor.rental_lease.is_none()) { + store.finish( &run_id, - &crate::local::ssh_identity::explain_launch_failure( + RunStatus::Failed, + None, + Some(&crate::local::ssh_identity::explain_launch_failure( &sandbox_id, &err.to_string(), - ), + )), )?; + teardown_box(store, &lifecycle, &sandbox_id, &run_id).await; + return Ok(()); } - teardown_box(&store, &lifecycle, &sandbox_id, &run_id).await; - return Ok(()); } + + break; } drop(bootstrap_heartbeat); @@ -1395,7 +1560,7 @@ async fn run_openresearch( ); // Legacy rentals require local teardown; leased rentals release remotely. let watch = watch_ssh_job( - &store, + store, status_of(&stored)?, target, dir, @@ -1405,7 +1570,7 @@ async fn run_openresearch( ) .await; if descriptor.rental_lease.is_none() { - teardown_box(&store, &lifecycle, &sandbox_id, &run_id).await; + teardown_box(store, &lifecycle, &sandbox_id, &run_id).await; } watch?; Ok(()) @@ -1414,7 +1579,12 @@ async fn run_openresearch( /// Delete the run's box; on failure warn loudly and leave a cleanup hint on /// the run. Teardown failure never changes the run's status — the run's /// outcome and the box's fate are separate facts. -async fn teardown_box(store: &Store, creds: &Credentials, sandbox_id: &str, run_id: &str) { +async fn teardown_box( + store: &(dyn RunSink + Sync), + creds: &Credentials, + sandbox_id: &str, + run_id: &str, +) { match openresearch::teardown(creds, sandbox_id).await { Ok(()) => eprintln!("supervise {run_id}: box {sandbox_id} deleted"), Err(err) => { @@ -1451,7 +1621,7 @@ async fn run_local( eprintln!("supervise {run_id}: watching local run {}", dir.display()); - let path = log_path(&run_id); + let path = log_path(&crate::store::data_dir(), &run_id); let (done_tx, done_rx) = tokio::sync::watch::channel(false); let mut log_task = tokio::spawn(tail_logs_local( dir.clone(), @@ -1476,7 +1646,12 @@ async fn run_local( { log_task.abort(); } - let applied = store.update_status(&run_id, status, Some(now_ms()), None)?; + let applied = store.update_status( + &run_id, + status, + Some(now_ms()), + job.exit_code.map(i64::from), + )?; if applied && status == RunStatus::Failed { if let Some(msg) = &job.message { if let Err(err) = @@ -1574,7 +1749,7 @@ async fn run_slurm( eprintln!("supervise {run_id}: watching slurm job {job_id} on {host}"); - let path = log_path(&run_id); + let path = log_path(&crate::store::data_dir(), &run_id); let (done_tx, done_rx) = tokio::sync::watch::channel(false); let (log_error_tx, log_error_rx) = tokio::sync::watch::channel(None); let mut log_task = tokio::spawn(tail_logs_ssh( @@ -1683,7 +1858,7 @@ async fn run_slurm( /// Queues the remote run dir once logs are local; `orx up` removes it when it falls past its /// project's newest few, unless the target keeps results. -fn queue_remote_cleanup(store: &Store, run_id: &str) { +fn queue_remote_cleanup(store: &dyn RunSink, run_id: &str) { if let Err(err) = store.queue_finished_remote_cleanup(run_id) { eprintln!("supervise {run_id}: could not queue remote cleanup: {err}"); } @@ -1713,7 +1888,7 @@ async fn run_ray( eprintln!("supervise {run_id}: watching ray job {submission_id} at {address}"); - let path = log_path(&run_id); + let path = log_path(&crate::store::data_dir(), &run_id); let (done_tx, done_rx) = tokio::sync::watch::channel(false); let mut log_task = tokio::spawn(tail_logs_ray( address.clone(), @@ -1747,6 +1922,7 @@ async fn run_ray( continue; } job = ray::JobInfo { + exit_code: None, stage: "ERROR".to_string(), message: Some( "job no longer known to the cluster (record purged or head restarted?)" @@ -1883,6 +2059,42 @@ mod tests { use super::*; use crate::store::StoredRun; + #[test] + fn store_sink_finishes_even_when_the_failure_reason_cannot_be_written() { + let dir = std::env::temp_dir().join(format!("orx-sink-reason-{}", uuid::Uuid::new_v4())); + let store = Store::open_at(dir.clone()).unwrap(); + let run = StoredRun { + id: "run".into(), + experiment_id: "exp".into(), + project_id: "proj".into(), + status: "running".into(), + backend_json: "{}".into(), + command: String::new(), + created_at: 1, + updated_at: 1, + ended_at: None, + exit_code: None, + commit_sha: None, + result_markdown: None, + cancel_requested: false, + cancel_reason: None, + chat_session_id: None, + }; + store.upsert_run(&run).unwrap(); + let fault = rusqlite::Connection::open(dir.join("orx.db")).unwrap(); + fault.execute_batch("CREATE TRIGGER reject_reason BEFORE UPDATE OF result_markdown ON runs BEGIN SELECT RAISE(FAIL, 'reason write rejected'); END;").unwrap(); + assert!(store + .finish("run", RunStatus::Failed, Some(7), Some("payload failed")) + .unwrap()); + let finished = store.get_run("run").unwrap().unwrap(); + assert_eq!(finished.status, "failed"); + assert_eq!(finished.exit_code, Some(7)); + assert!(finished.result_markdown.is_none()); + drop(fault); + drop(store); + std::fs::remove_dir_all(dir).unwrap(); + } + #[test] fn monitoring_errors_wait_for_grace_but_preserve_existing_reports() { assert!(!should_report_monitoring_error(false, None)); diff --git a/src/commands/tensorboard.rs b/src/commands/tensorboard.rs index 8f97ee9e9..825fde3dd 100644 --- a/src/commands/tensorboard.rs +++ b/src/commands/tensorboard.rs @@ -1,39 +1,69 @@ //! `orx tensorboard `: the command that opens a run's TensorBoard logs. +use crate::engine::handle::Handle; use crate::error::{anyhow, Result}; use crate::jobs::ssh::sh_quote; use crate::jobs::BackendDescriptor; -use crate::store::Store; +use crate::store::{LaunchSpec, Store, StoredRun}; const PORT: u16 = 6006; pub async fn run(args: crate::TensorboardArgs) -> Result<()> { let store = Store::open()?; let run = crate::local::resolve::resolve_run(&store, &args.run_id)?; - let backend = BackendDescriptor::parse(&run.backend_json)?; - println!("{}", viewer_command(&run.id, &backend)?); + let launch = store + .engine_run_state(&run.id)? + .and_then(|state| state.launch); + println!("{}", viewer_command(&run, launch.as_ref())?); Ok(()) } -fn viewer_command(run_id: &str, backend: &BackendDescriptor) -> Result { - let (host, dir) = match backend.kind.as_str() { +/// Where the run's `tensorboard/` directory is: its host (`None` for this machine) and run dir. +fn run_dir(run: &StoredRun, launch: Option<&LaunchSpec>) -> Result<(Option, String)> { + let containerized = launch.is_some_and(|launch| !launch.options["container"].is_null()); + let engine_dir = |root: &str| { + let root = root.strip_prefix("~/").unwrap_or(root); + format!("{root}/runs/{}", run.id) + }; + Ok(match crate::engine::handle_of(run) { + Some(Handle::Local { dir } | Handle::Tinker { dir }) => (None, dir), + Some(Handle::Ssh { host, root }) if !containerized => (Some(host), engine_dir(&root)), + Some(Handle::Slurm { host, root, .. }) => (Some(host), engine_dir(&root)), + Some(Handle::Legacy { descriptor }) => legacy_run_dir(&run.id, &descriptor)?, + None if !crate::engine::is_engine_row(run) => { + legacy_run_dir(&run.id, &BackendDescriptor::parse(&run.backend_json)?)? + } + _ => return Err(refusal()), + }) +} + +fn legacy_run_dir(run_id: &str, backend: &BackendDescriptor) -> Result<(Option, String)> { + Ok(match backend.kind.as_str() { "local_job" | "tinker_job" => { - let logdir = crate::jobs::localbox::run_dir(run_id).join("tensorboard"); - return Ok(format!("tensorboard --logdir \"{}\"", logdir.display())); + let dir = crate::jobs::localbox::run_dir(run_id); + (None, dir.to_string_lossy().into_owned()) } "ssh_job" if backend.ssh_container.is_none() => { let (host, dir) = backend.ssh_ref()?; - (host, dir.to_string()) + (Some(host.into()), dir.into()) } "slurm_job" => ( - backend.slurm_ref()?.0, + Some(backend.slurm_ref()?.0.into()), crate::jobs::slurm::run_dir(backend.remote_root.as_deref(), run_id), ), - _ => { - return Err(anyhow!( - "TensorBoard logs are kept only for local, Slurm, and SSH runs outside a container" - )) - } + _ => return Err(refusal()), + }) +} + +fn refusal() -> crate::error::Error { + anyhow!("TensorBoard logs are kept only for local, Slurm, and SSH runs outside a container") +} + +fn viewer_command(run: &StoredRun, launch: Option<&LaunchSpec>) -> Result { + let (host, dir) = run_dir(run, launch)?; + let Some(host) = host else { + let logdir = std::path::Path::new(&dir).join("tensorboard"); + return Ok(format!("tensorboard --logdir \"{}\"", logdir.display())); }; let remote = format!( "tensorboard --logdir {}/tensorboard --port {PORT}", @@ -41,7 +71,7 @@ fn viewer_command(run_id: &str, backend: &BackendDescriptor) -> Result { ); Ok(format!( "ssh -L {PORT}:localhost:{PORT} {} {}\nThen open http://localhost:{PORT}", - sh_quote(host), + sh_quote(&host), sh_quote(&remote) )) } @@ -50,16 +80,41 @@ fn viewer_command(run_id: &str, backend: &BackendDescriptor) -> Result { mod tests { use super::*; - fn backend(json: &str) -> BackendDescriptor { - BackendDescriptor::parse(json).unwrap() + fn run(id: &str, backend_json: &str) -> StoredRun { + StoredRun { + id: id.into(), + experiment_id: "exp".into(), + project_id: "project".into(), + status: "done".into(), + backend_json: backend_json.into(), + command: "train".into(), + created_at: 1, + updated_at: 1, + ended_at: None, + exit_code: None, + commit_sha: None, + result_markdown: None, + cancel_requested: false, + cancel_reason: None, + chat_session_id: None, + } + } + + fn command(json: &str) -> Result { + viewer_command(&run("r1", json), None) } #[test] fn local_runs_point_at_the_run_directory() { - let command = viewer_command("r1", &backend(r#"{"kind":"local_job"}"#)).unwrap(); let logdir = crate::jobs::localbox::run_dir("r1").join("tensorboard"); assert_eq!( - command, + command(r#"{"kind":"local_job"}"#).unwrap(), + format!("tensorboard --logdir \"{}\"", logdir.display()) + ); + let engine = r#"{"kind":"engine","jobId":"/data/local-runs/r1","handle":{"type":"Local","dir":"/data/local-runs/r1"}}"#; + let logdir = std::path::Path::new("/data/local-runs/r1").join("tensorboard"); + assert_eq!( + command(engine).unwrap(), format!("tensorboard --logdir \"{}\"", logdir.display()) ); } @@ -69,22 +124,40 @@ mod tests { for kind in ["ssh_job", "slurm_job"] { let json = format!(r#"{{"kind":"{kind}","namespace":"gpu-box","jobId":".orx/runs/r1"}}"#); - let command = viewer_command("r1", &backend(&json)).unwrap(); - assert!(command.starts_with( + assert!(command(&json).unwrap().starts_with( "ssh -L 6006:localhost:6006 'gpu-box' 'tensorboard --logdir \"$HOME/.orx/runs/r1\"/tensorboard --port 6006'" )); } let slurm = r#"{"kind":"slurm_job","namespace":"gpu-box","jobId":"7","remoteRoot":"/scratch/me/orx"}"#; - assert!(viewer_command("r1", &backend(slurm)).unwrap().contains( + assert!(command(slurm).unwrap().contains( "'tensorboard --logdir '\\''/scratch/me/orx/runs/r1'\\''/tensorboard --port 6006'" )); + let engine = + r#"{"kind":"engine","handle":{"type":"Ssh","host":"gpu-box","root":"~/.orx/engine"}}"#; + assert!(command(engine).unwrap().starts_with( + "ssh -L 6006:localhost:6006 'gpu-box' 'tensorboard --logdir \"$HOME/.orx/engine/runs/r1\"/tensorboard --port 6006'" + )); + let engine_slurm = r#"{"kind":"engine","jobId":"7","handle":{"type":"Slurm","host":"login","root":"/scratch/orx/engine","job":"7"}}"#; + assert!(command(engine_slurm) + .unwrap() + .contains("/scratch/orx/engine/runs/r1")); } #[test] fn container_and_ephemeral_runs_are_refused() { let container = r#"{"kind":"ssh_job","namespace":"gpu-box","jobId":".orx/runs/r1","sshContainer":{"reference":"img","id":"c1","startedAt":"t","runDir":"/root/.orx/runs/r1"}}"#; for json in [container, r#"{"kind":"modal_job"}"#, r#"{"kind":"hf_job"}"#] { - assert!(viewer_command("r1", &backend(json)).is_err(), "{json}"); + assert!(command(json).is_err(), "{json}"); } + let engine = + r#"{"kind":"engine","handle":{"type":"Ssh","host":"gpu-box","root":"~/.orx/engine"}}"#; + let launch = LaunchSpec { + kind: "ssh_job".into(), + target: Some("gpu-box".into()), + options: serde_json::json!({"container": {"reference": "img"}}), + }; + assert!(viewer_command(&run("r1", engine), Some(&launch)).is_err()); + let submitting = r#"{"kind":"engine"}"#; + assert!(command(submitting).is_err()); } } diff --git a/src/commands/up.rs b/src/commands/up.rs index 84f29fbdf..340df1cad 100644 --- a/src/commands/up.rs +++ b/src/commands/up.rs @@ -1,9 +1,10 @@ //! `orx up` — the local autoresearch dashboard server. //! -//! One axum process on 127.0.0.1 serving three surfaces: +//! One axum process on 127.0.0.1 that owns the run engine and serves: //! / embedded SPA (rust-embed over ui/dist, index.html fallback) //! /api/* JSON over the local SQLite store + run-log files -//! /api/events SSE: 500ms store + log-file diff loop (serve.rs idiom) +//! /api/v2/* the engine's API for the CLI and agents (`api_v2`) +//! /api/events SSE: run changes from the engine, a 500ms diff for everything else //! //! Fully local: no OpenResearch api anywhere on these paths (the /api/papers //! routes proxy alphaXiv's public, token-free endpoints — needed because the @@ -26,14 +27,13 @@ use axum::response::{Html, IntoResponse, Response}; use axum::routing::{get, post}; use axum::{Json, Router}; use base64::Engine as _; -use futures::Stream; use portable_pty::{native_pty_system, CommandBuilder, MasterPty, PtySize}; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use sha2::{Digest as _, Sha256}; use tokio::sync::mpsc; -use crate::commands::remote_host::{DashboardLock, DashboardLockMode, HostDescriptor, RemoteAuth}; +use crate::commands::remote_host::{DashboardLock, HostDescriptor, RemoteAuth}; use crate::commands::up_remote::RemoteSessionStatus; use crate::error::{anyhow, Result}; use crate::local; @@ -49,30 +49,36 @@ use crate::workspace_state::{GlobalWorkspaceState, WorkspaceState}; use crate::{browser, UpArgs}; mod agent_tools; +pub(crate) mod api_v2; pub(crate) mod compute_settings; mod harness_setup; mod network; use compute_settings::*; pub async fn run(args: UpArgs) -> Result<()> { + if !args.desktop_app && !args.remote_host && !args.headless { + let data_dir = crate::commands::remote_host::canonical_data_dir()?; + if let Some(server) = + crate::commands::remote_host::ServerDescriptor::live(&data_dir).await? + { + let url = format!("http://127.0.0.1:{}", server.port); + eprintln!("orx up: dashboard on {url}"); + if !args.no_browser { + browser::open_dashboard(&url, crate::telemetry::UpLaunchMode::of(&args)); + } + return Ok(()); + } + } updates::note_startup_image(); let port = args.port; let persistent_host = args.remote_host; - let remote_auth = if persistent_host { - let callback = format!("{}{}", uuid::Uuid::new_v4(), uuid::Uuid::new_v4()); - local::chat::set_up_auth_token(callback.clone()); - Some(RemoteAuth::new(&callback)) - } else { - None - }; - let dashboard_lock = DashboardLock::acquire( - &crate::commands::remote_host::canonical_data_dir()?, - if persistent_host { - DashboardLockMode::Exclusive - } else { - DashboardLockMode::Shared - }, - )?; + // Agent sessions and the CLI present this bearer to the server's API. + let token = format!("{}{}", uuid::Uuid::new_v4(), uuid::Uuid::new_v4()); + local::chat::set_up_auth_token(token.clone()); + let remote_auth = persistent_host.then(|| RemoteAuth::new(&token)); + let data_dir = crate::commands::remote_host::canonical_data_dir()?; + // The engine lock: one engine per data directory. + let dashboard_lock = DashboardLock::acquire(&data_dir)?; // Blocks only for a relaunched server, whose predecessor still holds the port. updates::await_replaced_parent(); let backend_lock = tokio::task::spawn_blocking(updates::BackendLock::acquire) @@ -93,14 +99,47 @@ pub async fn run(args: UpArgs) -> Result<()> { { let store = Store::open()?; local::chat::reconcile_unfinished_turns(&store)?; - for run in store.list_active_runs()? { - if store.get_local_experiment(&run.experiment_id)?.is_some() { - if let Err(err) = crate::commands::exp::spawn_detached_supervise(&run.id) { - eprintln!("could not recover supervisor for run {}: {err}", run.id); + // Under the engine lock, before any notice can be produced. + store.migrate_run_wakeups()?; + if !crate::config::run_engine_settings()?.0 { + for run in store.list_active_runs()? { + if !crate::engine::is_engine_row(&run) + && store.get_local_experiment(&run.experiment_id)?.is_some() + { + store.watch_legacy_run(&run.id, None)?; + if let Err(err) = crate::commands::exp::spawn_detached_supervise(&run.id) { + eprintln!("could not recover supervisor for run {}: {err}", run.id); + } } } } } + let clock: Arc = + Arc::new(crate::engine::clock::SystemClock::new()); + let engine = Arc::new(crate::engine::Engine::new(Store::open()?, clock.clone())); + let runtime = crate::engine::runtime::Runtime::new( + engine.clone(), + clock.clone(), + crate::store::data_dir(), + std::env::var_os("ORX_SSH_CONFIG").map(Into::into), + ); + let instance = uuid::Uuid::new_v4().to_string(); + let project_lifecycle = Arc::new(ProjectLifecycle::default()); + let data_dir_move_in_progress = Arc::new(AtomicBool::new(false)); + let stopping = Arc::new(AtomicBool::new(false)); + let api = Arc::new(api_v2::Api::new( + instance.clone(), + token.clone(), + engine.clone(), + runtime.clone(), + launch_admission( + project_lifecycle.clone(), + data_dir_move_in_progress.clone(), + stopping.clone(), + ), + crate::store::data_dir(), + )?); + api_v2::install(api.clone())?; // Harnesses spawn lazily on the first message to one of their sessions; // no eager agent bring-up. (--no-agent is now a no-op kept for compat.) @@ -110,24 +149,24 @@ pub async fn run(args: UpArgs) -> Result<()> { claude.start_reaper(); codex.start_reaper(); let remote_instance_id = persistent_host.then(|| uuid::Uuid::new_v4().to_string()); - let stopping = Arc::new(AtomicBool::new(false)); let state = AppState { agent: agent.clone(), chat: Arc::new(ChatHost::new(agent.clone(), codex.clone(), claude.clone())), claude: claude.clone(), harnesses: Arc::new(tokio::sync::Mutex::new(None)), - project_lifecycle: Arc::new(ProjectLifecycle::default()), + project_lifecycle, project_creation_lock: Arc::new(tokio::sync::Mutex::new(())), publication_locks: Arc::new(tokio::sync::Mutex::new(HashMap::new())), harness_fill_in_flight: Arc::new(std::sync::atomic::AtomicBool::new(false)), claude_catalog_queue: Arc::new(std::sync::Mutex::new(ClaudeCatalogQueue::default())), - data_dir_move_in_progress: Arc::new(std::sync::atomic::AtomicBool::new(false)), + data_dir_move_in_progress, data_dir_gate: Arc::new(tokio::sync::Mutex::new(())), remote_sessions: crate::commands::up_remote::RemoteSessionManager::new(), remote_instance_id: remote_instance_id.clone(), stopping: stopping.clone(), dashboard_lock: Arc::new(std::sync::Mutex::new(Some(dashboard_lock))), restart: Arc::new(tokio::sync::Notify::new()), + reopen: Arc::default(), trackio: Arc::default(), }; // Plan-mode turns hand this port to the `orx mcp` permission bridge. @@ -167,12 +206,18 @@ pub async fn run(args: UpArgs) -> Result<()> { let gate = state.data_dir_gate.clone(); tokio::task::spawn_blocking(move || local::demo::prewarm(move_in_progress, gate)); } - // Deliver explicitly registered run wake-ups once their chat becomes idle. - tokio::spawn(local::chat::watch_runs( + tokio::spawn(local::chat::keep_turn_leases( state.chat.clone(), state.data_dir_move_in_progress.clone(), state.data_dir_gate.clone(), )); + tokio::spawn(local::chat::watch_run_notices( + state.chat.clone(), + engine.bus.subscribe(), + state.data_dir_move_in_progress.clone(), + state.data_dir_gate.clone(), + )); + runtime.start(); tokio::spawn(adopt_orphaned_runs( state.data_dir_move_in_progress.clone(), state.data_dir_gate.clone(), @@ -201,6 +246,34 @@ pub async fn run(args: UpArgs) -> Result<()> { let app = router(state.clone(), remote_auth.clone()); let url = format!("http://127.0.0.1:{actual_port}"); + crate::commands::remote_host::ServerDescriptor { + instance, + pid: std::process::id(), + starttime: crate::engine::process::identity(std::process::id()) + .map_or(0, |identity| identity.starttime), + port: actual_port, + version: env!("CARGO_PKG_VERSION").into(), + proto: 2, + token, + } + .publish(&data_dir)?; + if args.headless { + tokio::spawn(async move { + let mut idle = api_v2::Idle::default(); + let started = tokio::time::Instant::now(); + loop { + tokio::time::sleep(Duration::from_secs(30)).await; + // An unreadable store is not proof of idleness. + if idle.check(&api, started.elapsed()).unwrap_or(false) + && stop_admitting_if_idle(&api).unwrap_or(false) + { + eprintln!("orx up: idle for ten minutes; stopping"); + SHUTDOWN_REQUESTED.notify_one(); + return; + } + } + }); + } let (stop_tx, mut stop_rx) = tokio::sync::watch::channel(false); let control_server = if persistent_host { Some( @@ -288,7 +361,7 @@ pub async fn run(args: UpArgs) -> Result<()> { state.dashboard_lock.lock().unwrap().take(); if restarting { drop(backend_lock); - if !updates::updated_exe_on_disk().await { + if !state.reopen.load(Ordering::SeqCst) && !updates::updated_exe_on_disk().await { eprintln!("orx up: installing the update before restarting"); let failures = updates::failure_count(); if let Err(err) = updates::apply_now().await { @@ -409,6 +482,9 @@ struct AppState { dashboard_lock: Arc>>, /// Fired by `POST /api/update/restart`; the serve loop relaunches on it. restart: Arc, + /// Set with `restart` when the data directory changed: the engine reopens there, and no + /// update is installed first. + reopen: Arc, trackio: Arc, } @@ -511,6 +587,29 @@ impl ProjectLifecycle { } } +/// Admits a launch the way the dashboard admits every project operation. +fn launch_admission( + lifecycle: Arc, + moving: Arc, + stopping: Arc, +) -> api_v2::Admit { + Box::new(move |project| { + if stopping.load(Ordering::SeqCst) { + return Err(anyhow!("The persistent OpenResearch host is stopping.")); + } + let admission = lifecycle + .admit(project) + .ok_or_else(|| anyhow!("project deletion is in progress"))?; + // Checked after admitting: a move that raised its flag first counts this admission. + if moving.load(Ordering::SeqCst) { + return Err(anyhow!( + "A data-directory move is in progress. Try again once it finishes." + )); + } + Ok(Box::new(admission)) + }) +} + fn router(state: AppState, remote_auth: Option) -> Router { let app = Router::new() .route("/api/health", get(health)) @@ -560,7 +659,6 @@ fn router(state: AppState, remote_auth: Option) -> Router { .route("/api/runs/{id}", get(get_run)) .route("/api/instances", get(list_instances)) .route("/api/runs/{id}/cancel", post(cancel_run)) - .route("/api/runs/{id}/log", get(run_log)) .route("/api/runs/{id}/logs", get(run_logs)) .route("/api/runs/{id}/diff", get(run_diff)) .route("/api/experiments/{id}/diff", get(experiment_diff)) @@ -641,6 +739,10 @@ fn router(state: AppState, remote_auth: Option) -> Router { ) .route("/api/projects/{id}/terminal", get(project_terminal)) .route("/api/events", get(events)) + .route( + "/api/settings/run-engine", + get(run_engine_settings).post(set_run_engine), + ) .route("/api/settings/hf", get(hf_settings).post(set_hf_token)) .route( "/api/settings/tinker", @@ -869,6 +971,10 @@ fn router(state: AppState, remote_auth: Option) -> Router { // above the client-side per-file limit so a full message still fits. .layer(DefaultBodyLimit::max(64 * 1024 * 1024)) .with_state(state); + server_router(app.merge(api_v2::router()), remote_auth) +} + +fn server_router(app: Router, remote_auth: Option) -> Router { let app = app .layer(middleware::from_fn(track_active)) .layer(middleware::from_fn( @@ -893,7 +999,11 @@ async fn require_remote_auth( ) .into_response(); } - if path == "/api/internal/permissions" || path == "/api/internal/mcp" { + // V2 checks its descriptor credential at the route layer, including the hello challenge. + if path.starts_with("/api/v2/") + || path == "/api/internal/permissions" + || path == "/api/internal/mcp" + { return next.run(request).await; } let provided = request @@ -995,8 +1105,6 @@ type ApiResult = std::result::Result, ApiError>; // --- wire types ----------------------------------------------------------- -/// The Run entity the API serves: StoredRun with `backend_json` parsed into an -/// object and cancellation intent exposed for pending UI state. #[derive(Deserialize, Serialize)] #[serde(rename_all = "camelCase")] struct ApiRun { @@ -1015,29 +1123,88 @@ struct ApiRun { created_at: i64, updated_at: i64, #[serde(skip_serializing_if = "Option::is_none")] + started_at: Option, + #[serde(skip_serializing_if = "Option::is_none")] ended_at: Option, #[serde(skip_serializing_if = "Option::is_none")] exit_code: Option, - cancel_requested: bool, + contact: Option, + cancelling: bool, + cancel_unconfirmed: Option>, + lost_reason: Option, + host: Option, + notice_error: Option, + #[serde(skip_serializing_if = "Option::is_none")] + log_collection: Option<&'static str>, + #[serde(skip_serializing_if = "Option::is_none")] + log_collection_error: Option, } -impl From<&StoredRun> for ApiRun { - fn from(run: &StoredRun) -> Self { - Self { +pub(crate) fn run_host(store: &Store, run: &StoredRun) -> Result> { + use crate::engine::handle::Handle; + Ok(match crate::engine::handle_of(run) { + Some(Handle::Ssh { host, .. } | Handle::Slurm { host, .. }) => Some(host), + Some(Handle::Legacy { descriptor }) + if matches!(descriptor.kind.as_str(), "ssh_job" | "slurm_job") => + { + descriptor.namespace + } + _ => store + .engine_run_state(&run.id)? + .and_then(|state| state.launch) + .filter(|launch| matches!(launch.kind.as_str(), "ssh_job" | "slurm_job")) + .and_then(|launch| launch.target), + }) +} + +impl ApiRun { + fn new(store: &Store, run: &StoredRun) -> Result { + let state = store.engine_run_state(&run.id)?; + let state = state.filter(|_| crate::engine::is_engine_row(run)); + let accepted = state + .as_ref() + .is_some_and(|state| state.cancel_accepted_at.is_some()); + let launch = state.as_ref().and_then(|state| state.launch.as_ref()); + let collection = store.log_collection(&run.id)?; + Ok(Self { id: run.id.clone(), experiment_id: run.experiment_id.clone(), project_id: run.project_id.clone(), status: run.status.clone(), - backend: crate::store::public_backend(&run.backend_json), + backend: crate::store::public_backend(&run.backend_json, launch), command: Some(run.command.clone()).filter(|c| !c.is_empty()), commit_sha: run.commit_sha.clone(), result_markdown: run.result_markdown.clone(), created_at: run.created_at, updated_at: run.updated_at, + started_at: state.as_ref().and_then(|state| state.started_at), ended_at: run.ended_at, exit_code: run.exit_code, - cancel_requested: run.cancel_requested, - } + cancel_unconfirmed: state + .as_ref() + .and_then(|state| state.cancel_unconfirmed.clone()), + contact: state + .map(|state| state.contact) + .filter(|contact| *contact != crate::store::Contact::Live), + cancelling: !is_terminal(&run.status) && (run.cancel_requested || accepted), + lost_reason: run + .result_markdown + .as_ref() + .filter(|_| run.status == "lost") + .map(|reason| { + if reason == crate::engine::reconcile::ABANDONED { + "abandoned".into() + } else { + reason.clone() + } + }), + host: run_host(store, run)?, + notice_error: store.run_notice_error(&run.id)?, + log_collection: collection + .as_ref() + .map(|(failed, _)| if *failed { "failed" } else { "pending" }), + log_collection_error: collection.and_then(|(_, error)| error), + }) } } @@ -2154,11 +2321,12 @@ async fn delete_project_inner(state: AppState, id: String, query: DeleteProjectQ if !in_flight.is_empty() { let mut failures = Vec::new(); for run in &in_flight { - if let Err(err) = crate::commands::exp::request_local_run_cancel( - &store, - &run.id, + if let Err(err) = api_v2::cancel_run( + run, "Cancel requested because the project is being deleted.", - ) { + ) + .await + { failures.push(format!("{}: {err}", run.id)); } } @@ -2296,11 +2464,11 @@ async fn list_project_runs(Path(id): Path) -> ApiResult { store .get_local_project(&id)? .ok_or_else(|| not_found("project"))?; - let runs: Vec = store + let runs = store .list_runs_by_project(&id)? .iter() - .map(ApiRun::from) - .collect(); + .map(|run| ApiRun::new(&store, run)) + .collect::>>()?; Ok(Json(json!({ "runs": runs }))) } @@ -2320,6 +2488,7 @@ struct CreateRunReq { backend: Option, cpus: Option, mem: Option, + partition: Option, flavor: Option, host: Option, container: Option, @@ -2340,35 +2509,6 @@ struct CreateRunReq { } impl CreateRunReq { - fn from_run_args(args: &crate::ExpRunArgs) -> Result { - Ok(Self { - telemetry_suppressed: args.telemetry_suppressed - || !crate::telemetry::accounting_reports_enabled(), - invocation_context: args - .invocation_identity()? - .map(|identity| serde_json::to_string(&identity)) - .transpose()?, - experiment_id: args.exp_id.clone(), - backend: args.backend.clone(), - cpus: args.cpus, - mem: args.mem.clone(), - flavor: args.flavor.clone(), - host: args.host.clone(), - container: args.container.clone(), - no_container: args.no_container, - manifest: args.manifest.clone(), - image: args.image.clone(), - timeout: args.timeout.clone(), - org: args.org.clone(), - provider: args.provider.clone(), - disk: args.disk, - force: args.force, - chat_session_id: args.launching_chat_session(), - agent_origin: args.agent_origin.clone(), - caller_config_dir: Some(absolute_config_dir()), - }) - } - fn into_run_args(self) -> crate::ExpRunArgs { let mut backend = self.backend; let mut flavor = self.flavor; @@ -2390,131 +2530,25 @@ impl CreateRunReq { timeout: self.timeout, cpus: self.cpus, mem: self.mem, + partition: self.partition, force: self.force, chat_session_id: self.chat_session_id, agent_origin: self.agent_origin, forwarded: true, + caller_config_dir: None, } } } -#[derive(Deserialize)] -struct CreateRunResponse { - run: ApiRun, -} - -pub(crate) struct RunLaunchSummary { - pub run_id: String, - pub experiment_id: String, - pub job_id: Option, - pub slurm_resources: Option, -} - -async fn decode_local_response( - response: reqwest::Response, - action: &str, -) -> Result { - let status = response.status(); - let body = response - .bytes() - .await - .map_err(|error| anyhow!("orx up {action} response failed: {error}"))?; - if !status.is_success() { - let detail = serde_json::from_slice::(&body) - .ok() - .and_then(|value| { - value - .get("error") - .and_then(Value::as_str) - .map(|error| error.trim().to_string()) - }) - .unwrap_or_else(|| String::from_utf8_lossy(&body).trim().to_string()); - if detail.is_empty() { - return Err(anyhow!("orx up could not {action}: HTTP {status}")); - } - if status.is_client_error() { - return Err(anyhow!("{detail}")); - } - return Err(anyhow!("orx up could not {action}: {detail}")); - } - serde_json::from_slice(&body) - .map_err(|error| anyhow!("orx up returned an invalid {action} response: {error}")) -} - -fn local_client() -> Result { - crate::net::loopback_client() - .connect_timeout(Duration::from_secs(3)) - .build() - .map_err(|error| anyhow!("Could not create the orx up client: {error}")) -} - -fn authenticate_up_request(builder: reqwest::RequestBuilder) -> reqwest::RequestBuilder { - match std::env::var(local::chat::UP_AUTH_TOKEN_ENV) - .ok() - .filter(|token| !token.is_empty()) - .or_else(|| local::chat::up_auth_token().map(str::to_string)) - { - Some(token) => builder.bearer_auth(token), - None => builder, - } -} - -pub(crate) async fn submit_run_via_up( - port: u16, - args: &crate::ExpRunArgs, -) -> Result { - let request = CreateRunReq::from_run_args(args)?; - let response = - authenticate_up_request(local_client()?.post(format!("http://127.0.0.1:{port}/api/runs"))) - .json(&request) - .send() - .await - .map_err(|error| anyhow!("Could not reach the trusted orx up process: {error}"))?; - let response: CreateRunResponse = decode_local_response(response, "start the run").await?; - let job_id = response - .run - .backend - .as_ref() - .and_then(|backend| backend.get("jobId")) - .and_then(Value::as_str) - .map(str::to_string); - let slurm_resources = response - .run - .backend - .and_then(|backend| serde_json::from_value(backend).ok()) - .and_then(|backend| local::slurm::requested_resources(&backend)); - Ok(RunLaunchSummary { - run_id: response.run.id, - experiment_id: args.exp_id.clone(), - job_id, - slurm_resources, - }) -} - -pub(crate) async fn cancel_run_via_up(port: u16, run_id: &str) -> Result<()> { - let response = authenticate_up_request( - local_client()? - .post(format!("http://127.0.0.1:{port}/api/runs/{run_id}/cancel")) - .json(&CancelRunReq { - chat_session_id: local::chat::launching_chat_session(), - }), - ) - .send() - .await - .map_err(|error| anyhow!("Could not reach the trusted orx up process: {error}"))?; - let _: Value = decode_local_response(response, "cancel the run").await?; - Ok(()) -} - /// Launching with orx up's settings after the caller checked its own would /// submit to a different cluster or namespace than the one the caller tested. /// A relative `XDG_CONFIG_HOME` names a different dir in each process's working directory. -fn absolute_config_dir() -> std::path::PathBuf { +pub(crate) fn absolute_config_dir() -> std::path::PathBuf { let dir = crate::config::config_dir(); std::path::absolute(&dir).unwrap_or(dir) } -fn require_caller_config_dir( +pub(crate) fn require_caller_config_dir( caller: Option<&std::path::Path>, own: &std::path::Path, ) -> Result<()> { @@ -2540,49 +2574,27 @@ fn require_caller_config_dir( )) } -async fn create_run(State(state): State, Json(req): Json) -> ApiResult { - reject_if_stopping(&state)?; - reject_if_moving(&state)?; +async fn create_run(Json(req): Json) -> ApiResult { require_caller_config_dir(req.caller_config_dir.as_deref(), &absolute_config_dir()) .map_err(bad_request)?; let store = Store::open()?; - let experiment = store + store .get_local_experiment(&req.experiment_id)? .ok_or_else(|| not_found("experiment"))?; - let _admission = state - .project_lifecycle - .admit(&experiment.project_id) - .ok_or_else(|| bad_request("project deletion is in progress"))?; // Dashboard callers may omit compute options; forwarded CLI requests arrive resolved. - let args = req.into_run_args(); - crate::compute::validate_run_args(&args).map_err(bad_request)?; - let run = crate::compute::submit(&args).await.map_err(bad_request)?; - Ok(Json(json!({ "run": ApiRun::from(&run) }))) -} - -fn backend_for_run( - run: &StoredRun, -) -> std::result::Result, ApiError> { - let descriptor = - crate::jobs::BackendDescriptor::parse(&run.backend_json).map_err(bad_request)?; - let id = descriptor - .kind - .strip_suffix("_job") - .unwrap_or(&descriptor.kind); - let id = if id == "k8s" { "k8s" } else { id }; - crate::compute::backend(id).map_err(bad_request) + let run = api_v2::launch(req.into_run_args()) + .await + .map_err(bad_request)?; + Ok(Json(json!({ "run": ApiRun::new(&store, &run)? }))) } async fn get_run(Path(id): Path) -> ApiResult { - let run = Store::open()? - .get_run(&id)? - .ok_or_else(|| not_found("run"))?; - let backend = backend_for_run(&run)?; - let run = backend.status(&run).await.map_err(bad_request)?; + let store = Store::open()?; + let run = store.get_run(&id)?.ok_or_else(|| not_found("run"))?; if is_terminal(&run.status) { - backend.cleanup(&run).await.map_err(bad_request)?; + crate::compute::remove_hf_staging(&run).map_err(bad_request)?; } - Ok(Json(json!({ "run": ApiRun::from(&run) }))) + Ok(Json(json!({ "run": ApiRun::new(&store, &run)? }))) } /// Newest-first cap for the cross-project instances list. Generous: the store @@ -2604,7 +2616,7 @@ async fn list_instances() -> ApiResult { for run in store.list_runs(INSTANCES_LIMIT)? { // ApiRun is a plain serializable struct, so this can't realistically // fail; propagate rather than emit a malformed row if it ever does. - let mut value = serde_json::to_value(ApiRun::from(&run)) + let mut value = serde_json::to_value(ApiRun::new(&store, &run)?) .map_err(|e| anyhow!("serialize run {}: {e}", run.id))?; if let (Some(obj), Some(name)) = (value.as_object_mut(), names.get(&run.project_id)) { obj.insert("projectName".into(), json!(name)); @@ -2637,8 +2649,9 @@ async fn cancel_run( Some(Json(req)) => crate::commands::exp::exp_cancel_reason(req.chat_session_id.as_deref()), None => "Cancel requested through orx up (dashboard or an older orx CLI).".into(), }; - let backend = backend_for_run(&run)?; - backend.cancel(&run, &reason).await.map_err(bad_request)?; + api_v2::cancel_run(&run, &reason) + .await + .map_err(bad_request)?; Ok(Json(json!({ "ok": true }))) } @@ -2649,39 +2662,22 @@ struct LogsQuery { } async fn run_logs(Path(id): Path, Query(q): Query) -> ApiResult { - let run = Store::open()? - .get_run(&id)? - .ok_or_else(|| not_found("run"))?; - let batch = backend_for_run(&run)? - .logs( - &run, - crate::compute::LogCursor(q.cursor.unwrap_or(0), q.generation), - ) - .await - .map_err(bad_request)?; - Ok(Json(json!(batch))) -} - -#[derive(Deserialize)] -struct LogQuery { - offset: Option, - generation: Option, -} - -async fn run_log(Path(id): Path, Query(q): Query) -> ApiResult { let store = Store::open()?; - store.get_run(&id)?.ok_or_else(|| not_found("run"))?; - let offset = q.offset.unwrap_or(0); - let snapshot = - crate::jobs::ssh::service::logs::read(&id, offset, 4_000_000, q.generation.as_deref())?; - let chunk = snapshot.bytes; - let next_offset = snapshot.offset + chunk.len() as u64; + let run = store.get_run(&id)?.ok_or_else(|| not_found("run"))?; + let complete = is_terminal(&run.status) && !store.log_collection_pending(&id)?; + let snapshot = crate::jobs::ssh::service::logs::read( + &run.id, + q.cursor.unwrap_or(0), + 256 * 1024, + q.generation.as_deref(), + )?; + let next = snapshot.offset + snapshot.bytes.len() as u64; Ok(Json(json!({ - "dataBase64": base64::engine::general_purpose::STANDARD.encode(&chunk), - "nextOffset": next_offset, - "eof": next_offset >= snapshot.size, - "offset": snapshot.offset, "generation": snapshot.generation, + "offset": snapshot.offset, + "dataBase64": base64::engine::general_purpose::STANDARD.encode(&snapshot.bytes), + "nextCursor": next, + "eof": complete && next >= snapshot.size, }))) } @@ -4682,10 +4678,24 @@ fn spawn_background_tasks(check_updates: bool) { }); } +#[cfg(test)] +static ACTIVE_TEST_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); /// Requests and terminals in flight, which an automatic restart would cut off. static ACTIVE: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); /// An automatic restart is checking for idleness; new requests wait it out. static DRAINING: AtomicBool = AtomicBool::new(false); +static IDLE_EXIT: AtomicBool = AtomicBool::new(false); + +fn stop_admitting_if_idle(api: &api_v2::Api) -> Result { + IDLE_EXIT.store(true, Ordering::SeqCst); + let idle = api + .busy() + .map(|busy| !busy && ACTIVE.load(Ordering::SeqCst) == 0); + if !matches!(idle, Ok(true)) { + IDLE_EXIT.store(false, Ordering::SeqCst); + } + idle +} struct Active; @@ -4703,13 +4713,21 @@ impl Drop for Active { } pub(crate) async fn track_active(request: axum::extract::Request, next: Next) -> Response { - // The dashboard holds its event stream open for as long as it is open. - if request.uri().path() == "/api/events" { + if IDLE_EXIT.load(Ordering::SeqCst) { + return axum::http::StatusCode::SERVICE_UNAVAILABLE.into_response(); + } + if matches!( + request.uri().path(), + "/api/events" | "/api/v2/events" | "/api/v2/hello" + ) { return next.run(request).await; } // Count first, then check: paired with the drain's set-then-count, one side always sees the other. let active = loop { let active = Active::new(); + if IDLE_EXIT.load(Ordering::SeqCst) { + return axum::http::StatusCode::SERVICE_UNAVAILABLE.into_response(); + } if !DRAINING.load(Ordering::SeqCst) { break active; } @@ -4754,11 +4772,7 @@ impl axum::body::HttpBody for ActiveBody { const ORPHANED_RUN_SCAN_INTERVAL: Duration = Duration::from_secs(60); const REMOTE_CLEANUP_INTERVAL: Duration = Duration::from_secs(60); -/// SSH container launches record their handle before the job starts; leave them this long to finish. -const ORPHANED_RUN_SETTLE_MS: i64 = 5 * 60 * 1000; -/// Give a supervisor to every submitted local run that has none, so a launch -/// whose supervisor spawn failed (OR-334) is tracked instead of stuck `starting`. async fn adopt_orphaned_runs(moving: Arc, gate: Arc>) { // Runs whose spawn failure is already logged, so a stuck run logs once. let mut reported = HashSet::new(); @@ -4787,6 +4801,31 @@ async fn adopt_orphaned_runs(moving: Arc, gate: Arc Result> { + let mut failures = Vec::new(); + if crate::config::run_engine_settings()?.0 { + return Ok(failures); + } + let store = Store::open()?; + for run in store.list_active_runs()? { + // Without a job handle the launch may still be submitting, and a supervisor would fail it. + let submitted = crate::jobs::BackendDescriptor::parse(&run.backend_json) + .is_ok_and(|descriptor| descriptor.job_id.is_some()); + if crate::engine::is_engine_row(&run) + || !submitted + || now_ms() - run.updated_at < crate::engine::ORPHANED_RUN_SETTLE_MS + || store.get_local_experiment(&run.experiment_id)?.is_none() + || crate::commands::supervise::supervisor_running(&run.id) + { + continue; + } + if let Err(err) = crate::commands::exp::spawn_detached_supervise(&run.id) { + failures.push((run.id, err)); + } + } + Ok(failures) +} + /// Background task so a large first reclaim never delays startup; it releases the gate between passes. async fn reclaim_orphaned_run_artifacts( moving: Arc, @@ -4854,7 +4893,7 @@ async fn reclaim_orphaned_run_artifacts( } /// Runs `f` on a fresh store under the data-dir gate; `None` while the data dir is moving. -async fn with_gated_store( +pub(crate) async fn with_gated_store( moving: &AtomicBool, gate: &tokio::sync::Mutex<()>, f: impl FnOnce(&Store) -> Result + Send + 'static, @@ -4892,7 +4931,7 @@ async fn reclaim_remote_run_dirs(moving: Arc, gate: Arc, gate: Arc Result> { - let store = Store::open()?; - let mut failures = Vec::new(); - for run in store.list_active_runs()? { - // Without a job handle the launch may still be submitting, and a supervisor would fail it. - let submitted = crate::jobs::BackendDescriptor::parse(&run.backend_json) - .is_ok_and(|descriptor| descriptor.job_id.is_some()); - if !submitted - || now_ms() - run.updated_at < ORPHANED_RUN_SETTLE_MS - || store.get_local_experiment(&run.experiment_id)?.is_none() - || crate::commands::supervise::supervisor_running(&run.id) - { - continue; - } - if let Err(err) = crate::commands::exp::spawn_detached_supervise(&run.id) { - failures.push((run.id, err)); - } - } - Ok(failures) -} - /// Relaunch into an update installed underneath this server once that interrupts nothing, /// so a long-lived `orx up` stops launching runs and building sandboxes with old code. fn spawn_restart_when_idle(state: AppState) { tokio::spawn(async move { loop { tokio::time::sleep(UPDATE_SAMPLE_INTERVAL).await; + if crate::commands::app::windowless() { + continue; + } let status = updates::status(); // The cache can claim an install the exec target doesn't have; never restart in a loop. if !(status.auto_update @@ -5282,20 +5302,10 @@ async fn set_data_dir(State(state): State, Json(req): Json .map_err(bad_request)?; let lock_path = std::path::PathBuf::from(&path); - let persistent_host = state.remote_instance_id.is_some(); - let next_lock = tokio::task::spawn_blocking(move || { - DashboardLock::acquire( - &lock_path, - if persistent_host { - DashboardLockMode::Exclusive - } else { - DashboardLockMode::Shared - }, - ) - }) - .await - .map_err(|e| ApiError::from(anyhow!("dashboard lock task failed: {e}")))? - .map_err(|error| ApiError(StatusCode::CONFLICT, error.to_string()))?; + let next_lock = tokio::task::spawn_blocking(move || DashboardLock::acquire(&lock_path)) + .await + .map_err(|e| ApiError::from(anyhow!("dashboard lock task failed: {e}")))? + .map_err(|error| ApiError(StatusCode::CONFLICT, error.to_string()))?; state.chat.shutdown_harnesses().await; tokio::task::spawn_blocking(move || crate::config::set_settings_data_dir(Some(path))) @@ -5303,6 +5313,8 @@ async fn set_data_dir(State(state): State, Json(req): Json .map_err(|e| ApiError::from(anyhow!("settings task failed: {e}")))??; *state.dashboard_lock.lock().unwrap() = Some(next_lock); state.chat.shutdown_harnesses().await; + state.reopen.store(true, Ordering::SeqCst); + state.restart.notify_one(); Ok(Json(data_dir_json())) } @@ -5434,18 +5446,8 @@ async fn move_data_dir(State(state): State, Json(req): Json lock, Ok(Err(error)) => { @@ -5469,6 +5471,7 @@ async fn move_data_dir(State(state): State, Json(req): Json, Json(req): Json chat.emit_event("datadir.move.error", json!({ "error": e.to_string() })), Err(e) => chat.emit_event( @@ -5518,6 +5522,9 @@ async fn move_data_dir(State(state): State, Json(req): Json std::result::Result<(), ApiError> { Ok(()) } +async fn run_engine_settings() -> ApiResult { + let (enabled, forced_by) = crate::config::run_engine_settings().map_err(bad_request)?; + Ok(Json(json!({"enabled": enabled, "forcedBy": forced_by}))) +} + +#[derive(Deserialize)] +struct RunEngineReq { + enabled: bool, +} + +async fn set_run_engine(Json(req): Json) -> ApiResult { + match crate::config::run_engine_settings().map_err(bad_request)?.1 { + Some("canary") => return Err(bad_request("Canary builds always use the new experiment engine.")), + Some(_) => return Err(bad_request("ORX_RUN_ENGINE controls this setting. Remove it from the server environment to use this switch.")), + None => {} + } + crate::config::set_run_engine_enabled(req.enabled)?; + run_engine_settings().await +} + // --- git settings ----------------------------------------------------------- fn git_out(args: &[&str]) -> Option { @@ -6400,91 +6427,85 @@ fn start_pty_with_env( }) } +/// The dashboard's Connect: the engine logs in through its own connection, and each +/// password, passphrase or MFA question is asked in this terminal. async fn ssh_connect_socket( mut socket: WebSocket, host: String, backend: SshConnectBackend, - target: crate::jobs::ssh::SshTarget, + _target: crate::jobs::ssh::SshTarget, ) { - #[cfg(windows)] - if !ssh_service_connect(&mut socket, &target).await { - return; - } - #[cfg(unix)] - if !crate::jobs::ssh::service::healthy(&target).await { - let connection = match crate::jobs::ssh::interactive_args(&target, None, None).await { - Ok(connection) => connection, - Err(error) => { - send_ssh_connect_error(&mut socket, &host, backend, error.to_string()).await; - return; - } - }; - let args = connection.args.clone(); - let session = match tokio::task::spawn_blocking(move || start_pty("ssh", args)).await { - Ok(Ok(session)) => session, - Ok(Err(error)) => { - send_ssh_connect_error(&mut socket, &host, backend, error.to_string()).await; - return; - } - Err(error) => { - send_ssh_connect_error( - &mut socket, - &host, - backend, - format!("SSH terminal task failed: {error}"), - ) - .await; - return; - } - }; - let mut size = DEFAULT_PTY_SIZE; - let Some(status) = relay_pty(&mut socket, session, None, &mut size, None).await else { - return; - }; - - match status { - Ok(status) if status.success() => { - if let Some(warning) = crate::jobs::ssh::setup_connection_sharing(&target).await { - let _ = socket - .send(Message::Binary( - format!("\r\norx: warning: {warning}\r\n") - .into_bytes() - .into(), - )) - .await; + type Question = (String, tokio::sync::oneshot::Sender); + let (questions_tx, mut questions) = mpsc::channel::(1); + let prompt: crate::engine::transport::Prompt = Arc::new(move |question| { + let questions = questions_tx.clone(); + Box::pin(async move { + let (reply, answer) = tokio::sync::oneshot::channel(); + questions + .send((question, reply)) + .await + .map_err(|_| anyhow!("The terminal closed"))?; + Ok(answer.await.ok()) + }) + }); + let backend_name = match backend { + SshConnectBackend::Ssh => "ssh", + SshConnectBackend::Slurm => "slurm", + }; + let connect = api_v2::check_compute( + "connect", + json!({"backend": backend_name, "host": host}), + Some(prompt), + ); + tokio::pin!(connect); + let mut pending: Option> = None; + let mut answer = String::new(); + let result = loop { + tokio::select! { + result = &mut connect => break result, + Some((question, reply)) = questions.recv() => { + let clean: String = question.chars().filter(|c| !c.is_control()).collect(); + if socket + .send(Message::Binary(format!("\r\n{clean} ").into_bytes().into())) + .await + .is_err() + { + return; } + answer.clear(); + pending = Some(reply); } - Ok(status) => { - send_ssh_connect_error( - &mut socket, - &host, - backend, - format!("ssh {host} exited with code {}", status.exit_code()), - ) - .await; - return; - } - Err(error) => { - send_ssh_connect_error(&mut socket, &host, backend, error).await; - return; - } - } - - drop(connection); - } - if let Err(error) = crate::jobs::ssh::service::attach(&target).await { - send_ssh_connect_error(&mut socket, &host, backend, error.to_string()).await; - return; - } - let (backend_name, result, ssh_test) = match backend { - SshConnectBackend::Ssh => { - let test = probe_ssh_host_preflight(host.clone()).await; - let result = json!(&test); - ("ssh", result, Some(test)) + message = socket.recv() => match message { + Some(Ok(Message::Binary(bytes))) if pending.is_some() => { + for character in String::from_utf8_lossy(&bytes).chars() { + match character { + '\r' | '\n' => { + if let Some(reply) = pending.take() { + let _ = reply.send(std::mem::take(&mut answer)); + } + let _ = socket.send(Message::Binary(b"\r\n".to_vec().into())).await; + break; + } + '\u{8}' | '\u{7f}' => { + answer.pop(); + } + character if !character.is_control() && answer.len() < 16384 => { + answer.push(character) + } + _ => {} + } + } + } + None | Some(Err(_)) | Some(Ok(Message::Close(_))) => return, + _ => {} + }, } - SshConnectBackend::Slurm => { - let result = crate::jobs::slurm::preflight(&host).await; - ("slurm", slurm_preflight_value(&result), None) + }; + let result = match result { + Ok(result) => result, + Err(error) => { + send_ssh_connect_error(&mut socket, &host, backend, error.to_string()).await; + return; } }; if socket @@ -6496,92 +6517,10 @@ async fn ssh_connect_socket( .await .is_ok() { - if let Some(test) = ssh_test { - record_ssh_host_test(&test).await; - } close_socket(&mut socket).await; } } -#[cfg(windows)] -async fn ssh_service_connect(socket: &mut WebSocket, target: &crate::jobs::ssh::SshTarget) -> bool { - use crate::jobs::ssh::service; - let start = match service::request(target, json!({"op":"connect_start"})).await { - Ok(start) => start, - Err(error) => { - send_ws_error(socket, error.to_string()).await; - return false; - } - }; - let Some(attempt) = start["attempt"].as_str() else { - return false; - }; - let mut prompt = None; - let mut answer = String::new(); - let success = loop { - let status = - match service::request(target, json!({"op":"connect_status", "attempt":attempt})).await - { - Ok(status) => status, - Err(error) => { - send_ws_error(socket, error.to_string()).await; - break false; - } - }; - if status["done"] == true { - if let Some(error) = status["error"].as_str() { - send_ws_error(socket, error.to_owned()).await; - break false; - } - break true; - } - if let Some(text) = status["prompt"].as_str() { - if prompt.as_deref() != Some(text) { - prompt = Some(text.to_owned()); - answer.clear(); - let clean: String = text - .chars() - .filter(|character| !character.is_control()) - .collect(); - if socket - .send(Message::Binary(format!("\r\n{clean} ").into_bytes().into())) - .await - .is_err() - { - break false; - } - } - } - tokio::select! { - message = socket.recv() => { - match message { - Some(Ok(Message::Binary(bytes))) if prompt.is_some() => { - let mut submit = false; - for character in String::from_utf8_lossy(&bytes).chars() { - match character { - '\r' | '\n' => {submit = true; break;}, - '\u{8}' | '\u{7f}' => {answer.pop();}, - character if !character.is_control() && answer.len() < 16384 => answer.push(character), - _ => {}, - } - } - if submit { - let result = service::request(target, json!({"op":"connect_answer", "attempt":attempt, "answer":answer})).await; - answer.clear(); prompt = None; - if let Err(error) = result {send_ws_error(socket, error.to_string()).await; break false;} - } - } - None | Some(Err(_)) | Some(Ok(Message::Close(_))) => break false, - _ => {}, - } - } - _ = tokio::time::sleep(Duration::from_millis(150)) => {}, - } - }; - let _ = service::request(target, json!({"op":"connect_cancel", "attempt":attempt})).await; - success -} - async fn send_ws_error(socket: &mut WebSocket, error: String) { let _ = socket .send(Message::Text( @@ -6599,7 +6538,13 @@ async fn ssh_run_socket( target: crate::jobs::ssh::SshTarget, command: String, ) { - let connection = match crate::jobs::ssh::interactive_args(&target, None, Some(command)).await { + let connection = match crate::jobs::ssh::prepare_interactive_connection( + &target, + None, + Some(command), + ) + .await + { Ok(connection) => connection, Err(error) => { send_ws_error(&mut socket, error.to_string()).await; @@ -8065,32 +8010,17 @@ fn sidebar_session_json(store: &Store, session: &StoredChatSession, busy: bool) } fn chat_active_runs_json(store: &Store) -> Result { - let mut associations: Vec<_> = store - .list_active_run_wakeups()? - .into_iter() - .map(|wakeup| (wakeup.chat_session_id, wakeup.run)) - .collect(); - for run in store.list_active_runs()? { - if let Some(session_id) = run.chat_session_id.clone() { - associations.push((session_id, run)); - } - } - let mut seen = HashSet::new(); let mut rows = Vec::new(); - for (session_id, run) in associations { - if !seen.insert((session_id.clone(), run.id.clone())) { - continue; - } + for (session_id, run) in store.chat_active_runs()? { let experiment_name = store .get_local_experiment(&run.experiment_id)? .map(|experiment| experiment.display_name().to_string()); rows.push(json!({ "sessionId": session_id, - "run": ApiRun::from(&run), + "run": ApiRun::new(store, &run)?, "experimentName": experiment_name, })); } - rows.sort_by_key(|row| (row["sessionId"].to_string(), row["run"]["id"].to_string())); Ok(json!(rows)) } @@ -8261,9 +8191,29 @@ async fn chat_session_experiments(Path(id): Path) -> ApiResult { store .get_chat_session(&id)? .ok_or_else(|| not_found("chat session"))?; - Ok(Json( - json!({ "experiments": store.list_experiments_by_chat_session(&id)? }), - )) + let experiments = store + .list_experiments_by_chat_session(&id)? + .into_iter() + .map(|row| { + let current_run = row + .current_run + .map(|run| { + let mut value = serde_json::to_value(ApiRun::new(&store, &run)?)?; + value["cancelRequested"] = json!(run.cancel_requested); + value["endedAt"] = json!(run.ended_at); + Ok::<_, crate::error::Error>(value) + }) + .transpose()?; + + Ok(json!({ + "experiment": row.experiment, + "projectName": row.project_name, + "currentRun": current_run, + })) + }) + .collect::>>()?; + + Ok(Json(json!({ "experiments": experiments }))) } async fn create_chat_session( @@ -9166,19 +9116,28 @@ async fn agent_status(State(state): State) -> Json { // --- /api/events SSE ------------------------------------------------------ -async fn events( - State(state): State, -) -> Sse>> { +async fn events(State(state): State) -> Response { + let Ok(client) = api_v2::event_client() else { + return axum::http::StatusCode::SERVICE_UNAVAILABLE.into_response(); + }; // Small buffer on purpose: run.log events can carry ~MB payloads, and a // stalled client must backpressure the loop, not queue hundreds of MB. let (tx, rx) = mpsc::channel::(16); - tokio::spawn(event_loop(tx.clone())); + // Subscribed before the snapshot, so no run change between them is lost. + let runs = api_v2::run_events().ok(); + let chat = tx.clone(); + tokio::spawn(async move { + event_loop(tx, runs).await; + drop(client); + }); // Chat events ride the same stream: chat.session / chat.message / chat.busy. - tokio::spawn(forward_chat_events(state.chat.subscribe(), tx)); + tokio::spawn(forward_chat_events(state.chat.subscribe(), chat)); let stream = futures::stream::unfold(rx, |mut rx| async move { - rx.recv().await.map(|ev| (Ok(ev), rx)) + rx.recv().await.map(|ev| (Ok::<_, Infallible>(ev), rx)) }); - Sse::new(stream).keep_alive(KeepAlive::default()) + Sse::new(stream) + .keep_alive(KeepAlive::default()) + .into_response() } async fn forward_chat_events( @@ -9218,7 +9177,12 @@ struct EventCursor { projects: HashMap, experiments: HashMap, files: HashMap, - runs: HashMap, + runs: HashMap, + /// Runs whose local log file may still grow: in flight, or finished with a final + /// collection not yet streamed. + tailed: HashSet, + /// Live engine runs, whose hosts report log growth while this stream is open. + followed: HashMap>, log_offsets: HashMap, log_generations: HashMap, chat_active_runs: Option, @@ -9233,27 +9197,65 @@ struct EventCursor { /// there for run logs; nothing about an update needs that resolution. const UPDATE_SAMPLE_INTERVAL: Duration = Duration::from_secs(10); -/// 500ms poll loop: diff the store + log files, push named events into the -/// channel. Ends when the subscriber disconnects (send fails). Same idiom as -/// serve.rs, extended with project/experiment diffs. -async fn event_loop(tx: mpsc::Sender) { +/// Run changes arrive from the engine's Bus; projects, experiments, files, updates and local +/// log files are diffed every 500ms. Ends when the subscriber disconnects. +async fn event_loop( + tx: mpsc::Sender, + mut runs: Option>, +) { + use tokio::sync::broadcast::error::RecvError; let mut cursor = EventCursor::default(); let mut first = true; loop { if !first { // An idle store never sends, so a failed send can't be the only // disconnect signal — watch the receiver side too or the loop - // (and its 2Hz store polling) leaks per closed EventSource. - tokio::select! { - _ = tokio::time::sleep(Duration::from_millis(500)) => {} + // leaks per closed EventSource. + let event = tokio::select! { + _ = tokio::time::sleep(Duration::from_millis(500)) => None, _ = tx.closed() => return, + event = async { + match runs.as_mut() { + Some(receiver) => receiver.recv().await, + None => std::future::pending().await, + } + } => Some(event), + }; + let batch = match event { + None => None, + Some(Ok(event)) => Some( + Store::open().and_then(|store| run_events(&store, &mut cursor, Some(event))), + ), + // Lagged: resynchronize every run from the store. + Some(Err(RecvError::Lagged(_))) => { + Some(Store::open().and_then(|store| run_events(&store, &mut cursor, None))) + } + Some(Err(RecvError::Closed)) => { + runs = None; + continue; + } + }; + if let Some(batch) = batch { + for ev in batch.unwrap_or_default() { + if tx.send(ev).await.is_err() { + return; + } + } + continue; } } if tx.is_closed() { return; } // Store hiccups (locked db) just skip a tick. - let batch = collect_events(&mut cursor, first).unwrap_or_default(); + let mut batch = collect_events(&mut cursor).unwrap_or_default(); + if first { + batch.extend( + Store::open() + .and_then(|store| run_events(&store, &mut cursor, None)) + .unwrap_or_default(), + ); + } first = false; for ev in batch { if tx.send(ev).await.is_err() { @@ -9267,9 +9269,9 @@ fn json_event(name: &str, data: &Value) -> Event { Event::default().event(name).data(data.to_string()) } -/// One diff pass. On the first pass everything is "changed", so a fresh +/// One non-run diff pass. On the first pass everything is "changed", so a fresh /// subscriber gets a full snapshot and needs no separate baseline fetches. -fn collect_events(cursor: &mut EventCursor, first: bool) -> Result> { +fn collect_events(cursor: &mut EventCursor) -> Result> { let mut out = Vec::new(); // Sampled far below the 2Hz loop — the updater works on the scale of @@ -9290,10 +9292,6 @@ fn collect_events(cursor: &mut EventCursor, first: bool) -> Result> { } let store = Store::open()?; - // Cap log bytes per tick so one pass never materializes a huge batch — - // remainders (whole-log replays included) stream out on later ticks. - let mut log_budget: u64 = 2_000_000; - for project in store.list_local_projects()? { if cursor.projects.get(&project.id) != Some(&project.updated_at) { cursor @@ -9317,42 +9315,97 @@ fn collect_events(cursor: &mut EventCursor, first: bool) -> Result> { } } - for run in store.list_runs(200)? { - let changed = match cursor.runs.get(&run.id) { - None => true, - Some((status, updated)) => *status != run.status || *updated != run.updated_at, - }; - if changed { - cursor - .runs - .insert(run.id.clone(), (run.status.clone(), run.updated_at)); + // Cap log bytes per tick so one pass never materializes a huge batch — + // remainders (whole-log replays included) stream out on later ticks. + let mut log_budget: u64 = 2_000_000; + let tailed: Vec = cursor.tailed.iter().cloned().collect(); + for run_id in tailed { + let delta = push_log_delta(&run_id, cursor, &mut out, &mut log_budget); + let live = cursor + .runs + .get(&run_id) + .is_some_and(|status| !is_terminal(status)); + if !live && !delta { + cursor.tailed.remove(&run_id); + } + } + // Committed only now that the batch is certain to be returned. + if let Some(update) = sampled_update { + cursor.update = Some(update); + } + Ok(out) +} + +/// Run events for one Bus event, or for every recent run when `event` is `None` (the first +/// pass, or after the subscriber lagged). +fn run_events( + store: &Store, + cursor: &mut EventCursor, + event: Option, +) -> Result> { + use crate::engine::bus::RunEvent; + let first = cursor.chat_active_runs.is_none(); + let runs = match &event { + None => store.list_runs(200)?, + Some(RunEvent::Changed { run_id, .. } | RunEvent::LogCollection { run_id }) => { + store.get_run(run_id)?.into_iter().collect() + } + Some(RunEvent::Grew { run_id, len, .. }) => { + // A followed engine run's log grew on its host; the client refetches it. + return Ok(vec![json_event( + "run.log", + &json!({"runId": run_id, "dataBase64": "", "offset": len}), + )]); + } + Some(RunEvent::Host { alias, root, state }) => { + return Ok(vec![json_event( + "host.updated", + &api_v2::host_view(store, alias, root, state)?, + )]) + } + Some(RunEvent::Notices { .. }) => return Ok(Vec::new()), + }; + let mut out = Vec::new(); + if event.is_none() { + for (alias, root, state) in store.engine_hosts()? { out.push(json_event( - "run.updated", - &json!({ "run": ApiRun::from(&run) }), + "host.updated", + &api_v2::host_view(store, &alias, &root, &state)?, )); } - if first { + } + for run in runs { + if !cursor.runs.contains_key(&run.id) { // Live runs replay their whole log through the stream (chunked per - // tick); terminal runs start at EOF — backfill is /api/runs/{id}/log. - let start = if is_terminal(&run.status) { + // tick); runs already finished start at EOF — backfill is /api/runs/{id}/log. + let start = if first && is_terminal(&run.status) { log_size(&run.id) } else { 0 }; cursor.log_offsets.insert(run.id.clone(), start); } - // Terminal runs were seeded at EOF above, so this is a no-op for them. - push_log_delta(&run, cursor, &mut out, &mut log_budget); + cursor.runs.insert(run.id.clone(), run.status.clone()); + cursor.tailed.insert(run.id.clone()); + if crate::engine::is_engine_row(&run) && !is_terminal(&run.status) { + if !cursor.followed.contains_key(&run.id) { + if let Ok(follow) = api_v2::follow_log(&run.id) { + cursor.followed.insert(run.id.clone(), follow); + } + } + } else { + cursor.followed.remove(&run.id); + } + out.push(json_event( + "run.updated", + &json!({ "run": ApiRun::new(store, &run)? }), + )); } - let active_runs = chat_active_runs_json(&store)?; + let active_runs = chat_active_runs_json(store)?; if cursor.chat_active_runs.as_ref() != Some(&active_runs) { out.push(json_event("chat.runs", &json!({}))); cursor.chat_active_runs = Some(active_runs); } - // Committed only now that the batch is certain to be returned. - if let Some(update) = sampled_update { - cursor.update = Some(update); - } Ok(out) } @@ -9374,35 +9427,37 @@ fn push_experiment_events( Ok(()) } +/// True when this pass sent or reset anything. fn push_log_delta( - run: &StoredRun, + run_id: &str, cursor: &mut EventCursor, out: &mut Vec, budget: &mut u64, -) { - let offset = *cursor.log_offsets.entry(run.id.clone()).or_insert(0); - let expected = cursor.log_generations.get(&run.id).map(String::as_str); - let Ok(snapshot) = crate::jobs::ssh::service::logs::read(&run.id, offset, *budget, expected) +) -> bool { + let offset = *cursor.log_offsets.entry(run_id.to_owned()).or_insert(0); + let expected = cursor.log_generations.get(run_id).map(String::as_str); + let Ok(snapshot) = crate::jobs::ssh::service::logs::read(run_id, offset, *budget, expected) else { - return; + return false; }; let reset = expected.is_some_and(|generation| generation != snapshot.generation) || snapshot.offset != offset; if snapshot.bytes.is_empty() && !reset { - return; + return false; } *budget -= snapshot.bytes.len() as u64; cursor.log_offsets.insert( - run.id.clone(), + run_id.to_owned(), snapshot.offset + snapshot.bytes.len() as u64, ); cursor .log_generations - .insert(run.id.clone(), snapshot.generation.clone()); + .insert(run_id.to_owned(), snapshot.generation.clone()); out.push(json_event("run.log", &json!({ - "runId":run.id, "dataBase64":base64::engine::general_purpose::STANDARD.encode(&snapshot.bytes), + "runId":run_id, "dataBase64":base64::engine::general_purpose::STANDARD.encode(&snapshot.bytes), "offset":snapshot.offset, "generation":snapshot.generation, }))); + true } fn log_size(run_id: &str) -> u64 { @@ -9483,6 +9538,174 @@ pub(crate) async fn spa(uri: Uri) -> Response { mod tests { use super::*; + async fn event_text(events: Vec) -> String { + let stream = futures::stream::iter(events.into_iter().map(Ok::<_, Infallible>)); + let bytes = axum::body::to_bytes(Sse::new(stream).into_response().into_body(), 8192) + .await + .unwrap(); + String::from_utf8(bytes.to_vec()).unwrap() + } + + #[tokio::test] + async fn host_bus_events_serialize_as_dashboard_sse_and_initial_snapshot() { + use crate::engine::bus::{Bus, RunEvent}; + use crate::engine::transport::{HostClass, HostState, Status}; + let directory = std::env::temp_dir().join(format!("orx-host-sse-{}", uuid::Uuid::new_v4())); + let store = Store::open_at(directory.clone()).unwrap(); + let bus = Bus::new(); + let mut receiver = bus.subscribe(); + let mut cursor = EventCursor::default(); + for (status, expected) in [ + (Status::Live, "live"), + (Status::Backoff, "backoff"), + (Status::Live, "live"), + (Status::NeedsAuth, "needs_auth"), + ] { + let state = HostState { + status, + since_ms: 123, + next_retry_ms: Some(456), + cause: Some("fixture".into()), + ..HostState::default() + }; + store + .seed_engine_host("lab", "/engine", Some(HostClass::Key), &state) + .unwrap(); + bus.publish(RunEvent::Host { + alias: "lab".into(), + root: "/engine".into(), + state: state.clone(), + }); + let events = + run_events(&store, &mut cursor, Some(receiver.recv().await.unwrap())).unwrap(); + let text = event_text(events).await; + assert!(text.contains("event: host.updated"), "{text}"); + let data = text + .lines() + .find_map(|line| line.strip_prefix("data: ")) + .unwrap(); + let value: Value = serde_json::from_str(data).unwrap(); + assert_eq!( + value, + api_v2::host_view(&store, "lab", "/engine", &state).unwrap() + ); + assert_eq!(value["status"], expected); + } + assert!(!run_events(&store, &mut cursor, None).unwrap().is_empty()); + drop(store); + std::fs::remove_dir_all(directory).unwrap(); + } + + #[tokio::test] + async fn run_bus_events_emit_contact_and_cancel_without_a_timestamp_change() { + use crate::engine::bus::RunEvent; + use crate::engine::Phase; + use crate::store::Contact; + let directory = std::env::temp_dir().join(format!("orx-run-sse-{}", uuid::Uuid::new_v4())); + let store = Store::open_at(directory.clone()).unwrap(); + let run = StoredRun { + id: "r".into(), + experiment_id: "e".into(), + project_id: "p".into(), + status: "running".into(), + backend_json: r#"{"kind":"engine","jobId":"/r","handle":{"type":"Local","dir":"/r"}}"# + .into(), + command: "true".into(), + created_at: 1, + updated_at: 1, + ended_at: None, + exit_code: None, + commit_sha: None, + result_markdown: None, + cancel_requested: false, + cancel_reason: None, + chat_session_id: None, + }; + store.upsert_run(&run).unwrap(); + store.accept_run_cancel("r", Some("user")).unwrap(); + let updated_at = store.get_run("r").unwrap().unwrap().updated_at; + let mut cursor = EventCursor::default(); + run_events(&store, &mut cursor, None).unwrap(); + for contact in [ + Contact::Unreachable { + since: 2, + cause: "offline".into(), + }, + Contact::NeedsAuth { + since: 3, + cause: "auth".into(), + }, + Contact::Live, + ] { + store.set_run_contact("r", &contact).unwrap(); + assert_eq!(store.get_run("r").unwrap().unwrap().updated_at, updated_at); + let event = RunEvent::Changed { + run_id: "r".into(), + phase: Phase::Running, + contact: contact.clone(), + cancelling: true, + }; + let events = run_events(&store, &mut cursor, Some(event)).unwrap(); + let text = event_text(events).await; + assert!(text.contains("event: run.updated")); + let data = text + .lines() + .find_map(|line| line.strip_prefix("data: ")) + .unwrap(); + let value: Value = serde_json::from_str(data).unwrap(); + assert_eq!(value["run"]["cancelling"], true); + assert_eq!( + value["run"]["contact"], + if contact == Contact::Live { + Value::Null + } else { + json!(contact) + } + ); + } + store + .set_engine_phase("r", "running", "done", Some(10), Some(0), None) + .unwrap(); + store.queue_log_collection("r").unwrap(); + for attempt in 0..=8 { + if attempt == 8 { + store.finish_log_collection("r").unwrap(); + } else if attempt > 0 { + store.defer_log_collection("r", "offline").unwrap(); + } + let events = run_events( + &store, + &mut cursor, + Some(RunEvent::LogCollection { run_id: "r".into() }), + ) + .unwrap(); + let text = event_text(events).await; + assert!(text.contains("event: run.updated")); + let data = text + .lines() + .find_map(|line| line.strip_prefix("data: ")) + .unwrap(); + let value: Value = serde_json::from_str(data).unwrap(); + if attempt == 8 { + assert!(value["run"].get("logCollection").is_none()); + assert!(value["run"].get("logCollectionError").is_none()); + } else { + assert_eq!( + value["run"]["logCollection"], + if attempt == 7 { "failed" } else { "pending" } + ); + if attempt == 0 { + assert!(value["run"].get("logCollectionError").is_none()); + } else { + assert_eq!(value["run"]["logCollectionError"], "offline"); + } + } + assert_eq!(value["run"]["cancelling"], false); + } + drop(store); + std::fs::remove_dir_all(directory).unwrap(); + } + #[test] fn chat_active_runs_tracks_owners_and_watchers_until_terminal() { let dir = std::env::temp_dir().join(format!("orx-chat-runs-{}", uuid::Uuid::new_v4())); @@ -9505,8 +9728,8 @@ mod tests { chat_session_id: Some("owner".into()), }; store.upsert_run(&run).unwrap(); - store.register_run_wakeup(&run.id, "owner").unwrap(); - store.register_run_wakeup(&run.id, "watcher").unwrap(); + store.subscribe_run(&run.id, "owner", 1).unwrap(); + store.subscribe_run(&run.id, "watcher", 1).unwrap(); let rows = chat_active_runs_json(&store).unwrap(); assert_eq!(rows.as_array().unwrap().len(), 2); assert_eq!(rows[0]["sessionId"], "owner"); @@ -9587,31 +9810,6 @@ mod tests { assert!(new_chat_settings("project".into(), preferences, &catalog).is_err()); } - #[tokio::test] - async fn empty_local_error_reports_the_http_status() { - for (status, body, expected) in [ - (StatusCode::BAD_GATEWAY, "", "HTTP 502 Bad Gateway"), - (StatusCode::NOT_FOUND, "", "HTTP 404 Not Found"), - ( - StatusCode::BAD_REQUEST, - r#"{"error":""}"#, - "HTTP 400 Bad Request", - ), - ] { - let response = axum::http::Response::builder() - .status(status) - .body(body.to_string()) - .unwrap(); - let error = decode_local_response::(response.into(), "start the run") - .await - .unwrap_err(); - assert_eq!( - error.to_string(), - format!("orx up could not start the run: {expected}") - ); - } - } - #[test] fn missing_claude_keeps_install_guidance_when_auth_was_cached() { let host = local::claude::ClaudeHost::new(); @@ -9714,8 +9912,38 @@ mod tests { assert_eq!(sender.receiver_count(), 0); } + #[tokio::test] + async fn v2_events_and_hello_bypass_update_drain_without_counting_active_requests() { + use tower::ServiceExt; + + let _guard = ACTIVE_TEST_LOCK.lock().await; + let app = Router::new() + .route("/api/v2/hello", get(|| async { "ready" })) + .route("/api/v2/events", get(|| async { "events" })) + .layer(middleware::from_fn(track_active)); + DRAINING.store(true, Ordering::SeqCst); + let result = tokio::time::timeout(Duration::from_secs(1), async { + for path in ["hello", "events"] { + let request = axum::http::Request::builder() + .uri(format!("/api/v2/{path}")) + .body(axum::body::Body::empty()) + .unwrap(); + let response = app.clone().oneshot(request).await.unwrap(); + assert!(response.status().is_success()); + axum::body::to_bytes(response.into_body(), 1024) + .await + .unwrap(); + } + }) + .await; + DRAINING.store(false, Ordering::SeqCst); + result.unwrap(); + assert_eq!(ACTIVE.load(Ordering::SeqCst), 0); + } + #[tokio::test] async fn a_streaming_response_stays_active_until_its_body_is_sent() { + let _guard = ACTIVE_TEST_LOCK.lock().await; let gate = Arc::new(tokio::sync::Notify::new()); let release = gate.clone(); let app = Router::new() @@ -10143,7 +10371,54 @@ mod tests { } #[test] - fn api_run_exposes_cancel_intent() { + fn launches_hold_their_project_against_moves_and_deletion() { + let lifecycle = Arc::new(ProjectLifecycle::default()); + let moving = Arc::new(AtomicBool::new(false)); + let stopping = Arc::new(AtomicBool::new(false)); + let admit = launch_admission(lifecycle.clone(), moving.clone(), stopping.clone()); + let admission = admit("p").unwrap(); + assert_eq!(lifecycle.operation_count(), 1); + assert!(lifecycle.begin_delete("p").is_none()); + drop(admission); + assert_eq!(lifecycle.operation_count(), 0); + moving.store(true, Ordering::SeqCst); + assert!(admit("p").err().unwrap().to_string().contains("move")); + assert_eq!(lifecycle.operation_count(), 0); + moving.store(false, Ordering::SeqCst); + let deleting = lifecycle.begin_delete("p").unwrap(); + assert!(admit("p").is_err()); + drop(deleting); + stopping.store(true, Ordering::SeqCst); + assert!(admit("p").is_err()); + } + + #[test] + fn create_run_request_preserves_forwarded_slurm_resources_and_attribution() { + let request: CreateRunReq = serde_json::from_value(json!({ + "experimentId": "experiment-1", + "backend": "slurm", + "cpus": 8, + "mem": "64G", + "partition": "gpu", + "chatSessionId": "session-1", + "telemetrySuppressed": true, + "force": true, + })) + .unwrap(); + let forwarded = request.into_run_args(); + assert_eq!(forwarded.exp_id, "experiment-1"); + assert_eq!(forwarded.backend.as_deref(), Some("slurm")); + assert_eq!(forwarded.cpus, Some(8)); + assert_eq!(forwarded.mem.as_deref(), Some("64G")); + assert_eq!(forwarded.partition.as_deref(), Some("gpu")); + assert_eq!(forwarded.chat_session_id.as_deref(), Some("session-1")); + assert!(forwarded.forwarded); + assert!(forwarded.telemetry_suppressed); + assert!(forwarded.force); + } + + #[test] + fn api_run_exposes_cancel_intent_contact_and_the_launched_backend() { let mut backend = crate::jobs::BackendDescriptor::parse(r#"{"kind":"openresearch_job"}"#).unwrap(); backend.rental_lease = Some(crate::jobs::rental::Rental { @@ -10169,13 +10444,132 @@ mod tests { chat_session_id: None, }; - let value = serde_json::to_value(ApiRun::from(&run)).unwrap(); - assert_eq!(value["cancelRequested"], true); + let dir = std::env::temp_dir().join(format!("orx-api-run-{}", uuid::Uuid::new_v4())); + let store = Store::open_at(dir.clone()).unwrap(); + let value = serde_json::to_value(ApiRun::new(&store, &run).unwrap()).unwrap(); + assert!(value.get("cancelRequested").is_none()); assert_eq!(value["backend"]["kind"], "openresearch_job"); + assert!(value["contact"].is_null()); assert!(!value.to_string().contains("private-rental-token")); let legacy = serde_json::to_value(&run).unwrap(); assert!(!legacy.to_string().contains("private-rental-token")); assert!(run.backend_json.contains("private-rental-token")); + + // An engine run shows what it launched, its reachability, and an accepted cancel. + let metadata = crate::jobs::BackendDescriptor::parse(r#"{"kind":"engine"}"#).unwrap(); + let launch = crate::store::LaunchSpec { + kind: "ssh_job".into(), + target: Some("lab".into()), + options: json!({"container": {"reference": "dev", "id": "c1", "startedAt": "t", "runDir": "/root/.orx/runs/e"}}), + }; + store + .insert_submitting_run(crate::store::SubmittingRun { + id: "e", + experiment_id: "experiment-1", + project_id: "project-1", + metadata: &metadata, + command: "train", + created_at: 1, + commit_sha: None, + chat_session_id: None, + spec_digest: "digest", + launch: &launch, + }) + .unwrap(); + store + .set_engine_phase("e", "submitting", "running", None, None, Some(1234)) + .unwrap(); + store.accept_run_cancel("e", Some("user")).unwrap().unwrap(); + let outage = crate::store::Contact::Unreachable { + since: 3, + cause: "eof".into(), + }; + store.set_run_contact("e", &outage).unwrap(); + let engine = store.get_run("e").unwrap().unwrap(); + let value = serde_json::to_value(ApiRun::new(&store, &engine).unwrap()).unwrap(); + assert!(value.get("cancelRequested").is_none()); + assert_eq!(value["contact"]["type"], "unreachable"); + assert_eq!(value["backend"]["kind"], "ssh_job"); + assert_eq!(value["backend"]["namespace"], "lab"); + assert_eq!(value["backend"]["sshContainer"]["reference"], "dev"); + assert_eq!(value["cancelling"], true); + assert_eq!(value["startedAt"], 1234); + assert!(value["lostReason"].is_null()); + assert_eq!(value["host"], "lab"); + assert!(value["noticeError"].is_null()); + store + .insert_run_notice("e", "chat", crate::store::TERMINAL, "terminal", "done", 1) + .unwrap(); + let batch = store.run_notice_batch_at("chat", 2).unwrap(); + store + .record_run_notice_failure( + "chat", + &batch[0].client_turn_id, + "Chat harness is no longer configured", + true, + 3, + ) + .unwrap(); + let value = serde_json::to_value(ApiRun::new(&store, &engine).unwrap()).unwrap(); + assert_eq!(value["noticeError"], "Chat harness is no longer configured"); + let mut engine = engine; + engine.backend_json = crate::engine::handle::backend_json( + "e", + Some(&crate::engine::handle::Handle::Ssh { + host: "lab".into(), + root: "/engine".into(), + }), + &metadata, + ) + .unwrap(); + for status in [ + "submitting", + "starting", + "running", + "done", + "failed", + "cancelled", + "lost", + ] { + engine.status = status.into(); + engine.result_markdown = (status == "lost").then(|| "abandoned".into()); + for contact in [ + crate::store::Contact::Live, + outage.clone(), + crate::store::Contact::NeedsAuth { + since: 4, + cause: "auth".into(), + }, + crate::store::Contact::Unreconciled { + since: 5, + detail: "unknown".into(), + }, + ] { + store.set_run_contact("e", &contact).unwrap(); + let value = serde_json::to_value(ApiRun::new(&store, &engine).unwrap()).unwrap(); + assert_eq!(value["status"], status); + assert_eq!(value["host"], "lab"); + assert_eq!(value["cancelling"], !is_terminal(status)); + assert_eq!( + value["lostReason"], + if status == "lost" { + json!("abandoned") + } else { + Value::Null + } + ); + assert_eq!( + value["contact"], + if contact == crate::store::Contact::Live { + Value::Null + } else { + json!(contact) + } + ); + } + } + drop(store); + std::fs::remove_dir_all(dir).unwrap(); } #[test] @@ -10201,48 +10595,6 @@ mod tests { assert!(ids.iter().position(|id| *id == "ray").unwrap() < vercel); } - #[test] - fn create_run_request_preserves_forwarded_slurm_resources_and_attribution() { - let args = crate::ExpRunArgs { - invocation_context: None, - telemetry_suppressed: true, - forwarded: false, - exp_id: "experiment-1".into(), - disk: None, - provider: None, - backend: Some("slurm".into()), - flavor: None, - org: None, - host: None, - container: None, - no_container: false, - manifest: None, - image: None, - timeout: None, - cpus: Some(8), - mem: Some("64G".into()), - force: true, - chat_session_id: Some("session-1".into()), - agent_origin: None, - }; - let request = CreateRunReq::from_run_args(&args).unwrap(); - - let value = serde_json::to_value(&request).unwrap(); - assert_eq!(value["callerConfigDir"], json!(absolute_config_dir())); - assert_eq!(value["experimentId"], "experiment-1"); - assert_eq!(value["cpus"], 8); - assert_eq!(value["mem"], "64G"); - assert_eq!(value["chatSessionId"], "session-1"); - assert_eq!(value["force"], true); - let forwarded = serde_json::from_value::(value) - .unwrap() - .into_run_args(); - assert_eq!(forwarded.cpus, Some(8)); - assert_eq!(forwarded.mem.as_deref(), Some("64G")); - assert_eq!(forwarded.chat_session_id.as_deref(), Some("session-1")); - assert!(forwarded.force); - } - #[test] fn require_caller_config_dir_rejects_a_different_dir() { let root = std::env::temp_dir().join(format!("orx-caller-config-{}", uuid::Uuid::new_v4())); @@ -10345,6 +10697,7 @@ mod tests { stopping: Default::default(), dashboard_lock: Default::default(), restart: Default::default(), + reopen: Default::default(), trackio: Default::default(), }; let error = delete_artifact( diff --git a/src/commands/up/api_v2.rs b/src/commands/up/api_v2.rs new file mode 100644 index 000000000..2521e4b71 --- /dev/null +++ b/src/commands/up/api_v2.rs @@ -0,0 +1,1023 @@ +use std::collections::{HashMap, HashSet}; +use std::convert::Infallible; +use std::path::PathBuf; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex, MutexGuard, OnceLock}; +use std::time::Duration; + +use async_trait::async_trait; +use axum::extract::{Path, Query, Request, State}; +use axum::http::StatusCode; +use axum::middleware::{self, Next}; +use axum::response::sse::{Event, KeepAlive, Sse}; +use axum::response::{IntoResponse, Response}; +use axum::routing::{get, post}; +use axum::{Json, Router}; +use futures::{Stream, StreamExt}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use tokio::sync::broadcast; + +use crate::engine::bus::RunEvent; +use crate::engine::{handle_of, Backend, ByteRange, Engine, LogFile, LogPage, Phase, WatchedRun}; +use crate::error::{anyhow, Result}; +use crate::store::{Contact, Store, StoredRun}; + +static SERVER: OnceLock<(Arc, Router)> = OnceLock::new(); + +/// The adapter registry and launch preparation the server owns (`engine::runtime`). +#[async_trait] +pub(crate) trait Commands: Send + Sync { + /// Holds `admission` until the run is durable. + async fn run(&self, args: crate::ExpRunArgs, admission: Box) -> Result; + fn backend(&self, run: &StoredRun) -> Result>; + async fn cancel(&self, run: &StoredRun, reason: &str) -> Result<()>; + async fn cleanup(&self, run: &WatchedRun) -> Result; + async fn compute( + &self, + action: &str, + args: Value, + prompt: Option, + ) -> Result; + /// Keeps the host feed following this run and publishing `RunEvent::Grew` until drop. + fn follow_log(&self, run: &str) -> Result>; + fn host_states(&self, alias: &str) -> Vec<(String, crate::engine::transport::HostState)>; + async fn retry_host(&self, alias: &str); + /// Commands on this target run over the engine's connection to the host. + fn host_target(&self, host: &str, slurm: bool) -> Result; +} + +/// Holds a project open against deletion and data-directory moves until dropped. +pub(crate) type Admit = Box Result> + Send + Sync>; + +pub(crate) struct Api { + instance: String, + token: String, + engine: Arc, + commands: Arc, + admit: Admit, + data_dir: PathBuf, + store: Mutex, + clients: AtomicUsize, +} + +impl Api { + pub fn new( + instance: String, + token: String, + engine: Arc, + commands: Arc, + admit: Admit, + data_dir: PathBuf, + ) -> Result { + let store = Mutex::new(Store::open_at(data_dir.clone())?); + Ok(Self { + instance, + token, + engine, + commands, + admit, + data_dir, + store, + clients: AtomicUsize::new(0), + }) + } + + fn store(&self) -> MutexGuard<'_, Store> { + self.store.lock().unwrap() + } + + /// Admitted before preparation and held until the run is durable, so a deletion or move + /// cannot pull storage out from under it. + async fn launch(&self, mut args: crate::ExpRunArgs) -> Result { + let project = self + .store() + .get_local_experiment(&args.exp_id)? + .ok_or_else(|| anyhow!("Local experiment {} not found.", args.exp_id))? + .project_id; + let admission = (self.admit)(&project)?; + args.forwarded = true; + crate::local::apply_compute_default(&mut args.backend, &mut args.flavor); + args.backend.get_or_insert_with(|| "local".into()); + if crate::config::run_engine_settings()?.0 { + self.commands.run(args, admission).await + } else { + let run = crate::compute::submit_supervised(&args).await?; + Ok(run.id) + } + } + + fn run(&self, id: &str) -> Result { + self.store() + .get_run(id)? + .ok_or_else(|| anyhow!("Run {id} not found")) + } + + fn view(&self, run: &StoredRun) -> Result { + let state = self.store().engine_run_state(&run.id)?; + let cancelling = !Phase::parse(&run.status).is_some_and(Phase::is_terminal) + && (run.cancel_requested + || state + .as_ref() + .is_some_and(|state| state.cancel_accepted_at.is_some())); + let mut value = serde_json::to_value(run)?; + value["startedAt"] = json!(state.as_ref().and_then(|state| state.started_at)); + let launch = state.as_ref().and_then(|state| state.launch.as_ref()); + if let Some(backend) = crate::store::public_backend(&run.backend_json, launch) { + value["backendJson"] = json!(backend.to_string()); + } + value["cancelUnconfirmed"] = json!(state + .as_ref() + .and_then(|state| state.cancel_unconfirmed.as_ref())); + value["contact"] = + serde_json::to_value(state.map_or(Contact::Live, |state| state.contact))?; + if let Some((failed, error)) = self.store().log_collection(&run.id)? { + value["logCollection"] = json!(if failed { "failed" } else { "pending" }); + value["logCollectionError"] = json!(error); + } + value["host"] = json!(super::run_host(&self.store(), run)?); + value["cancelling"] = json!(cancelling); + value["durationSecs"] = json!(crate::local::run_duration_secs(run)); + value["updatedDisplay"] = json!(crate::local::fmt_ago(run.updated_at)); + Ok(value) + } + + pub(super) fn busy(&self) -> Result { + Ok(self.store().engine_idle_blocked()? || self.sse_clients() != 0) + } + + pub fn sse_clients(&self) -> usize { + self.clients.load(Ordering::SeqCst) + } +} + +pub(crate) fn install(api: Arc) -> Result<()> { + SERVER + .set(( + api.clone(), + routes(api.clone()).merge(dashboard_routes(api)), + )) + .map_err(|_| anyhow!("API v2 is already installed")) +} + +pub(crate) fn router() -> Router { + Router::new().route("/api/{*path}", axum::routing::any(dispatch)) +} + +async fn dispatch(mut request: Request) -> Response { + use tower::ServiceExt; + match SERVER.get() { + Some((_, app)) => { + // The inner router must not inherit the outer wildcard's path captures. + request.extensions_mut().clear(); + app.clone().oneshot(request).await.unwrap() + } + None => ( + StatusCode::SERVICE_UNAVAILABLE, + "Run engine is not initialized", + ) + .into_response(), + } +} + +fn dashboard_routes(api: Arc) -> Router { + Router::new() + .route("/api/runs/{id}/log", get(log)) + .route("/api/runs/{id}/abandon", post(dashboard_abandon)) + .route("/api/runs/{id}/cleanup", post(cleanup)) + .route("/api/compute/hosts", get(hosts)) + .route("/api/compute/hosts/{alias}/retry", post(retry_host)) + .with_state(api) +} + +fn installed() -> Result<&'static Arc> { + SERVER + .get() + .map(|(api, _)| api) + .ok_or_else(|| anyhow!("Run engine is not initialized")) +} + +#[cfg(desktop_app)] +pub(crate) fn busy() -> Result { + installed()?.busy() +} + +#[cfg(desktop_app)] +pub(crate) fn runs_busy() -> Result { + installed()?.store().engine_runs_block_idle() +} + +/// For the dashboard's `/api/runs`: the same launch as `POST /api/v2/runs`. +pub(crate) async fn launch(args: crate::ExpRunArgs) -> Result { + let api = installed()?; + let id = api.launch(args).await?; + api.run(&id) +} + +pub(crate) async fn cancel_run(run: &StoredRun, reason: &str) -> Result<()> { + installed()?.commands.cancel(run, reason).await +} + +pub(crate) fn host_target(host: &str, slurm: bool) -> Result { + installed()?.commands.host_target(host, slurm) +} + +/// `compute test|connect` as the dashboard asks for it. +pub(crate) async fn check_compute( + action: &str, + args: Value, + prompt: Option, +) -> Result { + installed()?.commands.compute(action, args, prompt).await +} + +pub(crate) fn follow_log(run: &str) -> Result> { + installed()?.commands.follow_log(run) +} + +pub(crate) fn run_events() -> Result> { + Ok(installed()?.engine.bus.subscribe()) +} + +/// Counts a dashboard event stream as an idle blocker until dropped. +pub(crate) fn event_client() -> Result { + let api = installed()?.clone(); + api.clients.fetch_add(1, Ordering::SeqCst); + let subscription = Subscription { api, _log: None }; + if super::IDLE_EXIT.load(Ordering::SeqCst) { + return Err(anyhow!("Run engine is shutting down")); + } + Ok(subscription) +} + +fn routes(api: Arc) -> Router { + Router::new() + .route("/api/v2/runs", get(runs).post(run)) + .route("/api/v2/runs/{id}", get(get_run)) + .route("/api/v2/runs/{id}/cancel", post(cancel)) + .route("/api/v2/runs/{id}/abandon", post(abandon)) + .route("/api/v2/runs/{id}/cleanup", post(cleanup)) + .route("/api/v2/runs/{id}/log", get(log)) + .route("/api/v2/events", get(events)) + .route("/api/v2/compute/{action}", post(compute)) + .route_layer(middleware::from_fn_with_state(api.clone(), authenticate)) + .route("/api/v2/hello", get(hello)) + .with_state(api) +} + +async fn authenticate(State(api): State>, request: Request, next: Next) -> Response { + use sha2::{Digest, Sha256}; + let provided = request + .headers() + .get("authorization") + .and_then(|value| value.to_str().ok()) + .and_then(|value| value.strip_prefix("Bearer ")); + let authorized = !api.token.is_empty() + && provided.is_some_and(|provided| { + let left = Sha256::digest(provided.as_bytes()); + let right = Sha256::digest(api.token.as_bytes()); + left.iter() + .zip(right) + .fold(0u8, |diff, (a, b)| diff | (a ^ b)) + == 0 + }); + if authorized { + next.run(request).await + } else { + (StatusCode::UNAUTHORIZED, "Server bearer token required").into_response() + } +} + +type ApiResult = std::result::Result; +enum Failure { + Message(StatusCode, String), + Unavailable { + host: Option, + since: i64, + contact: &'static str, + }, +} +impl From for Failure { + fn from(error: crate::error::Error) -> Self { + Self::Message(StatusCode::BAD_REQUEST, error.to_string()) + } +} +impl IntoResponse for Failure { + fn into_response(self) -> Response { + match self { + Self::Message(status, message) => (status, message).into_response(), + Self::Unavailable { host, since, contact } => (StatusCode::SERVICE_UNAVAILABLE, Json(json!({ + "error": "Page not on this computer", "host": host, "since": since, "contact": contact, + }))).into_response(), + } + } +} + +#[derive(Deserialize)] +struct HelloQuery { + nonce: String, +} +async fn hello( + State(api): State>, + Query(query): Query, +) -> ApiResult> { + if query.nonce.len() > 256 || query.nonce.is_empty() { + return Err(Failure::Message( + StatusCode::BAD_REQUEST, + "Supply a discovery nonce".into(), + )); + } + let proof = crate::commands::remote_host::hello_proof(&api.token, &api.instance, &query.nonce); + Ok(Json( + json!({"instance":api.instance, "proto":2, "version":env!("CARGO_PKG_VERSION"), "proof":proof}), + )) +} + +#[derive(Default, Deserialize, Serialize)] +pub(crate) struct Filter { + pub project: Option, + pub experiment: Option, + pub run: Option, + #[serde(default)] + pub wait: bool, + #[serde(default)] + pub follow: bool, +} +impl Filter { + fn matches(&self, run: &StoredRun) -> bool { + self.project.as_ref().is_none_or(|id| *id == run.project_id) + && self + .experiment + .as_ref() + .is_none_or(|id| *id == run.experiment_id) + && self.run.as_ref().is_none_or(|id| *id == run.id) + } + fn rows(&self, api: &Api) -> Result> { + let store = api.store(); + let rows = if let Some(id) = &self.run { + store.get_run(id)?.into_iter().collect() + } else if let Some(id) = &self.experiment { + store.list_runs_by_experiment(id)? + } else if let Some(id) = &self.project { + store.list_runs_by_project(id)? + } else { + store.list_runs(usize::MAX)? + }; + Ok(rows.into_iter().filter(|run| self.matches(run)).collect()) + } +} + +async fn runs(State(api): State>, Query(filter): Query) -> ApiResult> { + let titles: HashMap<_, _> = if let Some(project) = &filter.project { + api.store() + .list_experiments_by_project(project)? + .into_iter() + .map(|exp| (exp.id.clone(), exp.display_name().to_string())) + .collect() + } else { + HashMap::new() + }; + let runs: Result> = filter.rows(&api)?.iter().map(|run| api.view(run)).collect(); + Ok(Json(json!({"runs":runs?, "titles":titles}))) +} +async fn get_run(State(api): State>, Path(id): Path) -> ApiResult> { + Ok(Json(api.view(&api.run(&id)?)?)) +} +async fn run( + State(api): State>, + Json(args): Json, +) -> ApiResult> { + crate::commands::up::require_caller_config_dir( + args.caller_config_dir.as_deref(), + &crate::commands::up::absolute_config_dir(), + )?; + let id = api.launch(args).await?; + Ok(Json(api.view(&api.run(&id)?)?)) +} +#[derive(Default, Deserialize)] +#[serde(rename_all = "camelCase")] +struct CancelRequest { + chat_session_id: Option, +} + +async fn cancel( + State(api): State>, + Path(id): Path, + request: Option>, +) -> ApiResult> { + let run = api.run(&id)?; + let chat = request.and_then(|Json(request)| request.chat_session_id); + api.commands + .cancel( + &run, + &crate::commands::exp::exp_cancel_reason(chat.as_deref()), + ) + .await?; + Ok(Json(api.view(&api.run(&id)?)?)) +} +async fn abandon(State(api): State>, Path(id): Path) -> ApiResult> { + abandon_run(&api, &id)?; + Ok(Json(api.view(&api.run(&id)?)?)) +} +fn abandon_run(api: &Api, id: &str) -> ApiResult<()> { + let run = api.run(id)?; + let contact = api + .store() + .engine_run_state(id)? + .map_or(Contact::Live, |state| state.contact); + if Phase::parse(&run.status).is_some_and(Phase::is_terminal) || contact == Contact::Live { + return Err(Failure::Message( + StatusCode::CONFLICT, + "Abandon requires a non-terminal run without live contact".into(), + )); + } + if !api.engine.abandon(id)? { + return Err(Failure::Message( + StatusCode::CONFLICT, + "Run cannot be abandoned".into(), + )); + } + Ok(()) +} + +async fn dashboard_abandon( + State(api): State>, + Path(id): Path, +) -> ApiResult> { + abandon_run(&api, &id)?; + let run = api.run(&id)?; + Ok(Json( + serde_json::to_value(super::ApiRun::new(&api.store(), &run)?) + .map_err(crate::error::Error::from)?, + )) +} + +pub(crate) fn host_view( + store: &Store, + alias: &str, + root: &str, + state: &crate::engine::transport::HostState, +) -> Result { + use crate::engine::transport::{HostClass, Status}; + let class = store.engine_host_auth(alias)?.class; + Ok(json!({ + "alias": alias, "root": root, + "status": match state.status { Status::Idle => "idle", Status::Connecting => "connecting", Status::Live => "live", Status::Backoff => "backoff", Status::NeedsAuth => "needs_auth" }, + "class": class.map(|class| match class { HostClass::Key => "key", HostClass::Interactive => "interactive" }), + "sinceMs": state.since_ms, "nextRetryMs": state.next_retry_ms, "cause": state.cause, + })) +} + +async fn hosts(State(api): State>) -> ApiResult> { + let store = api.store(); + let hosts: Result> = store + .engine_hosts()? + .into_iter() + .map(|(alias, root, state)| host_view(&store, &alias, &root, &state)) + .collect(); + Ok(Json(json!(hosts?))) +} + +async fn retry_host( + State(api): State>, + Path(alias): Path, +) -> ApiResult> { + use crate::engine::transport::{HostClass, Status}; + let states = api.commands.host_states(&alias); + if states.is_empty() { + return Err(Failure::Message( + StatusCode::NOT_FOUND, + "Host not in use".into(), + )); + } + let key = api.store().engine_host_auth(&alias)?.class == Some(HostClass::Key); + if states.iter().any(|(_, state)| { + !matches!(state.status, Status::Live | Status::Connecting) + && (state.status == Status::NeedsAuth || !key) + }) { + return Err(Failure::Message( + StatusCode::CONFLICT, + "Host requires Connect".into(), + )); + } + api.commands.retry_host(&alias).await; + let states = api.commands.host_states(&alias); + let (root, state) = states + .iter() + .max_by_key(|(_, state)| state.status.severity()) + .ok_or_else(|| Failure::Message(StatusCode::NOT_FOUND, "Host not in use".into()))?; + Ok(Json(host_view(&api.store(), &alias, root, state)?)) +} + +async fn cleanup(State(api): State>, Path(id): Path) -> ApiResult> { + let run = api.run(&id)?; + if !Phase::parse(&run.status).is_some_and(Phase::is_terminal) { + return Err(Failure::Message( + StatusCode::CONFLICT, + "Cleanup requires a finished run".into(), + )); + } + let handle = handle_of(&run).ok_or_else(|| { + Failure::Message( + StatusCode::CONFLICT, + "This run never started, so there is nothing to clean up".into(), + ) + })?; + Ok(Json( + api.commands.cleanup(&WatchedRun { id, handle }).await?, + )) +} +async fn compute( + State(api): State>, + Path(action): Path, + Json(mut args): Json, +) -> ApiResult> { + if !matches!(action.as_str(), "connect" | "test") { + return Err(Failure::Message( + StatusCode::NOT_FOUND, + "Unknown compute action".into(), + )); + } + #[derive(Deserialize)] + struct Endpoint { + port: u16, + token: String, + } + let endpoint: Option = args + .as_object_mut() + .and_then(|args| args.remove("prompt")) + .map(serde_json::from_value) + .transpose() + .map_err(crate::error::Error::from)?; + let prompt: Option = if let Some(endpoint) = endpoint { + if action != "connect" + || endpoint.port == 0 + || endpoint.token.len() < 32 + || endpoint.token.len() > 256 + { + return Err(Failure::Message( + StatusCode::BAD_REQUEST, + "Incorrect prompt callback".into(), + )); + } + let client = crate::net::loopback_client() + .build() + .map_err(crate::error::Error::from)?; + Some(Arc::new(move |question| { + let client = client.clone(); + let token = endpoint.token.clone(); + let port = endpoint.port; + Box::pin(async move { + Ok(client + .post(format!("http://127.0.0.1:{port}/prompt")) + .bearer_auth(token) + .json(&question) + .send() + .await? + .error_for_status()? + .json::>() + .await?) + }) + })) + } else { + None + }; + Ok(Json(api.commands.compute(&action, args, prompt).await?)) +} + +#[derive(Deserialize)] +struct LogQuery { + start: u64, + end: u64, + ident: Option, +} + +/// Kept ranges retain host offsets even when the middle of a large log is discarded. +#[derive(Serialize, Deserialize)] +pub(crate) struct KeptRange { + pub offset: u64, + pub len: u64, + pub file: PathBuf, + pub ident: crate::engine::FileIdent, + pub eof: bool, +} + +pub(crate) fn kept_ranges(data_dir: &std::path::Path, run: &str) -> Result> { + let path = data_dir.join("run-logs").join(format!("{run}.ranges.json")); + match std::fs::read(path) { + Ok(bytes) => Ok(serde_json::from_slice(&bytes)?), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()), + Err(error) => Err(error.into()), + } +} + +/// Replaces a run's kept ranges with a collected log, removing page files it no longer uses. +pub(crate) fn keep_ranges( + data_dir: &std::path::Path, + run: &str, + ranges: Vec, +) -> Result<()> { + let manifest = data_dir.join("run-logs").join(format!("{run}.ranges.json")); + let old = kept_ranges(data_dir, run)?; + crate::local::git::atomic_write_with_mode( + &manifest, + &serde_json::to_vec(&ranges)?, + Some(0o600), + )?; + for range in old { + if !ranges.iter().any(|kept| kept.file == range.file) { + std::fs::remove_file(range.file)?; + } + } + Ok(()) +} + +/// A page, and which of its ranges are kept for the identity it reads. +async fn log( + State(api): State>, + Path(id): Path, + Query(query): Query, +) -> ApiResult> { + let expected = query + .ident + .map(crate::engine::FileIdent::try_from) + .transpose() + .map_err(|error| Failure::Message(StatusCode::BAD_REQUEST, error))?; + let range = ByteRange { + start: query.start, + end: query.end, + }; + let page = read_log(&api, &id, range, expected).await?; + let mut value = serde_json::to_value(&page).map_err(crate::error::Error::from)?; + if let LogPage::Data { ident, .. } = &page { + let kept: Vec<_> = kept_ranges(&api.data_dir, &id)? + .iter() + .filter(|range| range.ident == *ident) + .map(|range| [range.offset, range.offset + range.len]) + .collect(); + value["kept"] = json!(kept); + } + Ok(Json(value)) +} + +async fn read_log( + api: &Api, + id: &str, + range: ByteRange, + expected: Option, +) -> ApiResult { + if range.end < range.start || range.end - range.start > orx_host_proto::MAX_PAGE_LEN { + return Err(Failure::Message( + StatusCode::BAD_REQUEST, + "Choose a log range of at most 1 MiB".into(), + )); + } + let run = api.run(id)?; + // Until its log is kept through the end, a finished run is read like a live one. + let terminal = Phase::parse(&run.status).is_some_and(Phase::is_terminal) + && !api.store().log_collection_pending(id)?; + let kept = kept_ranges(&api.data_dir, id)?; + let known_len = kept + .iter() + .filter(|range| range.eof) + .map(|range| range.offset + range.len) + .max(); + let mut cursor = range.start; + let mut bytes = Vec::new(); + let mut identity = None; + let mut eof = false; + while let Some(kept) = kept + .iter() + .filter(|kept| { + kept.offset <= cursor + && (cursor < kept.offset.saturating_add(kept.len) + || kept.eof && cursor == kept.offset.saturating_add(kept.len)) + }) + .max_by_key(|kept| kept.offset) + { + if identity.as_ref().is_some_and(|ident| *ident != kept.ident) { + break; + } + if expected.as_ref().is_some_and(|ident| *ident != kept.ident) { + return Ok(LogPage::Reset { + info: Some(orx_host_proto::LogInfo { + ident: kept.ident.clone(), + len: known_len.unwrap_or(kept.offset + kept.len), + }), + }); + } + identity = Some(kept.ident.clone()); + let end = range.end.min(kept.offset + kept.len); + use std::io::{Read, Seek, SeekFrom}; + let mut file = std::fs::File::open(&kept.file).map_err(crate::error::Error::from)?; + file.seek(SeekFrom::Start(cursor - kept.offset)) + .map_err(crate::error::Error::from)?; + let previous = bytes.len(); + bytes.resize(previous + (end - cursor) as usize, 0); + file.read_exact(&mut bytes[previous..]) + .map_err(crate::error::Error::from)?; + cursor = end; + eof = kept.eof && cursor == kept.offset + kept.len; + if cursor == range.end || eof { + break; + } + } + if let Some(ident) = identity { + if !bytes.is_empty() || cursor == range.end || eof && terminal { + return Ok(LogPage::Data { + len: known_len, + ident, + start: range.start, + bytes, + eof: eof && (terminal || cursor == range.end), + }); + } + } + + // A 0.2.x supervisor kept its log here; the host may no longer have it. + let legacy_log = api.data_dir.join("run-logs").join(format!("{id}.log")); + if !crate::engine::is_engine_row(&run) + && (legacy_log.is_file() || legacy_log.with_extension("cursor.json").is_file()) + { + let snapshot = crate::jobs::ssh::service::logs::read_from( + &api.data_dir, + id, + range.start, + range.end - range.start, + None, + )?; + use sha2::{Digest, Sha256}; + let digest = Sha256::digest(snapshot.generation.as_bytes()); + let ident = crate::engine::FileIdent { + dev: 0, + ino: u64::from_be_bytes(digest[..8].try_into().unwrap()), + }; + if snapshot.offset != range.start || expected.as_ref().is_some_and(|e| *e != ident) { + return Ok(LogPage::Reset { + info: Some(orx_host_proto::LogInfo { + ident, + len: snapshot.size, + }), + }); + } + let eof = snapshot.offset + snapshot.bytes.len() as u64 >= snapshot.size; + return Ok(LogPage::Data { + len: Some(snapshot.size), + ident, + start: range.start, + bytes: snapshot.bytes, + eof, + }); + } + + let Some(handle) = handle_of(&run) else { + let message = if terminal { + "This run never started, so it has no log" + } else { + "This run hasn't started yet, so it has no log" + }; + return Err(Failure::Message(StatusCode::NOT_FOUND, message.into())); + }; + let fetch = async { + let backend = api.commands.backend(&run)?; + let watched = WatchedRun { + id: id.to_owned(), + handle, + }; + let page = backend + .read_log(&watched, LogFile::Log, range, expected.as_ref()) + .await; + // A finished run's log is kept; what reading the rest set up goes again. + if terminal { + backend.unwatch(&watched).await; + } + page + } + .await; + let page = fetch.map_err(|error| { + let transport = error.chain().any(|cause| { + cause.downcast_ref::().is_some_and(|error| { + matches!( + error.kind(), + std::io::ErrorKind::ConnectionRefused + | std::io::ErrorKind::ConnectionAborted + | std::io::ErrorKind::ConnectionReset + | std::io::ErrorKind::NotConnected + | std::io::ErrorKind::BrokenPipe + | std::io::ErrorKind::TimedOut + ) + }) || cause + .downcast_ref::() + .is_some_and(|error| error.is_connect() || error.is_timeout()) + }); + let state = error + .downcast_ref::() + .map(|error| &error.state); + if state.is_some() || transport { + let contact = if state + .is_some_and(|state| state.status == crate::engine::transport::Status::NeedsAuth) + { + "needs_auth" + } else { + "unreachable" + }; + let since = state + .map(|state| state.since_ms) + .filter(|since| *since > 0) + .unwrap_or_else(crate::store::now_ms); + let host = super::run_host(&api.store(), &run).ok().flatten(); + Failure::Unavailable { + host, + since, + contact, + } + } else { + Failure::Message(StatusCode::BAD_REQUEST, error.to_string()) + } + })?; + Ok(page) +} + +struct Subscription { + api: Arc, + _log: Option>, +} +impl Drop for Subscription { + fn drop(&mut self) { + self.api.clients.fetch_sub(1, Ordering::SeqCst); + } +} + +async fn events( + State(api): State>, + Query(filter): Query, +) -> ApiResult>>> { + // Subscribe before taking the snapshot so a concurrent commit cannot be lost. + let receiver = api.engine.bus.subscribe(); + let rows = filter.rows(&api)?; + let snapshot = if filter.wait { + let values: Result> = rows.iter().map(|run| api.view(run)).collect(); + Some(Ok(Event::default() + .event("snapshot") + .data(json!({"snapshot":values?}).to_string()))) + } else { + None + }; + let completed: HashSet<_> = rows + .iter() + .filter(|run| Phase::parse(&run.status).is_some_and(Phase::is_terminal)) + .map(|run| run.id.clone()) + .collect(); + let initial = if filter.wait && filter.project.is_some() && filter.experiment.is_none() { + rows.iter() + .all(|run| Phase::parse(&run.status).is_some_and(Phase::is_terminal)) + .then(|| json!({"drained":true})) + } else if filter.wait { + rows.first() + .filter(|run| Phase::parse(&run.status).is_some_and(Phase::is_terminal)) + .map(|run| api.view(run)) + .transpose()? + } else if filter.run.is_some() { + rows.first().map(|run| api.view(run)).transpose()? + } else { + None + }; + let log = if filter.follow { + Some( + api.commands.follow_log( + filter + .run + .as_deref() + .ok_or_else(|| anyhow!("Following logs requires a run id"))?, + )?, + ) + } else { + None + }; + api.clients.fetch_add(1, Ordering::SeqCst); + let subscription = Subscription { api, _log: log }; + if super::IDLE_EXIT.load(Ordering::SeqCst) { + return Err(anyhow!("Run engine is shutting down").into()); + } + let stream = futures::stream::unfold( + (subscription, receiver, filter, initial, false, completed), + |(subscription, mut receiver, filter, initial, done, completed)| async move { + if done { + return None; + } + if let Some(initial) = initial { + let done = filter.wait; + return Some(( + Ok(Event::default().event("run").data(initial.to_string())), + (subscription, receiver, filter, None, done, completed), + )); + } + loop { + let api = &subscription.api; + let result = match receiver.recv().await { + Ok(event @ (RunEvent::Changed { .. } | RunEvent::Grew { .. })) => { + let run_id = match &event { + RunEvent::Changed { run_id, .. } | RunEvent::Grew { run_id, .. } => { + run_id + } + _ => unreachable!(), + }; + api.run(run_id).and_then(|run| { + if !filter.matches(&run) || filter.wait && completed.contains(run_id) { + return Ok(None); + } + let mut value = api.view(&run)?; + match &event { + RunEvent::Changed { + phase, + contact, + cancelling, + .. + } => { + value["status"] = json!(phase.as_str()); + value["contact"] = serde_json::to_value(contact)?; + value["cancelling"] = json!(cancelling); + value["event"] = json!("changed"); + } + RunEvent::Grew { file, len, .. } => { + if filter.wait { + return Ok(None); + } + value["file"] = serde_json::to_value(file)?; + value["len"] = json!(len); + } + _ => unreachable!(), + } + Ok(Some(value)) + }) + } + Ok( + RunEvent::Notices { .. } + | RunEvent::Host { .. } + | RunEvent::LogCollection { .. }, + ) => continue, + Err(broadcast::error::RecvError::Closed) => return None, + Err(broadcast::error::RecvError::Lagged(_)) => { + if filter.wait { + filter.rows(api).and_then(|rows| { + rows.iter() + .find(|run| { + Phase::parse(&run.status).is_some_and(Phase::is_terminal) + && !completed.contains(&run.id) + }) + .map(|run| api.view(run)) + .transpose() + }) + } else { + Ok(Some(json!({"resync":true}))) + } + } + }; + match result { + Ok(Some(value)) => { + let done = filter.wait + && Phase::parse(value["status"].as_str().unwrap_or_default()) + .is_some_and(Phase::is_terminal); + return Some(( + Ok(Event::default().event("run").data(value.to_string())), + (subscription, receiver, filter, None, done, completed), + )); + } + Ok(None) => continue, + Err(error) => { + return Some(( + Ok(Event::default().event("error").data(error.to_string())), + (subscription, receiver, filter, None, true, completed), + )) + } + } + } + }, + ); + let stream = futures::stream::iter(snapshot).chain(stream); + Ok(Sse::new(stream).keep_alive(KeepAlive::new().interval(Duration::from_secs(15)))) +} + +#[derive(Default)] +pub(crate) struct Idle { + since: Option, +} +impl Idle { + pub fn should_exit(&mut self, now: Duration, busy: bool) -> bool { + if busy { + self.since = None; + return false; + } + now.saturating_sub(*self.since.get_or_insert(now)) >= Duration::from_secs(600) + } + + pub fn check(&mut self, api: &Api, now: Duration) -> Result { + Ok(self.should_exit( + now, + api.busy()? || super::ACTIVE.load(Ordering::SeqCst) != 0, + )) + } +} + +#[cfg(test)] +mod tests; diff --git a/src/commands/up/api_v2/tests.rs b/src/commands/up/api_v2/tests.rs new file mode 100644 index 000000000..de539e8c5 --- /dev/null +++ b/src/commands/up/api_v2/tests.rs @@ -0,0 +1,2692 @@ +use super::*; +use crate::commands::remote_host::ServerDescriptor; +use crate::engine::handle::Handle; +use crate::engine::{ + CancelOutcome, Fence, FileIdent, LaunchError, Observation, Recovery, RunIntent, +}; +use crate::plane::local_plane::ApiClient; +use crate::store::{LaunchSpec, SubmittingRun}; +use futures::StreamExt; +use std::collections::VecDeque; +use std::sync::atomic::AtomicBool; + +#[derive(Default)] +struct Fake { + offline: AtomicBool, + outage: Mutex>, + invalid_log: AtomicBool, + scripted_pages: Mutex>, + identities: Mutex>>, + launch_gate: Mutex, Arc)>>, + reads: AtomicUsize, + follows: Arc, + /// Launch admissions currently held. + admitted: Arc, +} +#[async_trait] +impl Backend for Fake { + async fn launch( + &self, + _: &RunIntent, + _: &Fence<'_>, + ) -> std::result::Result { + let gate = self.launch_gate.lock().unwrap().clone(); + if let Some((entered, release)) = gate { + entered.notify_one(); + release.notified().await; + } + Ok(Handle::Local { + dir: "/fake".into(), + }) + } + async fn recover(&self, _: &RunIntent) -> Recovery { + Recovery::Absent + } + async fn observe(&self, _: &[WatchedRun], _: Duration) -> Vec<(String, Observation)> { + vec![] + } + async fn cancel(&self, _: &WatchedRun) -> CancelOutcome { + CancelOutcome::Pending + } + async fn read_log( + &self, + _: &WatchedRun, + _: LogFile, + range: ByteRange, + expected: Option<&FileIdent>, + ) -> Result { + self.reads.fetch_add(1, Ordering::SeqCst); + self.identities.lock().unwrap().push(expected.cloned()); + if let Some(page) = self.scripted_pages.lock().unwrap().pop_front() { + return Ok(page); + } + if self.offline.load(Ordering::SeqCst) { + if let Some(state) = self.outage.lock().unwrap().clone() { + return Err(anyhow!(crate::engine::transport::Unavailable { + state, + sent: false + })); + } + return Err(std::io::Error::from(std::io::ErrorKind::NotConnected).into()); + } + if self.invalid_log.load(Ordering::SeqCst) { + return Err(anyhow!("malformed host page")); + } + if expected.is_some_and(|expected| *expected != ident()) { + return Ok(LogPage::Reset { + info: Some(orx_host_proto::LogInfo { + ident: ident(), + len: 10, + }), + }); + } + let bytes = b"0123456789"; + let end = range.end.min(bytes.len() as u64); + Ok(LogPage::Data { + len: Some(10), + ident: ident(), + start: range.start, + bytes: bytes[range.start as usize..end as usize].to_vec(), + eof: end == bytes.len() as u64, + }) + } +} +struct Services(Arc, Arc, PathBuf); +#[async_trait] +impl Commands for Services { + async fn run(&self, args: crate::ExpRunArgs, admission: Box) -> Result { + assert_eq!(self.0.admitted.load(Ordering::SeqCst), 1); + self.1.insert(SubmittingRun { + id: "run", + experiment_id: &args.exp_id, + project_id: "project", + metadata: &crate::jobs::BackendDescriptor::parse(r#"{"kind":"local"}"#)?, + command: "train", + created_at: 1, + commit_sha: None, + chat_session_id: None, + spec_digest: "digest", + launch: &LaunchSpec { + kind: "local".into(), + target: None, + options: json!({}), + }, + })?; + drop(admission); + self.1.launch_inserted(self.0.as_ref(), "run").await?; + Ok("run".into()) + } + fn backend(&self, _: &StoredRun) -> Result> { + Ok(self.0.clone()) + } + async fn cancel(&self, run: &StoredRun, reason: &str) -> Result<()> { + self.1.cancel(self.0.as_ref(), &run.id, reason).await?; + Ok(()) + } + fn host_target(&self, _: &str, _: bool) -> Result { + Err(anyhow!("No hosts in this fixture")) + } + async fn cleanup(&self, _: &WatchedRun) -> Result { + Ok(json!({"accepted":true})) + } + async fn compute( + &self, + action: &str, + _: Value, + prompt: Option, + ) -> Result { + if let Some(prompt) = prompt { + assert_eq!(prompt("MFA code:".into()).await?, Some("123456".into())); + } + Ok(json!({"action":action, "ready":true})) + } + fn host_states(&self, alias: &str) -> Vec<(String, crate::engine::transport::HostState)> { + Store::open_at(self.2.clone()) + .unwrap() + .engine_hosts() + .unwrap() + .into_iter() + .filter(|(host, _, _)| host == alias) + .map(|(_, root, state)| (root, state)) + .collect() + } + async fn retry_host(&self, alias: &str) { + assert_eq!(alias, "lab"); + } + fn follow_log(&self, _: &str) -> Result> { + struct Guard(Arc); + impl Drop for Guard { + fn drop(&mut self) { + self.0.fetch_sub(1, Ordering::SeqCst); + } + } + self.0.follows.fetch_add(1, Ordering::SeqCst); + Ok(Box::new(Guard(self.0.follows.clone()))) + } +} +fn ident() -> FileIdent { + FileIdent { dev: 1, ino: 2 } +} + +/// Keeps `bytes` at `start` of the run's log, beside what is kept already. +fn keep(api: &Api, run: &str, start: u64, bytes: &[u8], eof: bool) { + let file = api.data_dir.join(format!("run-logs/{run}.{start}.page")); + std::fs::create_dir_all(file.parent().unwrap()).unwrap(); + std::fs::write(&file, bytes).unwrap(); + let mut ranges = kept_ranges(&api.data_dir, run).unwrap(); + ranges.push(KeptRange { + offset: start, + len: bytes.len() as u64, + file, + ident: ident(), + eof, + }); + keep_ranges(&api.data_dir, run, ranges).unwrap(); +} + +async fn completion(events: &mut (impl Stream> + Unpin)) -> Value { + while let Some(value) = events.next().await { + let value = value.unwrap(); + if value["drained"] == true + || Phase::parse(value["status"].as_str().unwrap_or_default()) + .is_some_and(Phase::is_terminal) + { + return value; + } + } + panic!("event stream ended before completion") +} + +fn run_with_engine(test: &str) -> bool { + if std::env::var("ORX_RUN_ENGINE").as_deref() == Ok("1") { + return false; + } + let output = crate::process::command(std::env::current_exe().unwrap()) + .env("ORX_RUN_ENGINE", "1") + .args(["--exact", test, "--nocapture"]) + .output() + .unwrap(); + assert!( + output.status.success(), + "{}\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + true +} + +struct Fixture { + api: Arc, + backend: Arc, + refuse_admission: Arc, + client: ApiClient, + descriptor: ServerDescriptor, + requests: Arc, + task: tokio::task::JoinHandle<()>, +} +impl Fixture { + async fn new() -> Self { + let data_dir = std::env::temp_dir().join(format!("orx-api-{}", uuid::Uuid::new_v4())); + let store = Store::open_at(data_dir.clone()).unwrap(); + store + .create_local_experiment(&crate::local::model::LocalExperiment { + id: "exp".into(), + project_id: "project".into(), + parent_experiment_id: None, + slug: "exp".into(), + branch_name: "orx/exp".into(), + title: None, + description: None, + run_command: "train".into(), + agent_status: "idle".into(), + created_at: 1, + updated_at: 1, + chat_session_id: None, + archived: false, + }) + .unwrap(); + let backend = Arc::new(Fake::default()); + let admitted = backend.admitted.clone(); + let refuse_admission = Arc::new(AtomicBool::new(false)); + let admit: Admit = { + let (admitted, refuse) = (admitted.clone(), refuse_admission.clone()); + Box::new(move |project| { + assert_eq!(project, "project"); + if refuse.load(Ordering::SeqCst) { + return Err(anyhow!("A data-directory move is in progress.")); + } + struct Held(Arc); + impl Drop for Held { + fn drop(&mut self) { + self.0.fetch_sub(1, Ordering::SeqCst); + } + } + admitted.fetch_add(1, Ordering::SeqCst); + Ok(Box::new(Held(admitted.clone()))) + }) + }; + let engine = Arc::new(Engine::new( + store, + Arc::new(crate::engine::clock::SystemClock::new()), + )); + let api = Arc::new( + Api::new( + "instance".into(), + "secret".into(), + engine.clone(), + Arc::new(Services(backend.clone(), engine, data_dir.clone())), + admit, + data_dir, + ) + .unwrap(), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let descriptor = ServerDescriptor { + instance: api.instance.clone(), + token: api.token.clone(), + pid: std::process::id(), + starttime: crate::engine::process::identity(std::process::id()) + .unwrap() + .starttime, + port: listener.local_addr().unwrap().port(), + version: env!("CARGO_PKG_VERSION").into(), + proto: 2, + }; + let requests = Arc::new(AtomicUsize::new(0)); + let count = requests.clone(); + let app = routes(api.clone()) + .merge(dashboard_routes(api.clone())) + .layer(middleware::from_fn(move |request: Request, next: Next| { + let count = count.clone(); + async move { + count.fetch_add(1, Ordering::SeqCst); + next.run(request).await + } + })); + let task = tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + let client = ApiClient::new(descriptor.clone()).unwrap(); + Self { + api, + backend, + refuse_admission, + client, + descriptor, + requests, + task, + } + } + fn insert(&self, id: &str, experiment: &str, project: &str, status: &str) { + self.api + .store() + .upsert_run(&StoredRun { + id: id.into(), + experiment_id: experiment.into(), + project_id: project.into(), + status: status.into(), + backend_json: + r#"{"kind":"engine","jobId":"/fake","handle":{"type":"Local","dir":"/fake"}}"# + .into(), + command: "train".into(), + created_at: 1, + updated_at: 1, + ended_at: None, + exit_code: None, + commit_sha: None, + result_markdown: None, + cancel_requested: false, + cancel_reason: None, + chat_session_id: None, + }) + .unwrap(); + } +} +impl Drop for Fixture { + fn drop(&mut self) { + self.task.abort(); + let _ = std::fs::remove_dir_all(&self.api.data_dir); + } +} + +#[tokio::test] +async fn authenticated_routes_expose_contact_and_commands() { + let f = Fixture::new().await; + let response = crate::net::loopback_client() + .build() + .unwrap() + .get(format!( + "http://127.0.0.1:{}/api/v2/runs", + f.descriptor.port + )) + .send() + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::UNAUTHORIZED); + assert_eq!( + f.client + .json(reqwest::Method::GET, "hello?nonce=test", None) + .await + .unwrap()["instance"], + "instance" + ); + f.insert("run", "exp", "project", "starting"); + f.api + .engine + .observe( + "run", + Observation::Running { + started_at: Some(1234), + }, + ) + .unwrap(); + let list = f + .client + .json(reqwest::Method::GET, "runs?project=project", None) + .await + .unwrap(); + let _: crate::plane::RunListing = serde_json::from_value(list.clone()).unwrap(); + let run_view: crate::plane::Run = serde_json::from_value(list["runs"][0].clone()).unwrap(); + assert_eq!(run_view.id, "run"); + assert_eq!(run_view.status, "running"); + assert_eq!(list["runs"][0]["contact"]["type"], "live"); + assert_eq!(list["runs"][0]["startedAt"], 1234); + let cancel = f + .client + .json(reqwest::Method::POST, "runs/run/cancel", None) + .await + .unwrap(); + assert_eq!(cancel["cancelling"], true); + assert!(f + .client + .json(reqwest::Method::POST, "runs/run/cleanup", None) + .await + .is_err()); + f.api + .store() + .set_run_contact( + "run", + &Contact::Unreachable { + since: 3, + cause: "offline".into(), + }, + ) + .unwrap(); + let abandoned = f + .client + .json(reqwest::Method::POST, "runs/run/abandon", None) + .await + .unwrap(); + assert_eq!(abandoned["status"], "lost"); + assert_eq!(abandoned["contact"]["type"], "unreconciled"); + assert_eq!( + f.client + .json(reqwest::Method::POST, "runs/run/cleanup", None) + .await + .unwrap()["accepted"], + true + ); + for action in ["test", "connect"] { + assert_eq!( + f.client + .json( + reqwest::Method::POST, + &format!("compute/{action}"), + Some(&json!({})) + ) + .await + .unwrap()["ready"], + true + ); + } + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let uninitialized = Router::new() + .route("/api/runs/{id}", get(|| async { "legacy" })) + .merge(router()); + let server = tokio::spawn(async move { + axum::serve(listener, uninitialized).await.unwrap(); + }); + let response = crate::net::loopback_client() + .build() + .unwrap() + .get(format!("http://{address}/api/v2/runs")) + .send() + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE); + install(f.api.clone()).unwrap(); + let response = crate::net::loopback_client() + .build() + .unwrap() + .get(format!("http://{address}/api/v2/runs/run")) + .bearer_auth("secret") + .send() + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + assert_eq!(response.json::().await.unwrap()["id"], "run"); + let response = crate::net::loopback_client() + .build() + .unwrap() + .get(format!("http://{address}/api/runs/run/log?start=0&end=2")) + .send() + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + assert_eq!(response.json::().await.unwrap()["data"], "MDE="); + server.abort(); + assert!(install(f.api.clone()).is_err()); +} + +#[tokio::test] +async fn wait_is_one_sse_request_completed_by_first_matching_bus_event() { + let f = Fixture::new().await; + f.insert("run", "exp", "project", "running"); + f.insert("other", "other", "other", "running"); + let filter = Filter { + experiment: Some("exp".into()), + wait: true, + ..Default::default() + }; + let mut events = f.client.events(&filter).await.unwrap(); + assert_eq!(f.api.sse_clients(), 1); + f.api + .engine + .observe( + "other", + Observation::Exited { + finished_at: None, + code: Some(0), + signal: None, + }, + ) + .unwrap(); + f.api + .engine + .observe("run", Observation::Running { started_at: None }) + .unwrap(); + f.api + .engine + .observe( + "run", + Observation::Exited { + finished_at: None, + code: Some(0), + signal: None, + }, + ) + .unwrap(); + let event = tokio::time::timeout(Duration::from_secs(1), completion(&mut events)) + .await + .unwrap(); + assert_eq!(event["id"], "run"); + assert_eq!(event["status"], "done"); + assert!(events.next().await.is_none()); + assert_eq!(f.requests.load(Ordering::SeqCst), 1); + f.client + .wait(Filter { + run: Some("run".into()), + wait: true, + ..Default::default() + }) + .await + .unwrap(); + assert_eq!(f.backend.reads.load(Ordering::SeqCst), 0); + assert_eq!(f.requests.load(Ordering::SeqCst), 2); +} + +#[tokio::test] +async fn project_wait_returns_drained_and_filters_other_projects() { + let f = Fixture::new().await; + f.insert("old", "exp", "project", "done"); + let mut events = f + .client + .events(&Filter { + project: Some("project".into()), + wait: true, + ..Default::default() + }) + .await + .unwrap(); + assert_eq!(completion(&mut events).await["drained"], true); + f.insert("new", "exp", "project", "running"); + let mut events = f + .client + .events(&Filter { + project: Some("project".into()), + wait: true, + ..Default::default() + }) + .await + .unwrap(); + f.api + .engine + .observe( + "new", + Observation::Exited { + finished_at: None, + code: Some(0), + signal: None, + }, + ) + .unwrap(); + assert_eq!(completion(&mut events).await["id"], "new"); +} + +#[tokio::test] +async fn log_pages_use_kept_offsets_remote_ranges_and_503_on_unreachable() { + let f = Fixture::new().await; + f.insert("run", "exp", "project", "running"); + keep(&f.api, "run", 6, b"6789", true); + let local = f + .client + .json(reqwest::Method::GET, "runs/run/log?start=7&end=10", None) + .await + .unwrap(); + assert_eq!(local["data"], json!("Nzg5")); + assert_eq!(f.backend.reads.load(Ordering::SeqCst), 0); + let remote = f + .client + .json(reqwest::Method::GET, "runs/run/log?start=2&end=5", None) + .await + .unwrap(); + assert_eq!(remote["data"], json!("MjM0")); + f.api + .store() + .set_engine_phase("run", "running", "done", Some(1), Some(0), None) + .unwrap(); + f.backend.offline.store(true, Ordering::SeqCst); + *f.backend.outage.lock().unwrap() = Some(crate::engine::transport::HostState { + status: crate::engine::transport::Status::Backoff, + since_ms: 123, + ..Default::default() + }); + f.api + .store() + .set_run_contact( + "run", + &Contact::Unreachable { + since: 123, + cause: "offline".into(), + }, + ) + .unwrap(); + let response = f + .client + .request(reqwest::Method::GET, "runs/run/log?start=0&end=2") + .send() + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE); + assert_eq!( + response.json::().await.unwrap(), + json!({"error":"Page not on this computer", "host":null, "since":123, "contact":"unreachable"}) + ); + assert!(f + .client + .json(reqwest::Method::GET, "runs/run/log?start=5&end=2", None) + .await + .is_err()); +} + +/// Pending final collection does not turn an earlier kept prefix into the final log. +#[tokio::test] +async fn finished_runs_read_from_their_host_until_the_log_is_kept() { + let f = Fixture::new().await; + f.insert("run", "exp", "project", "running"); + keep(&f.api, "run", 0, b"0123", true); + { + let store = f.api.store(); + store + .set_engine_phase("run", "running", "done", Some(1), Some(0), None) + .unwrap(); + store.queue_log_collection("run").unwrap(); + assert!(!store + .defer_log_collection("run", "host in backoff") + .unwrap()); + } + let run = f + .client + .json(reqwest::Method::GET, "runs/run", None) + .await + .unwrap(); + assert_eq!(run["logCollection"], "pending"); + assert_eq!(run["logCollectionError"], "host in backoff"); + let page = f + .client + .json(reqwest::Method::GET, "runs/run/log?start=0&end=100", None) + .await + .unwrap(); + assert_eq!(page["data"], json!("MDEyMw==")); + assert_eq!(page["eof"], false); + assert_eq!(f.backend.reads.load(Ordering::SeqCst), 0); + let rest = f + .client + .json(reqwest::Method::GET, "runs/run/log?start=4&end=100", None) + .await + .unwrap(); + assert_eq!(rest["data"], json!("NDU2Nzg5")); + assert_eq!(f.backend.reads.load(Ordering::SeqCst), 1); + f.backend.offline.store(true, Ordering::SeqCst); + assert!(f + .client + .json(reqwest::Method::GET, "runs/run/log?start=4&end=100", None) + .await + .is_err()); + + f.api.store().finish_log_collection("run").unwrap(); + let run = f + .client + .json(reqwest::Method::GET, "runs/run", None) + .await + .unwrap(); + assert!(run.get("logCollection").is_none()); + let kept = f + .client + .json(reqwest::Method::GET, "runs/run/log?start=0&end=100", None) + .await + .unwrap(); + assert_eq!(kept["data"], json!("MDEyMw==")); + assert_eq!(kept["eof"], true); +} + +#[tokio::test] +async fn idle_requires_ten_uninterrupted_minutes_and_all_blockers_clear() { + let _serial = crate::commands::up::ACTIVE_TEST_LOCK.lock().await; + let f = Fixture::new().await; + let mut idle = Idle::default(); + assert!(!idle.check(&f.api, Duration::ZERO).unwrap()); + assert!(idle.check(&f.api, Duration::from_secs(600)).unwrap()); + f.insert("run", "exp", "project", "running"); + assert!(f.api.store().engine_runs_block_idle().unwrap()); + assert!(!idle.check(&f.api, Duration::from_secs(601)).unwrap()); + f.api + .store() + .set_engine_phase("run", "running", "lost", Some(1), None, None) + .unwrap(); + f.api + .store() + .set_run_contact( + "run", + &Contact::Unreconciled { + since: 1, + detail: "kill pending".into(), + }, + ) + .unwrap(); + assert!(!f.api.store().engine_runs_block_idle().unwrap()); + assert!(!idle.check(&f.api, Duration::from_secs(1201)).unwrap()); + f.api.store().queue_log_collection("run").unwrap(); + assert!(idle.check(&f.api, Duration::from_secs(1801)).unwrap()); + f.api + .store() + .set_run_contact("run", &Contact::Live) + .unwrap(); + let connection = rusqlite::Connection::open(f.api.data_dir.join("orx.db")).unwrap(); + connection.execute("INSERT INTO run_notices(run_id, chat_session_id, kind, dedupe, body, created_at) VALUES ('run','chat','attention','one','body',1)", []).unwrap(); + assert!(!f.api.store().engine_runs_block_idle().unwrap()); + assert!(!idle.check(&f.api, Duration::from_secs(1801)).unwrap()); + connection + .execute("UPDATE run_notices SET delivered_at=1", []) + .unwrap(); + connection.execute("INSERT INTO chat_turns(id,session_id,assistant_message_id,client_turn_id,request_hash,prepared_input,settings_json,state,delivery_state,created_at,updated_at) VALUES ('turn','chat','assistant','client','hash','input','{}','running','pending',1,1)", []).unwrap(); + assert!(!f.api.store().engine_runs_block_idle().unwrap()); + assert!(!idle.check(&f.api, Duration::from_secs(2401)).unwrap()); + connection.execute("DELETE FROM chat_turns", []).unwrap(); + let events = f + .client + .events(&Filter { + run: Some("run".into()), + follow: true, + ..Default::default() + }) + .await + .unwrap(); + assert_eq!(f.backend.follows.load(Ordering::SeqCst), 1); + assert!(!f.api.store().engine_runs_block_idle().unwrap()); + assert!(!idle.check(&f.api, Duration::from_secs(3001)).unwrap()); + drop(events); + f.task.abort(); + tokio::task::yield_now().await; + assert!(!idle.should_exit(Duration::from_secs(3002), false)); + assert!(idle.should_exit(Duration::from_secs(3602), false)); +} + +#[tokio::test] +async fn cli_launch_and_cancel_use_the_server_and_kept_pages_span_file_boundaries() { + if run_with_engine(concat!( + module_path!(), + "::cli_launch_and_cancel_use_the_server_and_kept_pages_span_file_boundaries" + )) { + return; + } + use clap::Parser; + let f = Fixture::new().await; + let cli = + crate::Cli::try_parse_from(["orx", "exp", "run", "exp", "--backend", "local"]).unwrap(); + let Some(crate::Command::Exp(crate::ExpArgs { + command: crate::ExpCommand::Run(args), + })) = cli.command + else { + panic!("run command") + }; + f.client.launch(*args).await.unwrap(); + assert_eq!(f.api.run("run").unwrap().status, "starting"); + f.client.cancel(Some("exp"), None).await.unwrap(); + assert!(f + .api + .store() + .engine_run_state("run") + .unwrap() + .unwrap() + .cancel_accepted_at + .is_some()); + keep(&f.api, "run", 0, b"01234", false); + keep(&f.api, "run", 5, b"56789", true); + let value = f + .client + .json(reqwest::Method::GET, "runs/run/log?start=3&end=8", None) + .await + .unwrap(); + assert_eq!(value["data"], json!("MzQ1Njc=")); + assert_eq!(f.backend.reads.load(Ordering::SeqCst), 0); + f.client.logs("run", false).await.unwrap(); + f.api + .engine + .observe( + "run", + Observation::Exited { + finished_at: None, + code: Some(0), + signal: None, + }, + ) + .unwrap(); + // What the runtime records once the finished run's log is kept. + f.api.store().finish_log_collection("run").unwrap(); + f.backend.offline.store(true, Ordering::SeqCst); + f.client.logs("run", true).await.unwrap(); +} + +#[tokio::test] +async fn project_wait_resync_excludes_already_completed_runs() { + let f = Fixture::new().await; + f.insert("old", "exp", "project", "done"); + f.insert("run", "exp", "project", "running"); + let mut events = f + .client + .events(&Filter { + project: Some("project".into()), + wait: true, + ..Default::default() + }) + .await + .unwrap(); + for _ in 0..2048 { + f.api + .engine + .bus + .publish(RunEvent::Notices { chats: vec![] }); + } + f.api + .engine + .observe( + "run", + Observation::Exited { + finished_at: None, + code: Some(0), + signal: None, + }, + ) + .unwrap(); + assert_eq!( + tokio::time::timeout(Duration::from_secs(1), completion(&mut events)) + .await + .unwrap()["id"], + "run" + ); +} + +#[tokio::test] +async fn log_feed_is_refcounted_and_pushes_without_a_cli_poll() { + let f = Fixture::new().await; + f.insert("run", "exp", "project", "running"); + let mut events = f + .client + .events(&Filter { + run: Some("run".into()), + follow: true, + ..Default::default() + }) + .await + .unwrap(); + assert_eq!(events.next().await.unwrap().unwrap()["id"], "run"); + f.api.engine.bus.publish(RunEvent::Grew { + file: LogFile::Log, + run_id: "run".into(), + len: 10, + }); + let event = tokio::time::timeout(Duration::from_secs(1), events.next()) + .await + .unwrap() + .unwrap() + .unwrap(); + assert!(event.get("event").is_none()); + assert_eq!(event["file"], "log"); + assert_eq!(event["len"], 10); + assert_eq!(f.backend.follows.load(Ordering::SeqCst), 1); + drop(events); + tokio::time::timeout(Duration::from_secs(1), async { + while f.api.sse_clients() != 0 { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + assert_eq!(f.backend.follows.load(Ordering::SeqCst), 0); +} + +#[tokio::test] +async fn v2_launches_are_host_checked_admitted_and_keep_a_run_submission_active() { + if run_with_engine(concat!( + module_path!(), + "::v2_launches_are_host_checked_admitted_and_keep_a_run_submission_active" + )) { + return; + } + use clap::Parser; + let _guard = crate::commands::up::ACTIVE_TEST_LOCK.lock().await; + let f = Fixture::new().await; + let entered = Arc::new(tokio::sync::Notify::new()); + let release = Arc::new(tokio::sync::Notify::new()); + *f.backend.launch_gate.lock().unwrap() = Some((entered.clone(), release.clone())); + let app = crate::commands::up::server_router( + routes(f.api.clone()), + Some(crate::commands::remote_host::RemoteAuth::new( + "legacy-token", + )), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + let client = crate::net::loopback_client().build().unwrap(); + let response = client + .get(format!("http://{address}/api/v2/hello?nonce=test")) + .header("host", "evil.example") + .send() + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + let cli = + crate::Cli::try_parse_from(["orx", "exp", "run", "exp", "--backend", "local"]).unwrap(); + let Some(crate::Command::Exp(crate::ExpArgs { + command: crate::ExpCommand::Run(args), + })) = cli.command + else { + panic!("run command") + }; + let body = serde_json::to_value(&args).unwrap(); + let post = move || { + client + .post(format!("http://{address}/api/v2/runs")) + .bearer_auth("secret") + .json(&body) + .send() + }; + f.refuse_admission.store(true, Ordering::SeqCst); + let refused = post().await.unwrap(); + assert!(!refused.status().is_success()); + assert!(refused + .text() + .await + .unwrap() + .contains("move is in progress")); + assert!(f.api.store().get_run("run").unwrap().is_none()); + f.refuse_admission.store(false, Ordering::SeqCst); + let request = tokio::spawn(async move { post().await.unwrap().text().await.unwrap() }); + entered.notified().await; + assert_eq!(crate::commands::up::ACTIVE.load(Ordering::SeqCst), 1); + // Admitted through preparation (checked at insert), released once the row is durable. + assert_eq!(f.backend.admitted.load(Ordering::SeqCst), 0); + assert!(f.api.store().get_run("run").unwrap().is_some()); + release.notify_one(); + request.await.unwrap(); + tokio::time::timeout(Duration::from_secs(1), async { + while crate::commands::up::ACTIVE.load(Ordering::SeqCst) != 0 { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + server.abort(); +} + +#[tokio::test] +async fn terminal_nonlive_contacts_do_not_block_idle_exit() { + let _serial = crate::commands::up::ACTIVE_TEST_LOCK.lock().await; + let f = Fixture::new().await; + f.insert("run", "exp", "project", "lost"); + for contact in [ + Contact::Unreachable { + since: 1, + cause: "offline".into(), + }, + Contact::NeedsAuth { + since: 1, + cause: "login".into(), + }, + Contact::Unreconciled { + since: 1, + detail: "unknown".into(), + }, + ] { + let mut idle = Idle::default(); + f.api.store().set_run_contact("run", &contact).unwrap(); + assert!(!idle.check(&f.api, Duration::ZERO).unwrap()); + assert!(idle.check(&f.api, Duration::from_secs(601)).unwrap()); + } + f.api + .store() + .set_run_contact("run", &Contact::Live) + .unwrap(); + let mut idle = Idle::default(); + assert!(!idle.check(&f.api, Duration::ZERO).unwrap()); + assert!(idle.check(&f.api, Duration::from_secs(600)).unwrap()); +} + +#[tokio::test] +async fn experiment_wait_excludes_older_completed_runs_after_subscribing() { + let f = Fixture::new().await; + f.insert("old", "exp", "project", "done"); + f.insert("run", "exp", "project", "running"); + let connection = rusqlite::Connection::open(f.api.data_dir.join("orx.db")).unwrap(); + connection + .execute("UPDATE runs SET created_at=2 WHERE id='run'", []) + .unwrap(); + let mut events = f + .client + .events(&Filter { + experiment: Some("exp".into()), + wait: true, + ..Default::default() + }) + .await + .unwrap(); + f.api.engine.bus.publish(RunEvent::Changed { + run_id: "old".into(), + phase: Phase::Done, + contact: Contact::Live, + cancelling: false, + }); + f.api + .engine + .observe( + "run", + Observation::Exited { + finished_at: None, + code: Some(0), + signal: None, + }, + ) + .unwrap(); + assert_eq!(completion(&mut events).await["id"], "run"); +} + +#[tokio::test] +async fn log_replacement_is_marked_and_identity_reaches_the_backend() { + let f = Fixture::new().await; + f.insert("run", "exp", "project", "running"); + let mut next = ident(); + next.ino += 1; + f.backend.scripted_pages.lock().unwrap().extend([ + LogPage::Data { + len: None, + ident: ident(), + start: 0, + bytes: b"old".to_vec(), + eof: false, + }, + LogPage::Reset { + info: Some(orx_host_proto::LogInfo { + ident: next.clone(), + len: 3, + }), + }, + LogPage::Data { + len: None, + ident: next.clone(), + start: 0, + bytes: b"new".to_vec(), + eof: true, + }, + ]); + let mut output = Vec::new(); + f.client.logs_to("run", false, &mut output).await.unwrap(); + assert_eq!( + String::from_utf8(output).unwrap(), + "old\n[log replaced; starting new generation]\nnew" + ); + assert_eq!( + *f.backend.identities.lock().unwrap(), + vec![None, Some(ident()), Some(next)] + ); +} + +#[tokio::test] +async fn malformed_log_pages_are_not_reported_as_transport_outages() { + let f = Fixture::new().await; + f.insert("run", "exp", "project", "running"); + f.backend.invalid_log.store(true, Ordering::SeqCst); + let response = f + .client + .request(reqwest::Method::GET, "runs/run/log?start=0&end=5") + .send() + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + assert_eq!(response.text().await.unwrap(), "malformed host page"); +} + +#[tokio::test] +async fn compute_connect_relays_interactive_prompts_to_the_client() { + let f = Fixture::new().await; + let prompted = Arc::new(AtomicUsize::new(0)); + let count = prompted.clone(); + let prompt: crate::engine::transport::Prompt = Arc::new(move |question| { + assert_eq!(question, "MFA code:"); + count.fetch_add(1, Ordering::SeqCst); + Box::pin(async { Ok(Some("123456".into())) }) + }); + assert_eq!( + f.client + .connect(json!({"backend":"ssh","host":"test"}), prompt) + .await + .unwrap()["ready"], + true + ); + assert_eq!(prompted.load(Ordering::SeqCst), 1); +} + +#[tokio::test] +async fn reconnect_child() { + let Ok(mode) = std::env::var("ORX_TEST_STREAM_RECONNECT") else { + return; + }; + let client = ApiClient::discover().await.unwrap(); + if mode == "post" { + let port = std::env::var("ORX_TEST_STALE_PORT").unwrap_or_else(|_| "0".into()); + let stale = ApiClient::new( + ServerDescriptor::agent_session(Some(port), Some("old-token".into())) + .unwrap() + .unwrap(), + ) + .unwrap(); + let result = stale + .json( + reqwest::Method::POST, + "echo", + Some(&json!({"command":"one launch"})), + ) + .await + .unwrap(); + assert_eq!(result, json!({"command":"one launch"})); + if std::env::var_os("ORX_TEST_STALE_PORT").is_some() { + let events = stale.events(&Filter::default()).await.unwrap(); + futures::pin_mut!(events); + assert!(events.next().await.is_none()); + } + return; + } + if mode == "wait" || mode == "projectwait" { + client + .wait(Filter { + run: (mode == "wait").then(|| "run".into()), + project: (mode == "projectwait").then(|| "project".into()), + wait: true, + ..Default::default() + }) + .await + .unwrap(); + } else { + let mut output = Vec::new(); + client.logs_to("run", true, &mut output).await.unwrap(); + assert_eq!(output, b"0123456789"); + } +} + +#[tokio::test] +async fn wait_and_follow_rediscover_and_rebuild_snapshots_when_the_sse_connection_closes() { + for mode in ["wait", "projectwait", "logs"] { + let f = Fixture::new().await; + f.insert("run", "exp", "project", "running"); + if mode == "projectwait" { + f.insert("other", "other", "project", "running"); + } + let requests = Arc::new(AtomicUsize::new(0)); + let count = requests.clone(); + let api = f.api.clone(); + let app = Router::new() + .route( + "/api/v2/events", + get(move |Query(filter): Query| { + let count = count.clone(); + let api = api.clone(); + async move { + let number = count.fetch_add(1, Ordering::SeqCst); + if number != 0 { + api.engine + .observe( + "run", + Observation::Exited { + finished_at: None, + code: Some(0), + signal: None, + }, + ) + .unwrap(); + } + let bytes = if filter.project.is_some() { + let rows = api.store().list_runs_by_project("project").unwrap(); + let values: Vec<_> = + rows.iter().map(|run| api.view(run).unwrap()).collect(); + format!("event: snapshot\ndata: {}\n\n", json!({"snapshot":values})) + } else if number == 0 && filter.wait { + let run = api.view(&api.run("run").unwrap()).unwrap(); + format!("event: snapshot\ndata: {}\n\n", json!({"snapshot":[run]})) + } else { + format!( + "event: run\ndata: {}\n\n", + api.view(&api.run("run").unwrap()).unwrap() + ) + }; + ([("content-type", "text/event-stream")], bytes) + } + }), + ) + .route("/api/v2/runs/{id}/log", get(log)) + .with_state(f.api.clone()); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let server = tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + let output = tokio::time::timeout( + Duration::from_secs(5), + crate::process::tokio_command(std::env::current_exe().unwrap()) + .args([ + "--exact", + "commands::up::api_v2::tests::reconnect_child", + "--nocapture", + ]) + .env("ORX_TEST_STREAM_RECONNECT", mode) + .env("ORX_UP_PORT", port.to_string()) + .env("ORX_UP_AUTH_TOKEN", "secret") + .output(), + ) + .await + .unwrap() + .unwrap(); + assert!( + output.status.success(), + "{}\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + if mode == "wait" || mode == "projectwait" { + assert!(String::from_utf8_lossy(&output.stdout).contains("run done")); + } + if mode == "wait" { + let progress = String::from_utf8_lossy(&output.stderr); + assert!(progress.contains("run running"), "{progress}"); + assert!(!progress.contains("run done"), "{progress}"); + } + if mode == "projectwait" { + assert!(String::from_utf8_lossy(&output.stderr) + .contains("Watching 2 run(s) in project (2 in flight)")); + } + assert_eq!(requests.load(Ordering::SeqCst), 2); + server.abort(); + } +} + +#[tokio::test] +async fn stale_client_reset_preserves_kept_ranges_from_the_current_generation() { + let f = Fixture::new().await; + f.insert("run", "exp", "project", "running"); + keep(&f.api, "run", 6, b"6789", true); + let mut stale = ident(); + stale.ino += 1; + let response = f + .client + .request(reqwest::Method::GET, "runs/run/log") + .query(&[ + ("start", "0"), + ("end", "5"), + ("ident", &String::from(stale)), + ]) + .send() + .await + .unwrap(); + assert!( + matches!(response.json::().await.unwrap(), LogPage::Reset { info: Some(info) } if info.ident == ident()) + ); + f.backend.offline.store(true, Ordering::SeqCst); + let page = f + .client + .json(reqwest::Method::GET, "runs/run/log?start=6&end=10", None) + .await + .unwrap(); + assert_eq!(page["data"], json!("Njc4OQ==")); + assert_eq!(f.backend.reads.load(Ordering::SeqCst), 1); +} + +/// A finished run over 1 GiB whose host directory was cleaned: a sequential read past the +/// kept head meets a reset without identity, and the kept head and tail still answer. +#[tokio::test] +async fn a_reset_past_the_kept_head_leaves_kept_ranges_alone() { + const MIB: u64 = 1 << 20; + let f = Fixture::new().await; + f.insert("run", "exp", "project", "done"); + let len = 1100 * MIB; + let logs = f.api.data_dir.join("run-logs"); + std::fs::create_dir_all(&logs).unwrap(); + let mut ranges = Vec::new(); + for (offset, size, name, eof) in [ + (0, 64 * MIB, "log", false), + (len - 256 * MIB, 256 * MIB, "tail.log", true), + ] { + let file = logs.join(format!("run.{name}")); + std::fs::File::create(&file).unwrap().set_len(size).unwrap(); + ranges.push(KeptRange { + offset, + len: size, + file, + ident: ident(), + eof, + }); + } + keep_ranges(&f.api.data_dir, "run", ranges).unwrap(); + let manifest = std::fs::read(logs.join("run.ranges.json")).unwrap(); + let page = |start: u64| { + let end = start + MIB; + format!("runs/run/log?start={start}&end={end}&ident=1-2") + }; + + let last_head = f + .client + .json(reqwest::Method::GET, &page(63 * MIB), None) + .await + .unwrap(); + assert_eq!(last_head["kind"], "data"); + f.backend + .scripted_pages + .lock() + .unwrap() + .push_back(LogPage::Reset { info: None }); + let past_head = f + .client + .json(reqwest::Method::GET, &page(64 * MIB), None) + .await + .unwrap(); + assert_eq!(past_head, json!({"kind":"reset","info":null})); + assert_eq!(f.backend.reads.load(Ordering::SeqCst), 1); + + assert_eq!( + std::fs::read(logs.join("run.ranges.json")).unwrap(), + manifest + ); + f.backend.offline.store(true, Ordering::SeqCst); + for start in [0, len - MIB] { + let kept = f + .client + .json(reqwest::Method::GET, &page(start), None) + .await + .unwrap(); + assert_eq!(kept["kind"], "data", "{start}"); + } + assert_eq!(f.backend.reads.load(Ordering::SeqCst), 1); +} + +/// After a reconnect the host's log has another identity: the reset neither drops nor joins +/// what is kept. +#[tokio::test] +async fn a_new_identity_after_reconnect_leaves_kept_ranges_alone() { + let f = Fixture::new().await; + f.insert("run", "exp", "project", "done"); + keep(&f.api, "run", 0, b"0123", false); + let manifest = std::fs::read(f.api.data_dir.join("run-logs/run.ranges.json")).unwrap(); + let replaced = FileIdent { dev: 1, ino: 3 }; + f.backend + .scripted_pages + .lock() + .unwrap() + .push_back(LogPage::Reset { + info: Some(orx_host_proto::LogInfo { + ident: replaced.clone(), + len: 10, + }), + }); + let reset = f + .client + .json( + reqwest::Method::GET, + "runs/run/log?start=4&end=10&ident=1-2", + None, + ) + .await + .unwrap(); + assert_eq!(reset["info"]["ident"], String::from(replaced)); + assert_eq!( + std::fs::read(f.api.data_dir.join("run-logs/run.ranges.json")).unwrap(), + manifest + ); + + f.backend.offline.store(true, Ordering::SeqCst); + let kept = f + .client + .json(reqwest::Method::GET, "runs/run/log?start=0&end=10", None) + .await; + let kept = kept.unwrap(); + assert_eq!(kept["data"], json!("MDEyMw==")); + assert_eq!(kept["eof"], false); + let kept = f + .client + .json(reqwest::Method::GET, "runs/run/log?start=0&end=4", None) + .await + .unwrap(); + assert_eq!(kept["data"], json!("MDEyMw==")); +} + +#[tokio::test] +async fn following_logs_retries_transport_503_with_backoff_and_preserves_the_offset() { + let f = Fixture::new().await; + f.insert("run", "exp", "project", "done"); + let attempts = Arc::new(Mutex::new(Vec::new())); + let seen = attempts.clone(); + let app = Router::new() + .route( + "/api/v2/events", + get(|| async { + ( + [("content-type", "text/event-stream")], + "event: run\ndata: {\"status\":\"done\"}\n\n", + ) + }), + ) + .route( + "/api/v2/runs/{id}/log", + get(move |Query(query): Query| { + let seen = seen.clone(); + async move { + let count = { + let mut seen = seen.lock().unwrap(); + seen.push((std::time::Instant::now(), query.start)); + seen.len() + }; + if count == 1 || count == 3 { + return ( + StatusCode::SERVICE_UNAVAILABLE, + "page not on this computer; host unreachable since 1", + ) + .into_response(); + } + let bytes = if count == 2 { + b"first".to_vec() + } else if count == 4 { + b"last".to_vec() + } else { + vec![] + }; + Json(LogPage::Data { + len: None, + ident: ident(), + start: query.start, + bytes, + eof: count != 2, + }) + .into_response() + } + }), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let mut descriptor = f.descriptor.clone(); + descriptor.port = listener.local_addr().unwrap().port(); + let server = tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + let mut output = Vec::new(); + tokio::time::timeout( + Duration::from_secs(5), + ApiClient::new(descriptor) + .unwrap() + .logs_to("run", true, &mut output), + ) + .await + .unwrap() + .unwrap(); + assert_eq!(output, b"firstlast"); + let attempts = attempts.lock().unwrap(); + assert_eq!( + attempts + .iter() + .map(|(_, offset)| *offset) + .collect::>(), + [0, 0, 5, 5, 9] + ); + assert!(attempts[1].0.duration_since(attempts[0].0) >= Duration::from_millis(200)); + assert!(attempts[3].0.duration_since(attempts[2].0) >= Duration::from_millis(200)); + server.abort(); +} + +#[tokio::test] +async fn dashboard_log_pages_preserve_kept_ranges_gaps_resets_and_contact_errors() { + use tower::ServiceExt; + let f = Fixture::new().await; + f.insert("run", "exp", "project", "running"); + let mut run = f.api.run("run").unwrap(); + run.backend_json = r#"{"kind":"engine","jobId":"/root/runs/run","handle":{"type":"Ssh","host":"lab","root":"/root"}}"#.into(); + f.api.store().upsert_run(&run).unwrap(); + keep(&f.api, "run", 6, b"6789", true); + let app = dashboard_routes(f.api.clone()); + for (query, expected, reads) in [ + ( + "start=7&end=10", + json!({"kind":"data","ident":String::from(ident()),"start":7,"data":"Nzg5","eof":true,"len":10,"kept":[[6,10]]}), + 0, + ), + ( + "start=2&end=5", + json!({"kind":"data","ident":String::from(ident()),"start":2,"data":"MjM0","eof":false,"len":10,"kept":[[6,10]]}), + 1, + ), + ( + "start=5&end=8", + json!({"kind":"data","ident":String::from(ident()),"start":5,"data":"NTY3","eof":false,"len":10,"kept":[[6,10]]}), + 2, + ), + ] { + let response = app + .clone() + .oneshot( + Request::builder() + .uri(format!("/api/runs/run/log?{query}")) + .body(axum::body::Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + let bytes = axum::body::to_bytes(response.into_body(), 1024 * 1024) + .await + .unwrap(); + assert_eq!(serde_json::from_slice::(&bytes).unwrap(), expected); + assert_eq!(f.backend.reads.load(Ordering::SeqCst), reads); + } + let stale = FileIdent { dev: 0, ino: 0 }; + let response = app + .clone() + .oneshot( + Request::builder() + .uri(format!( + "/api/runs/run/log?start=0&end=1&ident={}", + String::from(stale) + )) + .body(axum::body::Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + let bytes = axum::body::to_bytes(response.into_body(), 4096) + .await + .unwrap(); + assert_eq!( + serde_json::from_slice::(&bytes).unwrap(), + json!({"kind":"reset","info":{"ident":String::from(ident()),"len":10}}) + ); + f.backend.offline.store(true, Ordering::SeqCst); + for (contact, kind) in [ + ( + Contact::Unreachable { + since: 123, + cause: "offline".into(), + }, + "unreachable", + ), + ( + Contact::NeedsAuth { + since: 123, + cause: "key rejected".into(), + }, + "needs_auth", + ), + ] { + f.api + .store() + .set_run_contact("run", &Contact::Live) + .unwrap(); + *f.backend.outage.lock().unwrap() = Some(crate::engine::transport::HostState { + status: match contact { + Contact::NeedsAuth { .. } => crate::engine::transport::Status::NeedsAuth, + _ => crate::engine::transport::Status::Backoff, + }, + since_ms: 123, + ..Default::default() + }); + let response = app + .clone() + .oneshot( + Request::builder() + .uri("/api/runs/run/log?start=0&end=1") + .body(axum::body::Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE); + let bytes = axum::body::to_bytes(response.into_body(), 4096) + .await + .unwrap(); + assert_eq!( + serde_json::from_slice::(&bytes).unwrap(), + json!({"error":"Page not on this computer","host":"lab","since":123,"contact":kind}) + ); + } + // Kept bytes remain available during an authentication outage. + let response = app + .oneshot( + Request::builder() + .uri("/api/runs/run/log?start=6&end=10") + .body(axum::body::Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); +} + +#[tokio::test] +async fn dashboard_abandon_rejects_live_and_terminal_runs_and_keeps_the_kill() { + use tower::ServiceExt; + let f = Fixture::new().await; + f.insert("run", "exp", "project", "running"); + let app = dashboard_routes(f.api.clone()); + let request = || { + Request::builder() + .method("POST") + .uri("/api/runs/run/abandon") + .body(axum::body::Body::empty()) + .unwrap() + }; + assert_eq!( + app.clone().oneshot(request()).await.unwrap().status(), + StatusCode::CONFLICT + ); + f.api + .store() + .set_run_contact( + "run", + &Contact::Unreachable { + since: 123, + cause: "offline".into(), + }, + ) + .unwrap(); + let response = app.clone().oneshot(request()).await.unwrap(); + assert_eq!(response.status(), StatusCode::OK); + let bytes = axum::body::to_bytes(response.into_body(), 4096) + .await + .unwrap(); + let value: Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(value["status"], "lost"); + assert_eq!(value["lostReason"], "abandoned"); + assert_eq!(value["cancelling"], false); + assert_eq!(value["contact"]["type"], "unreconciled"); + assert!(f + .api + .store() + .engine_run_state("run") + .unwrap() + .unwrap() + .cancel_accepted_at + .is_some()); + assert!(f.api.engine.holds("run")); + assert_eq!( + app.oneshot(request()).await.unwrap().status(), + StatusCode::CONFLICT + ); +} + +#[tokio::test] +async fn dashboard_host_routes_report_states_and_retry_only_key_hosts() { + use crate::engine::transport::{HostClass, HostState, Status}; + use tower::ServiceExt; + let f = Fixture::new().await; + f.api + .store() + .insert_submitting_run(SubmittingRun { + id: "pending", + experiment_id: "exp", + project_id: "project", + metadata: &crate::jobs::BackendDescriptor::parse(r#"{"kind":"ssh_job"}"#).unwrap(), + command: "train", + created_at: 1, + commit_sha: None, + chat_session_id: None, + spec_digest: "digest", + launch: &LaunchSpec { + kind: "ssh_job".into(), + target: Some("lab".into()), + options: json!({}), + }, + }) + .unwrap(); + let app = dashboard_routes(f.api.clone()); + let state = HostState { + status: Status::Backoff, + since_ms: 100, + next_retry_ms: Some(200), + cause: Some("offline".into()), + ..HostState::default() + }; + f.api + .store() + .seed_engine_host("lab", "/engine", Some(HostClass::Key), &state) + .unwrap(); + let response = app + .clone() + .oneshot( + Request::builder() + .uri("/api/compute/hosts") + .body(axum::body::Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + let bytes = axum::body::to_bytes(response.into_body(), 4096) + .await + .unwrap(); + assert_eq!( + serde_json::from_slice::(&bytes).unwrap(), + json!([{"alias":"lab","status":"backoff","class":"key","sinceMs":100,"nextRetryMs":200,"cause":"offline","root":"/engine"}]) + ); + let request = || { + Request::builder() + .method("POST") + .uri("/api/compute/hosts/lab/retry") + .body(axum::body::Body::empty()) + .unwrap() + }; + assert_eq!( + app.clone().oneshot(request()).await.unwrap().status(), + StatusCode::OK + ); + for (class, state) in [ + ( + HostClass::Key, + HostState { + status: Status::NeedsAuth, + ..state.clone() + }, + ), + (HostClass::Interactive, state), + ] { + f.api + .store() + .seed_engine_host("lab", "/engine", Some(class), &state) + .unwrap(); + assert_eq!( + app.clone().oneshot(request()).await.unwrap().status(), + StatusCode::CONFLICT + ); + } + let response = app + .oneshot( + Request::builder() + .method("POST") + .uri("/api/compute/hosts/missing/retry") + .body(axum::body::Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::NOT_FOUND); +} + +#[tokio::test] +async fn dashboard_retry_returns_the_worst_root_state() { + use crate::engine::transport::{HostClass, HostState, Status}; + use tower::ServiceExt; + let f = Fixture::new().await; + let app = dashboard_routes(f.api.clone()); + for (lower, worse, expected) in [ + (Status::Idle, Status::Live, "live"), + (Status::Live, Status::Connecting, "connecting"), + (Status::Connecting, Status::Backoff, "backoff"), + ] { + for (root, status) in [("/a-first", lower), ("/z-worst", worse)] { + f.api + .store() + .seed_engine_host( + "lab", + root, + Some(HostClass::Key), + &HostState { + status, + ..HostState::default() + }, + ) + .unwrap(); + } + let response = app + .clone() + .oneshot( + Request::builder() + .method("POST") + .uri("/api/compute/hosts/lab/retry") + .body(axum::body::Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + let bytes = axum::body::to_bytes(response.into_body(), 4096) + .await + .unwrap(); + let host: Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(host["alias"], "lab"); + assert_eq!(host["root"], "/z-worst"); + assert_eq!(host["status"], expected); + } +} + +#[cfg(unix)] +#[test] +fn dashboard_connect_clears_the_engine_breaker_and_resumes_pending_runs() { + let directory = + std::env::temp_dir().join(format!("orx-dashboard-host-{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&directory).unwrap(); + let mut command = crate::process::command(std::env::current_exe().unwrap()); + command + .args([ + "--exact", + "commands::up::api_v2::tests::dashboard_host_lifecycle_child", + "--ignored", + "--nocapture", + ]) + .env("ORX_HOST_BIN_DIR", orx_test_support::host_binaries()) + .env("HOME", &directory) + .env("XDG_CONFIG_HOME", directory.join("config")) + .env("XDG_DATA_HOME", directory.join("data")) + .env("ORX_DATA_DIR", directory.join("data/orx")); + let output = command.output().unwrap(); + std::fs::remove_dir_all(directory).unwrap(); + assert!( + output.status.success(), + "{}\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); +} + +#[cfg(unix)] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[ignore = "isolated dashboard SSH lifecycle subprocess"] +async fn dashboard_host_lifecycle_child() { + use crate::engine::transport::Status; + use tokio_tungstenite::tungstenite::client::IntoClientRequest; + let server = orx_test_support::Sshd::start().unwrap(); + let ssh_dir = PathBuf::from(std::env::var_os("HOME").unwrap()).join(".ssh"); + std::fs::create_dir_all(&ssh_dir).unwrap(); + std::fs::copy(server.config_path(), ssh_dir.join("config")).unwrap(); + let f = Fixture::new().await; + f.insert("seed", "exp", "project", "done"); + let mut seed = f.api.run("seed").unwrap(); + seed.backend_json = r#"{"kind":"engine","jobId":"~/.orx/engine/runs/seed","handle":{"type":"Ssh","host":"orx-test","root":"~/.orx/engine"}}"#.into(); + let total = 2 * (1u64 << 30); + let middle = 128 * (1u64 << 20); + let large_dir = server.home().join("large-root/runs/large"); + std::fs::create_dir_all(&large_dir).unwrap(); + let mut file = std::fs::File::create(large_dir.join("log")).unwrap(); + file.set_len(total).unwrap(); + use std::io::{Seek, SeekFrom, Write}; + file.seek(SeekFrom::Start(middle)).unwrap(); + file.write_all(b"middle page from host").unwrap(); + f.insert("large", "exp", "project", "done"); + let mut large = f.api.run("large").unwrap(); + large.backend_json = r#"{"kind":"engine","jobId":"~/large-root/runs/large","handle":{"type":"Ssh","host":"orx-test","root":"~/large-root"}}"#.into(); + f.api.store().upsert_run(&large).unwrap(); + let clock = Arc::new(crate::engine::clock::SystemClock::new()); + let before_restart = crate::engine::runtime::Runtime::new( + f.api.engine.clone(), + clock, + f.api.data_dir.clone(), + Some(server.config_path()), + ); + let old_backend = before_restart.backend(&large).unwrap(); + let watched = WatchedRun { + id: "large".into(), + handle: handle_of(&large).unwrap(), + }; + let info = match old_backend + .read_log( + &watched, + LogFile::Log, + ByteRange { + start: u64::MAX - 1, + end: u64::MAX, + }, + None, + ) + .await + .unwrap() + { + LogPage::Reset { info: Some(info) } => info, + page => panic!("{page:?}"), + }; + let directory = f.api.data_dir.join("run-logs"); + std::fs::create_dir_all(&directory).unwrap(); + let mut kept = Vec::new(); + for (offset, len, eof, name) in [ + (0, 64 * (1u64 << 20), false, "large.head"), + ( + total - 256 * (1u64 << 20), + 256 * (1u64 << 20), + true, + "large.tail", + ), + ] { + let file = directory.join(name); + std::fs::File::create(&file).unwrap().set_len(len).unwrap(); + kept.push(KeptRange { + offset, + len, + eof, + ident: info.ident.clone(), + file, + }); + } + keep_ranges(&f.api.data_dir, "large", kept).unwrap(); + drop(old_backend); + drop(before_restart); + tokio::time::sleep(Duration::from_millis(200)).await; + let clock = Arc::new(crate::engine::clock::SystemClock::new()); + let runtime = crate::engine::runtime::Runtime::new( + f.api.engine.clone(), + clock, + f.api.data_dir.clone(), + Some(server.config_path()), + ); + let api = Arc::new( + Api::new( + "dashboard".into(), + "token".into(), + f.api.engine.clone(), + runtime.clone(), + Box::new(|_| Ok(Box::new(()))), + f.api.data_dir.clone(), + ) + .unwrap(), + ); + install(api.clone()).unwrap(); + let mut receiver = api.engine.bus.subscribe(); + async fn host_event(receiver: &mut broadcast::Receiver, wanted: Status) { + tokio::time::timeout(Duration::from_secs(45), async { + loop { + if let RunEvent::Host { alias, root, state } = receiver.recv().await.unwrap() { + assert_eq!(alias, "orx-test"); + if root == "~/.orx/engine" && state.status == wanted { + return; + } + } + } + }) + .await + .unwrap(); + } + let backend = runtime.backend(&seed).unwrap(); + host_event(&mut receiver, Status::Live).await; + let app = dashboard_routes(api.clone()) + .route("/api/settings/ssh/connect", get(super::super::ssh_connect)) + .route( + "/api/settings/ssh/preflight", + post(super::super::compute_settings::ssh_preflight), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let task = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + let client = crate::net::loopback_client().build().unwrap(); + let page = client + .get(format!( + "http://{address}/api/runs/large/log?start={middle}&end={}", + middle + 6 + )) + .send() + .await + .unwrap(); + assert_eq!(page.status(), StatusCode::OK); + let page: Value = page.json().await.unwrap(); + assert_eq!(page["data"], "bWlkZGxl"); + assert_eq!(page["len"], total); + assert_eq!( + page["kept"], + json!([[0, 64 * (1u64 << 20)], [total - 256 * (1u64 << 20), total]]) + ); + assert_eq!( + api.store() + .engine_run_state("large") + .unwrap() + .unwrap() + .contact, + Contact::Live + ); + let live_dir = server.home().join("large-root/runs/live"); + std::fs::create_dir_all(&live_dir).unwrap(); + let mut live_file = std::fs::File::create(live_dir.join("log")).unwrap(); + live_file.set_len(total).unwrap(); + live_file.write_all(b"live!!").unwrap(); + f.insert("live", "exp", "project", "running"); + let mut live = f.api.run("live").unwrap(); + live.backend_json = r#"{"kind":"engine","jobId":"~/large-root/runs/live","handle":{"type":"Ssh","host":"orx-test","root":"~/large-root"}}"#.into(); + f.api.store().upsert_run(&live).unwrap(); + let page = client + .get(format!("http://{address}/api/runs/live/log?start=0&end=6")) + .send() + .await + .unwrap(); + assert_eq!(page.status(), StatusCode::OK); + let page: Value = page.json().await.unwrap(); + assert_eq!(page["len"], total); + assert_eq!(page["kept"], json!([])); + assert_eq!(page["eof"], false); + api.store() + .set_engine_phase("live", "running", "done", Some(1), Some(0), None) + .unwrap(); + let attempts = server.auth_attempts().unwrap(); + let tested = client + .post(format!("http://{address}/api/settings/ssh/preflight")) + .json(&json!({"host":"orx-test"})) + .send() + .await + .unwrap(); + assert_eq!(tested.status(), StatusCode::OK); + let tested: Value = tested.json().await.unwrap(); + assert_eq!(tested["reachable"], true, "{tested}"); + assert_eq!(server.auth_attempts().unwrap(), attempts); + let processes = crate::process::command("ps") + .args(["-axo", "ppid=,comm=,args="]) + .output() + .unwrap(); + let processes = String::from_utf8(processes.stdout).unwrap(); + let sessions: Vec<_> = processes + .lines() + .filter(|line| { + line.trim_start() + .starts_with(&format!("{} ", std::process::id())) + && line.contains(server.config_path().to_str().unwrap()) + && line.contains("BatchMode=yes") + }) + .collect(); + assert_eq!(sessions.len(), 2, "{sessions:?}"); + for session in sessions { + assert!( + session.contains("ControlMaster=no") && session.contains("ControlPath=none"), + "{session}" + ); + assert!(!session.contains(" -M "), "{session}"); + } + let hosts: Value = client + .get(format!("http://{address}/api/compute/hosts")) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + assert_eq!(hosts.as_array().unwrap().len(), 2); + assert_eq!(runtime.host_states("orx-test").len(), 2); + api.store() + .seed_engine_host( + "unused", + "/old-root", + Some(crate::engine::transport::HostClass::Key), + &crate::engine::transport::HostState::default(), + ) + .unwrap(); + assert_eq!( + client + .post(format!("http://{address}/api/compute/hosts/unused/retry")) + .send() + .await + .unwrap() + .status(), + StatusCode::NOT_FOUND + ); + assert!(runtime.host_states("unused").is_empty()); + let retry = format!("http://{address}/api/compute/hosts/orx-test/retry"); + server.proxy().reset().unwrap(); + host_event(&mut receiver, Status::Backoff).await; + tokio::time::timeout(Duration::from_secs(5), async { + while runtime + .host_states("orx-test") + .iter() + .any(|(_, state)| state.status != Status::Backoff) + { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + let outage = client + .get(format!( + "http://{address}/api/runs/large/log?start={}&end={}", + middle + 6, + middle + 7 + )) + .send() + .await + .unwrap(); + assert_eq!(outage.status(), StatusCode::SERVICE_UNAVAILABLE); + assert_eq!( + outage.json::().await.unwrap()["contact"], + "unreachable" + ); + let response = client.post(&retry).send().await.unwrap(); + assert_eq!(response.status(), StatusCode::OK); + host_event(&mut receiver, Status::Live).await; + assert_eq!(runtime.host_states("orx-test").len(), 2); + assert!(runtime + .host_states("orx-test") + .iter() + .all(|(_, state)| state.status == Status::Live)); + let attempts = server.auth_attempts().unwrap(); + assert_eq!( + client.post(&retry).send().await.unwrap().status(), + StatusCode::OK + ); + assert_eq!(server.auth_attempts().unwrap(), attempts); + let keys = std::fs::read(server.directory().join("authorized_keys")).unwrap(); + std::fs::write(server.directory().join("authorized_keys"), "").unwrap(); + server.proxy().reset().unwrap(); + host_event(&mut receiver, Status::Backoff).await; + let response = client.post(&retry).send().await.unwrap(); + assert_eq!(response.status(), StatusCode::OK); + assert_eq!( + response.json::().await.unwrap()["status"], + "needs_auth" + ); + host_event(&mut receiver, Status::NeedsAuth).await; + let outage = client + .get(format!( + "http://{address}/api/runs/large/log?start={}&end={}", + middle + 8, + middle + 9 + )) + .send() + .await + .unwrap(); + assert_eq!(outage.status(), StatusCode::SERVICE_UNAVAILABLE); + assert_eq!( + outage.json::().await.unwrap()["contact"], + "needs_auth" + ); + let attempts = server.auth_attempts().unwrap(); + assert_eq!( + client.post(&retry).send().await.unwrap().status(), + StatusCode::CONFLICT + ); + assert_eq!(server.auth_attempts().unwrap(), attempts); + api.engine + .submit( + backend.as_ref(), + SubmittingRun { + id: "pending", + experiment_id: "exp", + project_id: "project", + metadata: &crate::jobs::BackendDescriptor::parse(r#"{"kind":"ssh_job"}"#).unwrap(), + command: "printf resumed", + created_at: 1, + commit_sha: None, + chat_session_id: None, + spec_digest: &orx_host::sha(b"printf resumed"), + launch: &LaunchSpec { + kind: "ssh_job".into(), + target: Some("orx-test".into()), + options: json!({"root":"~/.orx/engine"}), + }, + }, + ) + .await + .unwrap(); + assert_eq!(api.run("pending").unwrap().status, "submitting"); + runtime.start(); + std::fs::write(server.directory().join("authorized_keys"), keys).unwrap(); + let mut request = format!("ws://{address}/api/settings/ssh/connect?host=orx-test&backend=ssh") + .into_client_request() + .unwrap(); + request + .headers_mut() + .insert("origin", format!("http://{address}").parse().unwrap()); + let (mut socket, _) = tokio_tungstenite::connect_async(request).await.unwrap(); + tokio::time::timeout(Duration::from_secs(45), async { + while let Some(message) = socket.next().await { + if let tokio_tungstenite::tungstenite::Message::Text(text) = message.unwrap() { + let value: Value = serde_json::from_str(&text).unwrap(); + assert_ne!(value["type"], "error", "{value}"); + if value["type"] == "complete" { + return; + } + } + } + panic!("Connect ended without completion"); + }) + .await + .unwrap(); + let _ = socket.close(None).await; + host_event(&mut receiver, Status::Live).await; + let attempts = server.auth_attempts().unwrap(); + let mut request = format!("ws://{address}/api/settings/ssh/connect?host=orx-test&backend=ssh") + .into_client_request() + .unwrap(); + request + .headers_mut() + .insert("origin", format!("http://{address}").parse().unwrap()); + let (mut socket, _) = tokio_tungstenite::connect_async(request).await.unwrap(); + tokio::time::timeout(Duration::from_secs(10), async { + while let Some(message) = socket.next().await { + if let tokio_tungstenite::tungstenite::Message::Text(text) = message.unwrap() { + let value: Value = serde_json::from_str(&text).unwrap(); + assert_ne!(value["type"], "prompt"); + assert_ne!(value["type"], "error", "{value}"); + if value["type"] == "complete" { + return; + } + } + } + panic!("Live Connect ended without completion"); + }) + .await + .unwrap(); + let _ = socket.close(None).await; + assert_eq!(server.auth_attempts().unwrap(), attempts); + let host = api + .store() + .engine_host("orx-test", "~/.orx/engine") + .unwrap() + .unwrap(); + assert_eq!(host.status, Status::Live); + assert!(runtime + .host_states("orx-test") + .iter() + .all(|(_, state)| state.status == Status::Live)); + assert!(host.cause.is_none()); + assert!(host.next_retry_ms.is_none()); + tokio::time::timeout(Duration::from_secs(45), async { + while api.run("pending").unwrap().status != "done" { + tokio::time::sleep(Duration::from_millis(50)).await; + } + }) + .await + .unwrap_or_else(|_| panic!("pending run: {:?}", api.run("pending").unwrap())); + task.abort(); +} + +#[tokio::test] +async fn runner_one_local_logs_use_pages_for_live_and_finished_runs() { + use tower::ServiceExt; + let f = Fixture::new().await; + f.insert("legacy", "exp", "project", "running"); + let mut run = f.api.run("legacy").unwrap(); + run.backend_json = r#"{"kind":"local","jobId":"/legacy"}"#.into(); + f.api.store().upsert_run(&run).unwrap(); + std::fs::create_dir_all(f.api.data_dir.join("run-logs")).unwrap(); + std::fs::write(f.api.data_dir.join("run-logs/legacy.log"), b"legacy output").unwrap(); + let app = dashboard_routes(f.api.clone()); + for (status, eof) in [("running", true), ("done", true)] { + if status == "done" { + f.api + .store() + .set_engine_phase("legacy", "running", "done", Some(10), Some(0), None) + .unwrap(); + } + let response = app + .clone() + .oneshot( + Request::builder() + .uri("/api/runs/legacy/log?start=7&end=20") + .body(axum::body::Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + let bytes = axum::body::to_bytes(response.into_body(), 4096) + .await + .unwrap(); + let value: Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(value["kind"], "data"); + assert_eq!(value["data"], "b3V0cHV0"); + assert_eq!(value["start"], 7); + assert_eq!(value["len"], 13); + assert_eq!(value["eof"], eof); + } + assert_eq!(f.backend.reads.load(Ordering::SeqCst), 0); +} + +#[tokio::test] +async fn dashboard_log_identity_is_opaque_and_preserves_large_device_and_inode_numbers() { + use tower::ServiceExt; + let f = Fixture::new().await; + f.insert("wide", "exp", "project", "running"); + let wide = FileIdent { + dev: u64::MAX - 2, + ino: (1u64 << 60) + 7, + }; + let page = LogPage::Data { + len: Some(4), + ident: wide.clone(), + start: 0, + bytes: b"wide".to_vec(), + eof: true, + }; + f.backend.scripted_pages.lock().unwrap().extend([ + page.clone(), + page.clone(), + LogPage::Reset { + info: Some(orx_host_proto::LogInfo { + ident: wide.clone(), + len: 4, + }), + }, + page, + ]); + let app = dashboard_routes(f.api.clone()); + let mut token = None; + for reset in [false, false, true] { + let query = token + .as_ref() + .map_or(String::new(), |token| format!("&ident={token}")); + let response = app + .clone() + .oneshot( + Request::builder() + .uri(format!("/api/runs/wide/log?start=0&end=4{query}")) + .body(axum::body::Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + let bytes = axum::body::to_bytes(response.into_body(), 4096) + .await + .unwrap(); + let value: Value = serde_json::from_slice(&bytes).unwrap(); + let actual = if reset { + assert_eq!(value["kind"], "reset"); + &value["info"]["ident"] + } else { + assert_eq!(value["kind"], "data"); + &value["ident"] + }; + let actual = actual.as_str().expect("dashboard identity must be opaque"); + if let Some(token) = &token { + assert_eq!(actual, token); + } + token = Some(actual.to_owned()); + } + assert_eq!( + *f.backend.identities.lock().unwrap(), + [None, Some(wide.clone()), Some(wide.clone())] + ); + let response = app + .oneshot( + Request::builder() + .uri("/api/runs/wide/log?start=0&end=4&ident=incorrect") + .body(axum::body::Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + let cli = f + .client + .json(reqwest::Method::GET, "runs/wide/log?start=0&end=4", None) + .await + .unwrap(); + assert_eq!(cli["ident"], String::from(wide)); +} + +#[tokio::test] +async fn idle_closes_admission_then_rechecks_in_flight_requests_and_sse() { + let _serial = crate::commands::up::ACTIVE_TEST_LOCK.lock().await; + let f = Fixture::new().await; + let mut idle = Idle::default(); + let active = crate::commands::up::Active::new(); + assert!(!idle.check(&f.api, Duration::ZERO).unwrap()); + assert!(!idle.check(&f.api, Duration::from_secs(600)).unwrap()); + assert!(!crate::commands::up::stop_admitting_if_idle(&f.api).unwrap()); + assert!(!crate::commands::up::IDLE_EXIT.load(Ordering::SeqCst)); + drop(active); + assert!(!idle.check(&f.api, Duration::from_secs(601)).unwrap()); + assert!(idle.check(&f.api, Duration::from_secs(1201)).unwrap()); + f.api.clients.fetch_add(1, Ordering::SeqCst); + assert!(!crate::commands::up::stop_admitting_if_idle(&f.api).unwrap()); + f.api.clients.fetch_sub(1, Ordering::SeqCst); + assert!(crate::commands::up::stop_admitting_if_idle(&f.api).unwrap()); + crate::commands::up::IDLE_EXIT.store(false, Ordering::SeqCst); +} + +#[tokio::test] +async fn kept_prefix_is_a_short_page_even_when_the_host_is_unavailable() { + let f = Fixture::new().await; + f.insert("run", "exp", "project", "running"); + keep(&f.api, "run", 0, b"0123", false); + f.backend.offline.store(true, Ordering::SeqCst); + let page = f + .client + .json(reqwest::Method::GET, "runs/run/log?start=2&end=10", None) + .await + .unwrap(); + assert_eq!(page["kind"], "data"); + assert_eq!(page["start"], 2); + assert_eq!(page["data"], "MjM="); + assert_eq!(page["eof"], false); + assert_eq!(f.backend.reads.load(Ordering::SeqCst), 0); + assert!(f + .client + .json(reqwest::Method::GET, "runs/run/log?start=4&end=10", None) + .await + .is_err()); +} + +#[tokio::test] +async fn cli_wait_skips_unknown_sse_event_names_before_decoding_their_data() { + let f = Fixture::new().await; + f.insert("run", "exp", "project", "done"); + let terminal = f.api.view(&f.api.run("run").unwrap()).unwrap(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let mut descriptor = f.descriptor.clone(); + descriptor.port = listener.local_addr().unwrap().port(); + let app = axum::Router::new().route("/api/v2/events", axum::routing::get(move || { + let body = format!("event: future-progress\ndata: this is not JSON\n\nevent: run\ndata: {terminal}\n\n"); + async move { ([("content-type", "text/event-stream")], body) } + })); + let server = tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + ApiClient::new(descriptor) + .unwrap() + .wait(Filter { + run: Some("run".into()), + wait: true, + ..Default::default() + }) + .await + .unwrap(); + server.abort(); +} + +#[tokio::test] +async fn initial_connection_failure_and_idle_refusal_rediscover_without_replaying_accepted_posts() { + for idle in [false, true] { + let calls = Arc::new(AtomicUsize::new(0)); + let count = calls.clone(); + let app = Router::new() + .route( + "/api/v2/echo", + post( + move |headers: axum::http::HeaderMap, Json(body): Json| { + let count = count.clone(); + async move { + assert_eq!(headers["authorization"], "Bearer secret"); + count.fetch_add(1, Ordering::SeqCst); + Json(body) + } + }, + ), + ) + .route( + "/api/v2/events", + get(|| async { ([("content-type", "text/event-stream")], "") }), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let server = tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + let refusals = Arc::new(AtomicUsize::new(0)); + let count = refusals.clone(); + let app = Router::new().fallback(move || { + count.fetch_add(1, Ordering::SeqCst); + async { StatusCode::SERVICE_UNAVAILABLE } + }); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let stale_port = listener.local_addr().unwrap().port(); + let exiting = tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + let mut command = crate::process::tokio_command(std::env::current_exe().unwrap()); + command + .args([ + "--exact", + "commands::up::api_v2::tests::reconnect_child", + "--nocapture", + ]) + .env("ORX_TEST_STREAM_RECONNECT", "post") + .env("ORX_UP_PORT", port.to_string()) + .env("ORX_UP_AUTH_TOKEN", "secret") + .env_remove("ORX_TEST_STALE_PORT"); + if idle { + command.env("ORX_TEST_STALE_PORT", stale_port.to_string()); + } + let output = command.output().await.unwrap(); + server.abort(); + exiting.abort(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!(calls.load(Ordering::SeqCst), 1); + assert_eq!(refusals.load(Ordering::SeqCst), if idle { 2 } else { 0 }); + } +} + +#[tokio::test] +async fn cli_abandon_uses_the_existing_route_and_preserves_its_guards() { + let f = Fixture::new().await; + f.insert("run", "exp", "project", "running"); + assert!(f.client.abandon("run").await.is_err()); + f.api + .store() + .set_run_contact( + "run", + &Contact::Unreachable { + since: 3, + cause: "offline".into(), + }, + ) + .unwrap(); + f.client.abandon("run").await.unwrap(); + let run = f.api.run("run").unwrap(); + assert_eq!(run.status, "lost"); + assert!(f + .api + .store() + .engine_run_state("run") + .unwrap() + .unwrap() + .cancel_accepted_at + .is_some()); +} + +#[tokio::test] +async fn cli_cancel_selects_one_run_and_checks_its_experiment() { + use clap::Parser; + let cli = crate::Cli::try_parse_from(["orx", "exp", "cancel", "--run", "first"]).unwrap(); + assert!(matches!( + cli.command, + Some(crate::Command::Exp(crate::ExpArgs { + command: crate::ExpCommand::Cancel { + exp_id: None, + run: Some(_) + } + })) + )); + let f = Fixture::new().await; + f.insert("first", "exp", "project", "running"); + f.insert("second", "exp", "project", "running"); + f.insert("done", "exp", "project", "done"); + assert!(f.client.cancel(Some("other"), Some("first")).await.is_err()); + assert!(f.client.cancel(None, Some("done")).await.is_err()); + f.client.cancel(None, Some("first")).await.unwrap(); + let accepted = |id| { + f.api + .store() + .engine_run_state(id) + .unwrap() + .unwrap() + .cancel_accepted_at + .is_some() + }; + assert!(accepted("first")); + assert!(!accepted("second")); + assert!(!accepted("done")); + f.client.cancel(Some("exp"), None).await.unwrap(); + assert!(accepted("second")); +} + +#[tokio::test] +async fn dashboard_cleanup_uses_the_existing_handler_and_abandon_security_boundary() { + use tower::ServiceExt; + let _guard = crate::commands::up::ACTIVE_TEST_LOCK.lock().await; + let f = Fixture::new().await; + f.insert("run", "exp", "project", "cancelled"); + let auth = crate::commands::remote_host::RemoteAuth::new("callback"); + auth.register("session"); + let app = crate::commands::up::server_router( + dashboard_routes(f.api.clone()).merge(routes(f.api.clone())), + Some(auth), + ); + let request = |action: &str, token: Option<&str>, origin: &str| { + let mut builder = Request::builder() + .method("POST") + .uri(format!("/api/runs/run/{action}")) + .header("host", "127.0.0.1:1234") + .header("origin", origin); + if let Some(token) = token { + builder = builder.header("authorization", format!("Bearer {token}")); + } + builder.body(axum::body::Body::empty()).unwrap() + }; + for action in ["cleanup", "abandon"] { + for token in [None, Some("callback")] { + assert_eq!( + app.clone() + .oneshot(request(action, token, "http://127.0.0.1:1234")) + .await + .unwrap() + .status(), + StatusCode::UNAUTHORIZED + ); + } + assert_eq!( + app.clone() + .oneshot(request(action, Some("session"), "https://evil.example")) + .await + .unwrap() + .status(), + StatusCode::FORBIDDEN + ); + } + let response = app + .clone() + .oneshot(request("cleanup", Some("session"), "http://127.0.0.1:1234")) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + let body = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap(); + assert_eq!( + serde_json::from_slice::(&body).unwrap(), + json!({"accepted":true}) + ); + f.insert("active", "exp", "project", "running"); + let response = dashboard_routes(f.api.clone()) + .oneshot( + Request::builder() + .method("POST") + .uri("/api/runs/active/cleanup") + .body(axum::body::Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::CONFLICT); +} + +#[tokio::test] +async fn cancellation_proof_reaches_both_api_projections_without_contact_prose() { + let f = Fixture::new().await; + for (id, remaining, note) in [ + ("survivors", 2, None), + ("unconfirmed", 0, Some(vec![])), + ("unreadable", 0, Some(vec![789, 790])), + ("verified", 0, None), + ] { + f.insert(id, "exp", "project", "running"); + f.api.store().set_backend_json(id, &json!({ + "kind": "engine", "handle": {"type": "Ssh", "host": "gpu-box", "root": "/engine"} + }).to_string()).unwrap(); + f.api + .engine + .observe( + id, + Observation::CancelReceipt { + finished_at: Some(10), + code: None, + remaining, + note: note.clone(), + }, + ) + .unwrap(); + let store = f.api.store(); + let run = store.get_run(id).unwrap().unwrap(); + let dashboard = + serde_json::to_value(crate::commands::up::ApiRun::new(&store, &run).unwrap()).unwrap(); + drop(store); + let view = f.api.view(&run).unwrap(); + for projection in [&view, &dashboard] { + assert_eq!(projection["host"], "gpu-box"); + assert_eq!(projection["cancelUnconfirmed"], json!(note)); + if remaining > 0 { + assert_eq!(projection["contact"]["type"], "stopping"); + assert_eq!(projection["contact"]["count"], remaining); + assert!(projection["contact"].get("detail").is_none()); + } else { + assert!(projection["contact"].is_null() || projection["contact"]["type"] == "live"); + } + assert_eq!( + projection["resultMarkdown"].as_str(), + note.as_ref().map(|pids| if pids.is_empty() { + "In-container processes or processes outside the host scan couldn't be checked." + } else { + "The host couldn't inspect processes 789, 790 to confirm the stop." + }) + ); + } + f.api + .store() + .set_result_markdown(id, "Edited result") + .unwrap(); + let edited = f.api.run(id).unwrap(); + assert_eq!( + f.api.view(&edited).unwrap()["cancelUnconfirmed"], + json!(note) + ); + } +} diff --git a/src/commands/up/compute_settings.rs b/src/commands/up/compute_settings.rs index 0f8be6ab5..cce8166bb 100644 --- a/src/commands/up/compute_settings.rs +++ b/src/commands/up/compute_settings.rs @@ -904,8 +904,11 @@ pub(super) async fn ssh_master_status(Query(req): Query) -> Api if host.is_empty() { return Err(bad_request("host is required")); } - let running = - crate::jobs::ssh::service::healthy(&crate::jobs::ssh::SshTarget::alias(host)).await; + let running = super::api_v2::host_target(host, false).is_ok_and(|target| { + target.transport.is_some_and(|transport| { + transport.ssh.conn.state().borrow().status == crate::engine::transport::Status::Live + }) + }); Ok(Json(json!({ "running": running }))) } @@ -921,11 +924,10 @@ pub(super) async fn ssh_preflight(Json(req): Json) -> ApiResult } let test = run_ssh_host_preflight(host.clone()).await; let container = if let Some(reference) = req.container { - let result = crate::jobs::ssh::resolve_container( - &crate::jobs::ssh::SshTarget::alias(&host), - &reference, - ) - .await; + let result = match super::api_v2::host_target(&host, false) { + Ok(target) => crate::jobs::ssh::resolve_container(&target, &reference).await, + Err(error) => Err(error), + }; Some( json!({"reference": reference, "ready": result.is_ok(), "error": result.err().map(|error| error.to_string())}), ) @@ -959,7 +961,15 @@ pub(super) async fn run_ssh_host_preflight(host: String) -> SshHostTest { } pub(super) async fn probe_ssh_host_preflight(host: String) -> SshHostTest { - let p = crate::jobs::ssh::preflight(&crate::jobs::ssh::SshTarget::alias(&host)).await; + let p = match super::api_v2::host_target(&host, false) { + Ok(target) => crate::jobs::ssh::preflight(&target).await, + Err(error) => crate::jobs::ssh::SshPreflight { + reachable: false, + tools_found: false, + missing_tools: Vec::new(), + error: Some(error.to_string()), + }, + }; SshHostTest { host, reachable: p.reachable, @@ -1090,8 +1100,10 @@ pub(super) async fn slurm_preflight(Json(req): Json) -> ApiRe if host.is_empty() { return Err(bad_request("host is required")); } - let p = slurm::preflight(&host).await; - Ok(Json(slurm_preflight_value(&p))) + let target = super::api_v2::host_target(&host, true).map_err(bad_request)?; + Ok(Json(slurm_preflight_value( + &slurm::preflight(&target).await, + ))) } pub(super) fn slurm_preflight_value(p: &slurm::SlurmPreflight) -> Value { diff --git a/src/commands/up_remote.rs b/src/commands/up_remote.rs index f020d5433..bc07b809a 100644 --- a/src/commands/up_remote.rs +++ b/src/commands/up_remote.rs @@ -41,7 +41,7 @@ use crate::{browser, UpArgs}; const HEALTH_TIMEOUT: Duration = Duration::from_secs(60); const INSTALL_TIMEOUT: Duration = Duration::from_secs(10 * 60); const PREPARE_TIMEOUT: Duration = Duration::from_secs(5 * 60); -pub(crate) const DASHBOARD_PROTOCOL: u32 = 3; +pub(crate) const DASHBOARD_PROTOCOL: u32 = 4; #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] #[serde(rename_all = "camelCase")] @@ -3284,6 +3284,7 @@ mod tests { managed_generation: None, auth_agent: None, run_id: None, + transport: None, extra_opts: vec!["-p".into(), "2222".into()], }; let args = diff --git a/src/compute.rs b/src/compute.rs index 8bd86c2bb..353a7d35e 100644 --- a/src/compute.rs +++ b/src/compute.rs @@ -19,7 +19,7 @@ use sha2::{Digest as _, Sha256}; use crate::error::{anyhow, Result}; use crate::jobs::BackendDescriptor; use crate::local::model::{LocalExperiment, LocalProject}; -use crate::store::{RunStatus, Store, StoredRun}; +use crate::store::{LaunchSpec, RunStatus, Store, StoredRun}; #[derive(Debug, Clone)] pub struct SourceSnapshot { @@ -272,19 +272,6 @@ pub struct Preflight { #[derive(Debug, Clone)] pub struct StagedSource(pub SourceSnapshot); -#[derive(Debug, Clone, Default)] -pub struct LogCursor(pub u64, pub Option); - -#[derive(Debug, Clone, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct LogBatch { - pub generation: String, - pub offset: u64, - pub data_base64: String, - pub next_cursor: u64, - pub eof: bool, -} - #[async_trait] // async-trait marks its boxed futures `#[must_use]`; clippy 1.99 flags that generated code. #[allow(clippy::double_must_use)] @@ -296,57 +283,33 @@ pub trait ComputeBackend: Send + Sync { project: &LocalProject, experiment: &LocalExperiment, ) -> Result; - async fn submit( + /// The launch intent the run engine stores before any side effect. Secrets are added by + /// the engine at launch. + async fn prepare( &self, args: &crate::ExpRunArgs, - source: StagedSource, - run_id: String, - ) -> Result; - - async fn status(&self, handle: &StoredRun) -> Result { - Store::open()? - .get_run(&handle.id)? - .ok_or_else(|| anyhow!("Run {} not found.", handle.id)) - } - - async fn logs(&self, handle: &StoredRun, cursor: LogCursor) -> Result { - use base64::Engine as _; - let snapshot = crate::jobs::ssh::service::logs::read( - &handle.id, - cursor.0, - 256 * 1024, - cursor.1.as_deref(), - )?; - let next = snapshot.offset + snapshot.bytes.len() as u64; - Ok(LogBatch { - generation: snapshot.generation, - offset: snapshot.offset, - data_base64: base64::engine::general_purpose::STANDARD.encode(snapshot.bytes), - next_cursor: next, - eof: crate::local::is_terminal(&handle.status) && next >= snapshot.size, - }) - } + source: &SourceSnapshot, + run_id: &str, + command: &str, + ) -> Result; +} - async fn cancel(&self, handle: &StoredRun, reason: &str) -> Result<()> { - // Agent-session callers route through orx up before reaching this trusted path. - crate::commands::exp::request_local_run_cancel(&Store::open()?, &handle.id, reason) +/// A finished Hugging Face run no longer needs the archive staged for its job volume. +pub fn remove_hf_staging(run: &StoredRun) -> Result<()> { + let descriptor = BackendDescriptor::parse(&run.backend_json)?; + if !matches!(descriptor.kind.as_str(), "hf_job" | "engine") { + return Ok(()); } - - async fn cleanup(&self, handle: &StoredRun) -> Result<()> { - if self.capabilities().id == "hf" && crate::local::is_terminal(&handle.status) { - let descriptor = BackendDescriptor::parse(&handle.backend_json)?; - if let (Some(path), Some(digest)) = (descriptor.source_path, descriptor.source_digest) { - let staging = Path::new(&path) - .parent() - .unwrap_or_else(|| Path::new(".")) - .join(format!("{digest}.hf")); - if staging.is_dir() { - std::fs::remove_dir_all(staging)?; - } - } + if let (Some(path), Some(digest)) = (descriptor.source_path, descriptor.source_digest) { + let staging = Path::new(&path) + .parent() + .unwrap_or_else(|| Path::new(".")) + .join(format!("{digest}.hf")); + if staging.is_dir() { + std::fs::remove_dir_all(staging)?; } - Ok(()) } + Ok(()) } async fn stage_snapshot( @@ -376,7 +339,7 @@ macro_rules! backend_adapter { $name:ident, $id:literal, $label:literal, $remote:literal, $flavors:literal, $requires_flavor:literal, $transport:literal, $ray_package:literal, preflight |$preflight_args:ident| $preflight:expr, - submit |$submit_args:ident, $source:ident, $run_id:ident| $submit:expr + prepare |$prepare_args:ident, $source:ident, $run_id:ident, $command:ident| $prepare:expr ) => { pub struct $name; @@ -406,16 +369,18 @@ macro_rules! backend_adapter { stage_snapshot(project, experiment, $ray_package).await } - async fn submit( + async fn prepare( &self, args: &crate::ExpRunArgs, - staged: StagedSource, - id: String, - ) -> Result { - let $submit_args = args; - let $source = staged.0; - let $run_id = id; - $submit + source: &SourceSnapshot, + run_id: &str, + command: &str, + ) -> Result { + let $prepare_args = args; + let $source = source; + let $run_id = run_id; + let $command = command; + $prepare } } }; @@ -431,9 +396,10 @@ backend_adapter!( "local archive", false, preflight | _args | ready(), - submit | args, - source, - run_id | crate::local::localrun::submit_local_run_with_source(args, source, run_id).await + prepare | args, + _source, + _run_id, + _command | crate::local::localrun::launch_spec(args, "local_job") ); backend_adapter!( @@ -449,9 +415,10 @@ backend_adapter!( crate::jobs::tinker::resolve_api_key()?; ready() }, - submit | args, - source, - run_id | crate::local::localrun::submit_tinker_run_with_source(args, source, run_id).await + prepare | args, + _source, + _run_id, + _command | crate::local::localrun::launch_spec(args, "tinker_job") ); backend_adapter!( @@ -471,9 +438,10 @@ backend_adapter!( crate::jobs::huggingface::whoami(&token).await?; ready() }, - submit | args, + prepare | args, source, - run_id | crate::local::hf::submit_local_hf_with_source(args, source, run_id).await + run_id, + command | crate::local::hf::launch_spec(args, source, run_id, command).await ); backend_adapter!( @@ -492,9 +460,10 @@ backend_adapter!( crate::jobs::modal::preflight().await?; ready() }, - submit | args, + prepare | args, source, - run_id | crate::local::modal::submit_local_modal_with_source(args, source, run_id).await + run_id, + command | crate::local::modal::launch_spec(args, source, run_id, command) ); backend_adapter!( @@ -513,9 +482,10 @@ backend_adapter!( crate::jobs::vercel::preflight().await?; ready() }, - submit | args, + prepare | args, source, - run_id | crate::local::vercel::submit_local_vercel_with_source(args, source, run_id).await + run_id, + command | crate::local::vercel::launch_spec(args, source, run_id, command).await ); backend_adapter!( @@ -539,57 +509,27 @@ backend_adapter!( } ready() }, - submit | args, + prepare | args, source, - run_id | crate::local::k8s::submit_local_k8s_with_source(args, source, run_id).await + run_id, + command | crate::local::k8s::launch_spec(args, source, run_id, command).await ); -#[derive(Default)] -pub struct SshCompute { - launch: tokio::sync::OnceCell, -} - -#[async_trait] -impl ComputeBackend for SshCompute { - fn capabilities(&self) -> Capabilities { - Capabilities { - id: "ssh", - label: "SSH", - remote: true, - flavors: false, - requires_flavor: false, - source_transport: "SSH tar stream", - } - } - - async fn preflight(&self, args: &crate::ExpRunArgs) -> Result { - self.launch - .get_or_try_init(|| crate::jobs::ssh::resolve_launch(args)) - .await?; - ready() - } - - async fn stage_source( - &self, - project: &LocalProject, - experiment: &LocalExperiment, - ) -> Result { - stage_snapshot(project, experiment, false).await - } - - async fn submit( - &self, - args: &crate::ExpRunArgs, - source: StagedSource, - run_id: String, - ) -> Result { - let launch = self - .launch - .get() - .ok_or_else(|| anyhow!("SSH launch was not prepared."))?; - crate::local::ssh::submit_local_ssh_with_source(args, source.0, run_id, launch).await - } -} +backend_adapter!( + SshCompute, + "ssh", + "SSH", + true, + false, + false, + "SSH tar stream", + false, + preflight | _args | ready(), + prepare | args, + _source, + _run_id, + command | crate::local::ssh::launch_spec(args, command) +); backend_adapter!( SlurmCompute, @@ -600,24 +540,11 @@ backend_adapter!( false, "SSH tar stream", false, - preflight | args | { - let settings = crate::jobs::slurm::load_settings()?.unwrap_or_default(); - let host = args - .host - .as_deref() - .or(settings.host.as_deref()) - .ok_or_else(|| anyhow!("Slurm requires --host or a configured host."))?; - let check = crate::jobs::slurm::preflight(host).await; - if !check.reachable || !check.slurm_found || !check.tools_found { - return Ok(not_ready(check.error.as_deref().unwrap_or( - "The Slurm host needs bash, tar, sbatch, squeue, and scancel.", - ))); - } - ready() - }, - submit | args, - source, - run_id | crate::local::slurm::submit_local_slurm_with_source(args, source, run_id).await + preflight | _args | ready(), + prepare | args, + _source, + _run_id, + command | crate::local::slurm::launch_spec(args, command) ); backend_adapter!( @@ -634,9 +561,10 @@ backend_adapter!( crate::jobs::ray::preflight(&address).await?; ready() }, - submit | args, + prepare | args, source, - run_id | crate::local::ray::submit_local_ray_with_source(args, source, run_id).await + run_id, + command | crate::local::ray::launch_spec(args, source, run_id, command).await ); backend_adapter!( @@ -679,11 +607,10 @@ backend_adapter!( } ready() }, - submit | args, - source, - run_id - | crate::local::openresearch::submit_local_openresearch_with_source(args, source, run_id) - .await + prepare | args, + _source, + _run_id, + _command | crate::local::openresearch::launch_spec(args).await ); pub fn backend(id: &str) -> Result> { @@ -693,7 +620,7 @@ pub fn backend(id: &str) -> Result> { "hf" => Ok(Box::new(HuggingFaceCompute)), "modal" => Ok(Box::new(ModalCompute)), "k8s" => Ok(Box::new(KubernetesCompute)), - "ssh" => Ok(Box::new(SshCompute::default())), + "ssh" => Ok(Box::new(SshCompute)), "slurm" => Ok(Box::new(SlurmCompute)), "ray" => Ok(Box::new(RayCompute)), "vercel" => Ok(Box::new(VercelCompute)), @@ -750,6 +677,21 @@ pub fn validate_run_args(args: &crate::ExpRunArgs) -> Result<()> { "--cpus/--mem only apply with --backend slurm. Size other backends with --flavor." )); } + if let Some(partition) = &args.partition { + if args.backend.as_deref() != Some("slurm") { + return Err(anyhow!("--partition only applies with --backend slurm.")); + } + if !partition.split(',').all(|name| { + !name.is_empty() + && name + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || b"_-.".contains(&byte)) + }) { + return Err(anyhow!( + "--partition expects names separated by commas (letters, digits, _, - or .)." + )); + } + } if args.cpus == Some(0) { return Err(anyhow!("--cpus must be at least 1.")); } @@ -794,11 +736,229 @@ pub fn validate_run_args(args: &crate::ExpRunArgs) -> Result<()> { Ok(()) } -pub async fn submit(args: &crate::ExpRunArgs) -> Result { +/// A run ready for the engine: its source snapshot and the launch intent stored with it. +pub struct Submission { + pub run_id: String, + pub experiment: LocalExperiment, + pub source: SourceSnapshot, + pub command: String, + pub launch: LaunchSpec, +} + +/// Snapshots the source and prepares the launch intent, then hands it to `insert` while the +/// snapshot is protected from cleanup and no other run of the experiment can start. +pub async fn submit(args: &crate::ExpRunArgs, insert: F) -> Result +where + F: FnOnce(Submission) -> Fut, + Fut: std::future::Future>, +{ + validate_run_args(args)?; + let backend_id = args.backend.as_deref().unwrap_or("local"); + let backend = backend(backend_id)?; + let store = Store::open()?; + let preflight = backend.preflight(args).await?; + if !preflight.ready { + return Err(anyhow!( + "{}", + preflight + .detail + .filter(|detail| !detail.trim().is_empty()) + .unwrap_or_else(|| "Compute backend is not ready.".to_string()) + )); + } + let artifacts_lock = store.run_artifacts_lock()?; + let deadline = std::time::Instant::now() + crate::store::RUN_ARTIFACTS_WAIT; + let _artifacts_guard = loop { + match artifacts_lock.try_read() { + Ok(guard) => break guard, + Err(error) + if error.kind() == std::io::ErrorKind::WouldBlock + && std::time::Instant::now() < deadline => + { + tokio::time::sleep(crate::store::RUN_ARTIFACTS_POLL).await; + } + Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => { + return Err(anyhow!("Run artifacts are busy; retry the run submission.")) + } + Err(error) => return Err(error.into()), + } + }; + let experiment = store + .get_local_experiment(&args.exp_id)? + .ok_or_else(|| anyhow!("Local experiment {} not found.", args.exp_id))?; + let project = store + .get_local_project(&experiment.project_id)? + .ok_or_else(|| anyhow!("Local project {} not found.", experiment.project_id))?; + let command = crate::local::experiments::effective_run_command( + &experiment, + project.run_command.as_deref(), + ) + .ok_or_else(|| anyhow!("{}", crate::invocation::no_run_command(&project.id)))? + .to_string(); + let source = backend.stage_source(&project, &experiment).await?.0; + let run_id = uuid::Uuid::new_v4().to_string(); + let launch = backend.prepare(args, &source, &run_id, &command).await?; + + let chat_session = args.launching_chat_session(); + let chat_harness = match &chat_session { + Some(session) => store.get_chat_session(session)?.map(|chat| chat.harness), + None => None, + }; + let identity = args.invocation_identity()?; + let report = (!args.telemetry_suppressed && backend_id != "openresearch") + .then(|| { + crate::telemetry::pending_event_payload( + "experiment_finished", + run_attribution( + identity.as_ref(), + chat_harness, + args.agent_origin.as_deref(), + ), + ) + }) + .flatten(); + + let dir = crate::store::data_dir().join("submission-locks"); + std::fs::create_dir_all(&dir)?; + let file = std::fs::OpenOptions::new() + .create(true) + .read(true) + .write(true) + .truncate(false) + .open(dir.join(&experiment.id))?; + let mut lock = fd_lock::RwLock::new(file); + let _guard = lock.write()?; + if !args.force { + if let Some(run) = store + .list_runs_by_experiment(&experiment.id)? + .into_iter() + .find(|run| !crate::local::is_terminal(&run.status)) + { + return Err(anyhow!( + "Run {} is already in flight for this experiment ({}). Wait for it with \ + `orx exp wait {exp}`; cancel it with `orx exp cancel {exp}` only if it \ + should stop, or pass --force to launch anyway.", + run.id, + run.status, + exp = experiment.id + )); + } + } + store.reserve_run_telemetry(&run_id, identity.as_ref(), report.as_ref())?; + let branch = experiment.branch_name.clone(); + insert(Submission { + run_id: run_id.clone(), + experiment, + source, + command, + launch, + }) + .await?; + if project.github_enabled() { + if let Err(error) = crate::local::git::spawn_branch_publication( + Path::new(&project.repo_path), + &branch, + &project.github_owner, + &project.github_repo, + ) { + eprintln!( + "GitHub sync could not start; compute is already running from the source snapshot: {error}" + ); + } + } + Ok(run_id) +} + +/// The run report's invoker: the forwarded native identity, else an explicit exception. A context +/// inherited from another agent around the app never stands in for the launching chat's own. +fn run_attribution( + identity: Option<&crate::store::InvocationIdentity>, + chat_harness: Option, + agent_origin: Option<&str>, +) -> serde_json::Value { + let identity = identity.filter(|identity| { + chat_harness + .as_ref() + .is_none_or(|harness| *harness == identity.harness) + }); + let (harness, model, provider, attribution, reason) = match (identity, chat_harness) { + (Some(identity), _) => ( + Some(identity.harness.clone()), + Some(identity.model.clone()), + identity.provider.clone(), + "exact", + None, + ), + (None, Some(harness)) => ( + Some(harness), + None, + None, + "unresolved", + Some("invoker_not_linked"), + ), + // The origin can arrive over HTTP: only the known marker labels reach telemetry. + (None, None) => match agent_origin.filter(|origin| { + ["claude-code", "codex", "opencode", "cursor", "unknown"].contains(origin) + }) { + Some(origin) => ( + Some(origin.to_string()).filter(|origin| origin != "unknown"), + None, + None, + "unresolved", + Some("external_agent"), + ), + None => (None, None, None, "manual", None), + }, + }; + serde_json::json!({ + "harness": harness, + "model": model, + "provider": provider, + "attribution": attribution, + "attributionReason": reason, + "status": "failed", + }) +} + +pub(crate) fn supervised_ssh_needed(engine_enabled: bool, runs: &[StoredRun], host: &str) -> bool { + !engine_enabled + || runs.iter().any(|run| { + !crate::local::is_terminal(&run.status) + && BackendDescriptor::parse(&run.backend_json).is_ok_and(|descriptor| { + matches!(descriptor.kind.as_str(), "ssh_job" | "slurm_job") + && descriptor.namespace.as_deref() == Some(host) + }) + }) +} + +pub async fn submit_supervised(args: &crate::ExpRunArgs) -> Result { validate_run_args(args)?; let backend_id = args.backend.as_deref().unwrap_or("local"); let backend = backend(backend_id)?; let store = Store::open()?; + let ssh_launch = if backend_id == "ssh" { + Some(crate::jobs::ssh::resolve_launch(args).await?) + } else { + None + }; + if backend_id == "slurm" { + let settings = crate::jobs::slurm::load_settings()?.unwrap_or_default(); + let host = args + .host + .as_deref() + .or(settings.host.as_deref()) + .ok_or_else(|| anyhow!("Slurm requires --host or a configured host."))?; + let check = crate::jobs::slurm::preflight(&crate::jobs::ssh::SshTarget::alias(host)).await; + if !check.reachable || !check.slurm_found || !check.tools_found { + return Err(anyhow!( + "{}", + check + .error + .as_deref() + .unwrap_or("The Slurm host needs bash, tar, sbatch, squeue, and scancel.") + )); + } + } let preflight = backend.preflight(args).await?; if !preflight.ready { return Err(anyhow!( @@ -912,7 +1072,54 @@ pub async fn submit(args: &crate::ExpRunArgs) -> Result { report.as_ref(), )?; let pending_backend_json = descriptor.to_json(); - match backend.submit(args, source, run_id.clone()).await { + let submitted = match backend_id { + "local" => { + crate::local::localrun::submit_local_run_with_source(args, source.0, run_id.clone()) + .await + } + "tinker" => { + crate::local::localrun::submit_tinker_run_with_source(args, source.0, run_id.clone()) + .await + } + "hf" => crate::local::hf::submit_local_hf_with_source(args, source.0, run_id.clone()).await, + "modal" => { + crate::local::modal::submit_local_modal_with_source(args, source.0, run_id.clone()) + .await + } + "vercel" => { + crate::local::vercel::submit_local_vercel_with_source(args, source.0, run_id.clone()) + .await + } + "k8s" => { + crate::local::k8s::submit_local_k8s_with_source(args, source.0, run_id.clone()).await + } + "ssh" => { + crate::local::ssh::submit_local_ssh_with_source( + args, + source.0, + run_id.clone(), + ssh_launch.as_ref().unwrap(), + ) + .await + } + "slurm" => { + crate::local::slurm::submit_local_slurm_with_source(args, source.0, run_id.clone()) + .await + } + "ray" => { + crate::local::ray::submit_local_ray_with_source(args, source.0, run_id.clone()).await + } + "openresearch" => { + crate::local::openresearch::submit_local_openresearch_with_source( + args, + source.0, + run_id.clone(), + ) + .await + } + _ => unreachable!("backend validated above"), + }; + match submitted { Ok(run) => { if project.github_enabled() { if let Err(error) = crate::local::git::spawn_branch_publication( @@ -949,57 +1156,6 @@ pub async fn submit(args: &crate::ExpRunArgs) -> Result { } } -/// The run report's invoker: the forwarded native identity, else an explicit exception. A context -/// inherited from another agent around the app never stands in for the launching chat's own. -fn run_attribution( - identity: Option<&crate::store::InvocationIdentity>, - chat_harness: Option, - agent_origin: Option<&str>, -) -> serde_json::Value { - let identity = identity.filter(|identity| { - chat_harness - .as_ref() - .is_none_or(|harness| *harness == identity.harness) - }); - let (harness, model, provider, attribution, reason) = match (identity, chat_harness) { - (Some(identity), _) => ( - Some(identity.harness.clone()), - Some(identity.model.clone()), - identity.provider.clone(), - "exact", - None, - ), - (None, Some(harness)) => ( - Some(harness), - None, - None, - "unresolved", - Some("invoker_not_linked"), - ), - // The origin can arrive over HTTP: only the known marker labels reach telemetry. - (None, None) => match agent_origin.filter(|origin| { - ["claude-code", "codex", "opencode", "cursor", "unknown"].contains(origin) - }) { - Some(origin) => ( - Some(origin.to_string()).filter(|origin| origin != "unknown"), - None, - None, - "unresolved", - Some("external_agent"), - ), - None => (None, None, None, "manual", None), - }, - }; - serde_json::json!({ - "harness": harness, - "model": model, - "provider": provider, - "attribution": attribution, - "attributionReason": reason, - "status": "failed", - }) -} - fn reserve_run( store: &Store, pending: &StoredRun, @@ -1036,6 +1192,7 @@ fn reserve_run( let tx = store.begin()?; store.reserve_run_telemetry(&pending.id, identity, report)?; store.upsert_run(pending)?; + store.watch_legacy_run(&pending.id, None)?; tx.commit()?; Ok(()) } @@ -1104,6 +1261,50 @@ fn not_ready(detail: impl Into) -> Preflight { pub(crate) mod tests { use super::*; + #[test] + fn supervisor_transport_is_needed_only_for_opt_out_or_active_runs_on_the_alias() { + let mut run = StoredRun { + id: "run".into(), + experiment_id: "exp".into(), + project_id: "project".into(), + status: "running".into(), + backend_json: String::new(), + command: String::new(), + created_at: 1, + updated_at: 1, + ended_at: None, + exit_code: None, + commit_sha: None, + result_markdown: None, + cancel_requested: false, + cancel_reason: None, + chat_session_id: None, + }; + assert!(supervised_ssh_needed(false, &[], "lab")); + assert!(!supervised_ssh_needed(true, &[], "lab")); + for kind in ["ssh_job", "slurm_job", "engine", "hf_job"] { + run.backend_json = + serde_json::json!({"kind": kind, "namespace": "lab", "jobId": "job"}).to_string(); + let expected = matches!(kind, "ssh_job" | "slurm_job"); + assert_eq!( + supervised_ssh_needed(true, std::slice::from_ref(&run), "lab"), + expected + ); + assert!(!supervised_ssh_needed( + true, + std::slice::from_ref(&run), + "other" + )); + run.status = "done".into(); + assert!(!supervised_ssh_needed( + true, + std::slice::from_ref(&run), + "lab" + )); + run.status = "running".into(); + } + } + #[test] fn run_reports_name_the_native_invoker_or_an_explicit_exception() { let identity = |harness: &str| crate::store::InvocationIdentity { @@ -1188,12 +1389,14 @@ pub(crate) mod tests { timeout: None, cpus: None, mem: None, + partition: None, force: false, chat_session_id: None, invocation_context: None, agent_origin: None, forwarded: false, telemetry_suppressed: false, + caller_config_dir: None, } } diff --git a/src/config.rs b/src/config.rs index 8912ea003..38192a96d 100644 --- a/src/config.rs +++ b/src/config.rs @@ -275,6 +275,34 @@ pub fn set_settings_data_dir(data_dir: Option) -> Result<()> { Ok(()) } +pub fn run_engine_settings() -> Result<(bool, Option<&'static str>)> { + let channel = crate::updates::current_release_channel(); + let override_value = std::env::var_os("ORX_RUN_ENGINE"); + let saved = crate::telemetry::load_settings().and_then(|settings| settings.run_engine); + run_engine_settings_for(channel, override_value.as_deref(), saved) +} + +fn run_engine_settings_for( + channel: crate::updates::ReleaseChannel, + override_value: Option<&std::ffi::OsStr>, + saved: Option, +) -> Result<(bool, Option<&'static str>)> { + if channel == crate::updates::ReleaseChannel::Canary { + return Ok((true, Some("canary"))); + } + match override_value { + Some(value) if value == "1" => Ok((true, Some("environment"))), + Some(value) if value == "0" => Ok((false, Some("environment"))), + None => Ok((saved.unwrap_or(false), None)), + Some(_) => Err(crate::error::anyhow!("ORX_RUN_ENGINE must be 1 or 0.")), + } +} + +pub fn set_run_engine_enabled(enabled: bool) -> Result<()> { + crate::telemetry::mutate_settings(|settings| settings.run_engine = Some(enabled))?; + Ok(()) +} + /// The persisted default compute target for local-mode launches, if any: /// `(backend, flavor)`. Lives in the telemetry-owned `settings.json` for the /// same single-writer reason as the data dir above. @@ -392,6 +420,16 @@ pub fn run_env(run_id: &str) -> std::collections::HashMap { env } +/// What a launched job sees: [`run_env`] plus a configured Hugging Face token. Resolved at +/// launch, so secrets never enter a stored launch intent. +pub fn launch_env(run_id: &str) -> std::collections::HashMap { + let mut env = run_env(run_id); + if let Ok(token) = crate::jobs::huggingface::resolve_token() { + env.entry("HF_TOKEN".to_string()).or_insert(token); + } + env +} + const EXPERIMENT_ENV: &str = "ORX_EXPERIMENT"; const EXPERIMENT_TITLE_ENV: &str = "ORX_EXPERIMENT_TITLE"; const PARENT_EXPERIMENT_ENV: &str = "ORX_PARENT_EXPERIMENT"; @@ -555,3 +593,46 @@ pub fn set_ssh_default(host: Option) -> Result<()> { crate::telemetry::set_ssh_default(host)?; Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + use crate::updates::ReleaseChannel; + use std::ffi::OsStr; + + #[test] + fn canary_forces_the_engine_while_stable_and_dev_allow_opt_in() { + for saved in [None, Some(false), Some(true)] { + for value in [None, Some("0"), Some("1"), Some("invalid")] { + let value = value.map(OsStr::new); + assert_eq!( + run_engine_settings_for(ReleaseChannel::Canary, value, saved).unwrap(), + (true, Some("canary")) + ); + let stable = run_engine_settings_for(ReleaseChannel::Stable, value, saved); + match value { + None => assert_eq!(stable.unwrap(), (saved.unwrap_or(false), None)), + Some(value) if value == "0" => { + assert_eq!(stable.unwrap(), (false, Some("environment"))) + } + Some(value) if value == "1" => { + assert_eq!(stable.unwrap(), (true, Some("environment"))) + } + Some(_) => assert!(stable.is_err()), + } + } + } + } + + #[cfg(unix)] + #[test] + fn canary_ignores_even_a_non_unicode_environment_override() { + use std::os::unix::ffi::OsStrExt; + let value = Some(OsStr::from_bytes(&[0xff])); + assert_eq!( + run_engine_settings_for(ReleaseChannel::Canary, value, None).unwrap(), + (true, Some("canary")) + ); + assert!(run_engine_settings_for(ReleaseChannel::Stable, value, None).is_err()); + } +} diff --git a/src/engine/adapters/api.rs b/src/engine/adapters/api.rs new file mode 100644 index 000000000..4f7a4d238 --- /dev/null +++ b/src/engine/adapters/api.rs @@ -0,0 +1,1036 @@ +use crate::engine::clock::Clock; +use crate::engine::handle::ApiAccount; +use crate::engine::*; +use crate::error::{anyhow, Result}; +use async_trait::async_trait; +use futures::{stream, StreamExt}; +use std::collections::HashMap; +use std::fs::File; +use std::io::{Seek, SeekFrom, Write}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::Duration; + +type ProviderFactory = fn(&ApiAccount, Arc, PathBuf) -> Result>; + +pub struct Provider { + pub kind: &'static str, + pub build: ProviderFactory, +} + +pub fn provider(kind: &str) -> Result<&'static Provider> { + super::PROVIDERS + .iter() + .find(|provider| provider.kind == kind) + .ok_or_else(|| anyhow!("Unknown API provider {kind}")) +} + +pub fn handle(intent: &RunIntent, ids: Vec) -> Handle { + Handle::Api { + provider: intent.launch.kind.clone(), + account: ApiAccount { + target: intent.launch.target.clone(), + context: intent.launch.options["context"].as_str().map(str::to_owned), + }, + ids, + } +} + +#[cfg(test)] +pub(crate) fn test_handle( + kind: &str, + target: Option<&str>, + context: Option<&str>, + ids: Vec, +) -> Handle { + Handle::Api { + provider: kind.into(), + account: ApiAccount { + target: target.map(str::to_owned), + context: context.map(str::to_owned), + }, + ids, + } +} + +pub fn id<'a>( + run: &'a WatchedRun, + kind: &str, + target: Option<&str>, + context: Option<&str>, +) -> Result<&'a str> { + let id = match &run.handle { + Handle::Api { + provider, + account, + ids, + } if provider == kind + && (target.is_none() || account.target.as_deref() == target) + && (target.is_none() || account.context.as_deref() == context) => + { + ids.first().map(String::as_str) + } + Handle::Legacy { descriptor } + if descriptor.kind == kind + && (target.is_none() || descriptor.namespace.as_deref() == target) + && (target.is_none() || descriptor.context.as_deref() == context) => + { + descriptor.job_id.as_deref() + } + _ => return Err(anyhow!("Run does not belong to this {kind} account")), + }; + id.filter(|id| !id.is_empty()) + .ok_or_else(|| anyhow!("API handle has no job id")) +} + +#[async_trait] +pub trait Api: Send + Sync { + type Cursor: Clone + Default + Send + 'static; + async fn launch(&self, intent: &RunIntent, fence: &Fence<'_>) -> Result; + async fn recover(&self, intent: &RunIntent) -> Recovery; + async fn inspect(&self, run: &WatchedRun) -> Result; + async fn cancel(&self, run: &WatchedRun) -> Result<()>; + async fn finish(&self, _run: &WatchedRun) -> Result<()> { + Ok(()) + } + /// Hands `sink` the bytes past `cursor` as they arrive, and says whether the stream closed + /// before `window` ran out. An error means nothing reached `sink`. + async fn logs( + &self, + run: &WatchedRun, + cursor: &mut Self::Cursor, + window: Duration, + sink: &mut (dyn for<'b> FnMut(&'b [u8]) + Send), + ) -> Result; +} + +const PAGE_STREAM_WAIT: Duration = Duration::from_millis(20); +const DRAIN_WINDOW: Duration = Duration::from_secs(60); +/// How long one draining stream may stay open across callers' windows. +const DRAIN_STREAM_LIMIT: Duration = Duration::from_secs(24 * 60 * 60); + +/// Where a provider run's log is spooled as it arrives; pages and final collection read it. +pub fn spool_path(directory: &Path, run: &str) -> Result { + if run.is_empty() + || !run + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b"-_".contains(&b)) + { + return Err(anyhow!("Invalid run id {run}")); + } + Ok(directory.join(format!("{run}.spool.log"))) +} + +/// A provider log on disk, from the stream position `cursor` reached. It lasts one engine: +/// a new one starts empty and reads the provider from the start. +struct Spool { + path: PathBuf, + /// `None` once the run is forgotten, so an aborted stream writes nothing more. + file: Option, + len: u64, + cursor: C, + error: Option, + complete: bool, + /// Final collection needs a pass started after the terminal observation. + generation: u64, + drain: Option, + #[cfg(test)] + fail_after: Option, +} + +impl Spool { + /// A failed append leaves none of its bytes behind. + fn append(&mut self, bytes: &[u8]) -> std::io::Result<()> { + let Some(file) = &mut self.file else { + return Ok(()); + }; + file.seek(SeekFrom::Start(self.len))?; + #[cfg(test)] + if let Some(limit) = self.fail_after.take() { + file.write_all(&bytes[..limit])?; + file.set_len(self.len)?; + return Err(std::io::Error::other("injected write failure")); + } + if let Err(error) = file.write_all(bytes) { + file.set_len(self.len)?; + return Err(error); + } + self.len += bytes.len() as u64; + Ok(()) + } + + /// Drops what was appended past `len`. + fn truncate(&mut self, len: u64) -> std::io::Result<()> { + if let Some(file) = &self.file { + file.set_len(len)?; + } + self.len = len; + Ok(()) + } + + /// Stops the drain; it writes nothing more, as it may be mid-write when aborted. + fn forget(&mut self) { + self.file = None; + if let Some(drain) = self.drain.take() { + drain.abort(); + } + } +} + +type Shared = Arc>>; +type Drain = tokio::task::JoinHandle>; + +/// One run's spool, and the stream draining it through the end. The stream outlives a +/// caller's window, since reopening would replay the history and meet the same pauses again. +struct Log { + spool: Shared, + drain: tokio::sync::Mutex>, +} + +impl Drop for Log { + fn drop(&mut self) { + lock(&self.spool).forget(); + } +} + +fn lock(mutex: &std::sync::Mutex) -> std::sync::MutexGuard<'_, T> { + mutex + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) +} + +pub struct Adapter { + account: Arc, + clock: Arc, + spools: PathBuf, + next_observe: tokio::sync::Mutex, + logs: std::sync::Mutex>>>, + drain_window: Duration, +} + +impl Adapter { + pub fn new(account: A, clock: Arc, spools: PathBuf) -> Self { + Self { + account: Arc::new(account), + clock, + spools, + next_observe: tokio::sync::Mutex::new(Duration::ZERO), + logs: std::sync::Mutex::default(), + drain_window: DRAIN_WINDOW, + } + } + + fn log(&self, run: &WatchedRun) -> Result>> { + let mut logs = lock(&self.logs); + if let Some(log) = logs.get(&run.id) { + return Ok(log.clone()); + } + let path = spool_path(&self.spools, &run.id)?; + std::fs::create_dir_all(&self.spools)?; + let mut options = std::fs::OpenOptions::new(); + options.create_new(true).write(true); + #[cfg(unix)] + std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600); + // A fresh inode per engine, so pages kept from an earlier spool never match this one. + match std::fs::remove_file(&path) { + Err(error) if error.kind() != std::io::ErrorKind::NotFound => return Err(error.into()), + _ => {} + } + let file = options.open(&path)?; + let log = Arc::new(Log { + spool: Arc::new(std::sync::Mutex::new(Spool { + path, + len: 0, + file: Some(file), + cursor: A::Cursor::default(), + error: None, + complete: false, + generation: 0, + drain: None, + #[cfg(test)] + fail_after: None, + })), + drain: tokio::sync::Mutex::new(None), + }); + logs.insert(run.id.clone(), log.clone()); + Ok(log) + } +} + +#[async_trait] +impl Backend for Adapter { + async fn launch(&self, intent: &RunIntent, fence: &Fence<'_>) -> Result { + self.account.launch(intent, fence).await + } + + async fn recover(&self, intent: &RunIntent) -> Recovery { + self.account.recover(intent).await + } + + async fn observe(&self, runs: &[WatchedRun], budget: Duration) -> Vec<(String, Observation)> { + let mut next = self.next_observe.lock().await; + let now = self.clock.monotonic(); + if now < *next || runs.is_empty() { + return vec![]; + } + *next = now + Duration::from_secs(10); + drop(next); + let work: Vec<_> = runs + .iter() + .map(|run| async move { + let result = tokio::time::timeout(budget, self.account.inspect(run)).await; + let observation = match result { + Ok(Ok(observation)) => observation, + Ok(Err(error)) => observation_error(error), + Err(_) => Observation::Unreachable { + cause: "Provider observation timed out".into(), + }, + }; + let settled = observation.ends_run(); + let mut observations = vec![(run.id.clone(), observation)]; + if settled { + observations + .push((run.id.clone(), Observation::Lingering { pids: Vec::new() })); + } + let log = lock(&self.logs).get(&run.id).cloned(); + if let Some(log) = log { + { + let mut spool = lock(&log.spool); + spool.generation += 1; + spool.complete = false; + } + let _ = tokio::time::timeout(PAGE_STREAM_WAIT, self.drain_log(run)).await; + observations.push(( + run.id.clone(), + Observation::Log { + len: lock(&log.spool).len, + }, + )); + } + observations + }) + .collect(); + stream::iter(work) + .buffer_unordered(8) + .flat_map(stream::iter) + .collect() + .await + } + + async fn finish(&self, run: &WatchedRun) -> Result<()> { + self.account.finish(run).await + } + + /// A finished run's spool goes with it; a later read starts a new one. + async fn unwatch(&self, run: &WatchedRun) { + self.forget_logs(&|id| id == run.id); + if let Ok(path) = spool_path(&self.spools, &run.id) { + let _ = std::fs::remove_file(path); + } + } + + /// Their drains stop and write nothing more; spool files stay for whoever keeps or deletes + /// them. + fn forget_logs(&self, forgotten: &dyn Fn(&str) -> bool) { + lock(&self.logs).retain(|id, log| { + if !forgotten(id) { + return true; + } + lock(&log.spool).forget(); + false + }); + } + + async fn drain_log(&self, run: &WatchedRun) -> Result<()> { + let log = self.log(run)?; + let mut drain = log.drain.lock().await; + loop { + if lock(&log.spool).complete { + return Ok(()); + } + let task = match &mut *drain { + Some(task) => task, + None => { + let (account, run, spool) = + (self.account.clone(), run.clone(), log.spool.clone()); + let (mut cursor, start, generation) = { + let spool = lock(&spool); + (spool.cursor.clone(), spool.len, spool.generation) + }; + let task = tokio::spawn(async move { + let mut failed = None; + let mut sink = |chunk: &[u8]| { + if failed.is_none() { + failed = lock(&spool).append(chunk).err(); + } + }; + let closed = account + .logs(&run, &mut cursor, DRAIN_STREAM_LIMIT, &mut sink) + .await; + let mut spool = lock(&spool); + match (closed, failed) { + (Ok(closed), None) => { + spool.cursor = cursor; + spool.complete = closed && generation == spool.generation; + spool.error = None; + Ok(closed) + } + // The stream's position is unknown; what it appended goes. + (closed, failed) => { + spool.truncate(start)?; + Err(failed.map_or_else(|| closed.unwrap_err(), Into::into)) + } + } + }); + lock(&log.spool).drain = Some(task.abort_handle()); + drain.insert(task) + } + }; + let Ok(joined) = tokio::time::timeout(self.drain_window, task).await else { + return Err(anyhow!("The provider log is still streaming its history")); + }; + *drain = None; + let mut spool = lock(&log.spool); + spool.drain = None; + match joined { + Ok(Ok(true)) => {} + outcome => { + let error = match outcome { + Ok(Ok(_)) => anyhow!("The provider log stopped short of its end"), + Ok(Err(error)) => error, + Err(error) => anyhow!("Provider log drain stopped: {error}"), + }; + spool.error = Some(error.to_string()); + return Err(error); + } + } + } + } + + async fn cancel(&self, run: &WatchedRun) -> CancelOutcome { + match self.account.cancel(run).await { + Ok(()) => CancelOutcome::Pending, + Err(error) => CancelOutcome::Undelivered { + detail: error.to_string(), + }, + } + } + + async fn read_log( + &self, + run: &WatchedRun, + file: LogFile, + range: ByteRange, + ident: Option<&FileIdent>, + ) -> Result { + if file != LogFile::Log { + return Err(std::io::Error::new( + std::io::ErrorKind::Unsupported, + "Provider has no notify file", + ) + .into()); + } + let log = self.log(run)?; + let deadline = tokio::time::Instant::now() + Duration::from_secs(2); + loop { + let _ = tokio::time::timeout(PAGE_STREAM_WAIT, self.drain_log(run)).await; + let (len, error, path, complete) = { + let spool = lock(&log.spool); + ( + spool.len, + spool.error.clone(), + spool.path.clone(), + spool.complete, + ) + }; + if let Some(error) = error.filter(|_| len == 0) { + return Err(anyhow!("{error}")); + } + if len > 0 || complete { + return Ok(super::local::log::read(&path, ident, &range, None)?); + } + if tokio::time::Instant::now() >= deadline { + return Err(anyhow!( + "Provider log stream timed out before receiving any bytes" + )); + } + } + } +} + +/// Hands `sink` each line of a stream, counting them into `received`. +pub fn lines<'a>( + sink: &'a mut (dyn for<'b> FnMut(&'b [u8]) + Send), + received: &'a mut u64, +) -> impl FnMut(&str) + Send + 'a { + |line| { + sink(format!("{line}\n").as_bytes()); + *received += 1; + } +} + +/// An error means none of the stream's `received` lines arrived. +pub fn closed( + outcome: Result, tokio::time::error::Elapsed>, + received: u64, +) -> Result> { + match outcome { + Ok(Ok(value)) => Ok(Some(value)), + Ok(Err(error)) if received == 0 => Err(error), + _ if received == 0 => Err(anyhow!( + "Provider log stream timed out before receiving any bytes" + )), + _ => Ok(None), + } +} + +fn observation_error(error: crate::error::Error) -> Observation { + let cause = error.to_string(); + let detail = cause.to_ascii_lowercase(); + let http_auth = error + .downcast_ref::() + .and_then(reqwest::Error::status) + .is_some_and(|status| matches!(status.as_u16(), 401 | 403)); + let sdk_auth = [ + "http 401:", + "http 403:", + "not authorized", + "modal.exception.autherror:", + "status.unauthenticated", + "status.permission_denied", + "error from server (unauthorized)", + "error from server (forbidden)", + "you must be logged in to the server", + ] + .iter() + .any(|rejection| detail.contains(rejection)); + + if http_auth || sdk_auth { + Observation::NeedsAuth { cause } + } else { + Observation::Unreachable { cause } + } +} + +pub fn stage( + stage: &str, + message: Option, + exit_code: Option, + started_at: Option, + finished_at: Option, +) -> Observation { + match stage { + "COMPLETED" | "ERROR" | "FAILED" if exit_code.is_some() => Observation::Exited { + finished_at, + code: exit_code, + signal: None, + }, + "COMPLETED" => Observation::Exited { + finished_at, + code: Some(0), + signal: None, + }, + "ERROR" | "FAILED" => Observation::Failed { + finished_at, + reason: message.unwrap_or_else(|| stage.into()), + }, + "CANCELED" | "CANCELLED" => Observation::Cancelled { + finished_at, + code: exit_code, + signal: None, + }, + "DELETED" | "GONE" => Observation::Unreconciled { + detail: "Provider no longer knows the job".into(), + }, + "RUNNING" => Observation::Running { started_at }, + _ => Observation::Queued { + detail: message.unwrap_or_else(|| stage.into()), + }, + } +} + +pub fn rejected(error: impl std::fmt::Display) -> LaunchError { + LaunchError::Rejected { + reason: error.to_string(), + } +} + +pub fn interrupted(error: impl std::fmt::Display) -> LaunchError { + LaunchError::Interrupted { + detail: error.to_string(), + } +} + +pub fn unknown(error: impl std::fmt::Display) -> Recovery { + Recovery::Unknown { + detail: error.to_string(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::engine::clock::TestClock; + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + + #[test] + fn api_identity_rejects_foreign_accounts_and_keeps_legacy_ids() { + let mut run = WatchedRun { + id: "run".into(), + handle: test_handle("hf_job", Some("lab"), None, vec!["job".into()]), + }; + assert_eq!(id(&run, "hf_job", Some("lab"), None).unwrap(), "job"); + assert!(id(&run, "ray_job", Some("lab"), None).is_err()); + assert!(id(&run, "hf_job", Some("other"), None).is_err()); + assert!(id(&run, "hf_job", Some("lab"), Some("other")).is_err()); + for (kind, namespace, target) in [ + ("hf_job", "lab", Some("lab")), + ("modal_job", "app", None), + ("ray_job", "http://ray", Some("http://ray")), + ("k8s_job", "lab", Some("lab")), + ] { + run.handle = Handle::Legacy { + descriptor: Box::new( + crate::jobs::BackendDescriptor::parse( + &serde_json::json!({"kind":kind, "namespace":namespace, "jobId":"job"}) + .to_string(), + ) + .unwrap(), + ), + }; + assert_eq!(id(&run, kind, target, None).unwrap(), "job"); + } + run.handle = test_handle("hf_job", Some("lab"), None, vec![]); + assert!(id(&run, "hf_job", Some("lab"), None).is_err()); + } + + #[derive(Default)] + struct Fake { + text: std::sync::Mutex>, + downloads: AtomicUsize, + inspecting: AtomicUsize, + peak: AtomicUsize, + block_logs: AtomicBool, + terminal: AtomicBool, + log_started: tokio::sync::Notify, + /// Draining passes pause after what they have sent until released, like a stream + /// paused mid-history. + pause_drains: AtomicBool, + drain_paused: tokio::sync::Notify, + drain_resumed: tokio::sync::Notify, + open_streams: Arc, + peak_streams: AtomicUsize, + /// History before this was rotated away: a stream from the start begins here. + rotated: AtomicUsize, + } + + struct Open(Arc); + impl Drop for Open { + fn drop(&mut self) { + self.0.fetch_sub(1, Ordering::SeqCst); + } + } + + #[async_trait] + impl Api for Arc { + type Cursor = usize; + async fn launch(&self, _: &RunIntent, _: &Fence<'_>) -> Result { + unreachable!() + } + async fn recover(&self, _: &RunIntent) -> Recovery { + unreachable!() + } + async fn inspect(&self, _: &WatchedRun) -> Result { + let active = self.inspecting.fetch_add(1, Ordering::SeqCst) + 1; + self.peak.fetch_max(active, Ordering::SeqCst); + tokio::time::sleep(Duration::from_millis(5)).await; + self.inspecting.fetch_sub(1, Ordering::SeqCst); + Ok(if self.terminal.load(Ordering::SeqCst) { + Observation::Exited { + code: Some(0), + signal: None, + finished_at: None, + } + } else { + Observation::Running { started_at: None } + }) + } + async fn cancel(&self, _: &WatchedRun) -> Result<()> { + Ok(()) + } + async fn logs( + &self, + _: &WatchedRun, + cursor: &mut usize, + _: Duration, + sink: &mut (dyn for<'b> FnMut(&'b [u8]) + Send), + ) -> Result { + self.downloads.fetch_add(1, Ordering::SeqCst); + *cursor = (*cursor).max(self.rotated.load(Ordering::SeqCst)); + let open = self.open_streams.fetch_add(1, Ordering::SeqCst) + 1; + self.peak_streams.fetch_max(open, Ordering::SeqCst); + let _open = Open(self.open_streams.clone()); + if self.block_logs.load(Ordering::SeqCst) { + self.log_started.notify_one(); + self.drain_resumed.notified().await; + } + let mut send = |sink: &mut (dyn for<'b> FnMut(&'b [u8]) + Send)| { + let text = self.text.lock().unwrap().clone(); + sink(&text[*cursor..]); + *cursor = text.len(); + }; + send(sink); + if self.pause_drains.load(Ordering::SeqCst) { + self.drain_paused.notify_one(); + self.drain_resumed.notified().await; + send(sink); + } + Ok(true) + } + } + + fn adapter(account: &Arc, clock: Arc) -> (Adapter>, PathBuf) { + let spools = std::env::temp_dir().join(format!("orx-spools-{}", uuid::Uuid::new_v4())); + (Adapter::new(account.clone(), clock, spools.clone()), spools) + } + + fn provider_run() -> WatchedRun { + WatchedRun { + id: "run".into(), + handle: crate::engine::adapters::api::test_handle( + "ray_job", + Some("fake"), + None, + vec!["provider-id".into()], + ), + } + } + + const WHOLE: ByteRange = ByteRange { + start: 0, + end: orx_host_proto::MAX_PAGE_LEN, + }; + + async fn page(backend: &Adapter>) -> Vec { + let page = tokio::time::timeout( + Duration::from_millis(500), + backend.read_log(&provider_run(), LogFile::Log, WHOLE, None), + ) + .await + .expect("a page waited on the stream") + .unwrap(); + let LogPage::Data { bytes, .. } = page else { + panic!("no page: {page:?}") + }; + bytes + } + + #[tokio::test] + async fn live_eof_refreshes_on_observation_and_keeps_its_identity() { + let clock = Arc::new(TestClock::new()); + let account = Arc::new(Fake::default()); + *account.text.lock().unwrap() = b"first\n".to_vec(); + let (backend, spools) = adapter(&account, clock.clone()); + let run = provider_run(); + let LogPage::Data { ident, bytes, .. } = backend + .read_log(&run, LogFile::Log, ByteRange { start: 0, end: 6 }, None) + .await + .unwrap() + else { + panic!() + }; + assert_eq!(bytes, b"first\n"); + for _ in 0..50 { + backend + .read_log( + &run, + LogFile::Log, + ByteRange { start: 0, end: 6 }, + Some(&ident), + ) + .await + .unwrap(); + } + assert_eq!(account.downloads.load(Ordering::SeqCst), 1); + backend + .observe(std::slice::from_ref(&run), Duration::from_secs(1)) + .await; + account.text.lock().unwrap().extend_from_slice(b"second\n"); + clock.advance(Duration::from_secs(10)); + backend + .observe(std::slice::from_ref(&run), Duration::from_secs(1)) + .await; + let LogPage::Data { + ident: grown, + bytes, + .. + } = backend + .read_log( + &run, + LogFile::Log, + ByteRange { start: 6, end: 13 }, + Some(&ident), + ) + .await + .unwrap() + else { + panic!("growing log reset") + }; + assert_eq!(grown, ident); + assert_eq!(bytes, b"second\n"); + assert_eq!(account.downloads.load(Ordering::SeqCst), 3); + backend.unwatch(&run).await; + assert!(lock(&backend.logs).is_empty()); + assert!(!spool_path(&spools, "run").unwrap().exists()); + std::fs::remove_dir_all(spools).unwrap(); + } + + #[tokio::test] + async fn live_provider_uses_one_stream_across_observation_ticks() { + let account = Arc::new(Fake::default()); + *account.text.lock().unwrap() = b"first\n".to_vec(); + account.pause_drains.store(true, Ordering::SeqCst); + let clock = Arc::new(TestClock::new()); + let (backend, spools) = adapter(&account, clock.clone()); + assert_eq!(page(&backend).await, b"first\n"); + for _ in 0..3 { + clock.advance(Duration::from_secs(10)); + backend + .observe(&[provider_run()], Duration::from_secs(1)) + .await; + assert_eq!(page(&backend).await, b"first\n"); + } + assert_eq!(account.downloads.load(Ordering::SeqCst), 1); + account.text.lock().unwrap().extend_from_slice(b"last\n"); + account.pause_drains.store(false, Ordering::SeqCst); + account.drain_resumed.notify_one(); + backend.drain_log(&provider_run()).await.unwrap(); + assert_eq!(page(&backend).await, b"first\nlast\n"); + assert_eq!(account.downloads.load(Ordering::SeqCst), 2); + assert_eq!(account.peak_streams.load(Ordering::SeqCst), 1); + backend.unwatch(&provider_run()).await; + std::fs::remove_dir_all(spools).unwrap(); + } + + #[tokio::test] + async fn terminal_observation_requires_a_pass_after_the_active_stream_finishes() { + let account = Arc::new(Fake::default()); + *account.text.lock().unwrap() = b"first\n".to_vec(); + account.pause_drains.store(true, Ordering::SeqCst); + let (backend, spools) = adapter(&account, Arc::new(TestClock::new())); + assert_eq!(page(&backend).await, b"first\n"); + account.terminal.store(true, Ordering::SeqCst); + let observations = backend + .observe(&[provider_run()], Duration::from_secs(1)) + .await; + assert!(observations + .iter() + .any(|(_, observation)| observation.ends_run())); + assert_eq!(account.downloads.load(Ordering::SeqCst), 1); + account.text.lock().unwrap().extend_from_slice(b"last\n"); + account.pause_drains.store(false, Ordering::SeqCst); + account.drain_resumed.notify_one(); + backend.drain_log(&provider_run()).await.unwrap(); + assert_eq!(page(&backend).await, b"first\nlast\n"); + assert_eq!(account.downloads.load(Ordering::SeqCst), 2); + assert_eq!(account.peak_streams.load(Ordering::SeqCst), 1); + backend.unwatch(&provider_run()).await; + std::fs::remove_dir_all(spools).unwrap(); + } + + /// A history paused longer than a caller's window is read on by the same stream on the + /// next call; reopening would meet the same pause forever. + #[tokio::test] + async fn a_drain_paused_past_its_window_keeps_one_stream_open() { + let account = Arc::new(Fake::default()); + *account.text.lock().unwrap() = b"first\n".to_vec(); + account.pause_drains.store(true, Ordering::SeqCst); + let (mut backend, spools) = adapter(&account, Arc::new(TestClock::new())); + backend.drain_window = Duration::from_millis(20); + let run = provider_run(); + for _ in 0..3 { + assert!(backend.drain_log(&run).await.is_err()); + } + assert_eq!(account.downloads.load(Ordering::SeqCst), 1); + account.text.lock().unwrap().extend_from_slice(b"last\n"); + account.drain_resumed.notify_one(); + backend.drain_log(&run).await.unwrap(); + assert_eq!(page(&backend).await, b"first\nlast\n"); + assert_eq!(account.downloads.load(Ordering::SeqCst), 1); + std::fs::remove_dir_all(spools).unwrap(); + } + + /// What an open drain has received is on disk: a viewer reads it at once. A restarted engine + /// starts over from the provider's history, so what rotated away meanwhile is not kept. + #[tokio::test] + async fn an_open_drain_spools_what_it_received_for_viewers_and_restarts() { + let account = Arc::new(Fake::default()); + *account.text.lock().unwrap() = b"first\n".to_vec(); + account.pause_drains.store(true, Ordering::SeqCst); + let (backend, spools) = adapter(&account, Arc::new(TestClock::new())); + let backend = Arc::new(backend); + let draining = { + let backend = backend.clone(); + tokio::spawn(async move { backend.drain_log(&provider_run()).await }) + }; + account.drain_paused.notified().await; + assert_eq!(page(&backend).await, b"first\n"); + + // The engine stops mid-drain, and the provider rotates its history. + draining.abort(); + let _ = draining.await; + drop(backend); + account.pause_drains.store(false, Ordering::SeqCst); + account.text.lock().unwrap().extend_from_slice(b"last\n"); + account.rotated.store(6, Ordering::SeqCst); + account.drain_resumed.notify_waiters(); + tokio::time::timeout(Duration::from_secs(1), async { + while account.open_streams.load(Ordering::SeqCst) != 0 { + tokio::task::yield_now().await; + } + }) + .await + .expect("the drain outlived its engine"); + let spool = spool_path(&spools, "run").unwrap(); + assert_eq!(std::fs::read(&spool).unwrap(), b"first\n"); + let restarted = Adapter::new(account.clone(), Arc::new(TestClock::new()), spools.clone()); + restarted.drain_log(&provider_run()).await.unwrap(); + assert_eq!(std::fs::read(&spool).unwrap(), b"last\n"); + assert_eq!(page(&restarted).await, b"last\n"); + std::fs::remove_dir_all(spools).unwrap(); + } + + /// An append that fails part way leaves none of its bytes, so the next follows the last + /// good one directly. + #[tokio::test] + async fn a_failed_append_leaves_nothing_behind() { + let account = Arc::new(Fake::default()); + let (backend, spools) = adapter(&account, Arc::new(TestClock::new())); + let log = backend.log(&provider_run()).unwrap(); + let mut spool = lock(&log.spool); + spool.append(b"head").unwrap(); + spool.fail_after = Some(2); + assert_eq!( + spool.append(b"tail").unwrap_err().to_string(), + "injected write failure" + ); + spool.append(b"-123").unwrap(); + let path = spool.path.clone(); + drop(spool); + assert_eq!(std::fs::read(path).unwrap(), b"head-123"); + std::fs::remove_dir_all(spools).unwrap(); + } + + /// Forgetting a run, as collection and deletion do, stops its open drain; nothing more + /// is written for it. + #[tokio::test] + async fn forgetting_a_run_stops_its_drain() { + let account = Arc::new(Fake::default()); + *account.text.lock().unwrap() = b"first\n".to_vec(); + account.pause_drains.store(true, Ordering::SeqCst); + let (mut backend, spools) = adapter(&account, Arc::new(TestClock::new())); + backend.drain_window = Duration::from_millis(20); + let run = provider_run(); + assert!(backend.drain_log(&run).await.is_err()); + assert_eq!(account.open_streams.load(Ordering::SeqCst), 1); + backend.forget_logs(&|id| id == "run"); + tokio::time::timeout(Duration::from_secs(1), async { + while account.open_streams.load(Ordering::SeqCst) != 0 { + tokio::task::yield_now().await; + } + }) + .await + .expect("the drain outlived its run"); + assert!(lock(&backend.logs).is_empty()); + account.text.lock().unwrap().extend_from_slice(b"late\n"); + account.drain_resumed.notify_one(); + tokio::task::yield_now().await; + assert_eq!( + std::fs::read(spool_path(&spools, "run").unwrap()).unwrap(), + b"first\n" + ); + std::fs::remove_dir_all(spools).unwrap(); + } + + #[tokio::test] + async fn account_observations_never_exceed_eight_in_flight() { + let account = Arc::new(Fake::default()); + let (backend, spools) = adapter(&account, Arc::new(TestClock::new())); + let runs: Vec<_> = (0..50) + .map(|id| WatchedRun { + id: id.to_string(), + handle: crate::engine::adapters::api::test_handle( + "modal_job", + None, + None, + vec![id.to_string()], + ), + }) + .collect(); + assert_eq!( + backend.observe(&runs, Duration::from_secs(1)).await.len(), + 50 + ); + assert_eq!(account.peak.load(Ordering::SeqCst), 8); + let _ = std::fs::remove_dir_all(spools); + } + #[tokio::test] + async fn stalled_stream_does_not_block_observations_or_cached_pages() { + let account = Arc::new(Fake::default()); + *account.text.lock().unwrap() = b"first\n".to_vec(); + let clock = Arc::new(TestClock::new()); + let (backend, spools) = adapter(&account, clock.clone()); + let run = provider_run(); + backend + .read_log(&run, LogFile::Log, ByteRange { start: 0, end: 6 }, None) + .await + .unwrap(); + account.block_logs.store(true, Ordering::SeqCst); + account.text.lock().unwrap().extend_from_slice(b"second\n"); + let runs = [run]; + { + let observing = backend.observe(&runs, Duration::from_millis(100)); + tokio::pin!(observing); + tokio::select! { + _ = account.log_started.notified() => {} + result = &mut observing => panic!("snapshot stream did not start: {result:?}"), + } + let page = tokio::time::timeout( + Duration::from_millis(200), + backend.read_log(&runs[0], LogFile::Log, ByteRange { start: 0, end: 6 }, None), + ) + .await + .expect("cached page was locked behind the network") + .unwrap(); + assert!(matches!(page, LogPage::Data { bytes, .. } if bytes == b"first\n")); + let observations = tokio::time::timeout(Duration::from_millis(200), observing) + .await + .expect("observation exceeded its log-fetch budget"); + assert_eq!( + observations, + vec![ + ("run".into(), Observation::Running { started_at: None }), + ("run".into(), Observation::Log { len: 6 }) + ] + ); + } + let log = lock(&backend.logs).get("run").unwrap().clone(); + assert!(lock(&log.spool).error.is_none()); + assert_eq!(lock(&log.spool).cursor, 6); + account.block_logs.store(false, Ordering::SeqCst); + account.drain_resumed.notify_one(); + clock.advance(Duration::from_secs(10)); + backend.observe(&runs, Duration::from_secs(1)).await; + let page = backend + .read_log( + &runs[0], + LogFile::Log, + ByteRange { start: 6, end: 13 }, + None, + ) + .await + .unwrap(); + assert!(matches!(page, LogPage::Data { bytes, .. } if bytes == b"second\n")); + std::fs::remove_dir_all(spools).unwrap(); + } +} diff --git a/src/engine/adapters/api_tests.rs b/src/engine/adapters/api_tests.rs new file mode 100644 index 000000000..b78244b67 --- /dev/null +++ b/src/engine/adapters/api_tests.rs @@ -0,0 +1,2081 @@ +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::Duration; + +use axum::{extract::State, routing::any, Json, Router}; +use serde_json::{json, Value}; +use sha2::{Digest, Sha256}; + +use super::{hf::HfAccount, k8s::K8sAccount, modal::ModalAccount, ray::RayAccount}; +use crate::engine::clock::TestClock; +use crate::engine::*; +use crate::jobs::BackendDescriptor; +use crate::local::model::LocalExperiment; +use crate::store::{LaunchSpec, Store, SubmittingRun}; + +fn script(path: &Path, body: &str) { + use std::os::unix::fs::PermissionsExt; + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, body).unwrap(); + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700)).unwrap(); +} + +pub(super) fn engine(root: &Path) -> Engine { + let store = Store::open_at(root.join("store")).unwrap(); + store + .create_local_experiment(&LocalExperiment { + id: "exp".into(), + project_id: "proj".into(), + parent_experiment_id: None, + slug: "exp".into(), + branch_name: "orx/exp".into(), + title: None, + description: None, + run_command: "true".into(), + agent_status: "idle".into(), + created_at: 1, + updated_at: 1, + chat_session_id: None, + archived: false, + }) + .unwrap(); + Engine::new(store, Arc::new(TestClock::new())) +} + +fn pending<'a>( + id: &'a str, + metadata: &'a BackendDescriptor, + launch: &'a LaunchSpec, +) -> SubmittingRun<'a> { + SubmittingRun { + id, + experiment_id: "exp", + project_id: "proj", + metadata, + command: "true", + created_at: 1, + commit_sha: Some("snapshot"), + chat_session_id: None, + spec_digest: "digest", + launch, + } +} + +async fn isolated(test: &str) -> Option { + if std::env::var("ORX_API_TEST").as_deref() == Ok(test) { + return Some(PathBuf::from(std::env::var_os("ORX_API_ROOT").unwrap())); + } + let root = std::env::temp_dir().join(format!("orx-api-{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(root.join("bin")).unwrap(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let endpoint = format!("http://{}", listener.local_addr().unwrap()); + async fn lookup( + State(root): State, + method: axum::http::Method, + uri: axum::http::Uri, + ) -> axum::response::Response { + use axum::response::IntoResponse; + use std::io::Write; + let mut requests = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(root.join("http.log")) + .unwrap(); + writeln!(requests, "{method} {}", uri.path()).unwrap(); + let headers = axum::http::HeaderMap::new(); + if uri.path().ends_with("/logs") && root.join("slow-logs").exists() { + tokio::time::sleep(Duration::from_secs(5)).await; + return (headers, Json(json!({}))).into_response(); + } + if method == axum::http::Method::POST && uri.path() == "/sandboxes" { + let body = std::fs::read(root.join("sandbox-response.json")).unwrap(); + return ( + headers, + Json(serde_json::from_slice::(&body).unwrap()), + ) + .into_response(); + } + if uri.path().starts_with("/sandboxes/") { + if method == axum::http::Method::GET { + if root.join("box-released").exists() { + return (axum::http::StatusCode::NOT_FOUND, Json(json!({}))).into_response(); + } + if root.join("lookup-fails").exists() { + return (axum::http::StatusCode::SERVICE_UNAVAILABLE, Json(json!({}))) + .into_response(); + } + return ( + headers, + Json(json!({"sandbox": { + "id":"box", "organizationId":"org", "status":"online", + "machineType":"cpu", "updatedAt":"now" + }})), + ) + .into_response(); + } + if (method == axum::http::Method::DELETE || uri.path().ends_with("/lease/release")) + && root.join("delete-fails").exists() + { + return (axum::http::StatusCode::SERVICE_UNAVAILABLE, Json(json!({}))) + .into_response(); + } + return (headers, Json(json!({}))).into_response(); + } + assert_eq!( + method, + axum::http::Method::GET, + "recovery must never create a job" + ); + if let Ok(body) = std::fs::read(root.join("inspect-response.json")) { + let status = std::fs::read_to_string(root.join("inspect-status")) + .unwrap_or_else(|_| "200".into()) + .parse::() + .unwrap(); + return ( + axum::http::StatusCode::from_u16(status).unwrap(), + Json(serde_json::from_slice::(&body).unwrap()), + ) + .into_response(); + } + let jobs = if root.join("created").exists() { + json!([{"id":"hf-1", "status":{"stage":"RUNNING"}, "labels":{"or_run":"run"}}]) + } else { + json!([]) + }; + let mut headers = axum::http::HeaderMap::new(); + if uri.path().starts_with("/api/jobs/") + && !uri.query().unwrap_or_default().contains("cursor=next") + { + headers.insert( + "link", + "; rel=\"next\"".parse().unwrap(), + ); + return (headers, Json(json!([]))).into_response(); + } + (headers, Json(jobs)).into_response() + } + let app = Router::new().fallback(any(lookup)).with_state(root.clone()); + let server = tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + let output = crate::process::tokio_command(std::env::current_exe().unwrap()) + .args([ + "--exact", + &format!("engine::adapters::api_tests::{test}"), + "--nocapture", + ]) + .env("ORX_API_TEST", test) + .env("ORX_API_ROOT", &root) + .env("XDG_CONFIG_HOME", root.join("config")) + .env("ORX_DATA_DIR", root.join("store")) + .env("HF_ENDPOINT", endpoint) + .env("HF_TOKEN", "fake") + .env("ORX_MODAL_PYTHON", root.join("bin/modal-python")) + .env("ORX_VERCEL_PYTHON", root.join("bin/vercel-python")) + .env( + "PATH", + format!( + "{}:{}", + root.join("bin").display(), + std::env::var("PATH").unwrap() + ), + ) + .output() + .await + .unwrap(); + server.abort(); + assert!( + output.status.success(), + "{}\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + std::fs::remove_dir_all(root).unwrap(); + None +} + +#[tokio::test] +async fn modal_interrupted_before_id_is_unreconciled() { + let root = std::env::temp_dir().join(format!("orx-modal-{}", uuid::Uuid::new_v4())); + let engine = engine(&root); + let metadata = BackendDescriptor::parse(r#"{"kind":"modal_job"}"#).unwrap(); + let launch = LaunchSpec { + kind: "modal_job".into(), + target: None, + options: json!({}), + }; + engine + .store() + .insert_submitting_run(pending("run", &metadata, &launch)) + .unwrap(); + engine + .store() + .set_submission_fence( + "run", + 1, + &crate::store::SubmissionFence { + taken_at: 1, + submitter: None, + }, + ) + .unwrap(); + let adapter = super::api::Adapter::new( + ModalAccount, + Arc::new(TestClock::new()), + root.join("spools"), + ); + engine.recover(&adapter, "run").await.unwrap(); + assert_eq!(engine.load("run").unwrap().0.status, "submitting"); + assert!(matches!( + engine.load("run").unwrap().1.contact, + crate::store::Contact::Unreconciled { .. } + )); + drop(engine); + std::fs::remove_dir_all(root).unwrap(); +} + +#[tokio::test] +async fn hf_live_launcher_is_fenced_before_recovery_and_never_created_twice() { + let Some(root) = + isolated("hf_live_launcher_is_fenced_before_recovery_and_never_created_twice").await + else { + return; + }; + let python = crate::config::config_dir().join("envs/huggingface/bin/python"); + script( + &python, + &format!( + r#"#!/bin/sh +case "$2" in *'assert hasattr'*) exit 0;; esac +cat > '{root}/submission.json' +printf 'created\n' >> '{root}/created' +exec sleep 120 +"#, + root = root.display() + ), + ); + let archive = root.join("source.tar"); + std::fs::write(&archive, "snapshot").unwrap(); + let digest = format!("{:x}", Sha256::digest(b"snapshot")); + let metadata = BackendDescriptor::parse( + &json!({ "kind":"hf_job", "sourcePath":archive, "sourceDigest":digest, "sourceSize":8 }) + .to_string(), + ) + .unwrap(); + let launch = LaunchSpec { + kind: "hf_job".into(), + target: Some("org".into()), + options: json!({ + "command":["true"], "docker_image":"python", "flavor":"cpu", "environment":{}, "secrets":{}, "timeout_seconds":3600, "labels":{} + }), + }; + let engine = engine(&root); + let adapter = super::api::Adapter::new( + HfAccount { + namespace: "org".into(), + }, + Arc::new(TestClock::new()), + root.join("spools"), + ); + let identity = { + let submit = engine.submit(&adapter, pending("run", &metadata, &launch)); + tokio::pin!(submit); + tokio::select! { + result = &mut submit => panic!("launcher returned: {result:?}"), + identity = async { + loop { + if root.join("created").exists() { + break engine.load("run").unwrap().1.submission_fence.unwrap().submitter.unwrap(); + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + } => identity, + } + }; + assert_eq!( + crate::engine::process::identity(identity.pid), + Some(identity.clone()) + ); + drop(engine); + let engine = Engine::new( + Store::open_at(root.join("store")).unwrap(), + Arc::new(TestClock::new()), + ); + engine.recover(&adapter, "run").await.unwrap(); + assert_eq!(engine.load("run").unwrap().0.status, "starting"); + assert_eq!(engine.load("run").unwrap().1.submission_attempt, 1); + assert!(crate::engine::process::identity(identity.pid).is_none()); + let submitted: Value = + serde_json::from_slice(&std::fs::read(root.join("submission.json")).unwrap()).unwrap(); + assert_eq!(submitted["labels"]["or_run"], "run"); + assert_eq!( + std::fs::read_to_string(root.join("created")) + .unwrap() + .lines() + .count(), + 1 + ); +} + +#[tokio::test] +async fn ray_submission_id_survives_lost_response_and_observations_are_batched() { + use std::sync::Mutex; + type Context = (Arc>>, Arc>); + let requests = Arc::new(Mutex::new(Vec::::new())); + let response = Arc::new(Mutex::new(json!({"status":"RUNNING", "start_time":1234}))); + async fn submit( + State((requests, _)): State, + Json(body): Json, + ) -> axum::http::StatusCode { + requests.lock().unwrap().push(body); + axum::http::StatusCode::INTERNAL_SERVER_ERROR + } + async fn inspect(State((_, response)): State) -> Json { + Json(response.lock().unwrap().clone()) + } + let app = Router::new() + .route("/api/jobs/", axum::routing::post(submit)) + .route("/api/jobs/run", axum::routing::get(inspect)) + .with_state((requests.clone(), response.clone())); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = format!("http://{}", listener.local_addr().unwrap()); + let server = tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + let root = std::env::temp_dir().join(format!("orx-ray-{}", uuid::Uuid::new_v4())); + let engine = engine(&root); + let metadata = BackendDescriptor::parse(r#"{"kind":"ray_job"}"#).unwrap(); + let launch = LaunchSpec { + kind: "ray_job".into(), + target: Some(address.clone()), + options: json!({ + "entrypoint":"true", "submission_id":"wrong", "resources":{"cpus":1.0,"gpus":0.0,"memory_bytes":null}, "env":{}, "metadata":{}, "working_dir":null + }), + }; + let clock = Arc::new(TestClock::new()); + let adapter = + super::api::Adapter::new(RayAccount { address }, clock.clone(), root.join("spools")); + engine + .submit(&adapter, pending("run", &metadata, &launch)) + .await + .unwrap(); + assert_eq!(engine.load("run").unwrap().0.status, "starting"); + assert_eq!(requests.lock().unwrap().len(), 1); + assert_eq!(requests.lock().unwrap()[0]["submission_id"], "run"); + let runs = [WatchedRun { + id: "run".into(), + handle: handle_of(&engine.load("run").unwrap().0).unwrap(), + }]; + assert_eq!( + adapter.observe(&runs, Duration::from_secs(2)).await, + vec![( + "run".into(), + Observation::Running { + started_at: Some(1234) + } + )] + ); + assert!(adapter + .observe(&runs, Duration::from_secs(2)) + .await + .is_empty()); + clock.advance(Duration::from_secs(10)); + assert_eq!( + adapter.observe(&runs, Duration::from_secs(2)).await.len(), + 1 + ); + *response.lock().unwrap() = json!({"status":"SUCCEEDED", "start_time":1234, "end_time":4567}); + clock.advance(Duration::from_secs(10)); + let observations = adapter.observe(&runs, Duration::from_secs(2)).await; + assert!(observations.iter().any(|(_, observation)| matches!( + observation, + Observation::Exited { + finished_at: Some(4567), + .. + } + ))); + for (id, observation) in observations { + engine.observe(&id, observation).unwrap(); + } + assert_eq!(engine.load("run").unwrap().0.ended_at, Some(4567)); + server.abort(); + drop(engine); + std::fs::remove_dir_all(root).unwrap(); +} + +#[test] +fn provider_terminal_observations_keep_source_finish_times_and_exit_codes() { + for (stage, code, expected) in [ + ( + "FAILED", + Some(17), + Observation::Exited { + finished_at: Some(123), + code: Some(17), + signal: None, + }, + ), + ( + "CANCELLED", + Some(137), + Observation::Cancelled { + finished_at: Some(123), + code: Some(137), + signal: None, + }, + ), + ( + "FAILED", + None, + Observation::Failed { + finished_at: Some(123), + reason: "FAILED".into(), + }, + ), + ] { + assert_eq!( + super::api::stage(stage, None, code, Some(100), Some(123)), + expected + ); + } +} + +#[tokio::test] +async fn k8s_recovery_resumes_staging_and_ready_is_immutable() { + let Some(root) = isolated("k8s_recovery_resumes_staging_and_ready_is_immutable").await else { + return; + }; + script( + &root.join("bin/kubectl"), + r#"#!/usr/bin/env python3 +import json, os, sys +from pathlib import Path +root=Path(os.environ['ORX_API_ROOT']) +a=sys.argv[1:] +with (root/'kubectl.log').open('a') as f: f.write(' '.join(a)+'\n') +if '--dry-run=client' in a: + print(sys.stdin.read()) +elif a[0]=='get' and a[1]=='pods': + print('{"items":[]}' if a[-1]=='json' else 'pod-1',end='') +elif a[0]=='get' and a[1]=='job' and a[2]!='-n' and (root/'finished').exists(): + print('{"status":{"succeeded":1}}') +elif a[0]=='get': + print((root/'resources.json').read_text()) +elif a[0]=='exec' and 'test' in a: + sys.exit(0 if (root/'ready').exists() else 1) +elif a[0]=='cp': + (root/'part').write_bytes(Path(a[1]).read_bytes()) + with (root/'copies').open('a') as f: f.write('copy\n') +elif a[0]=='exec' and 'sh' in a: + if not (root/'ready').exists(): + assert (root/'part').stat().st_size==8 + (root/'part').rename(root/'source.tar') + (root/'ready').touch() +elif a[0]=='delete': + (root/'resources.json').write_text('{"items":[]}') +else: + raise Exception(a) +"#, + ); + let manifest = json!({"apiVersion":"batch/v1","kind":"Job","metadata":{"name":"run"},"spec":{"template":{"spec":{"restartPolicy":"Never","containers":[{"name":"run","image":"python","command":["bash","-c","eval \"$ORX_SCRIPT\""]}]}}}}); + std::fs::write( + root.join("resources.json"), + json!({"items":[manifest.clone()]}).to_string(), + ) + .unwrap(); + let archive = root.join("archive.tar"); + std::fs::write(&archive, "snapshot").unwrap(); + // Simulate a crash after create, with an incomplete staging copy. + std::fs::write(root.join("part"), "snap").unwrap(); + let engine = engine(&root); + let metadata = BackendDescriptor::parse(r#"{"kind":"k8s_job"}"#).unwrap(); + let launch = LaunchSpec { + kind: "k8s_job".into(), + target: None, + options: json!({ + "manifest":manifest.to_string(), "script":"true", "run_token":"run", "env":{}, "timeout_seconds":3600, "labels":{}, "pod_env":[], "source_archive":archive + }), + }; + engine + .store() + .insert_submitting_run(pending("run", &metadata, &launch)) + .unwrap(); + engine + .store() + .set_submission_fence( + "run", + 1, + &crate::store::SubmissionFence { + taken_at: 1, + submitter: None, + }, + ) + .unwrap(); + let adapter = super::api::Adapter::new( + K8sAccount { + context: None, + namespace: "default".into(), + }, + Arc::new(TestClock::new()), + root.join("spools"), + ); + engine.recover(&adapter, "run").await.unwrap(); + assert_eq!(engine.load("run").unwrap().0.status, "starting"); + assert_eq!(std::fs::read(root.join("source.tar")).unwrap(), b"snapshot"); + let state = engine.load("run").unwrap().1; + let mut intent = RunIntent::new(engine.load("run").unwrap().0, &state).unwrap(); + assert!(matches!( + adapter.recover(&intent).await, + Recovery::Found(Handle::Api { .. }) + )); + assert_eq!( + std::fs::read_to_string(root.join("copies")).unwrap(), + "copy\n" + ); + let calls = std::fs::read_to_string(root.join("kubectl.log")).unwrap(); + assert!( + !calls + .lines() + .any(|call| call.starts_with("create -f") || call.starts_with("delete")), + "{calls}" + ); + let mut primary = manifest.clone(); + primary["metadata"]["name"] = json!("primary"); + primary["metadata"]["labels"] = json!({"orx-primary":"true"}); + let items = json!([manifest, primary, {"apiVersion":"v1","kind":"Service","metadata":{"name":"rendezvous"},"spec":{"clusterIP":"None"}}]); + intent.launch.options["manifest"] = json!({"kind":"List","items":items}).to_string().into(); + std::fs::write( + root.join("resources.json"), + json!({"items":items}).to_string(), + ) + .unwrap(); + let Recovery::Found(Handle::Api { ids: resources, .. }) = adapter.recover(&intent).await else { + panic!("primary Job was not recovered"); + }; + assert_eq!(resources[0], "job/primary"); + std::fs::write(root.join("finished"), "").unwrap(); + let before = std::fs::read_to_string(root.join("kubectl.log")) + .unwrap() + .lines() + .count(); + let recovered = adapter.recover(&intent).await; + assert!(matches!(recovered, Recovery::Found(_)), "{recovered:?}"); + let calls = std::fs::read_to_string(root.join("kubectl.log")).unwrap(); + assert!(!calls + .lines() + .skip(before) + .any(|call| call.starts_with("exec") || call.starts_with("cp"))); + let calls_before = std::fs::read_to_string(root.join("kubectl.log")) + .unwrap() + .lines() + .count(); + std::fs::write( + root.join("resources.json"), + json!({"items":[{"kind":"Service","metadata":{"name":"rendezvous"}}]}).to_string(), + ) + .unwrap(); + assert!(matches!( + adapter.recover(&intent).await, + Recovery::Unknown { .. } + )); + let calls = std::fs::read_to_string(root.join("kubectl.log")).unwrap(); + assert!(!calls + .lines() + .skip(calls_before) + .any(|call| call.starts_with("delete"))); + let partial = json!({"items":[{"kind":"Job","metadata":{"name":"primary"}}]}); + std::fs::write(root.join("resources.json"), partial.to_string()).unwrap(); + assert!(matches!(adapter.recover(&intent).await, Recovery::Absent)); + let calls = std::fs::read_to_string(root.join("kubectl.log")).unwrap(); + assert!(calls.contains("delete job/primary -n default --wait=false")); +} + +#[tokio::test] +async fn openresearch_cancel_and_abandon_release_without_ssh_and_retry_api_failures() { + use super::openresearch::OpenResearch; + use crate::store::{Contact, StoredRun}; + + let Some(root) = + isolated("openresearch_cancel_and_abandon_release_without_ssh_and_retry_api_failures") + .await + else { + return; + }; + crate::config::save_credentials(&crate::config::Credentials { + api_url: std::env::var("HF_ENDPOINT").unwrap(), + token: "fake".into(), + }) + .await + .unwrap(); + for leased in [false, true] { + for abandon in [false, true] { + for needs_auth in [false, true] { + let id = format!("box-{leased}-{abandon}-{needs_auth}"); + let mut descriptor = BackendDescriptor::parse( + &json!({"kind":"openresearch_job","namespace":"org","jobId":id}).to_string(), + ) + .unwrap(); + if leased { + descriptor.rental_lease = Some(crate::jobs::rental::Rental { + api_url: std::env::var("HF_ENDPOINT").unwrap(), + sandbox_id: id.clone(), + token: "fake".into(), + }); + } + let handle = Handle::Legacy { + descriptor: Box::new(descriptor.clone()), + }; + let backend_json = if leased { + handle::backend_json(&id, Some(&handle), &descriptor).unwrap() + } else { + descriptor.to_json() + }; + let mut engine = engine(&root.join(&id)); + let clock = Arc::new(TestClock::new()); + engine.clock = clock.clone(); + let engine = Arc::new(engine); + engine + .store() + .upsert_run(&StoredRun { + id: id.clone(), + experiment_id: "exp".into(), + project_id: "proj".into(), + status: "running".into(), + backend_json, + command: "true".into(), + created_at: 1, + updated_at: 1, + ended_at: None, + exit_code: None, + commit_sha: None, + result_markdown: None, + cancel_requested: false, + cancel_reason: None, + chat_session_id: Some("chat".into()), + }) + .unwrap(); + let observation = if needs_auth { + Observation::NeedsAuth { + cause: "Permission denied (publickey)".into(), + } + } else { + Observation::Unreachable { + cause: "Connection timed out".into(), + } + }; + engine.observe(&id, observation).unwrap(); + clock.advance(Duration::from_secs(600)); + engine.check_outages().unwrap(); + assert_eq!(engine.load(&id).unwrap().0.status, "running"); + assert!(engine + .store() + .run_notice_batch("chat") + .unwrap() + .iter() + .any(|notice| { + notice.kind == crate::store::ATTENTION + && notice.body.contains("still billing") + })); + let adapter = + OpenResearch::new(engine.clone(), Arc::new(|_| panic!("teardown used SSH"))); + let watched = [WatchedRun { + id: id.clone(), + handle, + }]; + std::fs::write(root.join("delete-fails"), "").unwrap(); + if abandon { + assert!(engine.abandon(&id).unwrap()); + engine + .observe_runs(&adapter, &watched, Duration::ZERO) + .await + .unwrap(); + } else { + assert!(engine.cancel(&adapter, &id, "user").await.unwrap()); + } + let (run, state) = engine.load(&id).unwrap(); + assert_eq!(run.status, if abandon { "lost" } else { "running" }); + assert_ne!(state.contact, Contact::Live); + assert!(!engine.memory().cancels_sent.contains(&id)); + std::fs::remove_file(root.join("delete-fails")).unwrap(); + engine + .observe_runs(&adapter, &watched, Duration::ZERO) + .await + .unwrap(); + let (run, state) = engine.load(&id).unwrap(); + assert_eq!(run.status, if abandon { "lost" } else { "cancelled" }); + assert_eq!(state.contact, Contact::Live); + let released = if leased { + format!("POST /sandboxes/{id}/lease/release") + } else { + format!("DELETE /sandboxes/{id}") + }; + assert!(std::fs::read_to_string(root.join("http.log")) + .unwrap() + .lines() + .any(|line| line == released)); + } + } + } +} + +#[tokio::test] +async fn openresearch_rejected_key_auto_cancel_checks_rental_and_survives_restart() { + use super::openresearch::{LegacyTransport, OpenResearch}; + use super::ssh::Ssh; + use crate::engine::transport::{Auth, Config, HostClass, HostConn, HostState, Status}; + use crate::store::StoredRun; + + let Some(root) = + isolated("openresearch_rejected_key_auto_cancel_checks_rental_and_survives_restart").await + else { + return; + }; + crate::config::save_credentials(&crate::config::Credentials { + api_url: std::env::var("HF_ENDPOINT").unwrap(), + token: "fake".into(), + }) + .await + .unwrap(); + for case in [ + "leased", "sandbox", "released", "restart", "retry", "lookup", "ssh", + ] { + let dir = root.join(case); + let mut initial = engine(&dir); + let clock = Arc::new(TestClock::new()); + initial.clock = clock.clone(); + let mut engine = Arc::new(initial); + let mut descriptor = BackendDescriptor::parse( + &json!({ + "kind": if case == "ssh" { "ssh_job" } else { "openresearch_job" }, + "namespace":"org", "jobId":"box", "sshHost":"unused", "sshPort":22, "sshUser":"root" + }) + .to_string(), + ) + .unwrap(); + if case != "sandbox" && case != "ssh" { + descriptor.rental_lease = Some(crate::jobs::rental::Rental { + api_url: std::env::var("HF_ENDPOINT").unwrap(), + sandbox_id: "box".into(), + token: "fake".into(), + }); + } + let watched = [WatchedRun { + id: case.into(), + handle: Handle::Legacy { + descriptor: Box::new(descriptor.clone()), + }, + }]; + engine + .store() + .upsert_run(&StoredRun { + id: case.into(), + experiment_id: "exp".into(), + project_id: "proj".into(), + status: "running".into(), + backend_json: descriptor.to_json(), + command: "true".into(), + created_at: clock.wall_ms(), + updated_at: clock.wall_ms(), + ended_at: None, + exit_code: None, + commit_sha: None, + result_markdown: None, + cancel_requested: false, + cancel_reason: None, + chat_session_id: Some("chat".into()), + }) + .unwrap(); + let live = clock.wall_ms(); + clock.advance(Duration::from_secs(1)); + engine + .store() + .seed_engine_host( + "box", + "/root", + Some(HostClass::Key), + &HostState { + status: Status::NeedsAuth, + since_ms: clock.wall_ms(), + last_live_ms: Some(live), + cause: Some("Permission denied (publickey)".into()), + ..HostState::default() + }, + ) + .unwrap(); + engine + .observe( + case, + Observation::NeedsAuth { + cause: "Permission denied (publickey)".into(), + }, + ) + .unwrap(); + let make_adapter = |engine: Arc| { + let store = Store::open_at(dir.join("store")).unwrap(); + let auth = Auth::new(&store, "box").unwrap(); + let conn = HostConn::start_shared( + Config { + alias: "box".into(), + root: "/root".into(), + ssh_config: Some(dir.join("never-connect")), + control_dir: dir.join("cm"), + sharing_home: None, + binary_dir: None, + askpass_executable: std::env::current_exe().unwrap(), + }, + store, + clock.clone(), + auth, + ) + .unwrap(); + let transport = Arc::new(LegacyTransport::new( + Arc::new(Ssh::new("box".into(), "/root".into(), conn)), + dir.join("logs"), + )); + OpenResearch::new(engine, Arc::new(move |_| Ok(transport.clone()))) + }; + let mut adapter = make_adapter(engine.clone()); + clock.advance(Duration::from_secs(7 * 60)); + adapter.observe(&watched, Duration::ZERO).await; + assert!(engine.load(case).unwrap().1.cancel_accepted_at.is_none()); + if case == "restart" { + drop(adapter); + tokio::time::timeout(Duration::from_secs(5), async { + while Arc::strong_count(&engine) != 1 { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + drop(engine); + engine = Arc::new(Engine::new( + Store::open_at(dir.join("store")).unwrap(), + clock.clone(), + )); + adapter = make_adapter(engine.clone()); + } + clock.advance(Duration::from_secs(8 * 60 - 1)); + adapter.observe(&watched, Duration::ZERO).await; + assert!(engine.load(case).unwrap().1.cancel_accepted_at.is_none()); + if case == "released" { + std::fs::write(root.join("box-released"), "").unwrap(); + } + if case == "retry" { + std::fs::write(root.join("delete-fails"), "").unwrap(); + } + if case == "lookup" { + std::fs::write(root.join("lookup-fails"), "").unwrap(); + } + std::fs::write(root.join("http.log"), "").unwrap(); + clock.advance(Duration::from_secs(1)); + adapter.observe(&watched, Duration::ZERO).await; + let (run, state) = engine.load(case).unwrap(); + if case == "retry" || case == "lookup" { + assert_eq!(run.status, "running"); + assert_eq!(state.cancel_accepted_at.is_some(), case == "retry"); + let flag = if case == "retry" { + "delete-fails" + } else { + "lookup-fails" + }; + std::fs::remove_file(root.join(flag)).unwrap(); + engine + .observe_runs(&adapter, &watched, Duration::ZERO) + .await + .unwrap(); + } + let (run, state) = engine.load(case).unwrap(); + assert_eq!( + run.status, + match case { + "released" => "lost", + "ssh" => "running", + _ => "cancelled", + }, + "{case}" + ); + let accepted = state.cancel_accepted_at; + if case != "ssh" && case != "released" { + assert!(accepted.is_some()); + assert_eq!( + run.cancel_reason.as_deref(), + Some(crate::plane::LABELS["run_notice_rental_key_cancelled"].as_str()) + ); + } else { + assert!(accepted.is_none()); + } + drop(adapter); + drop(engine); + engine = Arc::new(Engine::new( + Store::open_at(dir.join("store")).unwrap(), + clock.clone(), + )); + adapter = make_adapter(engine.clone()); + for _ in 0..2 { + engine + .observe_runs(&adapter, &watched, Duration::ZERO) + .await + .unwrap(); + } + assert_eq!(engine.load(case).unwrap().1.cancel_accepted_at, accepted); + let requests = std::fs::read_to_string(root.join("http.log")).unwrap(); + let releases = requests + .lines() + .filter(|line| line.ends_with("/lease/release") || line.starts_with("DELETE ")) + .count(); + assert_eq!( + releases, + match case { + "ssh" | "released" => 0, + "retry" => 2, + _ => 1, + }, + "{case}: {requests}" + ); + if case != "ssh" { + assert!(requests + .lines() + .next() + .unwrap() + .starts_with("GET /sandboxes/")); + let notices = engine.store().run_notice_batch("chat").unwrap(); + let terminal: Vec<_> = notices + .iter() + .filter(|notice| notice.kind == crate::store::TERMINAL) + .collect(); + assert_eq!(terminal.len(), 1, "{case}"); + assert!(terminal[0].body.contains(if case == "released" { + &crate::plane::LABELS["run_notice_rental_outcome_unavailable"] + } else { + &crate::plane::LABELS["run_notice_rental_key_cancelled"] + })); + } else { + assert!(requests.is_empty()); + } + if case == "released" { + std::fs::remove_file(root.join("box-released")).unwrap(); + } + } +} + +async fn legacy_rejected_key(root: PathBuf, watching: bool) { + use super::openresearch::{LegacyTransport, OpenResearch}; + use super::ssh::Ssh; + use crate::engine::transport::{Config, HostConn, Status}; + use crate::store::StoredRun; + use orx_test_support::host_binaries as binaries; + let server = orx_test_support::Sshd::start().unwrap(); + crate::config::save_credentials(&crate::config::Credentials { + api_url: std::env::var("HF_ENDPOINT").unwrap(), + token: "fake".into(), + }) + .await + .unwrap(); + let transport_clock = Arc::new(TestClock::new()); + let conn = { + let config = Config { + alias: server.alias().into(), + root: "~/engine-root".into(), + ssh_config: Some(server.config_path()), + control_dir: server.directory().join("cm"), + binary_dir: Some(binaries()), + #[cfg(unix)] + sharing_home: None, + askpass_executable: std::env::current_exe().unwrap(), + }; + let store = Store::open_at(root.join("transport")).unwrap(); + let auth = crate::engine::transport::Auth::new(&store, &config.alias).unwrap(); + HostConn::start_shared(config, store, transport_clock.clone(), auth) + } + .unwrap(); + let mut state = conn.state(); + tokio::time::timeout(Duration::from_secs(20), async { + loop { + let status = state.borrow_and_update().status.clone(); + if status == Status::Live { + break; + } + state.changed().await.unwrap(); + } + }) + .await + .unwrap(); + let ssh = Arc::new(Ssh::new( + server.alias().into(), + "~/engine-root".into(), + conn.clone(), + )); + let transport = Arc::new(LegacyTransport::new(ssh, root.join("store/run-logs"))); + let id = uuid::Uuid::new_v4().to_string(); + let archive = root.join("source.tar"); + let source = if watching { + b"snapshot".to_vec() + } else { + vec![42; 16 * 1024 * 1024] + }; + std::fs::write(&archive, &source).unwrap(); + let digest = format!("{:x}", Sha256::digest(&source)); + if watching { + transport + .upload("cat > \"$HOME/uploaded\"", &archive) + .await + .unwrap(); + assert_eq!( + std::fs::read(server.home().join("uploaded")).unwrap(), + source + ); + } + let descriptor = BackendDescriptor::parse( + &json!({ + "kind":"openresearch_job", "namespace":"org", "jobId":"box", + "sshHost":"127.0.0.1", "sshPort":server.port(), "sshUser":server.user(), + "sourceDigest":digest, "sourcePath":archive, "sourceSize":source.len(), + "rentalLease":{"apiUrl":std::env::var("HF_ENDPOINT").unwrap(),"sandboxId":"box","token":"fake"} + }) + .to_string(), + ) + .unwrap(); + if watching { + let dir = server.home().join(format!(".orx/runs/{id}")); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("pid"), server.pid().to_string()).unwrap(); + std::fs::write(dir.join("log"), vec![b'x'; 5000]).unwrap(); + } + let engine = Arc::new(engine(&root)); + let stored = StoredRun { + id: id.clone(), + experiment_id: "exp".into(), + project_id: "proj".into(), + status: "starting".into(), + backend_json: descriptor.to_json(), + command: "true".into(), + created_at: 1, + updated_at: 1, + ended_at: None, + exit_code: None, + commit_sha: Some("snapshot".into()), + result_markdown: None, + cancel_requested: false, + cancel_reason: None, + chat_session_id: None, + }; + engine.store().upsert_run(&stored).unwrap(); + let factory_transport = transport.clone(); + let adapter = OpenResearch::new( + engine.clone(), + Arc::new(move |_| Ok(factory_transport.clone())), + ); + let watched = [WatchedRun { + id: id.clone(), + handle: Handle::Legacy { + descriptor: Box::new(descriptor), + }, + }]; + adapter.observe(&watched, Duration::from_secs(1)).await; + if watching { + tokio::time::timeout(Duration::from_secs(20), async { + loop { + if engine.load(&id).unwrap().0.status == "running" + && root.join(format!("store/run-logs/{id}.log")).exists() + { + break; + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + }) + .await + .unwrap(); + let dir = format!(".orx/runs/{id}"); + assert_eq!(transport.collect(&id, &dir).await.unwrap()["eof"], true); + let remote = server.home().join(&dir).join("log"); + let mut changed = vec![b'x'; 5000]; + changed[4999] = b'y'; + std::fs::write(&remote, &changed).unwrap(); + assert_eq!(transport.collect(&id, &dir).await.unwrap()["eof"], false); + let local = root.join(format!("store/run-logs/{id}.log")); + assert_eq!(std::fs::read(&local).unwrap(), vec![b'x'; 5000]); + let resumed = LegacyTransport::new(transport.ssh.clone(), transport.log_dir.clone()); + assert_eq!(resumed.collect(&id, &dir).await.unwrap()["eof"], true); + assert_eq!(std::fs::read(local).unwrap(), changed); + } else { + let partial = server + .home() + .join(format!("engine-root/sources/{digest}.part")); + tokio::time::timeout(Duration::from_secs(20), async { + while !partial.exists() { + tokio::time::sleep(Duration::from_millis(1)).await; + } + }) + .await + .unwrap(); + } + std::fs::write(server.directory().join("authorized_keys"), "").unwrap(); + server.proxy().reset().unwrap(); + transport_clock.advance(Duration::from_secs(60)); + tokio::time::timeout(Duration::from_secs(20), async { + loop { + if state.borrow_and_update().status == Status::NeedsAuth { + break; + } + transport_clock.advance(Duration::from_secs(5)); + tokio::time::sleep(Duration::from_millis(100)).await; + } + }) + .await + .unwrap(); + tokio::time::timeout(Duration::from_secs(20), async { + loop { + if matches!( + engine.load(&id).unwrap().1.contact, + crate::store::Contact::NeedsAuth { .. } + ) { + break; + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + }) + .await + .unwrap(); + let heartbeats = || { + std::fs::read_to_string(root.join("http.log")) + .unwrap_or_default() + .lines() + .filter(|line| line.ends_with("/lease/heartbeat")) + .count() + }; + let stopped = heartbeats(); + let checks = if watching { 6 } else { 32 }; + for _ in 0..checks { + adapter.observe(&watched, Duration::from_secs(1)).await; + tokio::time::sleep(Duration::from_secs(1)).await; + assert_eq!( + heartbeats(), + stopped, + "an unreachable box renewed its lease" + ); + } + let attempts = server.auth_attempts().unwrap(); + assert_eq!( + attempts + .get(&("publickey".into(), "Failed".into())) + .copied() + .unwrap_or(0), + 1, + "{attempts:?}" + ); + transport_clock.advance(Duration::from_secs(1800)); + tokio::time::sleep(Duration::from_millis(300)).await; + assert_eq!(server.auth_attempts().unwrap(), attempts); + assert!(matches!( + engine.load(&id).unwrap().0.status.as_str(), + "starting" | "running" + )); + assert!(!std::fs::read_dir(root.join("store")) + .unwrap() + .any(|entry| entry + .unwrap() + .file_name() + .to_string_lossy() + .starts_with("ssh-service-"))); + let processes = crate::process::command("ps") + .args(["-axo", "command"]) + .output() + .unwrap(); + let needle = format!("{} ssh-service", std::env::current_exe().unwrap().display()); + assert!(!String::from_utf8_lossy(&processes.stdout).contains(&needle)); + if watching { + assert!(engine.cancel(&adapter, &id, "user").await.unwrap()); + assert_eq!(engine.load(&id).unwrap().0.status, "cancelled"); + } else { + assert!(engine.abandon(&id).unwrap()); + engine + .observe_runs(&adapter, &watched, Duration::ZERO) + .await + .unwrap(); + assert_eq!(engine.load(&id).unwrap().0.status, "lost"); + } + assert_eq!( + engine.load(&id).unwrap().1.contact, + crate::store::Contact::Live + ); + assert!(std::fs::read_to_string(root.join("http.log")) + .unwrap() + .lines() + .any(|line| line == "POST /sandboxes/box/lease/release")); + assert_eq!(server.auth_attempts().unwrap(), attempts); + drop(adapter); + drop(conn); +} + +#[tokio::test] +async fn openresearch_staging_rejected_key_needs_auth_after_one_attempt() { + let Some(root) = + isolated("openresearch_staging_rejected_key_needs_auth_after_one_attempt").await + else { + return; + }; + legacy_rejected_key(root, false).await; +} + +#[tokio::test] +async fn openresearch_watching_rejected_key_needs_auth_after_one_attempt() { + let Some(root) = + isolated("openresearch_watching_rejected_key_needs_auth_after_one_attempt").await + else { + return; + }; + legacy_rejected_key(root, true).await; +} + +#[tokio::test] +async fn unsupported_leases_are_deleted_or_keep_the_known_box_handle() { + let Some(root) = isolated("unsupported_leases_are_deleted_or_keep_the_known_box_handle").await + else { + return; + }; + let creds = crate::config::Credentials { + api_url: std::env::var("HF_ENDPOINT").unwrap(), + token: "fake".into(), + }; + crate::config::save_credentials(&creds).await.unwrap(); + let engine = Arc::new(engine(&root)); + let backend = super::openresearch::OpenResearch::new( + engine.clone(), + Arc::new(|_| panic!("no SSH before a valid handle")), + ); + let metadata = BackendDescriptor::parse(r#"{"kind":"openresearch_job"}"#).unwrap(); + let launch = LaunchSpec { + kind: "openresearch_job".into(), + target: Some("org".into()), + options: json!({"flavor":"cpu5c"}), + }; + for (id, lease, deletion_fails) in [ + ("missing", Value::Null, false), + ("unsupported", json!({"version":2,"token":"fake"}), false), + ("retained", Value::Null, true), + ] { + let response = json!({"sandbox":{"id":id,"organizationId":"org","status":"online","machineType":"cpu","updatedAt":"now"},"rentalLease":lease}); + std::fs::write(root.join("sandbox-response.json"), response.to_string()).unwrap(); + if deletion_fails { + std::fs::write(root.join("delete-fails"), "").unwrap(); + } + engine + .submit(&backend, pending(id, &metadata, &launch)) + .await + .unwrap(); + let (run, _) = engine.load(id).unwrap(); + if deletion_fails { + assert_eq!(run.status, "starting"); + let Some(Handle::Legacy { descriptor }) = handle_of(&run) else { + panic!("lost paid box id"); + }; + assert_eq!(descriptor.job_id.as_deref(), Some(id)); + assert!(descriptor.rental_lease.is_none()); + } else { + assert_eq!(run.status, "failed"); + assert!(run.result_markdown.unwrap().contains("box was deleted")); + } + let requests = std::fs::read_to_string(root.join("http.log")).unwrap(); + assert!(requests + .lines() + .any(|line| line == format!("DELETE /sandboxes/{id}"))); + } +} + +#[tokio::test] +async fn failed_submission_fences_kill_launchers_before_stdin_is_released() { + let Some(root) = + isolated("failed_submission_fences_kill_launchers_before_stdin_is_released").await + else { + return; + }; + let python = crate::config::config_dir().join("envs/huggingface/bin/python"); + script( + &python, + &format!( + r#"#!/bin/sh +case "$2" in *'assert hasattr'*) exit 0;; esac +cat >/dev/null +sleep 0.2 +touch '{}/leaked-hf' +"#, + root.display() + ), + ); + script( + &root.join("bin/kubectl"), + &format!( + r#"#!/bin/sh +case "$*" in *--dry-run=client*) cat; exit 0;; esac +cat >/dev/null +sleep 0.2 +touch '{}/leaked-k8s' +"#, + root.display() + ), + ); + let engine = engine(&root); + let fence = Fence { + store: &engine.store, + run_id: "not-submitting", + attempt: 1, + taken_at: 1, + }; + let archive = root.join("source.tar"); + std::fs::write(&archive, "snapshot").unwrap(); + let hf = serde_json::from_value(json!({"command":["true"],"docker_image":"python","flavor":"cpu","environment":{},"secrets":{},"timeout_seconds":60,"labels":{}})).unwrap(); + let error = crate::jobs::huggingface::run_job_with_source( + "fake", + "org", + &hf, + &archive, + "digest", + Some(&fence), + ) + .await + .unwrap_err(); + assert!(error.to_string().contains("no longer awaits"), "{error}"); + let manifest = json!({"apiVersion":"batch/v1","kind":"Job","metadata":{"name":"run"},"spec":{"template":{"spec":{"containers":[{"name":"run","command":["bash","-c","eval \"$ORX_SCRIPT\""]}]}}}}); + let spec = serde_json::from_value(json!({"manifest":manifest.to_string(),"script":"true","run_token":"run","env":{},"timeout_seconds":60,"labels":{},"pod_env":[],"source_archive":archive})).unwrap(); + let error = crate::jobs::kubernetes::run_manifest(None, "default", &spec, Some(&fence)) + .await + .err() + .expect("unfenced creation succeeded"); + assert!(error.to_string().contains("no longer awaits"), "{error}"); + tokio::time::sleep(Duration::from_secs(1)).await; + assert!(!root.join("leaked-hf").exists()); + assert!(!root.join("leaked-k8s").exists()); +} + +#[tokio::test] +async fn chatty_modal_logs_publish_a_partial_page_and_reuse_it() { + let Some(root) = isolated("chatty_modal_logs_publish_a_partial_page_and_reuse_it").await else { + return; + }; + let python = root.join("bin/modal-python"); + script( + &python, + &format!( + r#"#!/bin/sh +printf 'download\n' >> '{}/downloads' +while :; do printf 'line\n'; sleep 0.01; done +"#, + root.display() + ), + ); + let backend = super::api::Adapter::new( + ModalAccount, + Arc::new(TestClock::new()), + root.join("spools"), + ); + let run = WatchedRun { + id: "chatty".into(), + handle: crate::engine::adapters::api::test_handle( + "modal_job", + None, + None, + vec!["sandbox".into()], + ), + }; + let page = backend + .read_log(&run, LogFile::Log, ByteRange { start: 0, end: 100 }, None) + .await + .unwrap(); + let LogPage::Data { bytes, ident, .. } = page else { + panic!("no live log page") + }; + assert!(!bytes.is_empty()); + for _ in 0..5 { + backend + .read_log( + &run, + LogFile::Log, + ByteRange { start: 0, end: 100 }, + Some(&ident), + ) + .await + .unwrap(); + } + assert_eq!( + std::fs::read_to_string(root.join("downloads")) + .unwrap() + .lines() + .count(), + 1 + ); +} + +#[tokio::test] +async fn live_modal_eof_reconnects_and_final_collection_keeps_later_output() { + use crate::commands::up::api_v2::Commands; + + let Some(root) = + isolated("live_modal_eof_reconnects_and_final_collection_keeps_later_output").await + else { + return; + }; + script( + &root.join("bin/modal-python"), + &format!( + r#"#!/bin/sh +cd '{}' +case "$3" in +status) cat state ;; +logs) + if ! mkdir active-stream; then touch overlapping-streams; exit 1; fi + trap 'rmdir active-stream' EXIT + cat history + ;; +esac +"#, + root.display() + ), + ); + std::fs::write(root.join("state"), r#"{"stage":"RUNNING"}"#).unwrap(); + std::fs::write(root.join("history"), "first\n").unwrap(); + let engine = Arc::new(engine(&root)); + let clock = Arc::new(TestClock::new()); + let runtime = crate::engine::runtime::Runtime::new( + engine.clone(), + clock.clone(), + root.join("store"), + None, + ); + let handle = super::api::test_handle("modal_job", None, None, vec!["sandbox".into()]); + let row = crate::store::StoredRun { + id: "run".into(), + experiment_id: "exp".into(), + project_id: "proj".into(), + status: "running".into(), + backend_json: crate::engine::handle::backend_json( + "run", + Some(&handle), + &BackendDescriptor::parse(r#"{"kind":"modal_job"}"#).unwrap(), + ) + .unwrap(), + command: "true".into(), + created_at: 1, + updated_at: 1, + ended_at: None, + exit_code: None, + commit_sha: None, + result_markdown: None, + cancel_requested: false, + cancel_reason: None, + chat_session_id: None, + }; + engine.store().upsert_run(&row).unwrap(); + let backend = runtime.backend(&row).unwrap(); + let run = WatchedRun { + id: "run".into(), + handle, + }; + let whole = ByteRange { + start: 0, + end: orx_host_proto::MAX_PAGE_LEN, + }; + backend.drain_log(&run).await.unwrap(); + let observations = backend + .observe(std::slice::from_ref(&run), Duration::from_secs(5)) + .await; + assert!(observations.contains(&("run".into(), Observation::Running { started_at: None }))); + std::fs::write(root.join("history"), "first\nsecond\n").unwrap(); + clock.advance(Duration::from_secs(10)); + backend + .observe(std::slice::from_ref(&run), Duration::from_secs(5)) + .await; + backend.drain_log(&run).await.unwrap(); + let page = backend + .read_log(&run, LogFile::Log, whole, None) + .await + .unwrap(); + assert!(matches!(page, LogPage::Data { bytes, .. } if bytes == b"first\nsecond\n")); + std::fs::write(root.join("history"), "first\nsecond\nlast\n").unwrap(); + std::fs::write(root.join("state"), r#"{"stage":"COMPLETED"}"#).unwrap(); + clock.advance(Duration::from_secs(10)); + let observations = backend + .observe(std::slice::from_ref(&run), Duration::from_secs(5)) + .await; + assert!(observations + .iter() + .any(|(_, observation)| observation.ends_run())); + engine + .apply_observations(backend.as_ref(), &[run], observations) + .await + .unwrap(); + runtime.start(); + tokio::time::timeout(Duration::from_secs(30), async { + while engine.store().log_collection_pending("run").unwrap() { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("final log was not kept"); + assert_eq!( + std::fs::read(root.join("store/run-logs/run.log")).unwrap(), + b"first\nsecond\nlast\n" + ); + assert!(!root.join("overlapping-streams").exists()); + assert!(!root.join("active-stream").exists()); +} + +#[tokio::test] +async fn finished_modal_logs_drain_through_pauses_before_they_are_kept() { + let Some(root) = + isolated("finished_modal_logs_drain_through_pauses_before_they_are_kept").await + else { + return; + }; + script( + &root.join("bin/modal-python"), + "#!/bin/sh\nprintf 'first\\n'\nsleep 11\nprintf 'last\\n'\n", + ); + let backend = super::api::Adapter::new( + ModalAccount, + Arc::new(TestClock::new()), + root.join("spools"), + ); + let run = WatchedRun { + id: "drained".into(), + handle: crate::engine::adapters::api::test_handle( + "modal_job", + None, + None, + vec!["sandbox".into()], + ), + }; + let whole = ByteRange { + start: 0, + end: orx_host_proto::MAX_PAGE_LEN, + }; + let LogPage::Data { bytes, .. } = backend + .read_log(&run, LogFile::Log, whole.clone(), None) + .await + .unwrap() + else { + panic!("no live log page") + }; + assert_eq!(bytes, b"first\n"); + backend.drain_log(&run).await.unwrap(); + let LogPage::Data { bytes, eof, .. } = backend + .read_log(&run, LogFile::Log, whole, None) + .await + .unwrap() + else { + panic!("no drained log page") + }; + assert!(eof); + assert_eq!(bytes, b"first\nlast\n"); +} + +/// A pod lookup that fails, or finds no pod yet, is never a closed stream: draining errs, and +/// the log stays owed. +#[tokio::test] +async fn kubernetes_lookup_failures_never_complete_a_drain() { + use super::api::Api; + let Some(root) = isolated("kubernetes_lookup_failures_never_complete_a_drain").await else { + return; + }; + let run = WatchedRun { + id: "k8s".into(), + handle: crate::engine::adapters::api::test_handle( + "k8s_job", + Some("default"), + None, + vec!["job/job".into()], + ), + }; + for get in [ + "echo 'Unable to connect to the server' >&2; exit 1", + "printf '{\"items\":[]}'", + ] { + script( + &root.join("bin/kubectl"), + &format!("#!/bin/sh\ncase \"$1\" in\nget) {get} ;;\nlogs) exit 0 ;;\nesac\n"), + ); + let account = K8sAccount { + context: None, + namespace: "default".into(), + }; + let mut cursor = crate::jobs::kubernetes::LogResume::default(); + let closed = account + .logs(&run, &mut cursor, Duration::from_secs(5), &mut |_| {}) + .await; + assert!(!matches!(closed, Ok(true)), "{get}: {closed:?}"); + let backend = + super::api::Adapter::new(account, Arc::new(TestClock::new()), root.join("spools")); + assert!(backend.drain_log(&run).await.is_err(), "{get}"); + } +} + +#[tokio::test] +async fn empty_stream_timeouts_surface_for_hf_modal_and_kubernetes() { + use super::api::Api; + let Some(root) = isolated("empty_stream_timeouts_surface_for_hf_modal_and_kubernetes").await + else { + return; + }; + std::fs::write(root.join("slow-logs"), "").unwrap(); + script( + &root.join("bin/modal-python"), + "#!/bin/sh\nprintf 'download\n' >> \"$ORX_API_ROOT/downloads\"\nexec sleep 5\n", + ); + script( + &root.join("bin/kubectl"), + r#"#!/bin/sh +case "$1" in +get) printf '{"items":[{"metadata":{"name":"pod-1"}}]}' ;; +logs) exec sleep 5 ;; +esac +"#, + ); + let hf = HfAccount { + namespace: "org".into(), + }; + let hf_run = WatchedRun { + id: "hf".into(), + handle: crate::engine::adapters::api::test_handle( + "hf_job", + Some("org"), + None, + vec!["job".into()], + ), + }; + let mut hf_cursor = 0; + assert!(hf + .logs(&hf_run, &mut hf_cursor, Duration::from_secs(1), &mut |_| {}) + .await + .unwrap_err() + .to_string() + .contains("timed out")); + assert_eq!(hf_cursor, 0); + let modal_run = WatchedRun { + id: "modal".into(), + handle: crate::engine::adapters::api::test_handle( + "modal_job", + None, + None, + vec!["sandbox".into()], + ), + }; + let mut modal_cursor = 0; + assert!(ModalAccount + .logs( + &modal_run, + &mut modal_cursor, + Duration::from_secs(1), + &mut |_| {} + ) + .await + .unwrap_err() + .to_string() + .contains("timed out")); + assert_eq!(modal_cursor, 0); + let k8s = K8sAccount { + context: None, + namespace: "default".into(), + }; + let k8s_run = WatchedRun { + id: "k8s".into(), + handle: crate::engine::adapters::api::test_handle( + "k8s_job", + Some("default"), + None, + vec!["job/job".into()], + ), + }; + assert!(k8s + .logs( + &k8s_run, + &mut crate::jobs::kubernetes::LogResume::default(), + Duration::from_secs(1), + &mut |_| {} + ) + .await + .unwrap_err() + .to_string() + .contains("timed out")); + let backend = super::api::Adapter::new( + ModalAccount, + Arc::new(TestClock::new()), + root.join("spools"), + ); + for _ in 0..2 { + assert!(backend + .read_log( + &modal_run, + LogFile::Log, + ByteRange { start: 0, end: 1 }, + None + ) + .await + .unwrap_err() + .to_string() + .contains("timed out")); + } + assert_eq!( + std::fs::read_to_string(root.join("downloads")) + .unwrap() + .lines() + .count(), + 2 + ); +} + +#[tokio::test] +async fn vercel_uses_api_handles_and_adopts_legacy_sandboxes() { + let Some(root) = isolated("vercel_uses_api_handles_and_adopts_legacy_sandboxes").await else { + return; + }; + script( + &root.join("bin/vercel-python"), + &format!( + r#"#!/bin/sh +case "$3" in + submit) cat > '{root}/submitted.json'; printf '{{"sandboxName":"orx-run","processId":"proc-1"}}' ;; + status) + [ "$4" = orx-run ] && [ "$5" = proc-1 ] || exit 1 + if [ -f '{root}/cancelled' ]; then + printf '{{"stage":"CANCELED"}}' + else + printf '{{"stage":"RUNNING"}}' + fi ;; + logs) printf 'first\nlast\n' ;; + cancel) touch '{root}/cancelled' ;; + finish) touch '{root}/destroyed' ;; + *) exit 1 ;; +esac +"#, + root = root.display() + ), + ); + let engine = engine(&root); + let metadata = BackendDescriptor::parse(r#"{"kind":"vercel_job"}"#).unwrap(); + let launch = LaunchSpec { + kind: "vercel_job".into(), + target: None, + options: json!({ + "name":"ignored", "script":"true", "image":"python", "vcpus":2, + "env":{"VERCEL_TOKEN":"secret", "VERCEL_OIDC_TOKEN":"secret", "KEEP":"yes"}, + "timeout_seconds":60, "session_cap":2700, "region":null, "tags":{}, + "source_archive":null + }), + }; + let adapter = (super::api::provider("vercel_job").unwrap().build)( + &crate::engine::handle::ApiAccount { + target: None, + context: None, + }, + Arc::new(TestClock::new()), + root.join("spools"), + ) + .unwrap(); + engine + .submit(adapter.as_ref(), pending("run", &metadata, &launch)) + .await + .unwrap(); + let run = engine.load("run").unwrap().0; + let watched = WatchedRun { + id: run.id.clone(), + handle: handle_of(&run).unwrap(), + }; + assert!(matches!(&watched.handle, Handle::Api { provider, ids, .. } + if provider == "vercel_job" && ids == &["orx-run", "proc-1"])); + let submitted: Value = + serde_json::from_slice(&std::fs::read(root.join("submitted.json")).unwrap()).unwrap(); + assert_eq!(submitted["name"], "orx-run"); + assert_eq!(submitted["tags"]["or_run"], "run"); + assert_eq!(submitted["env"]["KEEP"], "yes"); + assert!(!submitted["env"] + .as_object() + .unwrap() + .keys() + .any(|key| key.starts_with("VERCEL_"))); + adapter.drain_log(&watched).await.unwrap(); + let page = adapter + .read_log( + &watched, + LogFile::Log, + ByteRange { start: 0, end: 11 }, + None, + ) + .await + .unwrap(); + assert!(matches!(page, LogPage::Data { bytes, .. } if bytes == b"first\nlast\n")); + engine + .cancel(adapter.as_ref(), "run", "stop") + .await + .unwrap(); + engine + .observe_runs( + adapter.as_ref(), + std::slice::from_ref(&watched), + Duration::from_secs(1), + ) + .await + .unwrap(); + assert_eq!(engine.load("run").unwrap().0.status, "cancelled"); + adapter.finish(&watched).await.unwrap(); + assert!(root.join("destroyed").exists()); + let legacy = WatchedRun { + id: "legacy".into(), + handle: Handle::Legacy { + descriptor: Box::new( + BackendDescriptor::parse( + r#"{"kind":"vercel_job","namespace":"orx-run","jobId":"proc-1"}"#, + ) + .unwrap(), + ), + }, + }; + assert!(matches!( + adapter.cancel(&legacy).await, + CancelOutcome::Pending + )); + adapter.finish(&legacy).await.unwrap(); + let mut legacy_row = run.clone(); + legacy_row.id = legacy.id.clone(); + legacy_row.updated_at = 1; + legacy_row.backend_json = serde_json::json!({ + "kind":"vercel_job", "namespace":"orx-run", "jobId":"proc-1" + }) + .to_string(); + engine.store().upsert_run(&legacy_row).unwrap(); + let adopted = engine.scan_legacy(true).unwrap(); + assert!(adopted.iter().any(|(id, adoption)| { + id == "legacy" + && matches!(adoption, + crate::engine::legacy::Adoption::Native { kind } if kind == "vercel_job") + })); + let intent = RunIntent { + run, + launch, + spec_digest: "digest".into(), + attempt: 1, + }; + assert!(matches!( + adapter.recover(&intent).await, + Recovery::Unknown { .. } + )); +} + +#[tokio::test] +async fn providers_reject_credentials_and_preserve_numeric_exits() { + let Some(root) = isolated("providers_reject_credentials_and_preserve_numeric_exits").await + else { + return; + }; + for launcher in ["modal-python", "vercel-python", "kubectl"] { + script( + &root.join("bin").join(launcher), + &format!( + r#"#!/bin/sh +cd '{}' +if test -f inspect-error; then cat inspect-error >&2; exit 1; fi +case "$*" in + *"get pods"*) cat pods.json ;; + *) cat inspect-response.json ;; +esac +"#, + root.display() + ), + ); + } + let engine = engine(&root); + let endpoint = std::env::var("HF_ENDPOINT").unwrap(); + for (kind, response, rejection) in [ + ("ray_job", json!({"status":"FAILED", "driver_exit_code":7}), ""), + ("hf_job", json!({"id":"job", "status":{"stage":"ERROR", "message":"Job failed with exit code: 7. Reason: Error"}}), ""), + ("vercel_job", json!({"stage":"ERROR", "exitCode":7}), "vercel.sandbox._internal.errors.SandboxApiError: HTTP 403: Not authorized (code=forbidden)"), + ("modal_job", json!({"stage":"ERROR", "exitCode":7}), "modal.exception.AuthError: Token is not authorized"), + ("k8s_job", json!({"status":{"conditions":[{"type":"Failed","status":"True","reason":"BackoffLimitExceeded"}]}}), "Error from server (Forbidden): jobs.batch is forbidden"), + ] { + let target = if kind == "ray_job" { + endpoint.as_str() + } else { + "org" + }; + let ids = match kind { + "vercel_job" => vec!["box".into(), "process".into()], + "k8s_job" => vec!["job/job".into()], + _ => vec!["job".into()], + }; + let handle = super::api::test_handle(kind, Some(target), None, ids); + let metadata = BackendDescriptor::parse(&json!({"kind":kind}).to_string()).unwrap(); + engine.store().upsert_run(&crate::store::StoredRun { + id: kind.into(), + experiment_id: "exp".into(), + project_id: "proj".into(), + status: "running".into(), + backend_json: crate::engine::handle::backend_json(kind, Some(&handle), &metadata).unwrap(), + command: "exit 7".into(), + created_at: 1, + updated_at: 1, + ended_at: None, + exit_code: None, + commit_sha: None, + result_markdown: None, + cancel_requested: false, + cancel_reason: None, + chat_session_id: None, + }).unwrap(); + + let clock = Arc::new(TestClock::new()); + let provider = super::api::provider(kind).unwrap(); + let adapter = (provider.build)( + &crate::engine::handle::ApiAccount { + target: Some(target.into()), + context: None, + }, + clock.clone(), + root.join("spools"), + ).unwrap(); + let runs = [WatchedRun { id: kind.into(), handle }]; + std::fs::write(root.join("inspect-response.json"), response.to_string()).unwrap(); + std::fs::write(root.join("pods.json"), json!({"items":[{ + "metadata":{"annotations":{"kubectl.kubernetes.io/default-container":"main"}}, + "status":{"containerStatuses":[ + {"name":"sidecar", "state":{"terminated":{"exitCode":99}}}, + {"name":"main", "state":{"terminated":{"exitCode":7}}} + ]} + }]}).to_string()).unwrap(); + + let rejections = match kind { + "ray_job" | "hf_job" => vec![("401", true), ("403", true), ("503", false)], + "vercel_job" => vec![ + ("SandboxApiError: HTTP 401: Unauthorized", true), + (rejection, true), + ("connection timed out", false), + ], + "modal_job" => vec![ + ("GRPCError: (, 'Token rejected')", true), + ("GRPCError: (, 'Access denied')", true), + (rejection, true), + ("connection timed out", false), + ], + _ => vec![ + ("Error from server (Unauthorized): You must be logged in to the server", true), + (rejection, true), + ("connection timed out", false), + ], + }; + for (rejection, needs_auth) in rejections { + let file = if kind == "ray_job" || kind == "hf_job" { + "inspect-status" + } else { + "inspect-error" + }; + std::fs::write(root.join(file), rejection).unwrap(); + let observations = adapter.observe(&runs, Duration::from_secs(5)).await; + assert_eq!(observations.len(), 1, "{kind}: {observations:?}"); + let (_, observation) = observations.into_iter().next().unwrap(); + assert!( + matches!( + (needs_auth, &observation), + (true, Observation::NeedsAuth { .. }) | (false, Observation::Unreachable { .. }) + ), + "{kind}: {observation:?}" + ); + engine.observe(kind, observation).unwrap(); + assert_eq!(engine.load(kind).unwrap().0.status, "running"); + assert_eq!( + matches!(engine.load(kind).unwrap().1.contact, crate::store::Contact::NeedsAuth { .. }), + needs_auth + ); + std::fs::remove_file(root.join(file)).unwrap(); + clock.advance(Duration::from_secs(10)); + } + for (_, observation) in adapter.observe(&runs, Duration::from_secs(5)).await { + engine.observe(kind, observation).unwrap(); + } + + let row = engine.load(kind).unwrap().0; + assert_eq!(row.status, "failed", "{kind}"); + assert_eq!(row.exit_code, Some(7), "{kind}"); + + let cancel_id = format!("{kind}-cancel"); + let cancel_runs = [WatchedRun { + id: cancel_id.clone(), + handle: runs[0].handle.clone(), + }]; + let pending_cancel = crate::store::StoredRun { + id: cancel_id.clone(), + status: "running".into(), + exit_code: None, + ended_at: None, + ..row + }; + engine.store().upsert_run(&pending_cancel).unwrap(); + assert!(engine.store().accept_run_cancel(&cancel_id, Some("Dashboard stop")).unwrap().is_some()); + let response = match kind { + "ray_job" => json!({"status":"FAILED", "driver_exit_code":137}), + "hf_job" => json!({"id":"job", "status":{"stage":"ERROR", "message":"Job failed with exit code: 137. Reason: Error"}}), + "k8s_job" => response, + _ => json!({"stage":"ERROR", "exitCode":137}), + }; + std::fs::write(root.join("inspect-response.json"), response.to_string()).unwrap(); + clock.advance(Duration::from_secs(10)); + for (id, observation) in adapter.observe(&cancel_runs, Duration::from_secs(5)).await { + engine.observe(&id, observation).unwrap(); + } + let row = engine.load(&cancel_id).unwrap().0; + assert_eq!(row.status, "cancelled", "{kind}"); + assert_eq!(row.exit_code, Some(if kind == "k8s_job" { 7 } else { 137 }), "{kind}"); + } +} + +#[tokio::test] +async fn hf_exit_evidence_requires_the_provider_failure_format() { + let Some(root) = isolated("hf_exit_evidence_requires_the_provider_failure_format").await else { + return; + }; + let account = HfAccount { + namespace: "org".into(), + }; + let run = WatchedRun { + id: "run".into(), + handle: super::api::test_handle("hf_job", Some("org"), None, vec!["job".into()]), + }; + for (stage, message, expected) in [ + ( + "ERROR", + "Job failed with exit code: 7. Reason: Error", + Some(7), + ), + ( + "ERROR", + "Job failed with exit code: -7. Reason: Error", + Some(-7), + ), + ( + "ERROR", + "Job failed with exit code: seven. Reason: Error", + None, + ), + ("ERROR", "Could not start: image unavailable", None), + ] { + std::fs::write( + root.join("inspect-response.json"), + json!({"id":"job", "status":{"stage":stage, "message":message}}).to_string(), + ) + .unwrap(); + let observation = super::api::Api::inspect(&account, &run).await.unwrap(); + match expected { + Some(code) => assert_eq!( + observation, + Observation::Exited { + finished_at: None, + code: Some(code), + signal: None + } + ), + None => assert_eq!( + observation, + Observation::Failed { + finished_at: None, + reason: message.into() + } + ), + } + } +} diff --git a/src/engine/adapters/hf.rs b/src/engine/adapters/hf.rs new file mode 100644 index 000000000..8abd4927b --- /dev/null +++ b/src/engine/adapters/hf.rs @@ -0,0 +1,105 @@ +use super::api::{self, Api}; +use crate::engine::*; +use crate::error::Result; +use crate::jobs::huggingface as hf; +use crate::local::trackio; +use async_trait::async_trait; + +pub struct HfAccount { + pub namespace: String, +} +impl HfAccount { + fn id<'a>(&self, run: &'a WatchedRun) -> Result<&'a str> { + api::id(run, "hf_job", Some(&self.namespace), None) + } +} + +#[async_trait] +impl Api for HfAccount { + type Cursor = u64; + + async fn launch(&self, intent: &RunIntent, fence: &Fence<'_>) -> Result { + let mut spec: hf::JobSubmission = + serde_json::from_value(intent.launch.options.clone()).map_err(api::rejected)?; + let token = hf::resolve_token().map_err(api::rejected)?; + spec.labels.insert("or_run".into(), intent.run.id.clone()); + // Tokens travel as job secrets; the environment carries the run context and Trackio's + // space, never every saved variable. + spec.secrets.insert("HF_TOKEN".into(), token.clone()); + for key in [trackio::SERVER_URL, trackio::WRITE_TOKEN] { + if let Some(value) = crate::config::synced_env_var(key) { + spec.secrets.insert(key.into(), value); + } + } + spec.environment + .extend(crate::config::run_context_env(&intent.run.id)); + if let Some(space) = crate::config::synced_env_var(trackio::SPACE_ID) { + spec.environment.insert(trackio::SPACE_ID.into(), space); + } + let descriptor = crate::jobs::BackendDescriptor::parse(&intent.run.backend_json) + .map_err(api::rejected)?; + let source = crate::compute::SourceSnapshot::from_run(&intent.run, &descriptor) + .map_err(api::rejected)?; + let job = hf::run_job_with_source( + &token, + &self.namespace, + &spec, + &source.path, + &source.digest, + Some(fence), + ) + .await + .map_err(api::interrupted)?; + Ok(api::handle(intent, vec![job.id])) + } + async fn recover(&self, intent: &RunIntent) -> Recovery { + let token = match hf::resolve_token() { + Ok(token) => token, + Err(error) => return api::unknown(error), + }; + match hf::find_run(&token, &self.namespace, &intent.run.id).await { + Ok(jobs) if jobs.is_empty() => Recovery::Absent, + Ok(jobs) if jobs.len() == 1 => { + Recovery::Found(api::handle(intent, vec![jobs[0].id.clone()])) + } + Ok(_) => api::unknown("Multiple HF jobs carry this run label"), + Err(error) => api::unknown(error), + } + } + async fn inspect(&self, run: &WatchedRun) -> Result { + let job = hf::inspect_job(&hf::resolve_token()?, &self.namespace, self.id(run)?).await?; + let exit_code = job.status.message.as_deref() + .and_then(|message| message.strip_prefix("Job failed with exit code: ")) + .and_then(|message| message.split_once(". Reason:")) + .and_then(|(code, _)| code.parse().ok()); + Ok(api::stage(&job.status.stage, job.status.message, exit_code, None, None)) + } + async fn cancel(&self, run: &WatchedRun) -> Result<()> { + hf::cancel_job(&hf::resolve_token()?, &self.namespace, self.id(run)?).await + } + async fn logs( + &self, + run: &WatchedRun, + cursor: &mut u64, + window: std::time::Duration, + sink: &mut (dyn for<'b> FnMut(&'b [u8]) + Send), + ) -> Result { + let token = hf::resolve_token()?; + let mut received = 0; + let outcome = { + let mut lines = api::lines(sink, &mut received); + let pass = hf::stream_logs( + &token, + &self.namespace, + self.id(run)?, + *cursor, + None, + &mut lines, + ); + tokio::time::timeout(window, pass).await + }; + let closed = api::closed(outcome, received)?; + *cursor += received; + Ok(closed.is_some()) + } +} diff --git a/src/engine/adapters/k8s.rs b/src/engine/adapters/k8s.rs new file mode 100644 index 000000000..d6228220c --- /dev/null +++ b/src/engine/adapters/k8s.rs @@ -0,0 +1,262 @@ +use super::api::{self, Api}; +use crate::engine::*; +use crate::error::{anyhow, Result}; +use crate::jobs::kubernetes as k8s; +use async_trait::async_trait; + +pub struct K8sAccount { + pub context: Option, + pub namespace: String, +} +impl K8sAccount { + fn resources(&self, run: &WatchedRun) -> Result> { + let id = api::id( + run, + "k8s_job", + Some(&self.namespace), + self.context.as_deref(), + )?; + Ok(match &run.handle { + Handle::Api { ids, .. } => ids.clone(), + Handle::Legacy { descriptor } => descriptor + .resources + .clone() + .unwrap_or_else(|| vec![format!("job/{id}")]), + _ => unreachable!(), + }) + } + + fn spec(&self, intent: &RunIntent) -> Result { + let mut spec: k8s::ManifestSpec = serde_json::from_value(intent.launch.options.clone())?; + spec.labels.insert("or_run".into(), intent.run.id.clone()); + spec.env.extend(crate::config::list_synced_env()); + if let Ok(token) = crate::jobs::huggingface::resolve_token() { + spec.env.entry("HF_TOKEN".into()).or_insert(token); + } + spec.pod_env = crate::config::run_context_env(&intent.run.id); + Ok(spec) + } + fn handle(intent: &RunIntent, mut resources: Vec, job: &str) -> Handle { + let primary = format!("job/{job}"); + if let Some(index) = resources.iter().position(|resource| resource == &primary) { + resources.swap(0, index); + } + api::handle(intent, resources) + } + fn job(&self, run: &WatchedRun) -> Result { + let resources = self.resources(run)?; + if let Handle::Legacy { descriptor } = &run.handle { + return Ok(descriptor.k8s_ref()?.1.to_owned()); + } + resources + .iter() + .find_map(|resource| resource.strip_prefix("job/").map(str::to_owned)) + .ok_or_else(|| anyhow!("Kubernetes handle has no Job")) + } +} +#[async_trait] +impl Api for K8sAccount { + type Cursor = k8s::LogResume; + + async fn launch(&self, intent: &RunIntent, fence: &Fence<'_>) -> Result { + let spec = self.spec(intent).map_err(api::rejected)?; + let submitted = k8s::run_manifest(self.context.as_deref(), &self.namespace, &spec, Some(fence)) + .await + .map_err(api::interrupted)?; + Ok(Self::handle( + intent, + submitted.resources, + &submitted.job_name, + )) + } + async fn recover(&self, intent: &RunIntent) -> Recovery { + match self.resume(intent).await { + Ok(Some(handle)) => Recovery::Found(handle), + Ok(None) => Recovery::Absent, + Err(error) => api::unknown(error), + } + } + async fn inspect(&self, run: &WatchedRun) -> Result { + let state = + k8s::inspect_job(self.context.as_deref(), &self.namespace, &self.job(run)?).await?; + if state.stage == "DELETED" { + let selector = format!("job-name={}", self.job(run)?); + let body = k8s::kubectl( + self.context.as_deref(), + &[ + "get", + "pods", + "-n", + &self.namespace, + "-l", + &selector, + "-o", + "json", + ], + None, + ) + .await?; + let pods: serde_json::Value = serde_json::from_str(&body)?; + return Ok(if pods["items"].as_array().is_some_and(Vec::is_empty) { + Observation::Gone { + reason: + "Outcome unavailable: the Job was deleted before orx recorded its outcome" + .into(), + } + } else { + Observation::Unreconciled { + detail: "Deleted Job still has pods".into(), + } + }); + } + Ok(api::stage(&state.stage, state.message, state.exit_code, None, None)) + } + async fn cancel(&self, run: &WatchedRun) -> Result<()> { + k8s::delete_resources( + self.context.as_deref(), + &self.namespace, + &self.resources(run)?, + ) + .await + } + async fn logs( + &self, + run: &WatchedRun, + cursor: &mut k8s::LogResume, + window: std::time::Duration, + sink: &mut (dyn for<'b> FnMut(&'b [u8]) + Send), + ) -> Result { + let mut resume = cursor.clone(); + let job = self.job(run)?; + let mut received = 0; + let outcome = { + let mut lines = api::lines(sink, &mut received); + let pass = k8s::stream_logs( + self.context.as_deref(), + &self.namespace, + &job, + &mut resume, + None, + &mut lines, + ); + tokio::time::timeout(window, pass).await + }; + let closed = api::closed(outcome, received)?; + *cursor = resume; + Ok(closed == Some(true)) + } +} +impl K8sAccount { + async fn resume(&self, intent: &RunIntent) -> Result> { + let spec = self.spec(intent)?; + let (docs, job) = + k8s::prepared_manifest(self.context.as_deref(), &self.namespace, &spec).await?; + let expected: Vec = docs.iter().map(k8s::resource_handle).collect(); + let kinds: std::collections::BTreeSet<_> = expected + .iter() + .filter_map(|resource| resource.split_once('/').map(|(kind, _)| kind)) + .collect(); + let kinds = kinds.into_iter().collect::>().join(","); + let selector = format!("or_run={}", intent.run.id); + let body = k8s::kubectl( + self.context.as_deref(), + &[ + "get", + &kinds, + "-n", + &self.namespace, + "-l", + &selector, + "-o", + "json", + ], + None, + ) + .await?; + let value: serde_json::Value = serde_json::from_str(&body)?; + let found: Vec = value["items"] + .as_array() + .ok_or_else(|| anyhow!("Missing Kubernetes items"))? + .iter() + .map(k8s::resource_handle) + .collect(); + if found.is_empty() { + return Ok(None); + } + if found.len() != expected.len() + || !expected.iter().all(|resource| found.contains(resource)) + { + if !found.contains(&format!("job/{job}")) { + return Err(anyhow!("Kubernetes Job is missing while other run resources remain; it may have completed")); + } + k8s::delete_resources(self.context.as_deref(), &self.namespace, &found).await?; + let remaining = k8s::kubectl( + self.context.as_deref(), + &[ + "get", + &kinds, + "-n", + &self.namespace, + "-l", + &selector, + "-o", + "json", + ], + None, + ) + .await?; + let remaining: serde_json::Value = serde_json::from_str(&remaining)?; + if !remaining["items"].as_array().is_some_and(Vec::is_empty) { + return Err(anyhow!( + "Partial Kubernetes resources are still terminating" + )); + } + return Ok(None); + } + let state = k8s::inspect_job(self.context.as_deref(), &self.namespace, &job).await?; + if !crate::jobs::is_terminal_stage(&state.stage) { + k8s::stage_source( + self.context.as_deref(), + &self.namespace, + &job, + &spec.source_archive, + ) + .await?; + } + Ok(Some(Self::handle(intent, expected, &job))) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn adopted_runs_keep_the_recorded_primary_and_pre_resource_cancel_target() { + let account = K8sAccount { + context: None, + namespace: "default".into(), + }; + for resources in [ + serde_json::Value::Null, + serde_json::json!(["job/worker", "job/primary"]), + ] { + let descriptor = crate::jobs::BackendDescriptor::parse(&serde_json::json!({ + "kind":"k8s_job", "namespace":"default", "jobId":"primary", "resources":resources + }).to_string()).unwrap(); + let run = WatchedRun { + id: "run".into(), + handle: Handle::Legacy { + descriptor: Box::new(descriptor), + }, + }; + assert_eq!(account.job(&run).unwrap(), "primary"); + let expected = if resources.is_null() { + vec!["job/primary"] + } else { + vec!["job/worker", "job/primary"] + }; + assert_eq!(account.resources(&run).unwrap(), expected); + } + } +} diff --git a/src/engine/adapters/local.rs b/src/engine/adapters/local.rs new file mode 100644 index 000000000..411bb08f4 --- /dev/null +++ b/src/engine/adapters/local.rs @@ -0,0 +1,550 @@ +use std::fs::{self, OpenOptions}; +#[cfg(windows)] +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::process::Stdio; +use std::time::Duration; + +use async_trait::async_trait; + +use super::super::{ + Backend, ByteRange, CancelOutcome, Fence, FileIdent, Handle, LaunchError, LogFile, LogPage, + Observation, Recovery, RunIntent, WatchedRun, +}; +use super::ssh::LaunchOptions; +use crate::error::{anyhow, bail, Result}; +use crate::jobs::localbox; + +#[path = "../../../crates/orx-host/src/log.rs"] +pub(super) mod log; + +pub struct Local { + root: PathBuf, +} + +impl Local { + pub fn new(root: PathBuf) -> Self { + Self { root } + } + + fn directory(&self, intent: &RunIntent) -> Result { + if intent.run.id.is_empty() + || !intent + .run + .id + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b"_-".contains(&b)) + { + bail!("Invalid local run id"); + } + Ok(self.root.join(&intent.run.id)) + } + + fn handle(&self, intent: &RunIntent, dir: &Path) -> Handle { + let dir = dir.to_string_lossy().into_owned(); + if matches!(intent.launch.kind.as_str(), "tinker" | "tinker_job") { + Handle::Tinker { dir } + } else { + Handle::Local { dir } + } + } + + fn dir<'a>(&self, run: &'a WatchedRun) -> Result<&'a Path> { + let dir = match &run.handle { + Handle::Local { dir } | Handle::Tinker { dir } => dir, + Handle::Legacy { descriptor } + if matches!(descriptor.kind.as_str(), "local_job" | "tinker_job") => + { + descriptor + .job_id + .as_deref() + .ok_or_else(|| anyhow!("Local directory missing"))? + } + _ => bail!("Run {} is not local", run.id), + }; + Ok(Path::new(dir)) + } + + pub(crate) fn cleanup(&self, run: &WatchedRun) -> Result { + #[cfg(unix)] + return Ok(orx_host::wrapper::cleanup(self.dir(run)?)?); + #[cfg(windows)] + { + localbox::cancel_job(self.dir(run)?)?; + Ok(orx_host_proto::CleanupAck::NothingLingering) + } + } + + async fn start( + &self, + intent: &RunIntent, + cancelled: &(dyn Fn() -> bool + Sync), + ) -> Result { + #[cfg(windows)] + let _ = cancelled; + let dir = self.directory(intent)?; + let options: LaunchOptions = serde_json::from_value(intent.launch.options.clone())?; + fs::create_dir_all(&dir)?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(&dir, fs::Permissions::from_mode(0o700))?; + } + let ownership = OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .open(dir.join("launch.lock"))?; + ownership.lock()?; + let launch = dir.join("launch.json"); + #[cfg(unix)] + let existing = match orx_host::read_json::(&launch) { + Ok(existing) + if existing.run == intent.run.id && existing.digest == intent.spec_digest => + { + Some((existing.run_sh, existing.env)) + } + Ok(_) => bail!("Local launch intent differs"), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => None, + Err(error) => return Err(error.into()), + }; + #[cfg(windows)] + match fs::read_to_string(&launch) { + Ok(digest) if digest != intent.spec_digest => bail!("Local launch intent differs"), + Ok(_) => {} + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + let temporary = dir.join(format!("launch-{}.tmp", uuid::Uuid::new_v4())); + let mut file = std::fs::File::create(&temporary)?; + file.write_all(intent.spec_digest.as_bytes())?; + file.sync_all()?; + let published = fs::hard_link(&temporary, &launch); + fs::remove_file(temporary)?; + published?; + } + Err(error) => return Err(error.into()), + } + if dir.join("started").try_exists()? + || dir.join("exit_code").try_exists()? + || dir.join("exit.json").try_exists()? + { + return Ok(self.handle(intent, &dir)); + } + let prepare = || -> Result<(String, std::collections::BTreeMap)> { + let payload = match options.run_sh { + Some(script) => script, + None => { + let metadata = crate::jobs::BackendDescriptor::parse(&intent.run.backend_json)?; + match metadata.source_path { + Some(path) => crate::compute::snapshot_script( + &crate::local::bash::bash_path(Path::new(&path)), + &crate::local::bash::local_run_command(&intent.run.command), + ), + None => intent.run.command.clone(), + } + } + }; + let mut env = crate::config::launch_env(&intent.run.id); + env.insert( + crate::compute::TENSORBOARD_LOGDIR.into(), + dir.join("tensorboard").to_string_lossy().into_owned(), + ); + env.extend(crate::local::trackio::local_run_env()); + crate::local::shell_env::export_to(|key, value| { + env.insert(key.into(), value.to_string_lossy().into_owned()); + }); + env.extend(options.env); + if matches!(intent.launch.kind.as_str(), "tinker" | "tinker_job") { + env.insert( + crate::jobs::tinker::API_KEY_ENV.into(), + crate::jobs::tinker::resolve_api_key()?, + ); + } + let mut env = crate::jobs::default_python_env(&env); + if let Some(path) = + crate::local::bash::path_with_toolchain(crate::local::shell_env::search_path()) + { + env.entry("PATH".into()) + .or_insert_with(|| path.to_string_lossy().into_owned()); + } + Ok((payload, env.into_iter().collect())) + }; + #[cfg(unix)] + let (payload, env) = match existing { + Some(accepted) => accepted, + None => prepare()?, + }; + #[cfg(windows)] + let (payload, env) = prepare()?; + #[cfg(unix)] + { + if !launch.try_exists()? { + orx_host::publish( + &launch, + &orx_host_proto::LaunchIntent { + run: intent.run.id.clone(), + digest: intent.spec_digest.clone(), + run_sh: payload.clone(), + env: env.clone(), + source: None, + cancel_sh: None, + }, + )?; + } + if !dir.join("run.sh").try_exists()? { + orx_host::publish_bytes(&dir.join("run.sh"), payload.as_bytes())?; + } + let binary = crate::engine::transport::local_binary(&self.root)?; + if cancelled() { + orx_host::wrapper::cancel(&dir)?; + return Ok(self.handle(intent, &dir)); + } + let diagnostics = OpenOptions::new() + .create(true) + .append(true) + .open(dir.join("wrapper.log"))?; + let status = crate::process::command(crate::local::bash::program()) + .args(["-c", "\"$@\" &", "orx-local"]) + .arg(binary) + .arg("wrap") + .arg(crate::paths::canonicalize(&dir)?) + .envs(&env) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(diagnostics) + .status()?; + if !status.success() { + bail!("Could not detach the local wrapper: {status}"); + } + drop(ownership); + let deadline = tokio::time::Instant::now() + Duration::from_secs(5); + while !dir.join("started").try_exists()? && !dir.join("exit.json").try_exists()? { + if cancelled() { + orx_host::wrapper::cancel(&dir)?; + return Ok(self.handle(intent, &dir)); + } + if tokio::time::Instant::now() >= deadline { + bail!( + "Local supervisor start is unconfirmed; see {}", + dir.join("wrapper.log").display() + ); + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + } + #[cfg(windows)] + { + let payload = format!("{}{}", localbox::python::prelude(&dir)?, payload); + fs::write(dir.join("payload.sh"), payload)?; + let script = "#!/usr/bin/env bash\nread -r ready || exit 98\nbash payload.sh > log 2>&1\ncode=$?\nprintf '%s\\n' \"$code\" > exit_code.part\nmv exit_code.part exit_code\nexit \"$code\"\n"; + fs::write(dir.join("run.sh"), script)?; + let script_path = crate::paths::canonicalize(dir.join("run.sh"))?; + fs::write( + dir.join("pid_script"), + script_path.to_string_lossy().as_bytes(), + )?; + let mut command = crate::process::command(crate::local::bash::program()); + command + .arg(crate::local::bash::bash_path(&script_path)) + .envs(&env) + .env("ORX_NOTIFY_FILE", dir.join("notify")) + .current_dir(&dir) + .stdin(Stdio::piped()) + .stdout(Stdio::null()) + .stderr(Stdio::null()); + let mut child = localbox::windows::spawn(&mut command, &dir)?; + let released = (|| -> Result<()> { + fs::write(dir.join("pid"), child.id().to_string())?; + let started = OpenOptions::new() + .write(true) + .create_new(true) + .open(dir.join("started"))?; + started.sync_all()?; + child + .stdin + .take() + .ok_or_else(|| anyhow!("Local launch gate missing"))? + .write_all(b"start\n")?; + Ok(()) + })(); + if let Err(error) = released { + let _ = child.kill(); + let _ = child.wait(); + return Err(error); + } + std::thread::spawn(move || { + let _ = child.wait(); + }); + } + Ok(self.handle(intent, &dir)) + } +} + +#[async_trait] +impl Backend for Local { + async fn launch(&self, intent: &RunIntent, fence: &Fence<'_>) -> Result { + self.directory(intent) + .map_err(|error| LaunchError::Rejected { + reason: error.to_string(), + })?; + match self.start(intent, &|| fence.cancelled()).await { + Ok(handle) => Ok(handle), + Err(error) => match self.recover(intent).await { + Recovery::Absent => Err(LaunchError::Rejected { + reason: error.to_string(), + }), + _ => Err(super::api::interrupted(error)), + }, + } + } + + async fn recover(&self, intent: &RunIntent) -> Recovery { + self.recover_with_cancel(intent, &|| intent.run.cancel_requested) + .await + } + + async fn recover_with_cancel( + &self, + intent: &RunIntent, + cancelled: &(dyn Fn() -> bool + Sync), + ) -> Recovery { + #[cfg(windows)] + let _ = cancelled; + let dir = match self.directory(intent) { + Ok(dir) => dir, + Err(error) => { + return Recovery::Unknown { + detail: error.to_string(), + } + } + }; + #[cfg(unix)] + return match orx_host::read_json::(&dir.join("launch.json")) { + Ok(accepted) + if accepted.run != intent.run.id || accepted.digest != intent.spec_digest => + { + Recovery::Unknown { + detail: "Local launch intent differs".into(), + } + } + Ok(_) if cancelled() => Recovery::Found(self.handle(intent, &dir)), + Ok(_) => match self.start(intent, cancelled).await { + Ok(handle) => Recovery::Found(handle), + Err(error) => Recovery::Unknown { + detail: error.to_string(), + }, + }, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Recovery::Absent, + Err(error) => Recovery::Unknown { + detail: error.to_string(), + }, + }; + #[cfg(windows)] + match fs::read_to_string(dir.join("launch.json")) { + Ok(digest) if digest != intent.spec_digest => Recovery::Unknown { + detail: "Local launch intent differs".into(), + }, + Ok(_) if dir.join("started").exists() || dir.join("exit_code").exists() => { + Recovery::Found(self.handle(intent, &dir)) + } + Ok(_) => Recovery::Absent, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Recovery::Absent, + Err(error) => Recovery::Unknown { + detail: error.to_string(), + }, + } + } + + async fn observe(&self, runs: &[WatchedRun], budget: Duration) -> Vec<(String, Observation)> { + if !runs.is_empty() { + tokio::time::sleep(budget).await; + } + let mut result = Vec::new(); + for run in runs { + let dir = match self.dir(run) { + Ok(dir) => dir, + Err(error) => { + let detail = error.to_string(); + result.push((run.id.clone(), Observation::Unreconciled { detail })); + continue; + } + }; + #[cfg(unix)] + if !matches!(run.handle, Handle::Legacy { .. }) { + let summary = (|| -> std::io::Result { + let len = |file: &str| match fs::metadata(dir.join(file)) { + Ok(metadata) => Ok(metadata.len()), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(0), + Err(error) => Err(error), + }; + Ok(orx_host_proto::Summary { + started_at: orx_host::wrapper::started_at(dir), + state: orx_host::wrapper::state(dir)?, + log_len: Some(len("log")?), + notify_len: len("notify")?, + cleanup: orx_host::wrapper::cleanup_result(dir)?, + }) + })(); + match summary { + Ok(summary) => { + result.extend(super::ssh::observations(run.id.clone(), &summary)) + } + Err(error) if error.kind() == std::io::ErrorKind::InvalidData => result.push(( + run.id.clone(), + Observation::Unreconciled { + detail: error.to_string(), + }, + )), + Err(error) => result.push(( + run.id.clone(), + Observation::Unreachable { + cause: error.to_string(), + }, + )), + } + continue; + } + #[cfg(unix)] + if orx_host::legacy::inspect(dir) + .is_ok_and(|inspection| inspection.pid.is_some() && !inspection.alive) + { + result.push((run.id.clone(), Observation::Lingering { pids: vec![] })); + } + let job = localbox::inspect_job(dir); + let observation = if let Some(code) = job.exit_code { + Observation::Exited { + finished_at: None, + code: Some(code), + signal: None, + } + } else if job.stage == "ERROR" && !localbox::process_group_alive(dir) { + Observation::Failed { + finished_at: None, + reason: job + .message + .unwrap_or_else(|| "Local process died without an exit code".into()), + } + } else { + // A killed launcher whose payload survives in its group is still running. + Observation::Running { started_at: None } + }; + result.push((run.id.clone(), observation)); + let len = |file| fs::metadata(dir.join(file)).map_or(0, |metadata| metadata.len()); + let (log, notify) = (len("log"), len("notify")); + if log > 0 { + result.push((run.id.clone(), Observation::Log { len: log })); + } + if notify > 0 { + result.push((run.id.clone(), Observation::Notify { len: notify })); + } + } + result + } + + async fn cancel(&self, run: &WatchedRun) -> CancelOutcome { + let dir = match self.dir(run) { + Ok(dir) => dir.to_path_buf(), + Err(error) => { + return CancelOutcome::Undelivered { + detail: error.to_string(), + } + } + }; + #[cfg(unix)] + if !matches!(run.handle, Handle::Legacy { .. }) { + return match orx_host::wrapper::cancel(&dir) { + Ok(_) => CancelOutcome::Pending, + Err(error) => CancelOutcome::Undelivered { + detail: format!("Local cancel: {error}"), + }, + }; + } + let result = tokio::task::spawn_blocking(move || -> Result { + localbox::cancel_job(&dir)?; + #[cfg(unix)] + { + let pid: i32 = fs::read_to_string(dir.join("pid"))?.trim().parse()?; + if pid <= 1 { + bail!("Invalid local process group"); + } + for poll in 0..110 { + if !localbox::process_group_alive(&dir) { + return Ok(CancelOutcome::Verified); + } + if poll == 100 { + // The still-existing group retains its id after its leader exits. + unsafe { + libc::kill(-pid, libc::SIGKILL); + } + } + std::thread::sleep(Duration::from_millis(100)); + } + let output = crate::process::command("ps") + .args(["-axo", "pgid=,stat="]) + .output()?; + if !output.status.success() { + bail!("Could not inspect the local process group"); + } + let remaining = String::from_utf8_lossy(&output.stdout) + .lines() + .filter(|line| { + let mut fields = line.split_whitespace(); + fields.next().and_then(|group| group.parse::().ok()) == Some(pid) + && fields.next().is_some_and(|state| !state.starts_with('Z')) + }) + .count(); + Ok(if remaining == 0 { + CancelOutcome::Verified + } else { + CancelOutcome::Survivors { count: remaining } + }) + } + #[cfg(windows)] + Ok(CancelOutcome::Verified) + }) + .await; + match result { + Ok(Ok(outcome)) => outcome, + Ok(Err(error)) => CancelOutcome::Undelivered { + detail: format!("Local cancel: {error}"), + }, + Err(error) => CancelOutcome::Undelivered { + detail: format!("Local cancel: {error}"), + }, + } + } + + async fn cleanup(&self, run: &WatchedRun) -> CancelOutcome { + let outcome = self.cancel(run).await; + if matches!(run.handle, Handle::Legacy { .. }) + || matches!( + outcome, + CancelOutcome::Verified | CancelOutcome::Undelivered { .. } + ) + { + return outcome; + } + match Local::cleanup(self, run) { + Ok(_) => outcome, + Err(error) if error.to_string() == "run has not finished" => CancelOutcome::Pending, + Err(error) => CancelOutcome::Undelivered { + detail: error.to_string(), + }, + } + } + + async fn read_log( + &self, + run: &WatchedRun, + file: LogFile, + range: ByteRange, + ident: Option<&FileIdent>, + ) -> Result { + let dir = self.dir(run)?; + let path = dir.join(match file { + LogFile::Log => "log", + LogFile::Notify => "notify", + }); + Ok(log::read(&path, ident, &range, None)?) + } +} diff --git a/src/engine/adapters/mod.rs b/src/engine/adapters/mod.rs new file mode 100644 index 000000000..a6ed15844 --- /dev/null +++ b/src/engine/adapters/mod.rs @@ -0,0 +1,290 @@ +pub(crate) mod api; +pub mod local; +pub mod openresearch; +pub mod slurm; +pub mod ssh; + +macro_rules! providers { + ($($module:ident => ($kind:literal, |$account:ident| $build:expr)),* $(,)?) => { + $(pub mod $module;)* + pub(crate) const PROVIDERS: &[api::Provider] = &[ + $(api::Provider { + kind: $kind, + build: |$account, clock, spools| { + Ok(std::sync::Arc::new(api::Adapter::new($build, clock, spools))) + }, + }),* + ]; + }; +} + +providers! { + hf => ("hf_job", |account| hf::HfAccount { namespace: account.target()?.into() }), + modal => ("modal_job", |_account| modal::ModalAccount), + k8s => ("k8s_job", |account| k8s::K8sAccount { + context: account.context.clone(), namespace: account.target()?.into() + }), + ray => ("ray_job", |account| ray::RayAccount { address: account.target()?.into() }), + vercel => ("vercel_job", |_account| vercel::VercelAccount), +} + +#[cfg(all(test, unix))] +mod tests; + +#[cfg(all(test, windows))] +mod windows_tests { + use std::sync::Arc; + use std::time::Duration; + + use super::{local::Local, slurm::Slurm, ssh::Ssh}; + use crate::engine::clock::TestClock; + use crate::engine::transport::{Config, HostConn, HostState, Status}; + use crate::engine::*; + use crate::store::{LaunchSpec, Store}; + + #[tokio::test] + async fn adapters_respect_the_auth_breaker_without_starting_an_ssh_process() { + let dir = std::env::temp_dir().join(format!("orx-adapters-{}", uuid::Uuid::new_v4())); + let store = Store::open_at(dir.clone()).unwrap(); + store + .seed_engine_host( + "host", + "/root", + None, + &HostState { + status: Status::NeedsAuth, + ..HostState::default() + }, + ) + .unwrap(); + let clock = Arc::new(TestClock::new()); + let conn = { + let config = Config { + alias: "host".into(), + root: "/root".into(), + ssh_config: None, + binary_dir: None, + askpass_executable: std::env::current_exe().unwrap(), + }; + let auth = crate::engine::transport::Auth::new(&store, &config.alias).unwrap(); + HostConn::start_shared(config, store, clock.clone(), auth) + } + .unwrap(); + let ssh = Arc::new(Ssh::new("host".into(), "/root".into(), conn)); + let slurm = Slurm::new(ssh.clone(), clock); + let store = std::sync::Mutex::new(Store::open_at(dir.clone()).unwrap()); + let fence = Fence { + store: &store, + run_id: "run", + attempt: 1, + taken_at: 1, + }; + let run = crate::store::StoredRun { + id: "run".into(), + experiment_id: "exp".into(), + project_id: "proj".into(), + status: "submitting".into(), + backend_json: "{\"kind\":\"engine\"}".into(), + command: "true".into(), + created_at: 1, + updated_at: 1, + ended_at: None, + exit_code: None, + commit_sha: None, + result_markdown: None, + cancel_requested: false, + cancel_reason: None, + chat_session_id: None, + }; + let intent = RunIntent { + run, + launch: LaunchSpec { + kind: "ssh_job".into(), + target: Some("host".into()), + options: serde_json::json!({}), + }, + spec_digest: "0".repeat(64), + attempt: 1, + }; + let watched = WatchedRun { + id: "run".into(), + handle: ssh.handle(), + }; + let subscription = ssh.follow_logs("run"); + assert!(ssh.summary("run").await.is_none()); + assert!(ssh + .stage_blob(&"0".repeat(64), &dir.join("absent"), 1) + .await + .is_err()); + assert!(ssh.cleanup(&watched).await.is_err()); + for backend in [ssh.as_ref() as &dyn Backend, &slurm] { + assert!(matches!( + backend.launch(&intent, &fence).await, + Err(LaunchError::Blocked { .. }) + )); + assert!(matches!( + backend.recover(&intent).await, + Recovery::Unknown { .. } + )); + assert!(matches!( + backend + .observe(std::slice::from_ref(&watched), Duration::ZERO) + .await[0] + .1, + Observation::NeedsAuth { .. } + )); + assert!(matches!( + backend.cancel(&watched).await, + CancelOutcome::Undelivered { .. } + )); + assert!(backend + .read_log( + &watched, + LogFile::Notify, + ByteRange { start: 0, end: 1 }, + None + ) + .await + .is_err()); + } + let clock = Arc::new(crate::engine::clock::SystemClock::new()); + let engine = Arc::new(Engine::new( + Store::open_at(dir.clone()).unwrap(), + clock.clone(), + )); + let transport = Arc::new(super::openresearch::LegacyTransport::new( + ssh.clone(), + dir.join("logs"), + )); + let adapters: Vec> = vec![ + Box::new(super::api::Adapter::new( + super::hf::HfAccount { + namespace: "org".into(), + }, + clock.clone(), + dir.join("spools"), + )), + Box::new(super::api::Adapter::new( + super::modal::ModalAccount, + clock.clone(), + dir.join("spools"), + )), + Box::new(super::api::Adapter::new( + super::k8s::K8sAccount { + context: None, + namespace: "default".into(), + }, + clock.clone(), + dir.join("spools"), + )), + Box::new(super::api::Adapter::new( + super::ray::RayAccount { + address: "unused".into(), + }, + clock, + dir.join("spools"), + )), + Box::new(super::openresearch::OpenResearch::new( + engine, + Arc::new(move |_| Ok(transport.clone())), + )), + ]; + for adapter in adapters { + assert!(matches!( + adapter.launch(&intent, &fence).await, + Err(LaunchError::Rejected { .. }) + )); + assert!(adapter + .read_log( + &watched, + LogFile::Notify, + ByteRange { start: 0, end: 1 }, + None + ) + .await + .is_err()); + } + drop(subscription); + drop(slurm); + drop(ssh); + drop(store); + tokio::time::sleep(Duration::from_millis(150)).await; + std::fs::remove_dir_all(dir).unwrap(); + } + + #[tokio::test] + async fn local_recovery_preserves_the_tinker_handle() { + let dir = std::env::temp_dir().join(format!("orx-local-{}", uuid::Uuid::new_v4())); + let store = std::sync::Mutex::new(Store::open_at(dir.clone()).unwrap()); + let local = Local::new(dir.join("runs")); + let run = crate::store::StoredRun { + id: "tinker".into(), + experiment_id: "exp".into(), + project_id: "proj".into(), + status: "submitting".into(), + backend_json: "{\"kind\":\"engine\"}".into(), + command: "true".into(), + created_at: 1, + updated_at: 1, + ended_at: None, + exit_code: None, + commit_sha: None, + result_markdown: None, + cancel_requested: false, + cancel_reason: None, + chat_session_id: None, + }; + let mut intent = RunIntent { + run, + launch: LaunchSpec { + kind: "tinker_job".into(), + target: None, + options: serde_json::json!({}), + }, + spec_digest: "digest".into(), + attempt: 1, + }; + let run_dir = dir.join("runs/tinker"); + std::fs::create_dir_all(&run_dir).unwrap(); + std::fs::write(run_dir.join("launch.json"), "digest").unwrap(); + std::fs::write(run_dir.join("started"), "").unwrap(); + assert!(matches!( + local.recover(&intent).await, + Recovery::Found(Handle::Tinker { .. }) + )); + let watched = WatchedRun { + id: "tinker".into(), + handle: Handle::Tinker { + dir: run_dir.to_string_lossy().into_owned(), + }, + }; + assert!(matches!( + local + .read_log(&watched, LogFile::Log, ByteRange { start: 0, end: 1 }, None) + .await + .unwrap(), + LogPage::Reset { .. } + )); + assert!(matches!( + local.cancel(&watched).await, + CancelOutcome::Undelivered { .. } + )); + assert!(!local.observe(&[watched], Duration::ZERO).await.is_empty()); + intent.run.id = "invalid/../id".into(); + let fence = Fence { + store: &store, + run_id: "tinker", + attempt: 1, + taken_at: 1, + }; + assert!(matches!( + local.launch(&intent, &fence).await, + Err(LaunchError::Rejected { .. }) + )); + drop(store); + std::fs::remove_dir_all(dir).unwrap(); + } +} + +#[cfg(all(test, unix))] +mod api_tests; diff --git a/src/engine/adapters/modal.rs b/src/engine/adapters/modal.rs new file mode 100644 index 000000000..96243782c --- /dev/null +++ b/src/engine/adapters/modal.rs @@ -0,0 +1,58 @@ +use super::api::{self, Api}; +use crate::engine::*; +use crate::error::Result; +use crate::jobs::modal; +use async_trait::async_trait; + +pub struct ModalAccount; + +#[async_trait] +impl Api for ModalAccount { + type Cursor = u64; + + async fn launch(&self, intent: &RunIntent, _fence: &Fence<'_>) -> Result { + let mut spec: modal::ModalJobSpec = + serde_json::from_value(intent.launch.options.clone()).map_err(api::rejected)?; + spec.tags.insert("or_run".into(), intent.run.id.clone()); + spec.env.extend(crate::config::launch_env(&intent.run.id)); + modal::ensure_env().await.map_err(api::rejected)?; + modal::run_job(&spec) + .await + .map(|sandbox| api::handle(intent, vec![sandbox])) + .map_err(api::interrupted) + } + async fn recover(&self, _intent: &RunIntent) -> Recovery { + api::unknown( + "Modal has no lookup by run label; abandon the run after inspecting the provider", + ) + } + async fn inspect(&self, run: &WatchedRun) -> Result { + let state = modal::inspect_job(api::id(run, "modal_job", None, None)?).await?; + Ok(api::stage(&state.stage, state.message, state.exit_code, None, None)) + } + async fn cancel(&self, run: &WatchedRun) -> Result<()> { + modal::cancel_job(api::id(run, "modal_job", None, None)?).await + } + async fn logs( + &self, + run: &WatchedRun, + cursor: &mut u64, + window: std::time::Duration, + sink: &mut (dyn for<'b> FnMut(&'b [u8]) + Send), + ) -> Result { + let mut received = 0; + let outcome = { + let mut lines = api::lines(sink, &mut received); + let pass = modal::stream_logs( + api::id(run, "modal_job", None, None)?, + *cursor, + None, + &mut lines, + ); + tokio::time::timeout(window, pass).await + }; + let closed = api::closed(outcome, received)?; + *cursor += received; + Ok(closed.is_some()) + } +} diff --git a/src/engine/adapters/openresearch.rs b/src/engine/adapters/openresearch.rs new file mode 100644 index 000000000..8e3c59869 --- /dev/null +++ b/src/engine/adapters/openresearch.rs @@ -0,0 +1,887 @@ +use std::collections::HashMap; +use std::io::{Read, Seek, Write}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::Duration; + +use async_trait::async_trait; +use orx_host_proto::{LogTarget, Request, Response}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; + +use super::ssh::Ssh; +use crate::commands::supervise::RunSink; +use crate::engine::*; +use crate::error::{anyhow, Result}; +use crate::jobs::{ssh, BackendDescriptor}; +use crate::store::{RunStatus, StoredRun}; + +pub type TransportFactory = + Arc Result> + Send + Sync>; + +pub struct LegacyTransport { + pub ssh: Arc, + pub log_dir: PathBuf, + collect: tokio::sync::Mutex<()>, +} + +impl std::fmt::Debug for LegacyTransport { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("LegacyTransport") + .field("host", &self.ssh.host) + .finish_non_exhaustive() + } +} + +#[derive(Serialize, Deserialize)] +pub(crate) struct Cursor { + ident: Option, + pub(crate) offset: u64, +} + +impl LegacyTransport { + pub fn new(ssh: Arc, log_dir: PathBuf) -> Self { + Self { + ssh, + log_dir, + collect: tokio::sync::Mutex::new(()), + } + } + + pub async fn execute(&self, command: &str, stdin: &[u8]) -> Result { + match self + .ssh + .request(Request::Exec { + command: command.into(), + stdin: stdin.into(), + timeout_ms: 120_000, + }) + .await? + { + Response::Exec { result } + if result.code == Some(0) && !result.timed_out && !result.stdout_truncated => + { + Ok(String::from_utf8(result.stdout)?) + } + Response::Exec { result } => Err(anyhow!( + "Legacy command failed: {}", + String::from_utf8_lossy(&result.stderr) + )), + _ => Err(anyhow!("Unexpected Exec response")), + } + } + + pub async fn upload(&self, command: &str, source: &Path) -> Result { + let mut hash = Sha256::new(); + let mut file = std::fs::File::open(source)?; + std::io::copy(&mut file, &mut hash)?; + let sha = format!("{:x}", hash.finalize()); + self.ssh + .stage_blob(&sha, source, file.metadata()?.len()) + .await + .map_err(|error| anyhow!("Source upload failed: {error:?}"))?; + let blob = format!("{}/sources/{sha}", self.ssh.root); + self.execute( + &format!( + "{{ {command}; }} < {}", + ssh::shell_path(blob.strip_prefix("~/").unwrap_or(&blob)) + ), + &[], + ) + .await + } + + pub async fn page( + &self, + dir: &str, + file: LogFile, + range: ByteRange, + ident: Option, + anchor: Option<[u8; 64]>, + ) -> Result { + let dir = super::ssh::legacy_dir(dir); + match self + .ssh + .request(Request::ReadLog { + target: LogTarget::Dir(dir), + file, + ident, + range, + anchor, + }) + .await? + { + Response::ReadLog { page } => Ok(page), + _ => Err(anyhow!("Unexpected legacy log response")), + } + } + + pub async fn collect(&self, run: &str, dir: &str) -> Result { + let _guard = self.collect.lock().await; + uuid::Uuid::parse_str(run)?; + std::fs::create_dir_all(&self.log_dir)?; + let path = self.log_dir.join(format!("{run}.log")); + let cursor_path = path.with_extension("engine-cursor.json"); + let mut cursor: Cursor = match std::fs::read(&cursor_path) { + Ok(bytes) => serde_json::from_slice(&bytes)?, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Cursor { + ident: None, + offset: 0, + }, + Err(error) => return Err(error.into()), + }; + let mut anchor = None; + if cursor.offset != 0 { + match std::fs::File::open(&path) { + Ok(mut file) if file.metadata()?.len() >= cursor.offset => { + if cursor.offset >= 64 { + let mut bytes = [0; 64]; + file.seek(std::io::SeekFrom::Start(cursor.offset - 64))?; + file.read_exact(&mut bytes)?; + anchor = Some(bytes); + } + } + Ok(_) => { + cursor = Cursor { + ident: None, + offset: 0, + } + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + cursor = Cursor { + ident: None, + offset: 0, + } + } + Err(error) => return Err(error.into()), + } + } + let page = self + .page( + dir, + LogFile::Log, + ByteRange { + start: cursor.offset, + end: cursor.offset + 256 * 1024, + }, + cursor.ident.clone(), + anchor, + ) + .await?; + let eof = match page { + LogPage::Reset { info: Some(_) } => { + cursor = Cursor { + ident: None, + offset: 0, + }; + false + } + LogPage::Reset { info: None } => return Err(anyhow!("Legacy log is not available")), + LogPage::Data { + len: _, + ident, + start, + bytes, + eof, + } => { + if start != cursor.offset { + return Err(anyhow!("Legacy log offset changed")); + } + let mut file = std::fs::OpenOptions::new() + .create(true) + .truncate(false) + .write(true) + .open(&path)?; + file.set_len(cursor.offset)?; + file.seek(std::io::SeekFrom::Start(cursor.offset))?; + file.write_all(&bytes)?; + file.sync_all()?; + cursor.ident = Some(ident); + cursor.offset += bytes.len() as u64; + eof + } + }; + crate::local::git::atomic_write_with_mode( + &cursor_path, + &serde_json::to_vec(&cursor)?, + Some(0o600), + )?; + #[cfg(unix)] + std::fs::File::open(&self.log_dir)?.sync_all()?; + Ok(serde_json::json!({ "eof": eof })) + } +} + +struct EngineSink { + engine: Arc, +} + +impl RunSink for EngineSink { + fn finish( + &self, + run: &str, + status: RunStatus, + exit_code: Option, + reason: Option<&str>, + ) -> Result { + let phase = + Phase::parse(status.as_str()).ok_or_else(|| anyhow!("Unknown legacy status"))?; + self.engine.commit(run, |_, state| { + if state.cancel_accepted_at.is_some() { + return reconcile::Change::default(); + } + reconcile::Change { + exit_code, + ..reconcile::Change::terminal(phase, reason.map(str::to_owned)) + } + })?; + Ok(true) + } + fn get_run(&self, run: &str) -> Result> { + let store = self.engine.store(); + let mut stored = store.get_run(run)?; + if let Some(stored) = &mut stored { + let state = store.engine_run_state(run)?; + stored.cancel_requested = state.is_some_and(|state| state.cancel_accepted_at.is_some()); + } + Ok(stored) + } + fn update_status( + &self, + run: &str, + status: RunStatus, + _ended_at: Option, + exit_code: Option, + ) -> Result { + let observation = match status { + RunStatus::Starting => Observation::Queued { + detail: "Legacy loop starting".into(), + }, + RunStatus::Running => Observation::Running { started_at: None }, + RunStatus::Done => Observation::Exited { + finished_at: None, + code: Some(0), + signal: None, + }, + RunStatus::Cancelled => return self.finish(run, status, exit_code, None), + RunStatus::Lost => Observation::Lost { + reason: "Legacy outcome unavailable".into(), + }, + RunStatus::Failed => Observation::Exited { + finished_at: None, + code: Some( + exit_code + .and_then(|code| i32::try_from(code).ok()) + .unwrap_or(1), + ), + signal: None, + }, + }; + self.engine.observe(run, observation)?; + Ok(true) + } + fn set_result_markdown(&self, run: &str, result: &str) -> Result<()> { + self.engine.store().set_result_markdown(run, result) + } + fn set_backend_json(&self, run: &str, descriptor: &str) -> Result<()> { + let descriptor = BackendDescriptor::parse(descriptor)?; + let handle = Handle::Legacy { + descriptor: Box::new(descriptor.clone()), + }; + let json = handle::backend_json(run, Some(&handle), &descriptor)?; + self.engine.store().set_backend_json(run, &json) + } + fn queue_finished_remote_cleanup(&self, run: &str) -> Result<()> { + self.engine.store().queue_finished_remote_cleanup(run) + } + fn transport_error(&self, run: &str, target: &ssh::SshTarget, cause: &str) -> Result<()> { + let transport = target + .transport + .as_ref() + .ok_or_else(|| anyhow!("Missing engine transport"))?; + self.engine + .observe(run, transport.ssh.disconnected(cause.into())) + } +} + +pub struct OpenResearch { + engine: Arc, + transport: TransportFactory, + loops: tokio::sync::Mutex>>, +} + +const REJECTED_KEY_GRACE_MS: i64 = 15 * 60 * 1000; + +fn rejected_key_expired( + created_at: i64, + contact: &crate::store::Contact, + host: &crate::engine::transport::HostState, + now: i64, +) -> bool { + let crate::store::Contact::NeedsAuth { since, .. } = contact else { + return false; + }; + let cause = host + .cause + .as_deref() + .unwrap_or_default() + .to_ascii_lowercase(); + host.status == crate::engine::transport::Status::NeedsAuth + && cause.contains("permission denied (publickey)") + && host + .last_live_ms + .is_some_and(|live| live >= created_at && live <= host.since_ms) + && now.saturating_sub(host.since_ms.max(*since)) >= REJECTED_KEY_GRACE_MS +} + +impl OpenResearch { + pub fn new(engine: Arc, transport: TransportFactory) -> Self { + Self { + engine, + transport, + loops: tokio::sync::Mutex::default(), + } + } + + async fn cancel_rejected_key( + &self, + run: &StoredRun, + contact: &crate::store::Contact, + descriptor: &BackendDescriptor, + ) -> Result { + let Some(target) = descriptor.openresearch_ssh_target() else { + return Ok(false); + }; + + let Ok(transport) = (self.transport)(&target) else { + return Ok(false); + }; + let host = transport.ssh.conn.state().borrow().clone(); + if !rejected_key_expired(run.created_at, contact, &host, self.engine.clock.wall_ms()) { + return Ok(false); + } + + let Some(_gate) = self.engine.try_gate(&run.id) else { + return Ok(true); + }; + let (_, sandbox) = descriptor.openresearch_ref()?; + let creds = crate::config::load_credentials() + .await? + .ok_or_else(|| anyhow!("Missing OpenResearch credentials"))?; + let released = match crate::client::get_sandbox(&creds, sandbox).await { + Ok(_) => false, + Err(error) if crate::jobs::openresearch::is_not_found_error(&error.to_string()) => true, + Err(error) => return Err(error), + }; + + let (current, state) = self.engine.load(&run.id)?; + let host = transport.ssh.conn.state().borrow().clone(); + if current.cancel_requested + || state.cancel_accepted_at.is_some() + || phase_of(¤t)?.is_terminal() + || !rejected_key_expired( + current.created_at, + &state.contact, + &host, + self.engine.clock.wall_ms(), + ) + { + return Ok(true); + } + + if released { + if let Some(task) = self.loops.lock().await.remove(&run.id) { + task.abort(); + let _ = task.await; + } + self.engine.observe( + &run.id, + Observation::Gone { + reason: crate::plane::LABELS["run_notice_rental_outcome_unavailable"].clone(), + }, + )?; + } else { + self.engine + .cancel( + self, + &run.id, + &crate::plane::LABELS["run_notice_rental_key_cancelled"], + ) + .await?; + } + + Ok(true) + } +} + +impl Drop for OpenResearch { + fn drop(&mut self) { + for task in self.loops.get_mut().values() { + task.abort(); + } + } +} + +#[async_trait] +impl Backend for OpenResearch { + async fn launch(&self, intent: &RunIntent, _fence: &Fence<'_>) -> Result { + let mut descriptor = + BackendDescriptor::parse(&intent.run.backend_json).map_err(super::api::rejected)?; + descriptor.kind = "openresearch_job".into(); + let org = intent + .launch + .target + .clone() + .ok_or_else(|| super::api::rejected("Missing organization"))?; + let flavor = intent.launch.options["flavor"] + .as_str() + .ok_or_else(|| super::api::rejected("Missing flavor"))?; + let target = crate::jobs::openresearch::parse_flavor( + flavor, + intent.launch.options["disk_gb"].as_i64().unwrap_or(100), + intent.launch.options["provider"] + .as_str() + .map(str::to_owned), + ) + .map_err(super::api::rejected)?; + let timeout = intent.launch.options["timeout_seconds"] + .as_u64() + .unwrap_or(4 * 3600); + let creds = crate::config::load_credentials() + .await + .map_err(super::api::rejected)? + .ok_or_else(|| super::api::rejected("Missing OpenResearch credentials"))?; + let created = crate::client::create_sandbox( + &creds, + &crate::client::CreateSandboxBody { + organization_id: org.clone(), + target, + rental_lease: Some(crate::client::CreateRentalLease { + version: 1, + max_active_seconds: timeout, + }), + }, + ) + .await + .map_err(|error| { + // A 4xx answer to the create request proves no box exists. + if error.to_string().contains(" failed (4") { + super::api::rejected(crate::local::openresearch::billing_friendly(error)) + } else { + super::api::interrupted(error) + } + })?; + descriptor.namespace = Some(org); + descriptor.job_id = Some(created.sandbox.id.clone()); + descriptor.timeout_secs = Some(timeout); + let lease = match created.rental_lease.filter(|lease| lease.version == 1) { + Some(lease) => lease, + None => match crate::jobs::openresearch::teardown(&creds, &created.sandbox.id).await { + Ok(()) => { + return Err(super::api::rejected( + "OpenResearch returned no supported rental lease; the box was deleted", + )) + } + Err(error) => { + eprintln!( + "Could not delete box {} after an unsupported rental lease: {error}", + created.sandbox.id + ); + return Ok(Handle::Legacy { + descriptor: Box::new(descriptor), + }); + } + }, + }; + descriptor.rental_lease = Some(crate::jobs::rental::Rental { + api_url: creds.api_url, + sandbox_id: created.sandbox.id, + token: lease.token, + }); + Ok(Handle::Legacy { + descriptor: Box::new(descriptor), + }) + } + async fn recover(&self, _intent: &RunIntent) -> Recovery { + super::api::unknown("OpenResearch provisioning outcome has no recorded sandbox id") + } + async fn observe(&self, runs: &[WatchedRun], _budget: Duration) -> Vec<(String, Observation)> { + for run in runs { + if !matches!(self.engine.own(&run.id), Ok(true)) { + continue; + } + let Handle::Legacy { .. } = &run.handle else { + continue; + }; + let Ok((stored, state)) = self.engine.load(&run.id) else { + continue; + }; + if stored.cancel_requested + || state.cancel_accepted_at.is_some() + || phase_of(&stored).is_ok_and(Phase::is_terminal) + { + continue; + } + let Some(Handle::Legacy { descriptor }) = handle_of(&stored) else { + continue; + }; + let descriptor = *descriptor; + if descriptor.kind != "openresearch_job" { + continue; + } + match self + .cancel_rejected_key(&stored, &state.contact, &descriptor) + .await + { + Ok(true) => continue, + Ok(false) => {} + Err(error) => { + eprintln!("Rental auto-cancel unavailable for {}: {error}", run.id); + continue; + } + } + let mut tasks = self.loops.lock().await; + if tasks.get(&run.id).is_some_and(|task| !task.is_finished()) { + continue; + } + let sink = EngineSink { + engine: self.engine.clone(), + }; + let factory = self.transport.clone(); + let id = run.id.clone(); + tasks.insert( + run.id.clone(), + tokio::spawn(async move { + if let Err(error) = crate::commands::supervise::run_openresearch_loop( + &sink, + stored, + descriptor, + id.clone(), + Some(factory), + ) + .await + { + let current = sink.engine.load(&id).ok().map(|(_, state)| state.contact); + if !matches!(current, Some(crate::store::Contact::NeedsAuth { .. })) { + let _ = sink.engine.observe( + &id, + Observation::Unreachable { + cause: error.to_string(), + }, + ); + } + } + }), + ); + } + vec![] + } + async fn cancel(&self, run: &WatchedRun) -> CancelOutcome { + let Handle::Legacy { descriptor } = &run.handle else { + return CancelOutcome::Pending; + }; + + if let Some(task) = self.loops.lock().await.remove(&run.id) { + task.abort(); + let _ = task.await; + } + + let released = async { + if let Some(rental) = &descriptor.rental_lease { + rental.operation("release").await + } else { + let (_, sandbox) = descriptor.openresearch_ref()?; + let creds = crate::config::load_credentials() + .await? + .ok_or_else(|| anyhow!("Missing OpenResearch credentials"))?; + crate::jobs::openresearch::teardown(&creds, sandbox).await + } + } + .await; + + match released { + Ok(()) => CancelOutcome::Verified, + Err(error) => CancelOutcome::Undelivered { + detail: error.to_string(), + }, + } + } + async fn unwatch(&self, run: &WatchedRun) { + let task = self.loops.lock().await.remove(&run.id); + if let Some(task) = task { + let _ = task.await; + } + } + async fn read_log( + &self, + run: &WatchedRun, + file: LogFile, + range: ByteRange, + ident: Option<&FileIdent>, + ) -> Result { + let Handle::Legacy { descriptor } = &run.handle else { + return Err(anyhow!("Not a legacy run")); + }; + let target = descriptor + .openresearch_ssh_target() + .ok_or_else(|| anyhow!("Sandbox has no SSH endpoint"))?; + (self.transport)(&target)? + .page( + &crate::jobs::openresearch::run_dir(&run.id), + file, + range, + ident.cloned(), + None, + ) + .await + } +} + +#[cfg(all(test, unix))] +mod tests { + use super::*; + + #[test] + fn rejected_key_grace_requires_continuous_auth_failure_and_live_contact_in_this_run() { + use crate::engine::transport::{HostState, Status}; + use crate::store::Contact; + + let created_at = 100; + let contact = Contact::NeedsAuth { + since: 200, + cause: "Permission denied (publickey)".into(), + }; + let host = HostState { + status: Status::NeedsAuth, + since_ms: 200, + last_live_ms: Some(100), + cause: Some("Permission denied (publickey)".into()), + ..HostState::default() + }; + assert!(!rejected_key_expired( + created_at, + &contact, + &host, + 200 + 14 * 60_000 + )); + assert!(rejected_key_expired( + created_at, + &contact, + &host, + 200 + 15 * 60_000 + )); + for (contact, host) in [ + ( + Contact::Live, + HostState { + status: Status::Live, + ..host.clone() + }, + ), + ( + Contact::Unreachable { + since: 200, + cause: "Connection timed out".into(), + }, + HostState { + status: Status::Backoff, + ..host.clone() + }, + ), + ( + contact.clone(), + HostState { + last_live_ms: None, + ..host.clone() + }, + ), + ( + contact.clone(), + HostState { + last_live_ms: Some(99), + ..host.clone() + }, + ), + ( + contact.clone(), + HostState { + last_live_ms: Some(201), + ..host.clone() + }, + ), + ( + contact.clone(), + HostState { + cause: Some("Host key verification failed".into()), + ..host.clone() + }, + ), + ( + contact.clone(), + HostState { + cause: Some("SSH master ended; press Connect".into()), + ..host.clone() + }, + ), + ( + contact.clone(), + HostState { + cause: Some("Permission denied (password)".into()), + ..host.clone() + }, + ), + ] { + assert!(!rejected_key_expired( + created_at, + &contact, + &host, + 200 + 60 * 60_000 + )); + } + let after_connect = HostState { + since_ms: 200 + 14 * 60_000, + ..host.clone() + }; + assert!(!rejected_key_expired( + created_at, + &contact, + &after_connect, + 200 + 15 * 60_000 + )); + assert!(rejected_key_expired( + created_at, + &contact, + &after_connect, + after_connect.since_ms + 15 * 60_000 + )); + let after_recovery = HostState { + last_live_ms: Some(200 + 13 * 60_000), + ..after_connect.clone() + }; + assert!(!rejected_key_expired( + created_at, + &contact, + &after_recovery, + 200 + 15 * 60_000 + )); + assert!(rejected_key_expired( + created_at, + &contact, + &after_recovery, + after_recovery.since_ms + 15 * 60_000 + )); + let recovered_at_fourteen = Contact::NeedsAuth { + since: 200 + 14 * 60_000, + cause: host.cause.clone().unwrap(), + }; + assert!(!rejected_key_expired( + created_at, + &recovered_at_fourteen, + &host, + 200 + 15 * 60_000 + )); + } + + #[test] + fn engine_sink_keeps_legacy_lease_and_terminal_reason_in_the_notice() { + let root = std::env::temp_dir().join(format!("orx-legacy-sink-{}", uuid::Uuid::new_v4())); + let engine = Arc::new(super::super::api_tests::engine(&root)); + let descriptor = BackendDescriptor::parse(r#"{"kind":"openresearch_job","namespace":"org","jobId":"box","rentalLease":{"apiUrl":"https://example.invalid","sandboxId":"box","token":"private"}}"#).unwrap(); + let run = StoredRun { + id: "run".into(), + experiment_id: "exp".into(), + project_id: "proj".into(), + status: "running".into(), + backend_json: descriptor.to_json(), + command: "true".into(), + created_at: 1, + updated_at: 1, + ended_at: None, + exit_code: None, + commit_sha: None, + result_markdown: None, + cancel_requested: false, + cancel_reason: None, + chat_session_id: Some("chat".into()), + }; + engine.store().upsert_run(&run).unwrap(); + let sink = EngineSink { + engine: engine.clone(), + }; + sink.set_backend_json("run", &descriptor.to_json()).unwrap(); + let stored = sink.get_run("run").unwrap().unwrap(); + let Some(Handle::Legacy { descriptor: saved }) = handle_of(&stored) else { + panic!("lost legacy envelope"); + }; + assert_eq!(saved.rental_lease.unwrap().token, "private"); + sink.finish( + "run", + RunStatus::Failed, + Some(7), + Some("Job failed: payload exited 7"), + ) + .unwrap(); + let notices = engine.store().run_notice_batch("chat").unwrap(); + assert_eq!(notices.len(), 1); + assert!(notices[0].body.contains("payload exited 7")); + + let pending = StoredRun { + id: "pending-stop".into(), + ..run.clone() + }; + engine.store().upsert_run(&pending).unwrap(); + engine + .store() + .accept_run_cancel(&pending.id, Some("user")) + .unwrap(); + sink.finish(&pending.id, RunStatus::Failed, None, None) + .unwrap(); + sink.update_status(&pending.id, RunStatus::Cancelled, None, None) + .unwrap(); + assert_eq!(engine.load(&pending.id).unwrap().0.status, "running"); + + engine + .observe( + &pending.id, + Observation::Unreachable { + cause: "offline".into(), + }, + ) + .unwrap(); + assert!(engine.abandon(&pending.id).unwrap()); + sink.finish(&pending.id, RunStatus::Cancelled, None, None) + .unwrap(); + let (abandoned, state) = engine.load(&pending.id).unwrap(); + assert_eq!(abandoned.status, "lost"); + assert_ne!(state.contact, crate::store::Contact::Live); + + // The shipped Store sink keeps the old descriptor and writes no engine notices. + let store = std::sync::Mutex::new(Store::open_at(root.join("legacy")).unwrap()); + store.lock().unwrap().upsert_run(&run).unwrap(); + store + .set_backend_json("run", &descriptor.to_json()) + .unwrap(); + store + .finish( + "run", + RunStatus::Failed, + Some(7), + Some("Job failed: payload exited 7"), + ) + .unwrap(); + let legacy = store.get_run("run").unwrap().unwrap(); + assert_eq!(legacy.backend_json, descriptor.to_json()); + assert_eq!(legacy.status, "failed"); + assert_eq!(legacy.exit_code, Some(7)); + assert!(store + .lock() + .unwrap() + .run_notice_batch("chat") + .unwrap() + .is_empty()); + drop(store); + drop(sink); + drop(engine); + std::fs::remove_dir_all(root).unwrap(); + } +} diff --git a/src/engine/adapters/ray.rs b/src/engine/adapters/ray.rs new file mode 100644 index 000000000..28e5818a6 --- /dev/null +++ b/src/engine/adapters/ray.rs @@ -0,0 +1,62 @@ +use super::api::{self, Api}; +use crate::engine::*; +use crate::error::{anyhow, Result}; +use crate::jobs::ray; +use async_trait::async_trait; + +pub struct RayAccount { + pub address: String, +} +impl RayAccount { + fn id<'a>(&self, run: &'a WatchedRun) -> Result<&'a str> { + api::id(run, "ray_job", Some(&self.address), None) + } +} + +#[async_trait] +impl Api for RayAccount { + type Cursor = usize; + + async fn launch(&self, intent: &RunIntent, _fence: &Fence<'_>) -> Result { + let mut spec: ray::JobSubmission = + serde_json::from_value(intent.launch.options.clone()).map_err(api::rejected)?; + spec.submission_id = intent.run.id.clone(); + spec.env.extend(crate::config::launch_env(&intent.run.id)); + ray::run_job(&self.address, &spec) + .await + .map_err(api::interrupted)?; + Ok(api::handle(intent, vec![intent.run.id.clone()])) + } + async fn recover(&self, intent: &RunIntent) -> Recovery { + match ray::inspect_job(&self.address, &intent.run.id).await { + Ok(job) if job.stage == "GONE" => Recovery::Absent, + Ok(_) => Recovery::Found(api::handle(intent, vec![intent.run.id.clone()])), + Err(error) => api::unknown(error), + } + } + async fn inspect(&self, run: &WatchedRun) -> Result { + let (state, started_at, finished_at) = ray::inspect_job_with_times(&self.address, self.id(run)?).await?; + Ok(api::stage(&state.stage, state.message, state.exit_code, started_at, finished_at)) + } + async fn cancel(&self, run: &WatchedRun) -> Result<()> { + ray::stop_job(&self.address, self.id(run)?).await + } + + async fn logs( + &self, + run: &WatchedRun, + cursor: &mut usize, + _window: std::time::Duration, + sink: &mut (dyn for<'b> FnMut(&'b [u8]) + Send), + ) -> Result { + let bytes = ray::fetch_logs(&self.address, self.id(run)?) + .await? + .into_bytes(); + if *cursor > bytes.len() { + return Err(anyhow!("Provider log was truncated")); + } + sink(&bytes[*cursor..]); + *cursor = bytes.len(); + Ok(true) + } +} diff --git a/src/engine/adapters/slurm.rs b/src/engine/adapters/slurm.rs new file mode 100644 index 000000000..5ccf2076c --- /dev/null +++ b/src/engine/adapters/slurm.rs @@ -0,0 +1,326 @@ +use std::collections::{BTreeMap, HashMap}; +use std::sync::Arc; +use std::time::Duration; + +use async_trait::async_trait; +use orx_host_proto::*; +use serde::Deserialize; +use tokio::sync::Mutex; + +use super::super::clock::Clock; +use super::super::{ + Backend, CancelOutcome, Fence, Handle, LaunchError, Observation, Recovery, RunIntent, + WatchedRun, +}; +use super::api::interrupted; +use super::ssh::{observations, LaunchOptions, Ssh, CANCELLED, UNEXPECTED}; +use crate::error::{bail, Result}; + +#[derive(Deserialize)] +struct Options { + #[serde(default)] + directives: BTreeMap, +} + +#[derive(Default)] +struct Queue { + next: Duration, + jobs: HashMap, +} + +pub struct Slurm { + ssh: Arc, + clock: Arc, + queue: Mutex, +} + +impl Slurm { + pub fn new(ssh: Arc, clock: Arc) -> Self { + Self { + ssh, + clock, + queue: Mutex::default(), + } + } + + fn handle(&self, job: Option) -> Handle { + Handle::Slurm { + host: self.ssh.host.clone(), + root: self.ssh.root.clone(), + job, + } + } + + async fn submit(&self, intent: &RunIntent, fence: &Fence<'_>) -> Result { + let payload_options: LaunchOptions = serde_json::from_value(intent.launch.options.clone()) + .map_err(|error| LaunchError::Rejected { + reason: error.to_string(), + })?; + let metadata = + crate::jobs::BackendDescriptor::parse(&intent.run.backend_json).map_err(|error| { + LaunchError::Rejected { + reason: error.to_string(), + } + })?; + if payload_options.cancel_sh.is_some() + || payload_options.container.is_some() + || metadata.ssh_container.is_some() + { + return Err(LaunchError::Rejected { + reason: "Slurm container runs are not supported. Use SSH for container runs." + .into(), + }); + } + let payload = self.ssh.payload(intent, &|| fence.cancelled()).await?; + if fence.cancelled() { + return Err(interrupted(CANCELLED)); + } + let options: Options = + serde_json::from_value(intent.launch.options.clone()).map_err(|error| { + LaunchError::Rejected { + reason: error.to_string(), + } + })?; + let mut directives = String::new(); + for (name, value) in options.directives { + if !matches!( + name.as_str(), + "partition" + | "ntasks" + | "account" + | "qos" + | "gres" + | "cpus-per-task" + | "mem" + | "time" + | "nodes" + ) || value.is_empty() + || value.contains(['\r', '\n', '\0']) + { + return Err(LaunchError::Rejected { + reason: format!("Invalid Slurm directive {name}"), + }); + } + directives.push_str(&format!("#SBATCH --{name}={value}\n")); + } + match self + .ssh + .launch_request(Request::SlurmSubmit { + intent: payload, + directives, + }) + .await? + { + Response::SlurmSubmit { job } => Ok(self.handle(Some(job))), + _ => Err(interrupted(UNEXPECTED)), + } + } + + async fn query( + &self, + names: Vec, + legacy: Vec, + ) -> Result> { + match self + .ssh + .request(Request::SlurmQueue { names, legacy }) + .await? + { + Response::SlurmQueue { jobs, .. } => Ok(jobs), + response => bail!("Unexpected Slurm queue reply: {response:?}"), + } + } +} + +#[async_trait] +impl Backend for Slurm { + async fn launch(&self, intent: &RunIntent, fence: &Fence<'_>) -> Result { + self.submit(intent, fence).await + } + + async fn recover(&self, intent: &RunIntent) -> Recovery { + match self + .ssh + .changes(std::slice::from_ref(&intent.run.id), Duration::ZERO) + .await + { + Ok(changed) + if changed.iter().any(|(_, summary)| { + matches!(summary.state, RunState::Missing | RunState::Staging) + }) => + { + return Recovery::Absent + } + Ok(_) => {} + Err(error) => { + return Recovery::Unknown { + detail: error.to_string(), + } + } + } + match self.query(vec![intent.run.id.clone()], Vec::new()).await { + Ok(jobs) => match jobs.into_iter().find(|job| { + job.run == intent.run.id && (job.state != "UNKNOWN" || !job.job.is_empty()) + }) { + Some(job) => { + let id = (!job.job.is_empty()).then_some(job.job); + Recovery::Found(self.handle(id)) + } + None => Recovery::Unknown { + detail: "Slurm submission marker exists without a scheduler record or receipt" + .into(), + }, + }, + Err(error) => Recovery::Unknown { + detail: error.to_string(), + }, + } + } + + async fn observe(&self, runs: &[WatchedRun], budget: Duration) -> Vec<(String, Observation)> { + let mut result = Vec::new(); + let mut names = Vec::new(); + let mut legacy = Vec::new(); + for run in runs { + match self.ssh.validate(run) { + Ok(()) => { + names.push(run.id.clone()); + if let Handle::Legacy { descriptor } = &run.handle { + if let Some(job) = &descriptor.job_id { + legacy.push(SlurmLegacyRun { + run: run.id.clone(), + job: job.clone(), + dir: super::ssh::legacy_dir(&crate::jobs::slurm::run_dir( + descriptor.remote_root.as_deref(), + &run.id, + )), + }); + } + } + } + Err(error) => result.push(( + run.id.clone(), + Observation::Unreconciled { + detail: error.to_string(), + }, + )), + } + } + if names.is_empty() { + return result; + } + let mut queue = self.queue.lock().await; + let now = self.clock.monotonic(); + let due = now >= queue.next || names.iter().any(|name| !queue.jobs.contains_key(name)); + if due { + match self.query(names.clone(), legacy.clone()).await { + Ok(jobs) => { + queue.jobs = jobs.into_iter().map(|job| (job.run.clone(), job)).collect(); + queue.next = now + Duration::from_secs(30); + } + Err(error) => { + result.extend( + names + .into_iter() + .map(|name| (name, self.ssh.disconnected(error.to_string()))), + ); + return result; + } + } + } + let wait = if due { + Duration::ZERO + } else { + budget.min(queue.next.saturating_sub(now)) + }; + match self.ssh.changes(&names, wait).await { + Ok(changed) => { + for (name, mut summary) in changed { + let receipt = matches!( + &summary.state, + RunState::Exited { .. } + | RunState::InvalidData { .. } + | RunState::Unreachable { .. } + ); + if !receipt { + if let Some(job) = queue.jobs.get(&name) { + summary.state = job.summary.state.clone(); + if legacy.iter().any(|old| old.run == name) { + summary.notify_len = job.summary.notify_len; + } + } else { + summary.state = RunState::Unreconciled { + detail: "Scheduler returned no job".into(), + }; + } + } + if !receipt && matches!(summary.state, RunState::Failed { .. }) { + result.push((name.clone(), Observation::Lingering { pids: Vec::new() })); + } + let mut observed = observations(name.clone(), &summary); + if matches!(&summary.state, RunState::Exited { receipt } + if receipt.reason != orx_host_proto::ExitReason::Cancelled) + { + observed.retain(|(_, observation)| { + !matches!(observation, Observation::Lingering { .. }) + }); + observed.push((name, Observation::Lingering { pids: Vec::new() })); + } + result.extend(observed); + } + } + Err(error) => result.extend( + names + .into_iter() + .map(|name| (name, self.ssh.disconnected(error.to_string()))), + ), + } + result + } + + async fn cancel(&self, run: &WatchedRun) -> CancelOutcome { + if let Err(error) = self.ssh.validate(run) { + return CancelOutcome::Undelivered { + detail: error.to_string(), + }; + } + let request = match &run.handle { + Handle::Legacy { descriptor } => Request::SlurmCancelLegacy { + job: descriptor.job_id.clone().unwrap_or_default(), + }, + _ => Request::Cancel { + run: run.id.clone(), + }, + }; + if let Err(error) = self.ssh.request(request).await { + return CancelOutcome::Undelivered { + detail: error.to_string(), + }; + } + + self.queue.lock().await.next = Duration::ZERO; + CancelOutcome::Pending + } + + async fn cleanup(&self, run: &WatchedRun) -> CancelOutcome { + if matches!(run.handle, Handle::Legacy { .. }) { + return self.cancel(run).await; + } + Backend::cleanup(self.ssh.as_ref(), run).await + } + + async fn unwatch(&self, run: &WatchedRun) { + self.queue.lock().await.jobs.remove(&run.id); + self.ssh.unwatch(run).await; + } + + async fn read_log( + &self, + run: &WatchedRun, + file: LogFile, + range: ByteRange, + ident: Option<&FileIdent>, + ) -> Result { + self.ssh.read_log(run, file, range, ident).await + } +} diff --git a/src/engine/adapters/ssh.rs b/src/engine/adapters/ssh.rs new file mode 100644 index 000000000..98ddaa59c --- /dev/null +++ b/src/engine/adapters/ssh.rs @@ -0,0 +1,807 @@ +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::path::Path; +use std::sync::Mutex; +use std::time::Duration; + +use async_trait::async_trait; +use orx_host_proto::{self as proto, *}; +use serde::{Deserialize, Serialize}; +use tokio::io::{AsyncReadExt, AsyncSeekExt}; + +use super::super::transport::{HostConn, Status}; +use super::super::{ + Backend, CancelOutcome, Fence, Handle, LaunchError, Observation, Recovery, RunIntent, + WatchedRun, +}; +use super::api::interrupted; +use crate::error::{anyhow, bail, Result}; +use crate::jobs::ssh::sh_quote; +use crate::jobs::BackendDescriptor; + +#[derive(Default, Serialize, Deserialize)] +pub struct LaunchOptions { + pub run_sh: Option, + /// Secrets are added at launch and never stored with the intent. + #[serde(default)] + pub env: BTreeMap, + pub cancel_sh: Option, + /// Runs inside this container, so run.sh and cancel.sh are built at launch. + pub container: Option, + /// A saved container the runtime resolves into `container` before the intent is stored. + pub container_reference: Option, + /// The engine root on the host, which selects the host connection. + pub root: Option, +} + +#[derive(Default)] +struct Feed { + summaries: HashMap, +} + +pub struct Ssh { + pub(crate) host: String, + pub(super) root: String, + pub(crate) conn: HostConn, + feed: tokio::sync::Mutex, + followers: Mutex>, +} + +/// Dropping the last subscription stops log-length checks in the host feed. +pub struct LogSubscription { + adapter: std::sync::Arc, + run: String, +} + +impl Drop for LogSubscription { + fn drop(&mut self) { + let mut followers = self.adapter.followers.lock().unwrap(); + if let Some(count) = followers.get_mut(&self.run) { + *count -= 1; + if *count == 0 { + followers.remove(&self.run); + } + } + } +} + +impl Ssh { + pub fn new(host: String, root: String, conn: HostConn) -> Self { + Self { + host, + root, + conn, + feed: tokio::sync::Mutex::new(Feed::default()), + followers: Mutex::default(), + } + } + + pub fn follow_logs(self: &std::sync::Arc, run: &str) -> LogSubscription { + *self + .followers + .lock() + .unwrap() + .entry(run.into()) + .or_default() += 1; + LogSubscription { + adapter: self.clone(), + run: run.into(), + } + } + + pub(super) fn handle(&self) -> Handle { + Handle::Ssh { + host: self.host.clone(), + root: self.root.clone(), + } + } + + pub(super) fn validate(&self, run: &WatchedRun) -> Result<()> { + match &run.handle { + Handle::Ssh { host, root } | Handle::Slurm { host, root, .. } + if host == &self.host && root == &self.root => + { + Ok(()) + } + Handle::Legacy { descriptor } + if matches!(descriptor.kind.as_str(), "ssh_job" | "slurm_job") + && descriptor.namespace.as_deref() == Some(&self.host) => + { + Ok(()) + } + _ => bail!("Run {} does not belong to host {}", run.id, self.host), + } + } + + pub(crate) async fn request(&self, request: Request) -> Result { + match self.conn.request(request).await? { + Response::Error { code, message } => bail!("orx-host {code:?}: {message}"), + response => Ok(response), + } + } + + pub(super) fn disconnected(&self, cause: String) -> Observation { + let state = self.conn.state(); + let state = state.borrow(); + let cause = state.cause.clone().unwrap_or(cause); + if state.status == Status::NeedsAuth { + Observation::NeedsAuth { cause } + } else { + Observation::Unreachable { cause } + } + } + + pub(super) async fn launch_request(&self, request: Request) -> Result { + let frame_len = serde_json::to_vec(&Message { + id: u64::MAX, + body: &request, + }) + .map_err(rejected)? + .len(); + if frame_len > MAX_FRAME_LEN { + return Err(rejected( + "Launch request exceeds the 8 MiB frame limit. Shorten the script or environment.", + )); + } + let submitting = matches!(&request, Request::Launch(_) | Request::SlurmSubmit { .. }); + match self.conn.request(request).await { + Ok(Response::Error { + code: ErrorCode::InvalidRequest | ErrorCode::Conflict, + message, + }) => Err(rejected(message)), + Err(error) + if !submitting + || error + .downcast_ref::() + .is_some_and(|error| !error.sent) => + { + let state = error + .downcast_ref::() + .map(|error| error.state.clone()) + .unwrap_or_else(|| self.conn.state().borrow().clone()); + let since = state.since_ms; + let cause = state.cause.unwrap_or_else(|| error.to_string()); + let contact = if state.status == Status::NeedsAuth { + crate::store::Contact::NeedsAuth { since, cause } + } else { + crate::store::Contact::Unreachable { since, cause } + }; + Err(LaunchError::Blocked { contact }) + } + Ok(Response::Error { message, .. }) => Err(interrupted(message)), + Err(error) => Err(interrupted(error)), + Ok(response) => Ok(response), + } + } + + pub async fn stage_blob(&self, sha: &str, path: &Path, len: u64) -> Result<(), LaunchError> { + if let Response::HasBlob { present: true } = self + .launch_request(Request::HasBlob { + sha: sha.into(), + len, + }) + .await? + { + return Ok(()); + } + let mut file = tokio::fs::File::open(path).await.map_err(rejected)?; + if file.metadata().await.map_err(rejected)?.len() != len { + return Err(rejected("Source snapshot length changed")); + } + let mut offset = 0; + let mut bytes = vec![0; 256 * 1024]; + loop { + let read = file.read(&mut bytes).await.map_err(rejected)?; + if read == 0 && len != 0 { + break; + } + match self + .launch_request(Request::PutBlob { + sha: sha.into(), + offset, + bytes: bytes[..read].to_vec(), + }) + .await? + { + Response::PutBlob { len: remote } + if remote >= offset + read as u64 && remote <= len => + { + offset = remote; + file.seek(std::io::SeekFrom::Start(offset)) + .await + .map_err(rejected)?; + } + _ => return Err(interrupted(UNEXPECTED)), + } + if offset == len { + break; + } + } + if offset != len + || !matches!( + self.launch_request(Request::HasBlob { + sha: sha.into(), + len + }) + .await?, + Response::HasBlob { present: true } + ) + { + return Err(rejected("Source snapshot digest or length differs")); + } + Ok(()) + } + + /// Holds the staged blob in the run dir against source sweeps, one bounded slice per + /// request when it must be copied. A blob swept since staging, or a cancel accepted + /// meanwhile, fails as Interrupted, so recovery decides what comes next. + pub(super) async fn pin_source( + &self, + run: &str, + sha: &str, + cancelled: &(dyn Fn() -> bool + Sync), + ) -> Result<(), LaunchError> { + loop { + if cancelled() { + return Err(interrupted(CANCELLED)); + } + match self + .launch_request(Request::PinSource { + run: run.into(), + sha: sha.into(), + }) + .await? + { + Response::PinSource { pinned: true } => return Ok(()), + Response::PinSource { pinned: false } => {} + _ => return Err(interrupted(UNEXPECTED)), + } + } + } + + pub(super) async fn payload( + &self, + intent: &RunIntent, + cancelled: &(dyn Fn() -> bool + Sync), + ) -> Result { + if intent.launch.target.as_deref() != Some(&self.host) { + return Err(rejected(format!( + "Launch target does not match host {}", + self.host + ))); + } + let options: LaunchOptions = + serde_json::from_value(intent.launch.options.clone()).map_err(rejected)?; + let metadata = BackendDescriptor::parse(&intent.run.backend_json).map_err(rejected)?; + if let Some(sha) = &metadata.source_digest { + let path = metadata + .source_path + .as_deref() + .ok_or_else(|| rejected("Source path missing"))?; + let len = metadata + .source_size + .ok_or_else(|| rejected("Source length missing"))?; + self.stage_blob(sha, Path::new(path), len).await?; + self.pin_source(&intent.run.id, sha, cancelled).await?; + } + let mut env = crate::config::launch_env(&intent.run.id); + env.extend(options.env); + let env: BTreeMap<_, _> = crate::jobs::default_python_env(&env).into_iter().collect(); + let run_sh = options.run_sh.unwrap_or_else(|| intent.run.command.clone()); + let (run_sh, env, cancel_sh) = match options.container { + Some(container) => { + let exports = env + .iter() + .map(|(key, value)| format!("export {key}={}", sh_quote(value))) + .collect::>() + .join("\n"); + // orx-host links the staged archive into the run dir as source.tar. + let source = metadata.source_digest.is_some().then_some("source.tar"); + ( + container.engine_run_sh(&exports, &run_sh, source), + BTreeMap::new(), + Some(container.engine_cancel_sh()), + ) + } + None => (run_sh, env, options.cancel_sh), + }; + Ok(LaunchIntent { + run: intent.run.id.clone(), + digest: intent.spec_digest.clone(), + run_sh, + env, + source: metadata.source_digest, + cancel_sh, + }) + } + + pub async fn cleanup(&self, run: &WatchedRun) -> Result { + self.validate(run)?; + match self + .request(Request::Cleanup { + run: run.id.clone(), + }) + .await? + { + Response::Cleanup { outcome } => Ok(outcome), + response => bail!("Unexpected cleanup reply: {response:?}"), + } + } + + #[cfg(test)] + pub async fn summary(&self, run: &str) -> Option { + self.feed.lock().await.summaries.get(run).cloned() + } + + pub(super) async fn changes( + &self, + runs: &[String], + budget: Duration, + ) -> Result> { + let mut feed = self.feed.lock().await; + let watched: HashSet<_> = runs.iter().collect(); + let watch = runs + .iter() + .map(|run| { + ( + run.clone(), + feed.summaries.get(run).cloned().unwrap_or_else(missing), + ) + }) + .collect(); + let follow_logs = self + .followers + .lock() + .unwrap() + .keys() + .filter(|run| watched.contains(run)) + .cloned() + .collect(); + let wait_ms = budget.min(Duration::from_secs(25)).as_millis() as u32; + let response = self + .request(Request::Changes { + watch, + follow_logs, + wait_ms, + }) + .await?; + let Response::Changes { runs: changed } = response else { + bail!("Unexpected feed reply: {response:?}"); + }; + for (run, summary) in changed { + if watched.contains(&run) { + feed.summaries.insert(run, summary); + } + } + // Replay current facts after reconnect, including when the remote summary did not change. + Ok(runs + .iter() + .map(|run| { + ( + run.clone(), + feed.summaries.get(run).cloned().unwrap_or_else(missing), + ) + }) + .collect()) + } +} + +/// A 0.2.x run dir as `orx-host` addresses it; 0.2.x stored HOME-relative dirs without `~/`. +pub(super) fn legacy_dir(dir: &str) -> String { + if dir.starts_with('/') || dir.starts_with("~/") { + dir.into() + } else { + format!("~/{dir}") + } +} + +pub(super) const CANCELLED: &str = "A cancel was accepted during the launch."; +pub(super) const UNEXPECTED: &str = "The host sent an unexpected response."; + +fn rejected(error: impl std::fmt::Display) -> LaunchError { + LaunchError::Rejected { + reason: error.to_string(), + } +} + +pub(super) fn missing() -> Summary { + Summary { + started_at: None, + state: RunState::Missing, + log_len: None, + notify_len: 0, + cleanup: None, + } +} + +pub(super) fn observations(run: String, summary: &Summary) -> Vec<(String, Observation)> { + let observation = match &summary.state { + RunState::Missing => Observation::NotFound, + RunState::Staging | RunState::Starting => Observation::Queued { + detail: "starting".into(), + }, + RunState::Running => Observation::Running { + started_at: summary.started_at, + }, + RunState::Exited { receipt } if receipt.reason == ExitReason::Cancelled => { + let proof = summary.cleanup.as_ref(); + let processes = proof.map_or(&receipt.processes, |proof| &proof.processes); + let outcome = proof.map_or(&receipt.outcome, |proof| &proof.outcome); + let note = match outcome { + proto::CancelOutcome::Verified | proto::CancelOutcome::Survivors => None, + proto::CancelOutcome::Unverifiable { unreadable } => Some(unreadable.clone()), + }; + Observation::CancelReceipt { + finished_at: receipt.finished_at, + code: receipt.code, + remaining: processes.len(), + note, + } + } + RunState::Exited { receipt } => Observation::Exited { + finished_at: receipt.finished_at, + code: receipt.code, + signal: receipt.signal, + }, + RunState::Failed { reason } => Observation::Failed { + finished_at: None, + reason: reason.clone(), + }, + RunState::Lost { reason } => Observation::Lost { + reason: reason.clone(), + }, + RunState::Cancelled { .. } => Observation::Cancelled { + finished_at: None, + code: None, + signal: None, + }, + RunState::Unreachable { cause } => Observation::Unreachable { + cause: cause.clone(), + }, + RunState::InvalidData { detail } | RunState::Unreconciled { detail } => { + Observation::Unreconciled { + detail: detail.clone(), + } + } + }; + let mut result = Vec::new(); + let processes = summary + .cleanup + .as_ref() + .map(|cleanup| &cleanup.processes) + .or(match &summary.state { + RunState::Exited { receipt } => Some(&receipt.processes), + _ => None, + }); + let settled = processes.map_or_else( + || { + matches!( + &summary.state, + RunState::Lost { .. } | RunState::Cancelled { .. } + ) + }, + |processes| processes.is_empty(), + ); + if let (Some(processes), RunState::Exited { receipt }) = (processes, &summary.state) { + if receipt.reason == ExitReason::Exited && !processes.is_empty() { + result.push(( + run.clone(), + Observation::Lingering { + pids: processes.iter().map(|process| process.pid).collect(), + }, + )); + } + } + if let Some(len) = summary.log_len { + result.push((run.clone(), Observation::Log { len })); + } + if let Some(started_at) = summary + .started_at + .filter(|_| matches!(&summary.state, RunState::Exited { .. })) + { + result.push(( + run.clone(), + Observation::Running { + started_at: Some(started_at), + }, + )); + } + // Persist attention before terminal runs leave the watch set. + result.push((run.clone(), observation)); + if settled { + result.push((run.clone(), Observation::Lingering { pids: Vec::new() })); + } + if summary.notify_len > 0 { + result.push(( + run, + Observation::Notify { + len: summary.notify_len, + }, + )); + } + result +} + +#[async_trait] +impl Backend for Ssh { + async fn launch(&self, intent: &RunIntent, fence: &Fence<'_>) -> Result { + let payload = self.payload(intent, &|| fence.cancelled()).await?; + if fence.cancelled() { + return Err(interrupted(CANCELLED)); + } + match self.launch_request(Request::Launch(payload)).await? { + Response::Launch { .. } => Ok(self.handle()), + _ => Err(interrupted(UNEXPECTED)), + } + } + + async fn recover(&self, intent: &RunIntent) -> Recovery { + self.recover_with_cancel(intent, &|| intent.run.cancel_requested) + .await + } + + async fn recover_with_cancel( + &self, + intent: &RunIntent, + cancelled: &(dyn Fn() -> bool + Sync), + ) -> Recovery { + match self + .request(Request::Inspect { + run: intent.run.id.clone(), + }) + .await + { + Ok(Response::Inspect { summary }) => match summary.state { + RunState::Missing => Recovery::Absent, + RunState::Staging if !cancelled() => { + let payload = match self.payload(intent, cancelled).await { + Ok(payload) => payload, + Err(_) if cancelled() => return Recovery::Found(self.handle()), + Err(error) => { + return Recovery::Unknown { + detail: format!("{error:?}"), + } + } + }; + if cancelled() { + return Recovery::Found(self.handle()); + } + match self.request(Request::Launch(payload)).await { + Ok(Response::Launch { .. }) => Recovery::Found(self.handle()), + result => Recovery::Unknown { + detail: format!("SSH recovery: {result:?}"), + }, + } + } + _ => Recovery::Found(self.handle()), + }, + Ok(response) => Recovery::Unknown { + detail: format!("Unexpected inspection reply: {response:?}"), + }, + Err(error) => Recovery::Unknown { + detail: error.to_string(), + }, + } + } + + async fn observe(&self, runs: &[WatchedRun], budget: Duration) -> Vec<(String, Observation)> { + if !runs.is_empty() + && runs + .iter() + .all(|run| matches!(run.handle, Handle::Legacy { .. })) + { + tokio::time::sleep(budget).await; + } + let mut result = Vec::new(); + let mut native = Vec::new(); + for run in runs { + if let Err(error) = self.validate(run) { + result.push(( + run.id.clone(), + Observation::Unreconciled { + detail: error.to_string(), + }, + )); + continue; + } + if let Handle::Legacy { descriptor } = &run.handle { + let request = Request::InspectLegacy { + dir: legacy_dir(descriptor.job_id.as_deref().unwrap_or_default()), + }; + let observation = match self.request(request).await { + Ok(Response::InspectLegacy { inspection }) => { + if inspection.pid.is_some() && !inspection.alive { + result.push((run.id.clone(), Observation::Lingering { pids: vec![] })); + } + if let Some(code) = inspection.exit_code { + Observation::Exited { + finished_at: None, + code: Some(code), + signal: None, + } + } else if inspection.alive { + Observation::Running { started_at: None } + } else { + Observation::Unreconciled { + detail: if inspection.receipt_unreadable { + "Legacy receipt unreadable" + } else { + "Legacy process gone without a receipt" + } + .into(), + } + } + } + Err(error) => self.disconnected(error.to_string()), + response => Observation::Unreconciled { + detail: format!("Unexpected legacy reply: {response:?}"), + }, + }; + result.push((run.id.clone(), observation)); + } else { + native.push(run.id.clone()); + } + } + if !native.is_empty() { + match self.changes(&native, budget).await { + Ok(changed) => result.extend( + changed + .into_iter() + .flat_map(|(run, summary)| observations(run, &summary)), + ), + Err(error) => result.extend( + native + .into_iter() + .map(|run| (run, self.disconnected(error.to_string()))), + ), + } + } + result + } + + async fn cancel(&self, run: &WatchedRun) -> CancelOutcome { + if let Err(error) = self.validate(run) { + return CancelOutcome::Undelivered { + detail: error.to_string(), + }; + } + if let Handle::Legacy { descriptor } = &run.handle { + let container = + descriptor + .ssh_container + .as_ref() + .map(|container| proto::ContainerRun { + reference: container.reference.clone(), + id: container.id.clone(), + started_at: container.started_at.clone(), + run_dir: container.run_dir.clone(), + }); + return match self + .request(Request::CancelLegacy { + dir: legacy_dir(descriptor.job_id.as_deref().unwrap_or_default()), + container, + }) + .await + { + Ok(Response::CancelLegacy { + outcome: LegacyCancelOutcome::GroupGone, + }) => CancelOutcome::Verified, + Ok(Response::CancelLegacy { + outcome: LegacyCancelOutcome::Survivors { pids }, + }) => CancelOutcome::Survivors { count: pids.len() }, + result => CancelOutcome::Undelivered { + detail: format!("Legacy cancel was not acknowledged: {result:?}"), + }, + }; + } + match self + .request(Request::Cancel { + run: run.id.clone(), + }) + .await + { + Ok(Response::Cancel { .. }) => CancelOutcome::Pending, + result => CancelOutcome::Undelivered { + detail: format!("Cancel was not acknowledged: {result:?}"), + }, + } + } + + async fn cleanup(&self, run: &WatchedRun) -> CancelOutcome { + let outcome = self.cancel(run).await; + if matches!(run.handle, Handle::Legacy { .. }) + || matches!( + outcome, + CancelOutcome::Verified | CancelOutcome::Undelivered { .. } + ) + { + return outcome; + } + match Ssh::cleanup(self, run).await { + Ok(_) => outcome, + Err(error) if error.to_string() == "orx-host InvalidRequest: run has not finished" => { + CancelOutcome::Pending + } + Err(error) => CancelOutcome::Undelivered { + detail: error.to_string(), + }, + } + } + + async fn unwatch(&self, run: &WatchedRun) { + self.feed.lock().await.summaries.remove(&run.id); + } + + async fn read_log( + &self, + run: &WatchedRun, + file: LogFile, + range: ByteRange, + ident: Option<&FileIdent>, + ) -> Result { + if range.end < range.start || range.end - range.start > MAX_PAGE_LEN { + bail!("Invalid log range"); + } + self.validate(run)?; + let target = match &run.handle { + Handle::Legacy { descriptor } if descriptor.kind == "slurm_job" => { + LogTarget::Dir(legacy_dir(&crate::jobs::slurm::run_dir( + descriptor.remote_root.as_deref(), + &run.id, + ))) + } + Handle::Legacy { descriptor } => LogTarget::Dir(legacy_dir( + descriptor + .job_id + .as_deref() + .ok_or_else(|| anyhow!("Legacy run directory missing"))?, + )), + _ => LogTarget::Run(run.id.clone()), + }; + // Sub-ranges small enough for one frame, all of the same log file. + let mut bytes = Vec::new(); + let mut identity = ident.cloned(); + let mut start = range.start; + loop { + let end = range.end.min(start.saturating_add(256 * 1024)); + let response = self + .request(Request::ReadLog { + target: target.clone(), + file, + ident: identity.clone(), + range: ByteRange { start, end }, + anchor: None, + }) + .await?; + match response { + Response::ReadLog { + page: + LogPage::Data { + len, + ident, + start: actual, + bytes: page, + eof, + }, + } if actual == start && page.len() as u64 <= end - start => { + identity = Some(ident.clone()); + start += page.len() as u64; + let short = page.is_empty(); + bytes.extend(page); + if eof || start == range.end || short { + return Ok(LogPage::Data { + len, + ident, + start: range.start, + bytes, + eof, + }); + } + } + Response::ReadLog { + page: reset @ LogPage::Reset { .. }, + } => return Ok(reset), + response => bail!("Unexpected log reply: {response:?}"), + } + } + } +} diff --git a/src/engine/adapters/tests.rs b/src/engine/adapters/tests.rs new file mode 100644 index 000000000..2a59b6546 --- /dev/null +++ b/src/engine/adapters/tests.rs @@ -0,0 +1,3049 @@ +use std::fs; +use std::io::{Read, Seek, SeekFrom, Write}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use async_trait::async_trait; +use orx_host_proto::{ExitReason, LogPage}; +use orx_test_support::{Faults, Sshd}; +use serde_json::json; + +use super::{local::Local, slurm::Slurm, ssh::Ssh}; +use crate::engine::clock::{Clock, TestClock}; +use crate::engine::transport::{Config, HostConn, Status}; +use crate::engine::*; +use crate::local::model::LocalExperiment; +use crate::store::{LaunchSpec, Store, StoredRun, SubmittingRun}; +use orx_test_support::host_binaries as binaries; + +struct Fixture { + server: Sshd, + clock: Arc, + transport_clock: Arc, + engine: Engine, + ssh: Arc, +} + +impl Fixture { + async fn new() -> Self { + Self::with_host_env("").await + } + + /// `exports` are shell lines run before each `orx-host` the fixture starts. + async fn with_host_env(exports: &str) -> Self { + let server = Sshd::start().unwrap(); + let command = server.directory().join("command"); + let text = fs::read_to_string(&command).unwrap(); + let bin = server.directory().join("shims"); + fs::create_dir(&bin).unwrap(); + fs::write( + command, + text.replace( + "export HOME", + &format!( + "export HOME\nexport PATH='{}':\"$PATH\"\nexport ORX_TEST_FAST_STOPS=1\n{exports}", + bin.display() + ), + ), + ) + .unwrap(); + let store = Store::open_at(server.directory().join("store")).unwrap(); + store + .create_local_experiment(&LocalExperiment { + id: "exp".into(), + project_id: "proj".into(), + parent_experiment_id: None, + slug: "exp".into(), + branch_name: "orx/exp".into(), + title: None, + description: None, + run_command: "true".into(), + agent_status: "idle".into(), + created_at: 1, + updated_at: 1, + chat_session_id: None, + archived: false, + }) + .unwrap(); + let clock = Arc::new(TestClock::new()); + let transport_clock = Arc::new(TestClock::new()); + let ssh = connect(&server, transport_clock.clone()).await; + let engine = Engine::new(store, clock.clone()); + Self { + server, + clock, + transport_clock, + engine, + ssh, + } + } + + fn store(&self) -> Store { + Store::open_at(self.server.directory().join("store")).unwrap() + } + + fn dir(&self, id: &str) -> PathBuf { + self.server.home().join("engine-root/runs").join(id) + } + + fn intent(&self, id: &str, script: &str, kind: &str) -> RunIntent { + RunIntent { + run: StoredRun { + id: id.into(), + experiment_id: "exp".into(), + project_id: "proj".into(), + status: "submitting".into(), + backend_json: "{\"kind\":\"engine\"}".into(), + command: script.into(), + created_at: 1, + updated_at: 1, + ended_at: None, + exit_code: None, + commit_sha: None, + result_markdown: None, + cancel_requested: false, + cancel_reason: None, + chat_session_id: Some("chat".into()), + }, + launch: LaunchSpec { + kind: kind.into(), + target: Some(self.server.alias().into()), + options: json!({}), + }, + spec_digest: orx_host::sha(script.as_bytes()), + attempt: 1, + } + } + + async fn submit(&self, backend: &dyn Backend, intent: &RunIntent) { + self.engine + .submit(backend, submitting(intent)) + .await + .unwrap(); + } + + async fn poll(&self, backend: &dyn Backend, ids: &[&str], budget: Duration) { + let runs: Vec<_> = ids + .iter() + .map(|id| { + let run = self.store().get_run(id).unwrap().unwrap(); + WatchedRun { + id: id.to_string(), + handle: handle_of(&run).unwrap(), + } + }) + .collect(); + self.engine + .observe_runs(backend, &runs, budget) + .await + .unwrap(); + } + + async fn terminal(&self, backend: &dyn Backend, id: &str) -> StoredRun { + tokio::time::timeout(Duration::from_secs(15), async { + loop { + self.poll(backend, &[id], Duration::from_millis(50)).await; + let run = self.store().get_run(id).unwrap().unwrap(); + if Phase::parse(&run.status).unwrap().is_terminal() { + return run; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap_or_else(|_| { + panic!( + "{id} never became terminal: {:?}", + self.store().engine_run_state(id) + ) + }) + } + + fn shim(&self, name: &str, script: &str) { + use std::os::unix::fs::PermissionsExt; + let path = self.server.directory().join("shims").join(name); + fs::write(&path, format!("#!/bin/sh\n{script}\n")).unwrap(); + fs::set_permissions(path, fs::Permissions::from_mode(0o700)).unwrap(); + } +} + +fn submitting(intent: &RunIntent) -> SubmittingRun<'_> { + static METADATA: std::sync::OnceLock = + std::sync::OnceLock::new(); + SubmittingRun { + id: &intent.run.id, + experiment_id: "exp", + project_id: "proj", + metadata: METADATA.get_or_init(|| { + crate::jobs::BackendDescriptor::parse("{\"kind\":\"ssh_job\"}").unwrap() + }), + command: &intent.run.command, + created_at: 1, + commit_sha: None, + chat_session_id: Some("chat"), + spec_digest: &intent.spec_digest, + launch: &intent.launch, + } +} + +fn config(directory: &Path, alias: &str) -> Config { + Config { + alias: alias.into(), + root: "~/engine-root".into(), + ssh_config: Some(directory.join("ssh_config")), + control_dir: directory.join("cm"), + binary_dir: Some(binaries()), + #[cfg(unix)] + sharing_home: None, + askpass_executable: std::env::current_exe().unwrap(), + } +} + +async fn live(conn: &HostConn) { + let mut state = conn.state(); + tokio::time::timeout(Duration::from_secs(60), async { + loop { + let current = state.borrow_and_update().clone(); + if current.status == Status::Live { + break; + } + assert_ne!(current.status, Status::NeedsAuth, "{current:?}"); + state.changed().await.unwrap(); + } + }) + .await + .unwrap_or_else(|_| panic!("Host did not connect: {:?}", *conn.state().borrow())); +} + +async fn connect(server: &Sshd, clock: Arc) -> Arc { + let mut config = config(server.directory(), server.alias()); + config.ssh_config = Some(server.config_path()); + let conn = { + let store = Store::open_at(server.directory().join("store")).unwrap(); + let auth = crate::engine::transport::Auth::new(&store, &config.alias).unwrap(); + HostConn::start_shared(config, store, clock, auth) + } + .unwrap(); + live(&conn).await; + Arc::new(Ssh::new( + server.alias().into(), + "~/engine-root".into(), + conn, + )) +} + +async fn exists(path: &Path) { + tokio::time::timeout(Duration::from_secs(60), async { + while !path.exists() { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); +} + +fn watched(f: &Fixture, id: &str) -> WatchedRun { + let run = f.store().get_run(id).unwrap().unwrap(); + WatchedRun { + id: id.into(), + handle: handle_of(&run).unwrap(), + } +} + +fn data(page: LogPage) -> (FileIdent, Vec, bool) { + match page { + LogPage::Data { + ident, bytes, eof, .. + } => (ident, bytes, eof), + page => panic!("Expected data: {page:?}"), + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn ssh_idempotent_launch_staging_notify_and_cleanup() { + let f = Fixture::new().await; + let snapshot = f.server.directory().join("source"); + fs::create_dir(&snapshot).unwrap(); + fs::write(snapshot.join("value"), "staged").unwrap(); + let archive = f.server.directory().join("source.tar"); + assert!(crate::process::command("tar") + .arg("-cf") + .arg(&archive) + .arg("-C") + .arg(&snapshot) + .arg(".") + .status() + .unwrap() + .success()); + let bytes = fs::read(&archive).unwrap(); + let digest = orx_host::sha(&bytes); + let mut intent = f.intent( + "staged", + r#"cat repo/value; printf notice > "$ORX_NOTIFY_FILE"; python3 -c 'import os,time; open("daemon.pid","w").write(str(os.getpid())); time.sleep(60)' >/dev/null 2>&1 & while [ ! -f daemon.pid ]; do sleep .01; done"#, + "ssh_job", + ); + intent.run.backend_json = json!({"kind":"ssh_job", "sourceDigest":digest,"sourcePath":archive,"sourceSize":bytes.len()}).to_string(); + let metadata = crate::jobs::BackendDescriptor::parse(&intent.run.backend_json).unwrap(); + let mut row = submitting(&intent); + row.metadata = &metadata; + f.engine.submit(f.ssh.as_ref(), row).await.unwrap(); + let subscription = f.ssh.follow_logs("staged"); + let second_subscription = f.ssh.follow_logs("staged"); + drop(subscription); + assert!(f + .ssh + .changes(&["staged".into()], Duration::ZERO) + .await + .unwrap()[0] + .1 + .log_len + .is_some()); + assert_eq!(f.terminal(f.ssh.as_ref(), "staged").await.status, "done"); + let run = watched(&f, "staged"); + assert_eq!( + data( + f.ssh + .read_log( + &run, + LogFile::Log, + ByteRange { + start: 0, + end: 1024 + }, + None + ) + .await + .unwrap() + ) + .1, + b"staged" + ); + assert_eq!( + data( + f.ssh + .read_log( + &run, + LogFile::Notify, + ByteRange { + start: 0, + end: 1024 + }, + None + ) + .await + .unwrap() + ) + .1, + b"notice" + ); + assert!(f.ssh.summary("staged").await.is_some()); + let receipt: orx_host_proto::ExitReceipt = + serde_json::from_slice(&fs::read(f.dir("staged").join("exit.json")).unwrap()).unwrap(); + assert_eq!(receipt.reason, ExitReason::Exited); + assert!(!receipt.processes.is_empty()); + let started = fs::read(f.dir("staged").join("started")).unwrap(); + assert!(matches!(f.ssh.recover(&intent).await, Recovery::Found(_))); + assert_eq!(fs::read(f.dir("staged").join("started")).unwrap(), started); + assert_eq!( + f.ssh.cleanup(&run).await.unwrap(), + orx_host_proto::CleanupAck::Accepted + ); + exists(&f.dir("staged").join("cleanup.json")).await; + let cleanup: orx_host_proto::ProcessOutcome = + serde_json::from_slice(&fs::read(f.dir("staged").join("cleanup.json")).unwrap()).unwrap(); + assert!(cleanup.processes.is_empty()); + #[cfg(target_os = "linux")] + assert_eq!(cleanup.outcome, orx_host_proto::CancelOutcome::Verified); + drop(second_subscription); + let notices = f.store().run_notice_batch("chat").unwrap(); + assert_eq!(notices[0].dedupe, "lingering"); + assert_eq!( + notices + .iter() + .filter(|notice| notice.dedupe == "lingering") + .count(), + 1 + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn black_hole_preserves_phase_and_reconnects_after_one_backoff_step() { + let f = Fixture::new().await; + let intent = f.intent("outage", "sleep 60", "ssh_job"); + f.submit(f.ssh.as_ref(), &intent).await; + exists(&f.dir("outage").join("started")).await; + f.poll(f.ssh.as_ref(), &["outage"], Duration::ZERO).await; + assert_eq!( + f.store().get_run("outage").unwrap().unwrap().status, + "running" + ); + f.server + .proxy() + .set(Faults { + black_hole: true, + ..Faults::default() + }) + .unwrap(); + f.transport_clock.advance(Duration::from_secs(36)); + tokio::time::sleep(Duration::from_millis(150)).await; + f.poll(f.ssh.as_ref(), &["outage"], Duration::ZERO).await; + assert_eq!( + f.store().get_run("outage").unwrap().unwrap().status, + "running" + ); + assert!(matches!( + f.store() + .engine_run_state("outage") + .unwrap() + .unwrap() + .contact, + crate::store::Contact::Unreachable { .. } + )); + f.engine + .cancel(f.ssh.as_ref(), "outage", "test") + .await + .unwrap(); + assert!(!f.dir("outage").join("cancel.req").exists()); + f.server.proxy().clear().unwrap(); + f.transport_clock.advance(Duration::from_secs(7)); + live(&f.ssh.conn).await; + f.poll(f.ssh.as_ref(), &["outage"], Duration::ZERO).await; + assert_eq!( + f.store() + .engine_run_state("outage") + .unwrap() + .unwrap() + .contact, + crate::store::Contact::Live + ); + + exists(&f.dir("outage").join("exit.json")).await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn restart_during_backoff_reconciles_a_finished_run_without_waiting_for_retry() { + let f = Fixture::new().await; + let id = "backoff-restart"; + let intent = f.intent( + id, + "touch ready; while [ ! -f release ]; do sleep .01; done", + "ssh_job", + ); + f.submit(f.ssh.as_ref(), &intent).await; + exists(&f.dir(id).join("ready")).await; + f.poll(f.ssh.as_ref(), &[id], Duration::ZERO).await; + assert_eq!(f.store().get_run(id).unwrap().unwrap().status, "running"); + + f.server + .proxy() + .set(Faults { + refuse_new: true, + ..Faults::default() + }) + .unwrap(); + f.server.proxy().reset().unwrap(); + tokio::time::timeout(Duration::from_secs(5), async { + while f.ssh.conn.state().borrow().status == Status::Live { + tokio::time::sleep(Duration::from_millis(1)).await; + } + }) + .await + .unwrap(); + assert!(f.ssh.conn.retry().await.is_err()); + assert_eq!(f.ssh.conn.state().borrow().status, Status::Backoff); + fs::write(f.dir(id).join("release"), "").unwrap(); + exists(&f.dir(id).join("exit.json")).await; + f.server.proxy().clear().unwrap(); + + let restarted = connect(&f.server, f.transport_clock.clone()).await; + f.poll(restarted.as_ref(), &[id], Duration::ZERO).await; + assert_eq!(f.store().get_run(id).unwrap().unwrap().status, "done"); + let terminals = f + .store() + .run_notice_batch("chat") + .unwrap() + .iter() + .filter(|notice| notice.kind == crate::store::TERMINAL) + .count(); + assert_eq!(terminals, 1); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn completion_while_paused_arrives_in_one_feed_reply() { + let f = Fixture::new().await; + f.submit( + f.ssh.as_ref(), + &f.intent( + "paused", + "while [ ! -f finish ]; do sleep 0.05; done", + "ssh_job", + ), + ) + .await; + exists(&f.dir("paused").join("started")).await; + f.poll(f.ssh.as_ref(), &["paused"], Duration::ZERO).await; + f.server + .proxy() + .set(Faults { + paused: true, + ..Faults::default() + }) + .unwrap(); + let run = watched(&f, "paused"); + let runs = [run]; + let reply = f.ssh.observe(&runs, Duration::from_secs(25)); + tokio::pin!(reply); + assert!(futures::poll!(reply.as_mut()).is_pending()); + fs::write(f.dir("paused").join("finish"), "").unwrap(); + exists(&f.dir("paused").join("exit.json")).await; + f.server.proxy().clear().unwrap(); + for (id, observation) in tokio::time::timeout(Duration::from_secs(5), reply) + .await + .unwrap() + { + f.engine.observe(&id, observation).unwrap(); + } + assert_eq!(f.store().get_run("paused").unwrap().unwrap().status, "done"); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn cancel_reaches_new_sessions_and_double_fork_children() { + let f = Fixture::new().await; + let script = "python3 -c 'import os,time; p=os.fork(); p and os._exit(0); os.setsid(); p=os.fork(); p and os._exit(0); open(\"daemon\",\"w\").write(str(os.getpid())); time.sleep(60)'\nwhile [ ! -f daemon ]; do sleep .01; done\nsleep 60"; + f.submit(f.ssh.as_ref(), &f.intent("fork", script, "ssh_job")) + .await; + exists(&f.dir("fork").join("daemon")).await; + f.engine + .cancel(f.ssh.as_ref(), "fork", "test") + .await + .unwrap(); + exists(&f.dir("fork").join("exit.json")).await; + f.poll(f.ssh.as_ref(), &["fork"], Duration::ZERO).await; + let receipt: orx_host_proto::ExitReceipt = + serde_json::from_slice(&fs::read(f.dir("fork").join("exit.json")).unwrap()).unwrap(); + assert!(receipt.processes.is_empty()); + #[cfg(target_os = "linux")] + { + assert_eq!(receipt.outcome, orx_host_proto::CancelOutcome::Verified); + assert_eq!( + f.store().get_run("fork").unwrap().unwrap().status, + "cancelled" + ); + } + #[cfg(target_os = "macos")] + assert!( + matches!(receipt.outcome, orx_host_proto::CancelOutcome::Verified) + || matches!(&receipt.outcome, orx_host_proto::CancelOutcome::Unverifiable { unreadable } if !unreadable.is_empty()) + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn cancel_script_is_staged_before_payload_starts() { + let f = Fixture::new().await; + let mut intent = f.intent("container", "sleep 60", "ssh_job"); + intent.launch.options = json!({"cancel_sh":"printf stopped > container-stopped"}); + f.submit(f.ssh.as_ref(), &intent).await; + exists(&f.dir("container").join("started")).await; + assert!(f.dir("container").join("cancel.sh").is_file()); + f.engine + .cancel(f.ssh.as_ref(), "container", "test") + .await + .unwrap(); + exists(&f.dir("container").join("exit.json")).await; + assert_eq!( + fs::read_to_string(f.dir("container").join("container-stopped")).unwrap(), + "stopped" + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn fifty_runs_share_one_ssh_session() { + let f = Fixture::new().await; + for index in 0..50 { + f.submit( + f.ssh.as_ref(), + &f.intent(&format!("run-{index}"), "printf x", "ssh_job"), + ) + .await; + } + let ids: Vec<_> = (0..50).map(|index| format!("run-{index}")).collect(); + let refs: Vec<_> = ids.iter().map(String::as_str).collect(); + tokio::time::timeout(Duration::from_secs(15), async { + loop { + f.poll(f.ssh.as_ref(), &refs, Duration::from_millis(50)) + .await; + if ids + .iter() + .all(|id| f.store().get_run(id).unwrap().unwrap().status == "done") + { + break; + } + } + }) + .await + .unwrap(); + let output = crate::process::command("ps") + .args(["-A", "-ww", "-o", "comm=,args="]) + .output() + .unwrap(); + let sessions = String::from_utf8_lossy(&output.stdout) + .lines() + .filter(|line| { + let mut fields = line.split_whitespace(); + fields.next().is_some_and(|name| { + Path::new(name) + .file_name() + .is_some_and(|name| name == "ssh") + }) && line.contains(f.server.config_path().to_str().unwrap()) + }) + .count(); + assert!((1..=2).contains(&sessions), "{sessions} ssh processes"); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn gigabyte_random_pages_survive_one_hundred_reconnects() { + let f = Fixture::new().await; + let dir = f.dir("large"); + fs::create_dir_all(&dir).unwrap(); + let mut file = fs::File::create(dir.join("log")).unwrap(); + let len = 1024 * 1024 * 1024 + 17; + file.set_len(len).unwrap(); + let mut seed = 7u64; + let mut offsets = Vec::new(); + for index in 0..100 { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1); + let offset = seed % (len - 8192); + offsets.push(offset); + file.seek(SeekFrom::Start(offset)).unwrap(); + file.write_all(&vec![index as u8; 8192]).unwrap(); + } + drop(file); + let run = WatchedRun { + id: "large".into(), + handle: f.ssh.handle(), + }; + let mut local = fs::File::open(dir.join("log")).unwrap(); + let first = data( + f.ssh + .read_log( + &run, + LogFile::Log, + ByteRange { + start: 0, + end: 1024 * 1024, + }, + None, + ) + .await + .unwrap(), + ); + let identity = first.0; + for offset in offsets { + f.server.proxy().reset().unwrap(); + let mut state = f.ssh.conn.state(); + tokio::time::timeout( + Duration::from_secs(5), + state.wait_for(|state| state.status != Status::Live), + ) + .await + .unwrap() + .unwrap(); + f.ssh.conn.retry().await.unwrap(); + let mut expected = vec![0; 8192]; + local.seek(SeekFrom::Start(offset)).unwrap(); + local.read_exact(&mut expected).unwrap(); + let page = data( + f.ssh + .read_log( + &run, + LogFile::Log, + ByteRange { + start: offset, + end: offset + 8192, + }, + Some(&identity), + ) + .await + .unwrap(), + ); + assert_eq!(page.1, expected); + } + let (_, final_bytes, eof) = data( + f.ssh + .read_log( + &run, + LogFile::Log, + ByteRange { + start: len - 17, + end: len + 4096, + }, + Some(&identity), + ) + .await + .unwrap(), + ); + assert_eq!(final_bytes, vec![0; 17]); + assert!(eof); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn adopted_legacy_run_uses_read_only_inspection_and_group_cancel() { + use std::os::unix::process::CommandExt; + let f = Fixture::new().await; + let dir = f.server.home().join("legacy"); + fs::create_dir(&dir).unwrap(); + let script = "sleep 60"; + fs::write(dir.join("run.sh"), script).unwrap(); + let mut child = crate::process::command("bash") + .arg(dir.join("run.sh")) + .process_group(0) + .spawn() + .unwrap(); + fs::write(dir.join("pid"), child.id().to_string()).unwrap(); + let descriptor = crate::jobs::BackendDescriptor::parse( + &json!({"kind":"ssh_job","namespace":f.server.alias(),"jobId":dir}).to_string(), + ) + .unwrap(); + let run = WatchedRun { + id: "legacy".into(), + handle: Handle::Legacy { + descriptor: Box::new(descriptor), + }, + }; + let began = Instant::now(); + assert!(matches!( + f.ssh + .observe(std::slice::from_ref(&run), Duration::from_millis(100)) + .await[0] + .1, + Observation::Running { started_at: None } + )); + assert!(began.elapsed() >= Duration::from_millis(100)); + let outcome = f.ssh.cancel(&run).await; + let _ = child.wait(); + assert!(matches!(outcome, CancelOutcome::Verified), "{outcome:?}"); + assert!(matches!( + Backend::cleanup(f.ssh.as_ref(), &run).await, + CancelOutcome::Verified + )); + assert_eq!(fs::read_to_string(dir.join("run.sh")).unwrap(), script); + assert!(!dir.join("launch.json").exists()); + fs::write(dir.join("exit_code"), "0\n").unwrap(); + assert!(f + .ssh + .observe(&[run], Duration::ZERO) + .await + .iter() + .any(|(_, observation)| matches!(observation, Observation::Exited { code: Some(0), .. }))); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn slurm_wrapper_receipt_wins_and_missing_accounting_never_terminalizes() { + let f = Fixture::new().await; + f.shim("sbatch", r#"cat > "$HOME/batch" +SLURM_JOB_ID=123 python3 -c 'import os,subprocess; subprocess.Popen(["bash",os.environ["HOME"]+"/batch"],stdin=subprocess.DEVNULL,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,start_new_session=True)' +printf '123\n'"#); + f.shim("squeue", "exit 0"); + f.shim("sacct", "exit 1"); + f.shim("scancel", "printf '%s' \"$*\" > \"$HOME/scancel\""); + let slurm = Slurm::new(f.ssh.clone(), f.clock.clone()); + let intent = f.intent("scheduled", "printf compute; printf notice > \"$ORX_NOTIFY_FILE\"; while [ ! -f release ]; do sleep .01; done", "slurm_job"); + f.submit(&slurm, &intent).await; + exists(&f.dir("scheduled").join("notify")).await; + let observed = slurm + .observe(&[watched(&f, "scheduled")], Duration::ZERO) + .await; + assert_eq!( + observed + .iter() + .filter(|(_, observation)| matches!(observation, Observation::Notify { .. })) + .count(), + 1 + ); + fs::write(f.dir("scheduled").join("release"), "").unwrap(); + assert_eq!(f.terminal(&slurm, "scheduled").await.status, "done"); + assert!( + matches!(slurm.recover(&intent).await, Recovery::Found(Handle::Slurm { job, .. }) if job.as_deref() == Some("123")) + ); + assert_eq!( + data( + slurm + .read_log( + &watched(&f, "scheduled"), + LogFile::Log, + ByteRange { start: 0, end: 100 }, + None + ) + .await + .unwrap() + ) + .1, + b"compute" + ); + fs::remove_file(f.dir("scheduled").join("slurm.job")).unwrap(); + assert!(matches!( + slurm.recover(&intent).await, + Recovery::Found(Handle::Slurm { job: None, .. }) + )); + f.shim("sbatch", "cat >/dev/null; printf '456\\n'"); + let intent = f.intent("forgotten", "false", "slurm_job"); + f.submit(&slurm, &intent).await; + f.poll(&slurm, &["forgotten"], Duration::ZERO).await; + assert!(matches!( + f.store() + .engine_run_state("forgotten") + .unwrap() + .unwrap() + .contact, + crate::store::Contact::Unreconciled { .. } + )); + f.clock.advance(Duration::from_secs(3600)); + f.poll(&slurm, &["forgotten"], Duration::ZERO).await; + assert_eq!( + f.store().get_run("forgotten").unwrap().unwrap().status, + "starting" + ); + f.shim("sacct", "printf '456|forgotten|FAILED|7:0\\n'"); + f.clock.advance(Duration::from_secs(31)); + f.poll(&slurm, &["forgotten"], Duration::ZERO).await; + assert_eq!( + f.store().get_run("forgotten").unwrap().unwrap().status, + "starting" + ); + tokio::time::sleep(Duration::from_millis(150)).await; + f.clock.advance(Duration::from_secs(31)); + f.poll(&slurm, &["forgotten"], Duration::ZERO).await; + assert_eq!( + f.store().get_run("forgotten").unwrap().unwrap().status, + "failed" + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn slurm_cancel_keeps_started_wrappers_and_scancels_pending_jobs() { + let f = Fixture::new().await; + let home = f.server.home(); + let status = |id: &str| f.store().get_run(id).unwrap().unwrap().status; + f.shim("sbatch", r#"printf '%s' "$*" > "$HOME/sbatch" +cat > "$HOME/batch" +SLURM_JOB_ID=123 python3 -c 'import os,subprocess; subprocess.Popen(["bash",os.environ["HOME"]+"/batch"],stdin=subprocess.DEVNULL,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,start_new_session=True)' +printf '123\n'"#); + f.shim( + "squeue", + "printf '%s' \"$*\" > \"$HOME/squeue\"; printf '123|started|RUNNING\\n'", + ); + f.shim("sacct", "exit 1"); + f.shim("scancel", "printf '%s' \"$*\" > \"$HOME/scancel\""); + let slurm = Slurm::new(f.ssh.clone(), f.clock.clone()); + let intent = f.intent( + "started", + "while [ ! -f release ]; do sleep .01; done", + "slurm_job", + ); + f.submit(&slurm, &intent).await; + exists(&f.dir("started").join("started")).await; + let sbatch = fs::read_to_string(home.join("sbatch")).unwrap(); + assert!(sbatch.contains(&format!( + "--output={}", + f.dir("started").join("slurm.out").display() + ))); + // A started wrapper owns the cancel: scancel would kill it before its receipt. + assert!(matches!( + slurm.cancel(&watched(&f, "started")).await, + CancelOutcome::Pending + )); + exists(&f.dir("started").join("exit.json")).await; + let receipt: orx_host_proto::ExitReceipt = + serde_json::from_slice(&fs::read(f.dir("started").join("exit.json")).unwrap()).unwrap(); + assert_eq!(receipt.reason, ExitReason::Cancelled); + assert!(!home.join("scancel").exists()); + #[cfg(target_os = "linux")] + assert_eq!(f.terminal(&slurm, "started").await.status, "cancelled"); + + f.shim("sbatch", "cat >/dev/null; printf '456\\n'"); + f.shim( + "squeue", + "printf '%s' \"$*\" > \"$HOME/squeue\"; printf '456|pending|PENDING\\n'", + ); + let intent = f.intent("pending", "true", "slurm_job"); + f.submit(&slurm, &intent).await; + f.poll(&slurm, &["pending"], Duration::ZERO).await; + assert_eq!(status("pending"), "starting"); + assert!(fs::read_to_string(home.join("squeue")) + .unwrap() + .contains("--states=all")); + // A due queue refresh reports at once instead of long-polling an unchanged feed. + f.shim("squeue", "printf '456|pending|RUNNING\\n'"); + f.clock.advance(Duration::from_secs(31)); + let began = Instant::now(); + f.poll(&slurm, &["pending"], Duration::from_secs(25)).await; + assert!(began.elapsed() < Duration::from_secs(5)); + assert_eq!(status("pending"), "running"); + assert!(matches!( + slurm.cancel(&watched(&f, "pending")).await, + CancelOutcome::Pending + )); + assert_eq!( + fs::read_to_string(home.join("scancel")).unwrap(), + "--name=pending" + ); + assert_eq!(f.terminal(&slurm, "pending").await.status, "cancelled"); + + // scancel behind orx's back: squeue keeps the terminal state until MinJobAge, no receipt. + f.shim("sbatch", "cat >/dev/null; printf '789\\n'"); + f.shim("squeue", "printf '789|killed|CANCELLED\\n'"); + let intent = f.intent("killed", "true", "slurm_job"); + f.submit(&slurm, &intent).await; + f.poll(&slurm, &["killed"], Duration::ZERO).await; + assert_eq!(status("killed"), "starting"); + tokio::time::sleep(Duration::from_millis(150)).await; + f.clock.advance(Duration::from_secs(31)); + f.poll(&slurm, &["killed"], Duration::ZERO).await; + assert_eq!(status("killed"), "cancelled"); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn local_direct_child_completion_recovery_and_pages() { + let f = Fixture::new().await; + let local = Local::new(f.server.directory().join("local-runs")); + let intent = f.intent( + "local", + "printf local; printf notice > \"$ORX_NOTIFY_FILE\"; while [ ! -f release ]; do sleep .01; done; sleep 3 >/dev/null 2>&1 &", + "local_job", + ); + f.submit(&local, &intent).await; + exists(&f.server.directory().join("local-runs/local/notify")).await; + assert!(matches!( + local.recover(&intent).await, + Recovery::Found(Handle::Local { .. }) + )); + let run = watched(&f, "local"); + let (identity, bytes, eof) = data( + local + .read_log(&run, LogFile::Log, ByteRange { start: 0, end: 100 }, None) + .await + .unwrap(), + ); + assert_eq!(bytes, b"local"); + assert!(eof); + let mut log = fs::OpenOptions::new() + .append(true) + .open(f.server.directory().join("local-runs/local/log")) + .unwrap(); + log.write_all(b" append").unwrap(); + assert_eq!( + data( + local + .read_log( + &run, + LogFile::Log, + ByteRange { start: 5, end: 100 }, + Some(&identity) + ) + .await + .unwrap() + ) + .1, + b" append" + ); + + fs::write(f.server.directory().join("local-runs/local/release"), "").unwrap(); + let started = Instant::now(); + assert_eq!(f.terminal(&local, "local").await.status, "done"); + let dir = f.server.directory().join("local-runs/local"); + let source_start = orx_host::wrapper::started_at(&dir).unwrap(); + assert_eq!( + f.store() + .engine_run_state("local") + .unwrap() + .unwrap() + .started_at, + Some(source_start) + ); + assert_eq!( + f.store().get_run("local").unwrap().unwrap().ended_at, + orx_host::wrapper::receipt(&dir) + .unwrap() + .unwrap() + .finished_at + .map(|finished_at| finished_at.min(f.clock.wall_ms())) + ); + assert!(started.elapsed() < Duration::from_secs(2)); + + assert!(matches!( + local + .read_log( + &run, + LogFile::Log, + ByteRange { + start: 50, + end: 100 + }, + Some(&identity) + ) + .await + .unwrap(), + LogPage::Reset { .. } + )); + assert_eq!( + data( + local + .read_log( + &run, + LogFile::Notify, + ByteRange { start: 0, end: 100 }, + None + ) + .await + .unwrap() + ) + .1, + b"notice" + ); + assert!(matches!( + local + .recover(&f.intent("absent", "true", "tinker_job")) + .await, + Recovery::Absent + )); +} + +struct Crash<'a> { + backend: &'a dyn Backend, + directory: PathBuf, + point: String, +} + +fn kill_engine() -> ! { + unsafe { + libc::kill(std::process::id() as i32, libc::SIGKILL); + } + unreachable!() +} + +#[async_trait] +impl Backend for Crash<'_> { + async fn launch(&self, intent: &RunIntent, fence: &Fence<'_>) -> Result { + if self.point == "fence" { + kill_engine(); + } + let handle = self.backend.launch(intent, fence).await; + if self.point == "response" { + exists(&self.directory.join("executions")).await; + kill_engine(); + } + handle + } + async fn recover(&self, intent: &RunIntent) -> Recovery { + self.backend.recover(intent).await + } + async fn observe(&self, runs: &[WatchedRun], budget: Duration) -> Vec<(String, Observation)> { + self.backend.observe(runs, budget).await + } + async fn cancel(&self, run: &WatchedRun) -> CancelOutcome { + self.backend.cancel(run).await + } + async fn read_log( + &self, + run: &WatchedRun, + file: LogFile, + range: ByteRange, + ident: Option<&FileIdent>, + ) -> crate::error::Result { + self.backend.read_log(run, file, range, ident).await + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn submission_child() { + let Ok(directory) = std::env::var("ORX_ADAPTER_CRASH_DIRECTORY") else { + return; + }; + let directory = PathBuf::from(directory); + let alias = std::env::var("ORX_ADAPTER_CRASH_ALIAS").unwrap(); + let point = std::env::var("ORX_ADAPTER_CRASH_POINT").unwrap(); + let intent: serde_json::Value = + serde_json::from_slice(&fs::read(directory.join("intent")).unwrap()).unwrap(); + let store = Store::open_at(directory.join("store")).unwrap(); + let clock = Arc::new(TestClock::new()); + let conn = { + let config = config(&directory, &alias); + let store = Store::open_at(directory.join("store")).unwrap(); + let auth = crate::engine::transport::Auth::new(&store, &config.alias).unwrap(); + HostConn::start_shared(config, store, clock.clone(), auth) + } + .unwrap(); + live(&conn).await; + let ssh = Ssh::new(alias.clone(), "~/engine-root".into(), conn); + let engine = Engine::new(store, clock); + let script = intent["script"].as_str().unwrap(); + let metadata = crate::jobs::BackendDescriptor::parse("{\"kind\":\"ssh_job\"}").unwrap(); + let kind = intent["kind"].as_str().unwrap(); + let launch = LaunchSpec { + kind: kind.into(), + target: Some(alias), + options: json!({}), + }; + let digest = orx_host::sha(script.as_bytes()); + let row = SubmittingRun { + id: intent["id"].as_str().unwrap(), + experiment_id: "exp", + project_id: "proj", + metadata: &metadata, + command: script, + created_at: 1, + commit_sha: None, + chat_session_id: Some("chat"), + spec_digest: &digest, + launch: &launch, + }; + if point == "intent" { + engine.store().insert_submitting_run(row).unwrap(); + kill_engine(); + } + let local = Local::new(directory.join("local-runs")); + let backend: &dyn Backend = if kind == "ssh_job" { &ssh } else { &local }; + let run_directory = if kind == "ssh_job" { + directory.join("home/engine-root/runs").join(row.id) + } else { + directory.join("local-runs").join(row.id) + }; + engine + .submit( + &Crash { + backend, + point, + directory: run_directory.clone(), + }, + row, + ) + .await + .unwrap(); + exists(&run_directory.join("executions")).await; + kill_engine(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn kill_engine_at_each_submission_boundary_then_restart_executes_once() { + if std::env::var_os("ORX_ADAPTER_CRASH_PARENT").is_none() { + let output = crate::process::tokio_command(std::env::current_exe().unwrap()) + .args(["--exact", "engine::adapters::tests::kill_engine_at_each_submission_boundary_then_restart_executes_once", "--nocapture"]) + .env("ORX_ADAPTER_CRASH_PARENT", "1") + .env(crate::jobs::tinker::API_KEY_ENV, "test-only-tinker-key") + .output().await.unwrap(); + assert!( + output.status.success(), + "{}\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + return; + } + + let mut f = Fixture::new().await; + let local = Local::new(f.server.directory().join("local-runs")); + for kind in ["ssh_job", "local_job", "tinker_job"] { + for point in ["intent", "fence", "response", "handle"] { + let id = format!("crash-{kind}-{point}"); + let script = "printf x >> executions; while [ ! -f release ]; do sleep .01; done"; + fs::write( + f.server.directory().join("intent"), + json!({"id":id,"script":script,"kind":kind}).to_string(), + ) + .unwrap(); + let output = crate::process::tokio_command(std::env::current_exe().unwrap()) + .args([ + "--exact", + "engine::adapters::tests::submission_child", + "--nocapture", + ]) + .env("ORX_ADAPTER_CRASH_DIRECTORY", f.server.directory()) + .env("ORX_ADAPTER_CRASH_ALIAS", f.server.alias()) + .env("ORX_ADAPTER_CRASH_POINT", point) + .output() + .await + .unwrap(); + use std::os::unix::process::ExitStatusExt; + assert_eq!( + output.status.signal(), + Some(libc::SIGKILL), + "{kind} {point}: {}", + String::from_utf8_lossy(&output.stdout) + ); + let run_directory = if kind == "ssh_job" { + f.dir(&id) + } else { + f.server.directory().join("local-runs").join(&id) + }; + f.ssh = connect(&f.server, f.transport_clock.clone()).await; + let backend: &dyn Backend = if kind == "ssh_job" { + f.ssh.as_ref() + } else { + &local + }; + let stored = f.store().engine_run_state(&id).unwrap().unwrap(); + assert!(stored + .submission_fence + .as_ref() + .is_none_or(|fence| fence.submitter.is_none())); + f.engine.recover(backend, &id).await.unwrap(); + exists(&run_directory.join("executions")).await; + f.poll(backend, &[&id], Duration::ZERO).await; + assert_eq!(f.store().get_run(&id).unwrap().unwrap().status, "running"); + fs::write(run_directory.join("release"), "").unwrap(); + assert_eq!(f.terminal(backend, &id).await.status, "done"); + let started = fs::read(run_directory.join("started")).unwrap(); + let intent = f.intent(&id, script, kind); + for _ in 0..3 { + assert!(matches!(backend.recover(&intent).await, Recovery::Found(_))); + } + assert_eq!(fs::read(run_directory.join("started")).unwrap(), started); + assert_eq!(fs::read(run_directory.join("executions")).unwrap(), b"x"); + } + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn adopted_slurm_uses_recorded_job_id_and_old_receipt_directory() { + let f = Fixture::new().await; + f.shim("squeue", "printf '789|orx-legacy-s|RUNNING\n'"); + f.shim("sacct", "exit 1"); + f.shim("scancel", "printf '%s' \"$*\" > \"$HOME/scancel\""); + let root = f.server.home().join("old-root"); + let dir = root.join("runs/legacy-slurm"); + fs::create_dir_all(&dir).unwrap(); + fs::write(dir.join("job.sbatch"), "old batch script").unwrap(); + fs::write(dir.join("log"), "old log").unwrap(); + fs::write(dir.join("notify"), "legacy notice").unwrap(); + let descriptor = crate::jobs::BackendDescriptor::parse( + &json!({ + "kind":"slurm_job", "namespace":f.server.alias(), "jobId":"789", "remoteRoot":root, + }) + .to_string(), + ) + .unwrap(); + let run = WatchedRun { + id: "legacy-slurm".into(), + handle: Handle::Legacy { + descriptor: Box::new(descriptor), + }, + }; + let slurm = Slurm::new(f.ssh.clone(), f.clock.clone()); + let observed = slurm + .observe(std::slice::from_ref(&run), Duration::ZERO) + .await; + assert!(matches!(observed[0].1, Observation::Running { .. })); + assert_eq!( + observed + .iter() + .filter(|(_, observation)| matches!(observation, Observation::Notify { len: 13 })) + .count(), + 1 + ); + assert!(matches!(slurm.cancel(&run).await, CancelOutcome::Pending)); + assert!(matches!( + Backend::cleanup(&slurm, &run).await, + CancelOutcome::Pending + )); + assert_eq!( + fs::read_to_string(f.server.home().join("scancel")).unwrap(), + "789" + ); + assert_eq!( + data( + slurm + .read_log(&run, LogFile::Log, ByteRange { start: 0, end: 100 }, None) + .await + .unwrap() + ) + .1, + b"old log" + ); + fs::write(dir.join("exit_code"), "").unwrap(); + f.clock.advance(Duration::from_secs(31)); + assert!(matches!( + slurm + .observe(std::slice::from_ref(&run), Duration::ZERO) + .await[0] + .1, + Observation::Unreconciled { .. } + )); + fs::write(dir.join("exit_code"), "0\n").unwrap(); + f.clock.advance(Duration::from_secs(31)); + assert!(matches!( + slurm.observe(&[run], Duration::ZERO).await[0].1, + Observation::Exited { code: Some(0), .. } + )); + assert_eq!( + fs::read_to_string(dir.join("job.sbatch")).unwrap(), + "old batch script" + ); + assert!(!dir.join("launch.json").exists()); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn local_cancel_uses_wrapper_observations_and_tinker_recovers_the_same_layout() { + let f = Fixture::new().await; + let root = f.server.directory().join("local-runs"); + let local = Local::new(root.clone()); + f.submit(&local, &f.intent("cancel-local", "sleep 60", "local_job")) + .await; + exists(&root.join("cancel-local/started")).await; + assert!(matches!( + local.cancel(&watched(&f, "cancel-local")).await, + CancelOutcome::Pending + )); + exists(&root.join("cancel-local/exit.json")).await; + let observed = local + .observe(&[watched(&f, "cancel-local")], Duration::ZERO) + .await; + let receipt = orx_host::wrapper::receipt(&root.join("cancel-local")) + .unwrap() + .unwrap(); + let summary = orx_host_proto::Summary { + started_at: orx_host::wrapper::started_at(&root.join("cancel-local")), + state: orx_host_proto::RunState::Exited { receipt }, + log_len: Some(0), + notify_len: 0, + cleanup: None, + }; + assert_eq!( + observed, + super::ssh::observations("cancel-local".into(), &summary) + ); + let intent = f.intent("tinker", "true", "tinker_job"); + fs::create_dir(root.join("tinker")).unwrap(); + orx_host::publish( + &root.join("tinker/launch.json"), + &orx_host_proto::LaunchIntent { + run: intent.run.id.clone(), + digest: intent.spec_digest.clone(), + run_sh: "true".into(), + env: Default::default(), + source: None, + cancel_sh: None, + }, + ) + .unwrap(); + fs::write(root.join("tinker/started"), "").unwrap(); + assert!(matches!( + local.recover(&intent).await, + Recovery::Found(Handle::Tinker { .. }) + )); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn term_resistant_local_run_stays_running_until_the_wrapper_receipt() { + let f = Fixture::new().await; + let root = f.server.directory().join("local-runs"); + let local = Local::new(root.clone()); + let script = "trap '' TERM; echo first; touch ready; while :; do sleep 1; done"; + f.submit(&local, &f.intent("stubborn", script, "local_job")) + .await; + let dir = root.join("stubborn"); + exists(&dir.join("ready")).await; + f.poll(&local, &["stubborn"], Duration::ZERO).await; + assert!(f.engine.cancel(&local, "stubborn", "user").await.unwrap()); + assert_eq!( + f.store().get_run("stubborn").unwrap().unwrap().status, + "running" + ); + let deadline = Instant::now() + Duration::from_secs(15); + while !dir.join("exit.json").exists() { + assert!(Instant::now() < deadline); + f.poll(&local, &["stubborn"], Duration::ZERO).await; + if !dir.join("exit.json").exists() { + assert_eq!( + f.store().get_run("stubborn").unwrap().unwrap().status, + "running" + ); + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + let receipt = orx_host::wrapper::receipt(&dir).unwrap().unwrap(); + assert!(receipt.processes.is_empty()); + assert_eq!(receipt.reason, ExitReason::Cancelled); + f.poll(&local, &["stubborn"], Duration::ZERO).await; + let status = f.store().get_run("stubborn").unwrap().unwrap().status; + assert_eq!(status, "cancelled"); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn invalid_launch_configuration_is_rejected_without_a_job_or_recovery_loop() { + let f = Fixture::new().await; + let slurm = Slurm::new(f.ssh.clone(), f.clock.clone()); + let local = Local::new(f.server.directory().join("local-runs")); + let mut ssh_intent = f.intent("invalid-ssh", "true", "ssh_job"); + ssh_intent.launch.options = json!({"env":42}); + let mut slurm_intent = f.intent("invalid-slurm", "true", "slurm_job"); + slurm_intent.launch.options = json!({"directives":{"output":"wrong"}}); + let mut local_intent = f.intent("invalid-local", "true", "local_job"); + local_intent.launch.options = json!({"env":42}); + for (backend, intent) in [ + (f.ssh.as_ref() as &dyn Backend, &ssh_intent), + (&slurm, &slurm_intent), + (&local, &local_intent), + ] { + let store = std::sync::Mutex::new(f.store()); + let fence = Fence { + store: &store, + run_id: &intent.run.id, + attempt: 1, + taken_at: 1, + }; + assert!(matches!( + backend.launch(intent, &fence).await, + Err(LaunchError::Rejected { .. }) + )); + f.submit(backend, intent).await; + assert_eq!( + f.store().get_run(&intent.run.id).unwrap().unwrap().status, + "failed" + ); + assert!(!f.dir(&intent.run.id).exists()); + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn interrupted_blob_upload_recovers_without_failing_the_run() { + let f = Fixture::new().await; + let source = f.server.directory().join("upload-source"); + fs::create_dir(&source).unwrap(); + fs::write(source.join("large"), vec![b'x'; 8 * 1024 * 1024]).unwrap(); + let archive = f.server.directory().join("upload.tar"); + assert!(crate::process::command("tar") + .arg("-cf") + .arg(&archive) + .arg("-C") + .arg(&source) + .arg(".") + .status() + .unwrap() + .success()); + let bytes = fs::read(&archive).unwrap(); + let digest = orx_host::sha(&bytes); + let mut intent = f.intent("upload", "printf x >> executions", "ssh_job"); + intent.run.backend_json = json!({"kind":"ssh_job", "sourceDigest":digest,"sourcePath":archive,"sourceSize":bytes.len()}).to_string(); + let metadata = crate::jobs::BackendDescriptor::parse(&intent.run.backend_json).unwrap(); + let mut row = submitting(&intent); + row.metadata = &metadata; + let interrupted = async { + let part = f + .server + .home() + .join("engine-root/sources") + .join(format!("{digest}.part")); + tokio::time::timeout(Duration::from_secs(10), async { + while !fs::metadata(&part).is_ok_and(|metadata| metadata.len() >= 256 * 1024) { + tokio::time::sleep(Duration::from_millis(1)).await; + } + }) + .await + .unwrap(); + f.server.proxy().reset().unwrap(); + }; + let (submitted, ()) = tokio::join!(f.engine.submit(f.ssh.as_ref(), row), interrupted); + submitted.unwrap(); + assert_eq!( + f.store().get_run("upload").unwrap().unwrap().status, + "submitting" + ); + f.transport_clock.advance(Duration::from_secs(7)); + live(&f.ssh.conn).await; + f.clock.advance(Duration::from_secs(7)); + f.engine.recover(f.ssh.as_ref(), "upload").await.unwrap(); + assert_eq!(f.terminal(f.ssh.as_ref(), "upload").await.status, "done"); + assert_eq!(fs::read(f.dir("upload").join("executions")).unwrap(), b"x"); +} + +/// A source sweep can remove a blob between `HasBlob` and its pin: the launch fails rather +/// than leaving the run staging forever, and the next attempt stages the source again. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_source_swept_before_launch_is_restaged_and_runs() { + let f = Fixture::new().await; + let source = f.server.directory().join("swept-source"); + fs::create_dir(&source).unwrap(); + fs::write(source.join("train"), "x").unwrap(); + let archive = f.server.directory().join("swept.tar"); + assert!(crate::process::command("tar") + .arg("-cf") + .arg(&archive) + .arg("-C") + .arg(&source) + .arg(".") + .status() + .unwrap() + .success()); + let bytes = fs::read(&archive).unwrap(); + let digest = orx_host::sha(&bytes); + let mut intent = f.intent("swept", "cat repo/train >> executions", "ssh_job"); + intent.run.backend_json = json!({"kind":"ssh_job", "sourceDigest":digest,"sourcePath":archive,"sourceSize":bytes.len()}).to_string(); + f.ssh + .stage_blob(&digest, &archive, bytes.len() as u64) + .await + .unwrap(); + let blob = f.server.home().join("engine-root/sources").join(&digest); + fs::remove_file(&blob).unwrap(); + assert!(matches!( + f.ssh.pin_source("swept", &digest, &|| false).await, + Err(LaunchError::Interrupted { .. }) + )); + assert!(matches!(f.ssh.recover(&intent).await, Recovery::Absent)); + let metadata = crate::jobs::BackendDescriptor::parse(&intent.run.backend_json).unwrap(); + let mut row = submitting(&intent); + row.metadata = &metadata; + f.engine.submit(f.ssh.as_ref(), row).await.unwrap(); + let executions = f.dir("swept").join("executions"); + tokio::time::timeout(Duration::from_secs(10), async { + while fs::read(&executions).unwrap_or_default() != b"x" { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + assert!(blob.exists()); +} + +/// A cancel accepted while a source is pinned slice by slice stops the pin and is honored by +/// recovery; the payload never launches. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_cancel_accepted_while_pinning_stops_before_launch() { + let f = Fixture::with_host_env("export ORX_TEST_CROSS_DEVICE=1\nexport ORX_TEST_SLOW_RPC=100") + .await; + let archive = f.server.directory().join("large.tar"); + fs::write(&archive, vec![b'x'; 8 << 20]).unwrap(); + let bytes = fs::read(&archive).unwrap(); + let digest = orx_host::sha(&bytes); + let mut intent = f.intent("pinning", "touch ran", "ssh_job"); + intent.run.backend_json = json!({"kind":"ssh_job", "sourceDigest":digest,"sourcePath":archive,"sourceSize":bytes.len()}).to_string(); + let metadata = crate::jobs::BackendDescriptor::parse(&intent.run.backend_json).unwrap(); + let mut row = submitting(&intent); + row.metadata = &metadata; + let part = f.dir("pinning").join(format!("source.tar.{digest}.part")); + let submitted = f.engine.submit(f.ssh.as_ref(), row); + let cancelled = async { + // Staging the source over a loaded machine can take a while. + tokio::time::timeout(Duration::from_secs(60), async { + while !part.exists() { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + assert!(f + .engine + .cancel(f.ssh.as_ref(), "pinning", "user") + .await + .unwrap()); + }; + let (submitted, ()) = tokio::join!(submitted, cancelled); + submitted.unwrap(); + assert_eq!( + f.store().get_run("pinning").unwrap().unwrap().status, + "cancelled" + ); + assert!(fs::metadata(&part).unwrap().len() < bytes.len() as u64); + for never in ["source.tar", "launch.json", "started", "ran"] { + assert!(!f.dir("pinning").join(never).exists(), "{never}"); + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn sbatch_rejection_fails_with_stderr_and_slurm_containers_are_rejected() { + let f = Fixture::new().await; + f.shim( + "sbatch", + "cat >/dev/null; echo 'Invalid partition name: missing' >&2; exit 2", + ); + f.shim("squeue", "exit 0"); + let slurm = Slurm::new(f.ssh.clone(), f.clock.clone()); + let intent = f.intent("rejected-batch", "true", "slurm_job"); + f.submit(&slurm, &intent).await; + let run = f.store().get_run(&intent.run.id).unwrap().unwrap(); + assert_eq!(run.status, "failed"); + assert!(run + .result_markdown + .unwrap() + .contains("Invalid partition name: missing")); + assert!(!f.dir(&intent.run.id).join("job.sbatch").exists()); + assert!(matches!(slurm.recover(&intent).await, Recovery::Absent)); + let mut container = f.intent("slurm-container", "true", "slurm_job"); + container.launch.options = json!({"cancel_sh":"true"}); + let source = f.server.directory().join("rejected-source"); + let bytes = b"This run must never stage"; + fs::write(&source, bytes).unwrap(); + let sha = orx_host::sha(bytes); + container.run.backend_json = + json!({"kind":"slurm_job","sourceDigest":sha,"sourcePath":source,"sourceSize":bytes.len()}) + .to_string(); + let metadata = crate::jobs::BackendDescriptor::parse(&container.run.backend_json).unwrap(); + let mut row = submitting(&container); + row.metadata = &metadata; + f.engine.submit(&slurm, row).await.unwrap(); + assert!(!f + .server + .home() + .join("engine-root/sources") + .join(sha) + .exists()); + let run = f.store().get_run(&container.run.id).unwrap().unwrap(); + assert_eq!(run.status, "failed"); + assert!(run + .result_markdown + .unwrap() + .contains("Use SSH for container runs")); + assert!(!f.dir(&container.run.id).exists()); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn interleaved_recovery_keeps_other_feed_cursors() { + let f = Fixture::new().await; + let first = f.intent( + "cursor-a", + "touch ready; while [ ! -f release ]; do sleep .01; done", + "ssh_job", + ); + let second = f.intent("cursor-b", &first.run.command, "ssh_job"); + f.submit(f.ssh.as_ref(), &first).await; + f.submit(f.ssh.as_ref(), &second).await; + exists(&f.dir("cursor-a").join("ready")).await; + exists(&f.dir("cursor-b").join("ready")).await; + f.ssh + .changes(&["cursor-a".into(), "cursor-b".into()], Duration::ZERO) + .await + .unwrap(); + assert!(matches!(f.ssh.recover(&first).await, Recovery::Found(_))); + let began = Instant::now(); + f.ssh + .changes(&["cursor-b".into()], Duration::from_millis(150)) + .await + .unwrap(); + assert!(began.elapsed() >= Duration::from_millis(140)); + fs::write(f.dir("cursor-a").join("release"), "").unwrap(); + fs::write(f.dir("cursor-b").join("release"), "").unwrap(); + f.terminal(f.ssh.as_ref(), "cursor-a").await; + f.terminal(f.ssh.as_ref(), "cursor-b").await; + assert!(f.ssh.summary("cursor-a").await.is_some()); + assert!(f.ssh.summary("cursor-b").await.is_some()); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn killed_local_payload_has_a_receipt_and_observation_honors_its_budget() { + let f = Fixture::new().await; + let root = f.server.directory().join("local-runs"); + let local = Local::new(root.clone()); + let intent = f.intent( + "killed-local", + "echo $$ > payload-pid; touch ready; exec sleep 60", + "local_job", + ); + f.submit(&local, &intent).await; + let dir = root.join("killed-local"); + exists(&dir.join("ready")).await; + let pid: i32 = fs::read_to_string(dir.join("payload-pid")) + .unwrap() + .trim() + .parse() + .unwrap(); + assert_eq!(unsafe { libc::kill(pid, libc::SIGKILL) }, 0); + exists(&dir.join("exit.json")).await; + let began = Instant::now(); + f.poll(&local, &["killed-local"], Duration::from_millis(1100)) + .await; + assert!(began.elapsed() >= Duration::from_millis(1100)); + assert_eq!( + f.store().get_run("killed-local").unwrap().unwrap().status, + "failed" + ); + assert_eq!( + f.store() + .engine_run_state("killed-local") + .unwrap() + .unwrap() + .contact, + crate::store::Contact::Live + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn local_notify_notices_are_not_repeated_after_exit() { + let f = Fixture::new().await; + let root = f.server.directory().join("local-runs"); + let local = Local::new(root.clone()); + let intent = f.intent("notify-exit", "printf one > \"$ORX_NOTIFY_FILE\"; touch ready; while [ ! -f grow ]; do sleep .01; done; printf two >> \"$ORX_NOTIFY_FILE\"; touch grown; while [ ! -f release ]; do sleep .01; done", "local_job"); + f.submit(&local, &intent).await; + let dir = root.join("notify-exit"); + exists(&dir.join("ready")).await; + for text in ["one", "two"] { + if text == "two" { + f.clock.advance(Duration::from_secs(10 * 60)); + fs::write(dir.join("grow"), "").unwrap(); + exists(&dir.join("grown")).await; + } + f.poll(&local, &["notify-exit"], Duration::ZERO).await; + f.engine + .deliver_notify(&local, "notify-exit") + .await + .unwrap(); + let notices = f.store().run_notice_batch("chat").unwrap(); + assert_eq!(notices.len(), 1); + assert_eq!(notices[0].kind, crate::store::NOTIFY); + assert!(notices[0].body.ends_with(text)); + f.store() + .mark_run_notice_batch_delivered("chat", ¬ices[0].client_turn_id, f.clock.wall_ms()) + .unwrap(); + } + fs::write(dir.join("release"), "").unwrap(); + exists(&dir.join("exit.json")).await; + f.poll(&local, &["notify-exit"], Duration::ZERO).await; + assert_eq!( + f.store().get_run("notify-exit").unwrap().unwrap().status, + "done" + ); + f.clock.advance(Duration::from_secs(10 * 60)); + f.engine + .deliver_notify(&local, "notify-exit") + .await + .unwrap(); + let notices = f.store().run_notice_batch("chat").unwrap(); + assert_eq!( + notices + .iter() + .filter(|notice| notice.kind == crate::store::NOTIFY) + .count(), + 0 + ); + let cursor = f + .store() + .engine_run_state("notify-exit") + .unwrap() + .unwrap() + .notify_cursor + .unwrap(); + assert_eq!(cursor.generation, 0); + assert_eq!(cursor.offset, 6); + assert!(f.engine.notify_due().unwrap().is_empty()); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn sbatch_error_adopts_the_job_already_in_the_queue() { + let f = Fixture::new().await; + f.shim( + "sbatch", + "cat >/dev/null; echo 'Socket timed out' >&2; exit 1", + ); + f.shim("squeue", "printf '987|queued-on-error|PENDING\\n'"); + let slurm = Slurm::new(f.ssh.clone(), f.clock.clone()); + let intent = f.intent("queued-on-error", "true", "slurm_job"); + f.submit(&slurm, &intent).await; + let run = f.store().get_run(&intent.run.id).unwrap().unwrap(); + assert_eq!(run.status, "starting"); + assert!(matches!(handle_of(&run), Some(Handle::Slurm { job: Some(job), .. }) if job == "987")); + assert_eq!( + fs::read_to_string(f.dir(&intent.run.id).join("slurm.job")).unwrap(), + "987" + ); + assert!(f.dir(&intent.run.id).join("job.sbatch").exists()); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn controller_errors_keep_the_submit_marker_and_recover_without_resubmitting() { + let f = Fixture::new().await; + let slurm = Slurm::new(f.ssh.clone(), f.clock.clone()); + f.shim("sacct", "exit 1"); + for (index, error) in [ + "Socket timed out", + "Unable to contact slurm controller", + "Connection refused", + "Connection reset by peer", + ] + .iter() + .enumerate() + { + f.shim("squeue", "exit 0"); + f.shim( + "sbatch", + &format!( + "cat >/dev/null; printf x >> \"$HOME/sbatch-calls\"; printf '%s\\n' {} >&2; exit 1", + crate::jobs::ssh::sh_quote(error) + ), + ); + let id = format!("controller-{index}"); + let intent = f.intent(&id, "true", "slurm_job"); + f.submit(&slurm, &intent).await; + assert_eq!( + f.store().get_run(&id).unwrap().unwrap().status, + "submitting" + ); + assert!(f.dir(&id).join("job.sbatch").exists()); + f.shim("squeue", &format!("printf '987|{id}|RUNNING\\n'")); + f.clock.advance(Duration::from_secs(7)); + f.engine.recover(&slurm, &id).await.unwrap(); + let run = f.store().get_run(&id).unwrap().unwrap(); + assert_eq!(run.status, "starting"); + assert!( + matches!(handle_of(&run), Some(Handle::Slurm { job: Some(job), .. }) if job == "987") + ); + assert_eq!( + fs::read(f.server.home().join("sbatch-calls")) + .unwrap() + .len(), + index + 1 + ); + } +} + +#[tokio::test] +async fn escaped_launch_frames_are_rejected_before_transmission() { + use orx_host_proto::{LaunchIntent, Request}; + let f = Fixture::new().await; + let script = "\u{1}".repeat(1024 * 1024); + let result = f + .ssh + .launch_request(Request::Launch(LaunchIntent { + run: "too-large".into(), + digest: orx_host::sha(b"too-large"), + run_sh: script.clone(), + env: Default::default(), + source: None, + cancel_sh: Some(script.clone()), + })) + .await; + assert!( + matches!(result, Err(LaunchError::Rejected { reason }) if reason.contains("8 MiB frame limit")) + ); + assert!(!f.dir("too-large").exists()); + let result = f + .ssh + .launch_request(Request::SlurmSubmit { + intent: LaunchIntent { + run: "too-large".into(), + digest: orx_host::sha(b"too-large"), + run_sh: script.clone(), + env: Default::default(), + source: None, + cancel_sh: None, + }, + directives: script.repeat(2), + }) + .await; + assert!( + matches!(result, Err(LaunchError::Rejected { reason }) if reason.contains("8 MiB frame limit")) + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn ssh_launch_auth_failure_before_send_keeps_a_retryable_submission() { + let f = Fixture::new().await; + fs::write(f.server.directory().join("authorized_keys"), "").unwrap(); + let mut cfg = config(f.server.directory(), f.server.alias()); + cfg.root = "~/never-launched".into(); + let conn = { + let config = cfg; + let store = f.store(); + let auth = crate::engine::transport::Auth::new(&store, &config.alias).unwrap(); + HostConn::start_shared(config, store, f.transport_clock.clone(), auth) + } + .unwrap(); + let ssh = Ssh::new(f.server.alias().into(), "~/never-launched".into(), conn); + let intent = f.intent("blocked-auth", "echo should-not-start", "ssh_job"); + f.submit(&ssh, &intent).await; + let state = f.store().engine_run_state(&intent.run.id).unwrap().unwrap(); + assert_eq!( + state.contact, + crate::store::Contact::NeedsAuth { + since: ssh.conn.state().borrow().since_ms, + cause: "Permission denied (publickey)".into() + } + ); + assert!(state.submission_fence.is_none()); + assert_eq!( + f.store().get_run(&intent.run.id).unwrap().unwrap().status, + "submitting" + ); + assert!(!f + .server + .home() + .join("never-launched/runs/blocked-auth") + .exists()); + fs::write( + f.server.directory().join("authorized_keys"), + fs::read(f.server.directory().join("client_key.pub")).unwrap(), + ) + .unwrap(); + ssh.conn.retry().await.unwrap(); + f.engine.recover(&ssh, &intent.run.id).await.unwrap(); + assert_eq!(f.terminal(&ssh, &intent.run.id).await.status, "done"); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn ssh_launch_unreachable_before_send_keeps_a_retryable_submission() { + let f = Fixture::new().await; + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + drop(listener); + let alias = "unreachable"; + let cfg_path = f.server.directory().join("refused_config"); + fs::write( + &cfg_path, + fs::read_to_string(f.server.config_path()) + .unwrap() + .replace( + &format!("Host {}", f.server.alias()), + &format!("Host {alias}"), + ) + .replace( + &format!("Port {}", f.server.port()), + &format!("Port {port}"), + ), + ) + .unwrap(); + let mut cfg = config(f.server.directory(), alias); + cfg.ssh_config = Some(cfg_path); + cfg.root = "~/never-launched".into(); + let conn = { + let config = cfg; + let store = f.store(); + let auth = crate::engine::transport::Auth::new(&store, &config.alias).unwrap(); + HostConn::start_shared(config, store, f.transport_clock.clone(), auth) + } + .unwrap(); + let ssh = Ssh::new(alias.into(), "~/never-launched".into(), conn); + let mut intent = f.intent("blocked-network", "true", "ssh_job"); + intent.launch.target = Some(alias.into()); + f.submit(&ssh, &intent).await; + let state = f.store().engine_run_state(&intent.run.id).unwrap().unwrap(); + assert!( + matches!(state.contact, crate::store::Contact::Unreachable { cause, .. } if cause == "Connection refused") + ); + assert_eq!(ssh.conn.state().borrow().status, Status::Backoff); + assert!(state.submission_fence.is_none()); + assert_eq!( + f.store().get_run(&intent.run.id).unwrap().unwrap().status, + "submitting" + ); + assert!(!f + .server + .home() + .join("never-launched/runs/blocked-network") + .exists()); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn ssh_launch_written_with_response_lost_stays_unreconciled() { + let f = Fixture::new().await; + let command = f.server.directory().join("command"); + let original = fs::read_to_string(&command).unwrap(); + fs::write( + &command, + original.replace( + "export HOME", + "export HOME\nexport ORX_TEST_CRASH_AT=launch_published", + ), + ) + .unwrap(); + f.server.proxy().reset().unwrap(); + tokio::time::timeout(Duration::from_secs(5), async { + while f.ssh.conn.state().borrow().status == Status::Live { + tokio::time::sleep(Duration::from_millis(1)).await; + } + }) + .await + .unwrap(); + f.ssh.conn.retry().await.unwrap(); + let intent = f.intent("lost-response", "echo launched", "ssh_job"); + f.submit(f.ssh.as_ref(), &intent).await; + let state = f.store().engine_run_state(&intent.run.id).unwrap().unwrap(); + assert!(matches!( + state.contact, + crate::store::Contact::Unreconciled { .. } + )); + assert!(state.submission_fence.is_some()); + assert!(f.dir(&intent.run.id).join("launch.json").exists()); + assert_eq!( + f.store().get_run(&intent.run.id).unwrap().unwrap().status, + "submitting" + ); + fs::write(command, original).unwrap(); + f.transport_clock.advance(Duration::from_secs(7)); + live(&f.ssh.conn).await; + f.clock.advance(Duration::from_secs(7)); + f.engine + .recover(f.ssh.as_ref(), &intent.run.id) + .await + .unwrap(); + assert_eq!( + f.terminal(f.ssh.as_ref(), &intent.run.id).await.status, + "done" + ); +} + +#[test] +fn cancelled_receipts_use_the_latest_process_proof_and_describe_unchecked_processes() { + use orx_host_proto::{CancelOutcome as Outcome, ProcessOutcome, RunState, Summary, Survivor}; + let mut summary = Summary { + started_at: None, + state: RunState::Exited { + receipt: orx_host_proto::ExitReceipt { + finished_at: Some(1234), + code: Some(0), + signal: Some(15), + reason: ExitReason::Cancelled, + processes: vec![Survivor { + pid: 123, + starttime: 1, + state: "S".into(), + }], + outcome: Outcome::Survivors, + }, + }, + log_len: None, + notify_len: 0, + cleanup: None, + }; + assert!(matches!( + &super::ssh::observations("run".into(), &summary)[0].1, + Observation::CancelReceipt { + finished_at: Some(1234), + remaining: 1, + note: None, + .. + } + )); + for unreadable in [vec![], vec![789]] { + summary.cleanup = Some(ProcessOutcome { + processes: vec![], + outcome: Outcome::Unverifiable { + unreadable: unreadable.clone(), + }, + }); + let observed = super::ssh::observations("run".into(), &summary); + assert!(matches!(&observed[0].1, + Observation::CancelReceipt { remaining: 0, note: Some(note), .. } if *note == unreadable)); + } + summary.cleanup = Some(ProcessOutcome { + processes: vec![], + outcome: Outcome::Verified, + }); + assert!(matches!( + &super::ssh::observations("run".into(), &summary)[0].1, + Observation::CancelReceipt { + remaining: 0, + note: None, + .. + } + )); + summary.started_at = Some(500); + let observed = super::ssh::observations("run".into(), &summary); + assert!(matches!( + &observed[0].1, + Observation::Running { + started_at: Some(500) + } + )); + assert!(matches!( + &observed[1].1, + Observation::CancelReceipt { + finished_at: Some(1234), + .. + } + )); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn recovery_checks_accepted_cancel_before_and_during_resumed_staging() { + use orx_host_proto::LaunchIntent; + for during in [false, true] { + let f = + Fixture::with_host_env("export ORX_TEST_CROSS_DEVICE=1\nexport ORX_TEST_SLOW_RPC=100") + .await; + let archive = f.server.directory().join("resume.tar"); + fs::write(&archive, vec![b'x'; 4 << 20]).unwrap(); + let bytes = fs::read(&archive).unwrap(); + let sha = orx_host::sha(&bytes); + let mut intent = f.intent("resume", "touch ran", "ssh_job"); + intent.run.backend_json = json!({"kind":"ssh_job", "sourceDigest":sha, "sourcePath":archive, "sourceSize":bytes.len()}).to_string(); + let metadata = crate::jobs::BackendDescriptor::parse(&intent.run.backend_json).unwrap(); + let mut row = submitting(&intent); + row.metadata = &metadata; + f.engine.insert(row).unwrap(); + assert!(f + .store() + .set_submission_fence( + "resume", + 1, + &crate::store::SubmissionFence { + taken_at: 1, + submitter: None + } + ) + .unwrap()); + let dir = f.dir("resume"); + fs::create_dir_all(&dir).unwrap(); + orx_host::publish( + &dir.join("launch.json"), + &LaunchIntent { + run: "resume".into(), + digest: intent.spec_digest.clone(), + run_sh: "touch ran".into(), + env: Default::default(), + source: Some(sha.clone()), + cancel_sh: None, + }, + ) + .unwrap(); + let accept = || { + assert!(f + .store() + .accept_run_cancel("resume", Some("user")) + .unwrap() + .is_some()); + assert!( + !f.store() + .get_run("resume") + .unwrap() + .unwrap() + .cancel_requested + ); + }; + if during { + f.ssh + .stage_blob(&sha, &archive, bytes.len() as u64) + .await + .unwrap(); + let part = dir.join(format!("source.tar.{sha}.part")); + let recovery = f.engine.recover(f.ssh.as_ref(), "resume"); + let cancellation = async { + exists(&part).await; + accept(); + }; + let (result, ()) = tokio::join!(recovery, cancellation); + result.unwrap(); + assert!(fs::metadata(part).unwrap().len() < bytes.len() as u64); + } else { + accept(); + f.engine.recover(f.ssh.as_ref(), "resume").await.unwrap(); + } + assert_eq!( + f.terminal(f.ssh.as_ref(), "resume").await.status, + "cancelled" + ); + for file in ["started", "run.sh", "ran", "source.tar"] { + assert!(!dir.join(file).exists(), "{file}"); + } + let receipt: orx_host_proto::ExitReceipt = + orx_host::read_json(&dir.join("exit.json")).unwrap(); + assert_eq!(receipt.reason, ExitReason::Cancelled); + assert_eq!(receipt.outcome, orx_host_proto::CancelOutcome::Verified); + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn ssh_recovery_cancels_a_fully_staged_intent_before_launch_repair() { + let f = Fixture::new().await; + let intent = f.intent("staged-cancel", "touch should-not-run", "ssh_job"); + f.engine.insert(submitting(&intent)).unwrap(); + f.store() + .set_submission_fence( + &intent.run.id, + 1, + &crate::store::SubmissionFence { + taken_at: 1, + submitter: None, + }, + ) + .unwrap(); + let dir = f.dir(&intent.run.id); + fs::create_dir_all(dir.join("repo")).unwrap(); + let archive = dir.join("source.tar"); + assert!(crate::process::command("tar") + .args(["-cf"]) + .arg(&archive) + .arg("-C") + .arg(dir.join("repo")) + .arg(".") + .status() + .unwrap() + .success()); + let source = orx_host::sha(&fs::read(archive).unwrap()); + orx_host::publish( + &dir.join("launch.json"), + &orx_host_proto::LaunchIntent { + run: intent.run.id.clone(), + digest: intent.spec_digest.clone(), + run_sh: intent.run.command.clone(), + env: Default::default(), + source: Some(source), + cancel_sh: None, + }, + ) + .unwrap(); + fs::write(dir.join("run.sh"), &intent.run.command).unwrap(); + f.store() + .accept_run_cancel(&intent.run.id, Some("test")) + .unwrap(); + f.engine + .recover(f.ssh.as_ref(), &intent.run.id) + .await + .unwrap(); + assert_eq!( + f.terminal(f.ssh.as_ref(), &intent.run.id).await.status, + "cancelled" + ); + assert!(dir.join("cancel.req").exists()); + assert!(!dir.join("started").exists()); + assert!(!dir.join("wrapper.log").exists()); + assert!(!dir.join("repo/should-not-run").exists()); + assert!(!dir.join("should-not-run").exists()); + + let absent = f.intent("absent-cancel", "touch should-not-run", "ssh_job"); + assert!(matches!( + f.ssh.recover_with_cancel(&absent, &|| true).await, + Recovery::Absent + )); + assert!(!f.dir(&absent.run.id).exists()); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn slurm_recovery_finishes_batch_only_preparation_without_a_scheduler_record() { + let f = Fixture::new().await; + f.shim( + "sbatch", + "cat >/dev/null; echo submit >> \"$HOME/submissions\"; printf '123\\n'", + ); + f.shim("squeue", "exit 0"); + f.shim("sacct", "exit 0"); + let slurm = Slurm::new(f.ssh.clone(), f.clock.clone()); + let intent = f.intent("batch-only", "true", "slurm_job"); + f.engine.insert(submitting(&intent)).unwrap(); + f.store() + .set_submission_fence( + &intent.run.id, + 1, + &crate::store::SubmissionFence { + taken_at: 1, + submitter: None, + }, + ) + .unwrap(); + let dir = f.dir(&intent.run.id); + fs::create_dir_all(&dir).unwrap(); + fs::write(dir.join("job.sbatch"), "interrupted batch preparation").unwrap(); + f.engine.recover(&slurm, &intent.run.id).await.unwrap(); + assert_eq!(fs::read_to_string(dir.join("slurm.job")).unwrap(), "123"); + assert_eq!( + fs::read_to_string(f.server.home().join("submissions")).unwrap(), + "submit\n" + ); + assert!(dir.join("launch.json").exists()); + assert!(matches!( + watched(&f, &intent.run.id).handle, + Handle::Slurm { job: Some(_), .. } + )); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn slurm_foreign_node_uses_scheduler_without_inspecting_or_signalling_local_pid() { + let f = Fixture::new().await; + f.shim("sbatch", "cat >/dev/null; printf '123\\n'"); + f.shim("squeue", "printf '123|foreign-node|RUNNING\\n'"); + f.shim("sacct", "exit 1"); + let slurm = Slurm::new(f.ssh.clone(), f.clock.clone()); + let intent = f.intent("foreign-node", "true", "slurm_job"); + f.submit(&slurm, &intent).await; + let dir = f.dir(&intent.run.id); + let mut identity = orx_host::platform::identity(std::process::id()).unwrap(); + identity.node.push_str("-compute-node"); + orx_host::publish(&dir.join("wrapper.json"), &identity).unwrap(); + fs::write(dir.join("started"), "foreign-tag").unwrap(); + let run = watched(&f, &intent.run.id); + let observed = slurm + .observe(std::slice::from_ref(&run), Duration::ZERO) + .await; + assert!(observed + .iter() + .any(|(_, observation)| matches!(observation, Observation::Running { .. }))); + assert!(!observed + .iter() + .any(|(_, observation)| matches!(observation, Observation::Unreachable { .. }))); + assert!(matches!(slurm.cancel(&run).await, CancelOutcome::Pending)); + assert!(orx_host::platform::process(identity.pid).unwrap().live()); + f.shim("squeue", "printf '123|foreign-node|NODE_FAIL\\n'"); + f.clock.advance(Duration::from_secs(31)); + let observed = slurm + .observe(std::slice::from_ref(&run), Duration::ZERO) + .await; + assert!(!observed + .iter() + .any(|(_, observation)| matches!(observation, Observation::Failed { .. }))); + tokio::time::sleep(Duration::from_millis(150)).await; + f.clock.advance(Duration::from_secs(31)); + let observed = slurm.observe(&[run], Duration::ZERO).await; + assert!(observed.iter().any(|(_, observation)| matches!(observation, Observation::Failed { reason, .. } if reason == "scheduler NODE_FAIL; no receipt"))); + assert!(!dir.join("exit.json").exists()); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn slurm_receipt_survivors_do_not_offer_wrapper_cleanup_after_step_teardown() { + let f = Fixture::new().await; + f.shim("sbatch", "cat >/dev/null; printf '123\\n'"); + f.shim("squeue", "exit 0"); + f.shim("sacct", "exit 1"); + let slurm = Slurm::new(f.ssh.clone(), f.clock.clone()); + let intent = f.intent("step-teardown", "true", "slurm_job"); + f.submit(&slurm, &intent).await; + let receipt = orx_host_proto::ExitReceipt { + code: Some(0), + signal: None, + reason: ExitReason::Exited, + processes: vec![orx_host_proto::Survivor { + pid: 12345, + starttime: 1, + state: "S".into(), + }], + outcome: orx_host_proto::CancelOutcome::Survivors, + finished_at: None, + }; + orx_host::publish(&f.dir(&intent.run.id).join("exit.json"), &receipt).unwrap(); + let observed = slurm + .observe(&[watched(&f, &intent.run.id)], Duration::ZERO) + .await; + assert!(observed + .iter() + .any(|(_, observation)| matches!(observation, Observation::Exited { code: Some(0), .. }))); + assert!(observed.iter().any( + |(_, observation)| matches!(observation, Observation::Lingering { pids } if pids.is_empty()) + )); + assert!(!observed.iter().any(|(_, observation)| matches!(observation, Observation::Lingering { pids } if !pids.is_empty()))); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn slurm_merge_keeps_invalid_and_unreadable_receipts_authoritative() { + use orx_host_proto::{Request, Response}; + let f = Fixture::new().await; + f.shim("sbatch", "cat >/dev/null; printf '123\\n'"); + f.shim("squeue", "printf '123|receipt-errors|FAILED\\n'"); + f.shim("sacct", "exit 1"); + let slurm = Slurm::new(f.ssh.clone(), f.clock.clone()); + let intent = f.intent("receipt-errors", "true", "slurm_job"); + f.submit(&slurm, &intent).await; + let run = watched(&f, "receipt-errors"); + slurm + .observe(std::slice::from_ref(&run), Duration::ZERO) + .await; + tokio::time::sleep(Duration::from_millis(150)).await; + f.clock.advance(Duration::from_secs(31)); + let observations = slurm + .observe(std::slice::from_ref(&run), Duration::ZERO) + .await; + assert!(observations + .iter() + .any(|(_, observation)| matches!(observation, Observation::Failed { .. }))); + let receipt = f.dir("receipt-errors").join("exit.json"); + for bytes in [b"{".as_slice(), br#"{"code":0,"signal":null,"reason":"future","processes":[],"outcome":{"kind":"verified"}}"#] { + fs::write(&receipt, bytes).unwrap(); + let observations = slurm.observe(std::slice::from_ref(&run), Duration::ZERO).await; + assert!(observations.iter().any(|(_, observation)| matches!(observation, Observation::Unreconciled { .. }))); + assert!(!observations.iter().any(|(_, observation)| matches!(observation, Observation::Failed { .. } | Observation::Lost { .. }))); + } + fs::remove_file(&receipt).unwrap(); + fs::create_dir(&receipt).unwrap(); + let observations = slurm + .observe(std::slice::from_ref(&run), Duration::ZERO) + .await; + assert!(observations + .iter() + .any(|(_, observation)| matches!(observation, Observation::Unreachable { .. }))); + // A receipt metadata error is also authoritative through the scheduler query. + fs::remove_dir(&receipt).unwrap(); + std::os::unix::fs::symlink("exit.json", &receipt).unwrap(); + let Response::SlurmQueue { jobs, .. } = f + .ssh + .request(Request::SlurmQueue { + names: vec![run.id], + legacy: vec![], + }) + .await + .unwrap() + else { + panic!() + }; + assert!(matches!( + jobs[0].summary.state, + orx_host_proto::RunState::Unreachable { .. } + )); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn paused_container_cancel_retries_until_unpause_or_removal() { + use orx_host_proto::{ExitReceipt, Request, Response, RunState}; + let f = Fixture::with_host_env("unset ORX_TEST_FAST_STOPS").await; + f.shim("docker", r#"case "$1 $2" in +'container ls') [ -f "$HOME/removed" ] || printf cid;; +'container inspect') if [ -f "$HOME/unpaused" ]; then printf 'generation running'; else printf 'generation paused'; fi;; +'exec -i') printf x >> "$HOME/hook-attempts"; [ -f "$HOME/unpaused" ];; +*) exit 1;; esac"#); + for remove in [false, true] { + let id = if remove { + "removed-container" + } else { + "unpaused-container" + }; + let container = crate::jobs::ssh::ContainerRun { + reference: "fixture".into(), + id: "cid".into(), + started_at: "generation".into(), + run_dir: "/unused".into(), + }; + let mut intent = f.intent(id, "touch ready; sleep 60", "ssh_job"); + intent.launch.options = json!({"cancel_sh":container.engine_cancel_sh()}); + f.submit(f.ssh.as_ref(), &intent).await; + exists(&f.dir(id).join("ready")).await; + let run = watched(&f, id); + assert!(matches!(f.ssh.cancel(&run).await, CancelOutcome::Pending)); + let attempts = f.server.home().join("hook-attempts"); + tokio::time::timeout(Duration::from_secs(60), async { + while fs::read(&attempts).map_or(0, |bytes| bytes.len()) < 2 { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + assert!(!f.dir(id).join("exit.json").exists()); + fs::write( + f.server + .home() + .join(if remove { "removed" } else { "unpaused" }), + "", + ) + .unwrap(); + exists(&f.dir(id).join("exit.json")).await; + let receipt: ExitReceipt = orx_host::read_json(&f.dir(id).join("exit.json")).unwrap(); + assert_eq!(receipt.reason, ExitReason::Cancelled); + assert!(matches!( + receipt.outcome, + orx_host_proto::CancelOutcome::Unverifiable { .. } + )); + let Response::Changes { runs } = f + .ssh + .request(Request::Changes { + watch: vec![(id.into(), super::ssh::missing())], + follow_logs: vec![], + wait_ms: 0, + }) + .await + .unwrap() + else { + panic!() + }; + assert!(matches!(runs[0].1.state, RunState::Exited { .. })); + for marker in ["unpaused", "hook-attempts"] { + let _ = fs::remove_file(f.server.home().join(marker)); + } + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn local_cancel_reaches_new_sessions_and_double_fork_children() { + let f = Fixture::new().await; + let root = f.server.directory().join("local-runs"); + let local = Local::new(root.clone()); + let script = "python3 -c 'import os,time; p=os.fork(); p and os._exit(0); os.setsid(); p=os.fork(); p and os._exit(0); f=open(\"daemon.tmp\",\"w\"); f.write(str(os.getpid())); f.close(); os.rename(\"daemon.tmp\",\"daemon\"); time.sleep(60)'\nwhile [ ! -f daemon ]; do sleep .01; done\nsleep 60"; + f.submit(&local, &f.intent("fork-local", script, "local_job")) + .await; + let dir = root.join("fork-local"); + exists(&dir.join("daemon")).await; + let pid: u32 = fs::read_to_string(dir.join("daemon")) + .unwrap() + .parse() + .unwrap(); + let identity = orx_host::platform::identity(pid).unwrap(); + f.engine.cancel(&local, "fork-local", "test").await.unwrap(); + exists(&dir.join("exit.json")).await; + let receipt = orx_host::wrapper::receipt(&dir).unwrap().unwrap(); + assert!(receipt.processes.is_empty()); + assert!(!orx_host::platform::alive(&identity).unwrap()); + let expected = super::ssh::observations( + "fork-local".into(), + &orx_host_proto::Summary { + started_at: orx_host::wrapper::started_at(&dir), + state: orx_host_proto::RunState::Exited { receipt }, + log_len: Some(fs::metadata(dir.join("log")).unwrap().len()), + notify_len: 0, + cleanup: None, + }, + ); + assert_eq!( + local + .observe(&[watched(&f, "fork-local")], Duration::ZERO) + .await, + expected + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn local_cleanup_stops_a_worker_that_outlives_the_payload() { + let f = Fixture::new().await; + let root = f.server.directory().join("local-runs"); + let local = Local::new(root.clone()); + let script = "python3 -c 'import os,time; open(\"worker\",\"w\").write(str(os.getpid())); time.sleep(60)' >/dev/null 2>&1 &\nwhile [ ! -f worker ]; do sleep .01; done"; + f.submit(&local, &f.intent("cleanup-local", script, "local_job")) + .await; + let dir = root.join("cleanup-local"); + exists(&dir.join("exit.json")).await; + let receipt = orx_host::wrapper::receipt(&dir).unwrap().unwrap(); + assert_eq!(receipt.reason, ExitReason::Exited); + assert!(!receipt.processes.is_empty()); + let pid: u32 = fs::read_to_string(dir.join("worker")) + .unwrap() + .parse() + .unwrap(); + let identity = orx_host::platform::identity(pid).unwrap(); + let run = watched(&f, "cleanup-local"); + assert!(matches!( + Backend::cleanup(&local, &run).await, + CancelOutcome::Pending + )); + assert!(dir.join("cleanup.req").exists()); + exists(&dir.join("cleanup.json")).await; + assert!(orx_host::wrapper::cleanup_result(&dir) + .unwrap() + .unwrap() + .processes + .is_empty()); + assert!(!orx_host::platform::alive(&identity).unwrap()); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn local_recovery_never_starts_a_staged_payload_after_an_accepted_cancel() { + let f = Fixture::new().await; + let root = f.server.directory().join("local-runs"); + let local = Local::new(root.clone()); + let intent = f.intent("staged-cancel", "touch should-not-run", "local_job"); + f.engine.insert(submitting(&intent)).unwrap(); + f.store() + .set_submission_fence( + &intent.run.id, + 1, + &crate::store::SubmissionFence { + taken_at: 1, + submitter: None, + }, + ) + .unwrap(); + let dir = root.join(&intent.run.id); + fs::create_dir_all(&dir).unwrap(); + orx_host::publish( + &dir.join("launch.json"), + &orx_host_proto::LaunchIntent { + run: intent.run.id.clone(), + digest: intent.spec_digest.clone(), + run_sh: intent.run.command.clone(), + env: Default::default(), + source: None, + cancel_sh: None, + }, + ) + .unwrap(); + f.store() + .accept_run_cancel(&intent.run.id, Some("test")) + .unwrap(); + f.engine.recover(&local, &intent.run.id).await.unwrap(); + f.poll(&local, &[&intent.run.id], Duration::ZERO).await; + assert_eq!( + f.store().get_run(&intent.run.id).unwrap().unwrap().status, + "cancelled" + ); + assert!(!dir.join("run.sh").exists()); + assert!(!dir.join("started").exists()); + assert!(!dir.join("should-not-run").exists()); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn local_recovery_waits_for_the_wrapper_start_marker_before_returning_a_handle() { + let f = Fixture::new().await; + let root = f.server.directory().join("local-runs"); + let local = Local::new(root.clone()); + let intent = f.intent("starting-local", "sleep 60", "local_job"); + let dir = root.join(&intent.run.id); + fs::create_dir_all(&dir).unwrap(); + orx_host::publish( + &dir.join("launch.json"), + &orx_host_proto::LaunchIntent { + run: intent.run.id.clone(), + digest: intent.spec_digest.clone(), + run_sh: intent.run.command.clone(), + env: Default::default(), + source: None, + cancel_sh: None, + }, + ) + .unwrap(); + let gate = orx_host::lock(&dir.join("start.lock")).unwrap().unwrap(); + let recovery = local.recover(&intent); + tokio::pin!(recovery); + let wrapper = dir.join("wrapper.json"); + tokio::select! { + biased; + result = &mut recovery => panic!("recovery returned before started: {result:?}"), + () = exists(&wrapper) => {}, + } + assert!(!dir.join("started").exists()); + drop(gate); + let Recovery::Found(handle) = recovery.await else { + panic!("wrapper did not start") + }; + assert!(dir.join("started").exists()); + local + .cancel(&WatchedRun { + id: intent.run.id.clone(), + handle, + }) + .await; + exists(&dir.join("exit.json")).await; +} + +#[tokio::test] +async fn abandon_before_handle_recovery_attaches_once_and_settles_through_real_ssh() { + let mut f = Fixture::new().await; + let intent = f.intent( + "abandoned-response", + "echo payload >> count; sleep 60 &", + "ssh_job", + ); + f.engine.insert(submitting(&intent)).unwrap(); + f.store() + .set_submission_fence( + &intent.run.id, + 1, + &crate::store::SubmissionFence { + taken_at: 1, + submitter: None, + }, + ) + .unwrap(); + let fence = Fence { + store: &f.engine.store, + run_id: &intent.run.id, + attempt: 1, + taken_at: 1, + }; + let launched = f.ssh.launch(&intent, &fence).await.unwrap(); + assert!(matches!(launched, Handle::Ssh { .. })); + exists(&f.dir(&intent.run.id).join("exit.json")).await; + f.engine + .unreconciled(&intent.run.id, &crate::error::anyhow!("lost reply")) + .unwrap(); + assert!(f.engine.abandon(&intent.run.id).unwrap()); + f.engine = Engine::new(f.store(), f.clock.clone()); + f.engine + .recover(f.ssh.as_ref(), &intent.run.id) + .await + .unwrap(); + let row = f.store().get_run(&intent.run.id).unwrap().unwrap(); + assert_eq!(row.status, "lost"); + assert!(handle_of(&row).is_some()); + assert!(f.store().log_collection_pending(&intent.run.id).unwrap()); + tokio::time::timeout(Duration::from_secs(15), async { + loop { + f.poll(f.ssh.as_ref(), &[&intent.run.id], Duration::from_millis(50)) + .await; + if f.store() + .engine_run_state(&intent.run.id) + .unwrap() + .unwrap() + .contact + == crate::store::Contact::Live + { + break; + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + }) + .await + .unwrap(); + for _ in 0..3 { + f.engine + .recover(f.ssh.as_ref(), &intent.run.id) + .await + .unwrap(); + } + assert_eq!( + f.store().get_run(&intent.run.id).unwrap().unwrap().status, + "lost" + ); + assert_eq!( + fs::read_to_string(f.dir(&intent.run.id).join("count")).unwrap(), + "payload\n" + ); + let notices = f.store().run_notice_batch("chat").unwrap(); + assert_eq!( + notices + .iter() + .filter(|notice| notice.kind == crate::store::TERMINAL) + .count(), + 1 + ); +} + +#[tokio::test] +async fn a_verified_cancel_receipt_after_a_lost_reply_settles_the_recovered_tombstone() { + let f = Fixture::new().await; + let intent = f.intent("already-cancelled", "true", "ssh_job"); + f.engine.insert(submitting(&intent)).unwrap(); + f.store() + .set_submission_fence( + &intent.run.id, + 1, + &crate::store::SubmissionFence { + taken_at: 1, + submitter: None, + }, + ) + .unwrap(); + let dir = f.dir(&intent.run.id); + fs::create_dir_all(&dir).unwrap(); + orx_host::publish( + &dir.join("exit.json"), + &orx_host_proto::ExitReceipt { + finished_at: None, + code: None, + signal: Some(15), + reason: ExitReason::Cancelled, + processes: Vec::new(), + outcome: orx_host_proto::CancelOutcome::Verified, + }, + ) + .unwrap(); + assert!(f.engine.abandon(&intent.run.id).unwrap()); + f.engine + .recover(f.ssh.as_ref(), &intent.run.id) + .await + .unwrap(); + assert!(handle_of(&f.store().get_run(&intent.run.id).unwrap().unwrap()).is_some()); + f.poll(f.ssh.as_ref(), &[&intent.run.id], Duration::from_millis(50)) + .await; + assert_eq!( + f.store() + .engine_run_state(&intent.run.id) + .unwrap() + .unwrap() + .contact, + crate::store::Contact::Live + ); + assert_eq!( + f.store().get_run(&intent.run.id).unwrap().unwrap().status, + "lost" + ); + f.engine + .recover(f.ssh.as_ref(), &intent.run.id) + .await + .unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn running_tombstone_cleanup_keeps_the_once_per_connection_latch() { + let f = Fixture::new().await; + let root = f.server.directory().join("local-runs"); + let local = Local::new(root.clone()); + for (id, backend, kind, dir) in [ + ( + "pending-local", + &local as &dyn Backend, + "local_job", + root.join("pending-local"), + ), + ( + "pending-ssh", + f.ssh.as_ref() as &dyn Backend, + "ssh_job", + f.dir("pending-ssh"), + ), + ] { + f.submit( + backend, + &f.intent(id, "touch ready; while :; do sleep .1; done", kind), + ) + .await; + exists(&dir.join("ready")).await; + let identity: orx_host_proto::ProcessIdentity = + orx_host::read_json(&dir.join("wrapper.json")).unwrap(); + assert_eq!(unsafe { libc::kill(identity.pid as i32, libc::SIGSTOP) }, 0); + assert!(f.engine.abandon(id).unwrap()); + let first = f.engine.deliver_cancel(backend, id).await; + let latched = f.engine.memory().cancels_sent.contains(id); + let second = f.engine.deliver_cancel(backend, id).await; + assert_eq!(unsafe { libc::kill(identity.pid as i32, libc::SIGCONT) }, 0); + first.unwrap(); + second.unwrap(); + assert!(latched); + assert!(f.engine.memory().cancels_sent.contains(id)); + exists(&dir.join("exit.json")).await; + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn slurm_cancel_survivors_settle_on_scheduler_teardown_without_a_new_receipt() { + let f = Fixture::new().await; + f.shim("sbatch", "cat > /dev/null; printf '123\n'"); + f.shim( + "squeue", + "echo query >> \"$HOME/scheduler-calls\"; printf '123|survivors|RUNNING\n'", + ); + f.shim("sacct", "exit 1"); + let slurm = Slurm::new(f.ssh.clone(), f.clock.clone()); + let intent = f.intent("survivors", "sleep 60", "slurm_job"); + f.submit(&slurm, &intent).await; + let calls = f.server.home().join("scheduler-calls"); + let submitted_calls = fs::read_to_string(&calls) + .unwrap_or_default() + .lines() + .count(); + let dir = f.dir("survivors"); + fs::write(dir.join("started"), "survivors:tag\n").unwrap(); + let mut identity = orx_host::platform::identity(std::process::id()).unwrap(); + identity.node = "compute-node".into(); + orx_host::publish(&dir.join("wrapper.json"), &identity).unwrap(); + orx_host::publish( + &f.dir("survivors").join("exit.json"), + &orx_host_proto::ExitReceipt { + finished_at: None, + code: None, + signal: None, + reason: ExitReason::Cancelled, + processes: vec![orx_host_proto::Survivor { + pid: 123456, + starttime: 1, + state: "D".into(), + }], + outcome: orx_host_proto::CancelOutcome::Survivors, + }, + ) + .unwrap(); + let receipt = fs::read(dir.join("exit.json")).unwrap(); + f.poll(&slurm, &["survivors"], Duration::ZERO).await; + assert_eq!( + f.store().get_run("survivors").unwrap().unwrap().status, + "cancelled" + ); + assert!(matches!( + f.store() + .engine_run_state("survivors") + .unwrap() + .unwrap() + .contact, + crate::store::Contact::Stopping { count: 1, .. } + )); + assert_eq!( + fs::read_to_string(&calls).unwrap().lines().count(), + submitted_calls + 1 + ); + f.shim( + "squeue", + "echo query >> \"$HOME/scheduler-calls\"; printf '123|survivors|COMPLETED\n'", + ); + f.clock.advance(Duration::from_secs(31)); + f.poll(&slurm, &["survivors"], Duration::ZERO).await; + assert_eq!( + f.store() + .engine_run_state("survivors") + .unwrap() + .unwrap() + .contact, + crate::store::Contact::Live + ); + assert_eq!( + fs::read_to_string(&calls).unwrap().lines().count(), + submitted_calls + 2 + ); + f.clock.advance(Duration::from_secs(31)); + f.poll(&slurm, &["survivors"], Duration::ZERO).await; + assert_eq!( + fs::read_to_string(&calls).unwrap().lines().count(), + submitted_calls + 2 + ); + let notices = f.store().run_notice_batch("chat").unwrap(); + assert_eq!( + notices + .iter() + .filter(|notice| notice.dedupe == "cancel-stopped") + .count(), + 1 + ); + assert_eq!(fs::read(dir.join("exit.json")).unwrap(), receipt); + let proof = orx_host::wrapper::cleanup_result(&dir).unwrap().unwrap(); + assert!(proof.processes.is_empty()); + assert_eq!(proof.outcome, orx_host_proto::CancelOutcome::Verified); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn wrapper_gone_cancel_ack_stays_pending_until_observation() { + let f = Fixture::new().await; + let intent = f.intent("gone", "true", "ssh_job"); + let dir = f.dir("gone"); + fs::create_dir_all(&dir).unwrap(); + fs::write(dir.join("started"), "gone:tag").unwrap(); + let mut identity = orx_host::platform::identity(std::process::id()).unwrap(); + identity.starttime += 1; + orx_host::publish(&dir.join("wrapper.json"), &identity).unwrap(); + f.engine.insert(submitting(&intent)).unwrap(); + let run = WatchedRun { + id: "gone".into(), + handle: f.ssh.handle(), + }; + assert!(matches!( + Backend::cancel(f.ssh.as_ref(), &run).await, + CancelOutcome::Pending + )); + let local = Local::new(f.dir("unused")); + let run = WatchedRun { + id: "gone".into(), + handle: Handle::Local { + dir: dir.to_string_lossy().into_owned(), + }, + }; + assert!(matches!( + Backend::cancel(&local, &run).await, + CancelOutcome::Pending + )); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn dead_wrapper_survivors_settle_through_host_observation_after_engine_restart() { + let mut f = + Fixture::with_host_env("export ORX_TEST_DEFER_SIGNALS=\"$HOME/hold-signals\"").await; + let hold = f.server.home().join("hold-signals"); + fs::write(&hold, "hold").unwrap(); + let id = "dead-wrapper"; + f.submit( + f.ssh.as_ref(), + &f.intent(id, "touch ready; exec sleep 60", "ssh_job"), + ) + .await; + let dir = f.dir(id); + exists(&dir.join("ready")).await; + f.engine.cancel(f.ssh.as_ref(), id, "test").await.unwrap(); + exists(&dir.join("exit.json")).await; + let bytes = fs::read(dir.join("exit.json")).unwrap(); + f.poll(f.ssh.as_ref(), &[id], Duration::ZERO).await; + assert!(matches!( + f.store().engine_run_state(id).unwrap().unwrap().contact, + crate::store::Contact::Stopping { count, .. } if count > 0 + )); + let identity: orx_host_proto::ProcessIdentity = + orx_host::read_json(&dir.join("wrapper.json")).unwrap(); + assert_eq!(unsafe { libc::kill(identity.pid as i32, libc::SIGKILL) }, 0); + tokio::time::timeout(Duration::from_secs(3), async { + while orx_host::platform::alive(&identity).unwrap() { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + f.engine = Engine::new(f.store(), f.clock.clone()); + f.poll(f.ssh.as_ref(), &[id], Duration::ZERO).await; + let proof = orx_host::wrapper::cleanup_result(&dir).unwrap().unwrap(); + assert!(!proof.processes.is_empty()); + assert!(matches!( + f.store().engine_run_state(id).unwrap().unwrap().contact, + crate::store::Contact::Stopping { count, .. } if count == proof.processes.len() + )); + fs::remove_file(hold).unwrap(); + tokio::time::timeout(Duration::from_secs(5), async { + loop { + f.poll(f.ssh.as_ref(), &[id], Duration::ZERO).await; + if f.store().engine_run_state(id).unwrap().unwrap().contact + == crate::store::Contact::Live + { + break; + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + }) + .await + .unwrap(); + f.engine = Engine::new(f.store(), f.clock.clone()); + f.poll(f.ssh.as_ref(), &[id], Duration::ZERO).await; + let notices = f.store().run_notice_batch("chat").unwrap(); + assert_eq!( + notices + .iter() + .filter(|notice| notice.kind == crate::store::TERMINAL) + .count(), + 1 + ); + assert_eq!( + notices + .iter() + .filter(|notice| notice.dedupe == "cancel-stopped") + .count(), + 1 + ); + assert_eq!(fs::read(dir.join("exit.json")).unwrap(), bytes); + let proof = orx_host::wrapper::cleanup_result(&dir).unwrap().unwrap(); + assert!(proof.processes.is_empty()); + assert_eq!(proof.outcome, orx_host_proto::CancelOutcome::Verified); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn legacy_survivors_settle_on_group_absence_without_reconnect() { + use std::os::unix::process::CommandExt; + let f = Fixture::new().await; + let local = Local::new(f.server.home().join("legacy-local")); + for (id, kind, backend) in [ + ("legacy-ssh", "ssh_job", f.ssh.as_ref() as &dyn Backend), + ("legacy-local", "local_job", &local as &dyn Backend), + ] { + let dir = f.server.home().join(id); + fs::create_dir(&dir).unwrap(); + let mut child = crate::process::command("sleep") + .arg("60") + .process_group(0) + .spawn() + .unwrap(); + let pid = child.id().to_string(); + fs::write(dir.join("pid"), &pid).unwrap(); + let mut row = f.intent(id, "sleep 60", kind).run; + row.status = "running".into(); + row.backend_json = + json!({"kind":kind,"namespace":f.server.alias(),"jobId":dir}).to_string(); + f.store().upsert_run(&row).unwrap(); + assert_eq!(f.engine.scan_legacy(true).unwrap().len(), 1); + f.engine + .apply_cancel(&row, CancelOutcome::Survivors { count: 1 }) + .unwrap(); + f.engine.memory().cancels_sent.insert(id.into()); + let pending = f.store().engine_run_state(id).unwrap().unwrap().contact; + assert_ne!(pending, crate::store::Contact::Live); + f.poll(backend, &[id], Duration::ZERO).await; + assert_eq!( + f.store().engine_run_state(id).unwrap().unwrap().contact, + pending + ); + + fs::write(dir.join("pid"), "invalid").unwrap(); + let failed = backend.observe(&[watched(&f, id)], Duration::ZERO).await; + assert!(!failed.iter().any(|(_, observation)| { + matches!(observation, Observation::Lingering { pids } if pids.is_empty()) + })); + fs::remove_file(dir.join("pid")).unwrap(); + fs::create_dir(dir.join("pid")).unwrap(); + let failed = backend.observe(&[watched(&f, id)], Duration::ZERO).await; + assert!(!failed.iter().any(|(_, observation)| { + matches!(observation, Observation::Lingering { pids } if pids.is_empty()) + })); + fs::remove_dir(dir.join("pid")).unwrap(); + fs::write(dir.join("pid"), pid).unwrap(); + assert!(f.engine.memory().cancels_sent.contains(id)); + child.kill().unwrap(); + child.wait().unwrap(); + f.poll(backend, &[id], Duration::ZERO).await; + assert_eq!( + f.store().engine_run_state(id).unwrap().unwrap().contact, + crate::store::Contact::Live + ); + assert_eq!(f.store().get_run(id).unwrap().unwrap().status, "cancelled"); + assert!(!f.engine.memory().cancels_sent.contains(id)); + } +} diff --git a/src/engine/adapters/vercel.rs b/src/engine/adapters/vercel.rs new file mode 100644 index 000000000..954d056b3 --- /dev/null +++ b/src/engine/adapters/vercel.rs @@ -0,0 +1,78 @@ +use super::api::{self, Api}; +use crate::engine::*; +use crate::error::{anyhow, Result}; +use crate::jobs::vercel; +use async_trait::async_trait; + +pub struct VercelAccount; + +fn ids(run: &WatchedRun) -> Result<(&str, &str)> { + match &run.handle { + Handle::Api { provider, ids, .. } if provider == "vercel_job" => { + match ids.as_slice() { + [sandbox, process] if !sandbox.is_empty() && !process.is_empty() => { + Ok((sandbox, process)) + } + _ => Err(anyhow!("Vercel handle is missing its sandbox or process ID")), + } + } + Handle::Legacy { descriptor } => descriptor.vercel_ref(), + _ => Err(anyhow!("Run does not belong to Vercel Sandbox")), + } +} + +#[async_trait] +impl Api for VercelAccount { + type Cursor = u64; + + async fn launch(&self, intent: &RunIntent, _fence: &Fence<'_>) -> Result { + let mut spec: vercel::VercelJobSpec = + serde_json::from_value(intent.launch.options.clone()).map_err(api::rejected)?; + spec.name = vercel::sandbox_name(&intent.run.id); + spec.tags.insert("or_run".into(), intent.run.id.clone()); + spec.env.extend(crate::config::launch_env(&intent.run.id)); + vercel::strip_credentials(&mut spec.env); + vercel::ensure_env().await.map_err(api::rejected)?; + let submitted = vercel::run_job(&spec).await.map_err(api::interrupted)?; + Ok(api::handle(intent, vec![submitted.sandbox_name, submitted.process_id])) + } + + async fn recover(&self, intent: &RunIntent) -> Recovery { + api::unknown(format!( + "Vercel did not return a process ID. Inspect sandbox {} in Vercel before abandoning this run.", + vercel::sandbox_name(&intent.run.id) + )) + } + + async fn inspect(&self, run: &WatchedRun) -> Result { + let (sandbox, process) = ids(run)?; + let state = vercel::inspect_job(sandbox, process).await?; + Ok(api::stage(&state.stage, state.message, state.exit_code, None, None)) + } + + async fn cancel(&self, run: &WatchedRun) -> Result<()> { + vercel::cancel_job(ids(run)?.0).await + } + + async fn finish(&self, run: &WatchedRun) -> Result<()> { + vercel::finish_job(ids(run)?.0).await + } + + async fn logs( + &self, + run: &WatchedRun, + cursor: &mut u64, + window: std::time::Duration, + sink: &mut (dyn for<'b> FnMut(&'b [u8]) + Send), + ) -> Result { + let mut received = 0; + let outcome = { + let mut lines = api::lines(sink, &mut received); + let pass = vercel::stream_logs(ids(run)?.0, *cursor, window.saturating_mul(2), &mut lines); + tokio::time::timeout(window, pass).await + }; + let closed = api::closed(outcome, received)?; + *cursor += received; + Ok(closed.is_some()) + } +} diff --git a/src/engine/bus.rs b/src/engine/bus.rs new file mode 100644 index 000000000..f880dcef6 --- /dev/null +++ b/src/engine/bus.rs @@ -0,0 +1,49 @@ +use tokio::sync::broadcast; + +use super::Phase; +use crate::store::Contact; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum RunEvent { + LogCollection { + run_id: String, + }, + Host { + alias: String, + root: String, + state: super::transport::HostState, + }, + Changed { + run_id: String, + phase: Phase, + contact: Contact, + cancelling: bool, + }, + /// New undelivered notices for these chats. + Notices { + chats: Vec, + }, + Grew { + run_id: String, + file: super::LogFile, + len: u64, + }, +} + +/// Events published after their transaction commits. A lagged subscriber resyncs from the store. +pub struct Bus(broadcast::Sender); + +impl Bus { + pub fn new() -> Self { + Self(broadcast::channel(1024).0) + } + + pub fn subscribe(&self) -> broadcast::Receiver { + self.0.subscribe() + } + + pub fn publish(&self, event: RunEvent) { + // No subscribers is fine: every event is already durable in the store. + let _ = self.0.send(event); + } +} diff --git a/src/engine/clock.rs b/src/engine/clock.rs new file mode 100644 index 000000000..609f9d5fe --- /dev/null +++ b/src/engine/clock.rs @@ -0,0 +1,139 @@ +use std::time::{Duration, Instant}; + +/// A wall step larger than this against the monotonic clock is a sleep, suspend or clock change. +pub const CLOCK_JUMP: Duration = Duration::from_secs(30); + +const BACKOFF: [Duration; 5] = [ + Duration::from_secs(5), + Duration::from_secs(15), + Duration::from_secs(60), + Duration::from_secs(5 * 60), + Duration::from_secs(15 * 60), +]; + +pub trait Clock: Send + Sync { + /// Time since an arbitrary origin; never goes backwards and pauses while the machine sleeps. + fn monotonic(&self) -> Duration; + fn wall_ms(&self) -> i64; +} + +pub struct SystemClock { + origin: Instant, +} + +impl SystemClock { + pub fn new() -> Self { + Self { + origin: Instant::now(), + } + } +} + +impl Clock for SystemClock { + fn monotonic(&self) -> Duration { + self.origin.elapsed() + } + + fn wall_ms(&self) -> i64 { + crate::store::now_ms() + } +} + +/// Delay before retry number `failures` (1-based), capped at 15 minutes. +pub fn backoff(failures: u32) -> Duration { + let step = usize::try_from(failures.saturating_sub(1)).unwrap_or(usize::MAX); + BACKOFF[step.min(BACKOFF.len() - 1)] +} + +/// Detects the wall clock moving apart from the monotonic one between two checks. +pub struct JumpDetector { + monotonic: Duration, + wall_ms: i64, +} + +impl JumpDetector { + pub fn new(clock: &dyn Clock) -> Self { + Self { + monotonic: clock.monotonic(), + wall_ms: clock.wall_ms(), + } + } + + pub fn jumped(&mut self, clock: &dyn Clock) -> bool { + let next = Self::new(clock); + let monotonic_ms = + i64::try_from((next.monotonic - self.monotonic).as_millis()).unwrap_or(i64::MAX); + let skew = (next.wall_ms - self.wall_ms).saturating_sub(monotonic_ms); + *self = next; + skew.unsigned_abs() > CLOCK_JUMP.as_millis() as u64 + } +} + +#[cfg(test)] +pub struct TestClock(std::sync::Mutex<(Duration, i64)>); + +#[cfg(test)] +impl TestClock { + pub fn new() -> Self { + Self(std::sync::Mutex::new((Duration::ZERO, 1_700_000_000_000))) + } + + pub fn advance(&self, by: Duration) { + let mut now = self.0.lock().unwrap(); + now.0 += by; + now.1 += i64::try_from(by.as_millis()).unwrap(); + } + + /// Moves only the wall clock, as a suspend or a manual clock change does. + pub fn jump_wall(&self, by_ms: i64) { + self.0.lock().unwrap().1 += by_ms; + } +} + +#[cfg(test)] +impl Clock for TestClock { + fn monotonic(&self) -> Duration { + self.0.lock().unwrap().0 + } + + fn wall_ms(&self) -> i64 { + self.0.lock().unwrap().1 + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_system_clock_tracks_real_time() { + let clock = SystemClock::new(); + let before = clock.monotonic(); + assert!((clock.wall_ms() - crate::store::now_ms()).abs() < 1000); + assert!(clock.monotonic() >= before); + assert!(!JumpDetector::new(&clock).jumped(&clock)); + } + + #[test] + fn backoff_steps_then_caps() { + let steps: Vec<_> = (1..=7).map(|n| backoff(n).as_secs()).collect(); + assert_eq!(steps, [5, 15, 60, 300, 900, 900, 900]); + assert_eq!(backoff(0), Duration::from_secs(5)); + assert_eq!(backoff(u32::MAX), Duration::from_secs(900)); + } + + #[test] + fn jumps_are_wall_steps_beyond_the_monotonic_clock_in_either_direction() { + let clock = TestClock::new(); + let mut detector = JumpDetector::new(&clock); + clock.advance(Duration::from_secs(3600)); + assert!(!detector.jumped(&clock)); + clock.jump_wall(30_000); + assert!(!detector.jumped(&clock)); + clock.jump_wall(30_001); + assert!(detector.jumped(&clock)); + assert!(!detector.jumped(&clock)); + clock.jump_wall(-8 * 3600 * 1000); + assert!(detector.jumped(&clock)); + } +} diff --git a/src/engine/fake.rs b/src/engine/fake.rs new file mode 100644 index 000000000..2d3b6bed9 --- /dev/null +++ b/src/engine/fake.rs @@ -0,0 +1,262 @@ +use std::collections::VecDeque; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Mutex; +use std::time::Duration; + +use async_trait::async_trait; + +use orx_host_proto::{LogInfo, MAX_PAGE_LEN}; + +use super::{ + Backend, ByteRange, CancelOutcome, Fence, FileIdent, Handle, LaunchError, LogFile, LogPage, + Observation, Recovery, RunIntent, WatchedRun, +}; +use crate::error::{anyhow, Result}; +use crate::store::LaunchSpec; + +/// Answers from scripted queues and records every call; an unscripted call panics. +#[derive(Default)] +pub struct FakeBackend { + pub launches: Mutex>>, + pub recoveries: Mutex>, + pub cancels: Mutex>, + /// Observations the feed reports, in order, for whichever of them are watched. + pub feed: Mutex>, + pub log: Mutex, + pub notify: Mutex, + /// Every launch intent the backend was asked to launch or recover. + pub intents: Mutex>, + /// Child pid each launch records as its submitter. + pub submitter: Mutex>, + /// Runs inside the next launch, after its fence and before its answer. + pub during_launch: Mutex>>, + /// Launches never answer, as when the caller's future is dropped mid-launch. + pub hang_launch: AtomicBool, + pub calls: Mutex>, + pub unwatched: Mutex>, + /// Runs whose logs are held for reading, until forgotten. + pub held: Mutex>, +} + +impl FakeBackend { + pub fn then_launch(&self, result: std::result::Result) -> &Self { + self.launches.lock().unwrap().push_back(result); + self + } + + pub fn then_recover(&self, recovery: Recovery) -> &Self { + self.recoveries.lock().unwrap().push_back(recovery); + self + } + + pub fn then_cancel(&self, outcome: CancelOutcome) -> &Self { + self.cancels.lock().unwrap().push_back(outcome); + self + } + + pub fn calls(&self) -> Vec { + self.calls.lock().unwrap().clone() + } + + /// Records the call and yields, so concurrent callers interleave as with a real backend. + async fn call(&self, name: String) { + self.calls.lock().unwrap().push(name); + tokio::task::yield_now().await; + } +} + +fn next(queue: &Mutex>, call: &str) -> T { + queue + .lock() + .unwrap() + .pop_front() + .unwrap_or_else(|| panic!("unscripted {call}")) +} + +#[async_trait] +impl Backend for FakeBackend { + async fn launch( + &self, + intent: &RunIntent, + fence: &Fence<'_>, + ) -> std::result::Result { + assert!(!intent.spec_digest.is_empty()); + self.intents.lock().unwrap().push(intent.launch.clone()); + self.call(format!("launch {} #{}", intent.run.id, intent.attempt)) + .await; + let submitter = *self.submitter.lock().unwrap(); + if let Some(pid) = submitter { + fence.record_submitter(pid).unwrap(); + } + if self.hang_launch.load(Ordering::SeqCst) { + std::future::pending::<()>().await; + } + let during = self.during_launch.lock().unwrap().take(); + if let Some(during) = during { + during(); + } + next(&self.launches, "launch") + } + + async fn recover(&self, intent: &RunIntent) -> Recovery { + self.intents.lock().unwrap().push(intent.launch.clone()); + self.call(format!("recover {} #{}", intent.run.id, intent.attempt)) + .await; + next(&self.recoveries, "recover") + } + + async fn observe(&self, runs: &[WatchedRun], _: Duration) -> Vec<(String, Observation)> { + let mut feed = self.feed.lock().unwrap(); + let (watched, rest) = feed + .drain(..) + .partition(|(id, _)| runs.iter().any(|run| run.id == *id)); + *feed = rest; + watched.into() + } + + async fn cancel(&self, run: &WatchedRun) -> CancelOutcome { + let handle = serde_json::to_value(&run.handle).unwrap(); + self.call(format!( + "cancel {} {}", + run.id, + handle["type"].as_str().unwrap() + )) + .await; + next(&self.cancels, "cancel") + } + + async fn unwatch(&self, run: &WatchedRun) { + self.unwatched.lock().unwrap().push(run.id.clone()); + } + + fn forget_logs(&self, forgotten: &dyn Fn(&str) -> bool) { + self.held.lock().unwrap().retain(|run| !forgotten(run)); + } + + async fn read_log( + &self, + _: &WatchedRun, + file: LogFile, + range: ByteRange, + ident: Option<&FileIdent>, + ) -> Result { + tokio::task::yield_now().await; + match file { + LogFile::Log => self.log.lock().unwrap().read(2, ident, &range), + LogFile::Notify => self.notify.lock().unwrap().read(3, ident, &range), + } + } +} + +/// A run file as `orx-host` serves it (`crates/orx-host/src/log.rs`): its identity is its +/// inode, which a replacement bumps, and requests are validated the same way. +#[derive(Default)] +pub struct HostFile { + pub bytes: Vec, + pub ino: u64, +} + +impl HostFile { + pub fn read(&self, dev: u64, ident: Option<&FileIdent>, range: &ByteRange) -> Result { + if range.end < range.start || range.end - range.start > MAX_PAGE_LEN { + return Err(anyhow!("invalid log range")); + } + let info = LogInfo { + ident: FileIdent { dev, ino: self.ino }, + len: self.bytes.len() as u64, + }; + if ident.is_some_and(|ident| *ident != info.ident) || info.len < range.start { + return Ok(LogPage::Reset { info: Some(info) }); + } + let end = range.end.min(info.len); + Ok(LogPage::Data { + len: Some(info.len), + ident: info.ident, + start: range.start, + bytes: self.bytes[range.start as usize..end as usize].to_vec(), + eof: end >= info.len, + }) + } +} + +#[cfg(all(test, unix))] +mod tests { + use super::*; + + /// Replays the engine's request shapes against the real host and compares page shapes, + /// with identities renamed by first appearance on each side. + #[test] + fn the_fake_validates_and_pages_like_orx_host() { + let dir = std::env::temp_dir().join(format!("orx-fake-host-{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("notify"); + let mut fake = HostFile::default(); + let mut idents: [Vec; 2] = Default::default(); + let mut name = |side: usize, ident: &FileIdent| { + let seen = &mut idents[side]; + if !seen.contains(ident) { + seen.push(ident.clone()); + } + seen.iter().position(|known| known == ident).unwrap() + }; + let mut shape = |side: usize, page: std::io::Result| match page { + Err(_) => "error".to_string(), + Ok(LogPage::Reset { info }) => { + format!( + "reset {:?}", + info.map(|info| (name(side, &info.ident), info.len)) + ) + } + Ok(LogPage::Data { + len: _, + ident, + start, + bytes, + eof, + }) => { + format!("data {} {start} {bytes:?} {eof}", name(side, &ident)) + } + }; + + let mut last: [Option; 2] = [None, None]; + let steps: [(&str, u64, u64, bool); 8] = [ + ("hello", 0, 5, false), + ("hello world", 5, 11, true), + ("hello world", 11, 11, true), + ("hello world", 12, 11, true), + ("hello world", 20, 30, true), + ("jello world", 11, 11, true), + ("bye", 0, 3, true), + ("bye", 0, 3, false), + ]; + for (content, start, end, with_ident) in steps { + std::fs::write(&path, content).unwrap(); + fake.bytes = content.as_bytes().to_vec(); + let range = ByteRange { start, end }; + let real = + orx_host::log::read(&path, last[0].as_ref().filter(|_| with_ident), &range, None); + let modeled = fake.read(3, last[1].as_ref().filter(|_| with_ident), &range); + for (side, page) in [ + (0, &real.as_ref().ok().cloned()), + (1, &modeled.as_ref().ok().cloned()), + ] { + if let Some( + LogPage::Data { ident, .. } + | LogPage::Reset { + info: Some(LogInfo { ident, .. }), + }, + ) = page + { + last[side] = Some(ident.clone()); + } + } + let modeled = modeled.map_err(|error| std::io::Error::other(error.to_string())); + assert_eq!( + shape(0, real), + shape(1, modeled), + "{content:?} {start}..{end}" + ); + } + std::fs::remove_dir_all(dir).unwrap(); + } +} diff --git a/src/engine/handle.rs b/src/engine/handle.rs new file mode 100644 index 000000000..72302892c --- /dev/null +++ b/src/engine/handle.rs @@ -0,0 +1,263 @@ +use serde::{Deserialize, Serialize}; + +use crate::error::{anyhow, Result}; +use crate::jobs::BackendDescriptor; + +#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub struct ApiAccount { + pub target: Option, + pub context: Option, +} + +impl ApiAccount { + pub fn target(&self) -> Result<&str> { + self.target + .as_deref() + .ok_or_else(|| anyhow!("API account has no target")) + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(tag = "type")] +pub enum Handle { + Ssh { + host: String, + root: String, + }, + Slurm { + host: String, + root: String, + job: Option, + }, + Local { + dir: String, + }, + Tinker { + dir: String, + }, + Api { + provider: String, + account: ApiAccount, + ids: Vec, + }, + Legacy { + descriptor: Box, + }, +} + +pub fn backend_json( + run_id: &str, + handle: Option<&Handle>, + metadata: &BackendDescriptor, +) -> Result { + let metadata = match handle { + Some(Handle::Legacy { descriptor }) => descriptor.as_ref(), + _ => metadata, + }; + + let job_id = match handle { + None => None, + Some( + Handle::Ssh { root, .. } + | Handle::Slurm { + root, job: None, .. + }, + ) => Some(format!("{}/runs/{run_id}", root.trim_end_matches('/'))), + Some(Handle::Slurm { job: Some(job), .. }) => Some(job.clone()), + Some(Handle::Local { dir } | Handle::Tinker { dir }) => Some(dir.clone()), + Some(Handle::Api { ids, .. }) => ids.first().cloned(), + Some(Handle::Legacy { descriptor }) => descriptor.job_id.clone(), + }; + + if handle.is_some() && job_id.as_deref().is_none_or(str::is_empty) { + return Err(anyhow!("Engine handle has no job id")); + } + + let mut value = serde_json::json!({ "kind": "engine" }); + if let Some(job_id) = job_id { + value["jobId"] = job_id.into(); + } + if let Some(digest) = &metadata.source_digest { + value["sourceDigest"] = digest.clone().into(); + } + if let Some(path) = &metadata.source_path { + value["sourcePath"] = path.clone().into(); + } + if let Some(size) = metadata.source_size { + value["sourceSize"] = size.into(); + } + if let Some(handle) = handle { + value["handle"] = serde_json::to_value(handle)?; + } + + Ok(serde_json::to_string(&value)?) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_handle_keeps_old_descriptor_fields_and_round_trips() { + let metadata = BackendDescriptor::parse( + r#"{"kind":"ssh_job","jobId":"stale","sourceDigest":"abc","sourcePath":"/sources/abc.tar","sourceSize":123}"#, + ).unwrap(); + let handles = [ + ( + Handle::Ssh { + host: "host".into(), + root: "/orx/".into(), + }, + "/orx/runs/run", + ), + ( + Handle::Slurm { + host: "login".into(), + root: "/shared".into(), + job: Some("1234".into()), + }, + "1234", + ), + ( + Handle::Slurm { + host: "login".into(), + root: "/shared".into(), + job: None, + }, + "/shared/runs/run", + ), + ( + Handle::Local { + dir: "/local/run".into(), + }, + "/local/run", + ), + ( + Handle::Tinker { + dir: "/local/tinker".into(), + }, + "/local/tinker", + ), + ( + crate::engine::adapters::api::test_handle( + "hf_job", + Some("lab"), + None, + vec!["hf-1".into()], + ), + "hf-1", + ), + ( + crate::engine::adapters::api::test_handle( + "modal_job", + None, + None, + vec!["sb-1".into()], + ), + "sb-1", + ), + ( + crate::engine::adapters::api::test_handle( + "k8s_job", + Some("lab"), + Some("cluster"), + vec!["job/run".into(), "configmap/run".into()], + ), + "job/run", + ), + ( + crate::engine::adapters::api::test_handle( + "ray_job", + Some("http://ray"), + None, + vec!["ray-1".into()], + ), + "ray-1", + ), + ( + Handle::Legacy { + descriptor: Box::new(metadata.clone()), + }, + "stale", + ), + ]; + let pending = backend_json("run", None, &metadata).unwrap(); + let pending_old = BackendDescriptor::parse(&pending).unwrap(); + assert_eq!(pending_old.kind, "engine"); + assert!(pending_old.job_id.is_none()); + assert_eq!(pending_old.source_digest, metadata.source_digest); + for (handle, id) in handles { + let json = backend_json("run", Some(&handle), &metadata).unwrap(); + let old = BackendDescriptor::parse(&json).unwrap(); + assert_eq!(old.kind, "engine"); + assert_eq!(old.job_id.as_deref(), Some(id)); + assert_eq!(old.source_digest, metadata.source_digest); + assert_eq!(old.source_path, metadata.source_path); + assert_eq!(old.source_size, metadata.source_size); + let value: serde_json::Value = serde_json::from_str(&json).unwrap(); + let decoded: Handle = serde_json::from_value(value["handle"].clone()).unwrap(); + assert_eq!( + serde_json::to_value(&decoded).unwrap(), + serde_json::to_value(&handle).unwrap() + ); + assert_eq!(serde_json::to_value(old).unwrap().get("handle"), None); + } + } + + #[test] + fn legacy_handle_preserves_one_rental_and_endpoint_and_public_json_hides_token() { + let descriptor = BackendDescriptor::parse( + r#"{"kind":"openresearch_job","namespace":"org","jobId":"sb","sshHost":"compute","sshPort":2200,"sshUser":"root","rentalLease":{"apiUrl":"https://example.invalid","sandboxId":"sb","token":"private-token"},"sourceDigest":"snapshot","sourcePath":"/snapshot.tar","sourceSize":456}"#, + ).unwrap(); + let json = backend_json( + "run", + Some(&Handle::Legacy { + descriptor: Box::new(descriptor), + }), + &BackendDescriptor::parse(r#"{"kind":"local_job"}"#).unwrap(), + ) + .unwrap(); + let value: serde_json::Value = serde_json::from_str(&json).unwrap(); + assert_eq!(json.matches("private-token").count(), 1); + assert!(value.get("rentalLease").is_none()); + assert!(value.get("namespace").is_none()); + assert!(value.get("sshHost").is_none()); + let inner: BackendDescriptor = + serde_json::from_value(value["handle"]["descriptor"].clone()).unwrap(); + assert_eq!(inner.openresearch_ref().unwrap(), ("org", "sb")); + assert_eq!( + inner.openresearch_ssh_target().unwrap().dest, + "root@compute" + ); + assert_eq!(inner.rental_lease.unwrap().token, "private-token"); + let old = BackendDescriptor::parse(&json).unwrap(); + assert_eq!(old.source_digest.as_deref(), Some("snapshot")); + assert_eq!(old.source_path.as_deref(), Some("/snapshot.tar")); + assert_eq!(old.source_size, Some(456)); + let public = crate::store::public_backend(&json, None).unwrap(); + assert_eq!(public["kind"], "openresearch_job"); + assert!(!public.to_string().contains("private-token")); + assert!(public.get("rentalLease").is_none()); + assert!(public["handle"]["descriptor"].get("rentalLease").is_none()); + assert_eq!(public["handle"]["descriptor"]["jobId"], "sb"); + } + + #[test] + fn handles_without_a_legacy_visible_id_are_rejected() { + let metadata = BackendDescriptor::parse(r#"{"kind":"ssh_job"}"#).unwrap(); + for handle in [ + crate::engine::adapters::api::test_handle("k8s_job", Some("lab"), None, vec![]), + Handle::Legacy { + descriptor: Box::new(metadata.clone()), + }, + crate::engine::adapters::api::test_handle( + "hf_job", + Some("lab"), + None, + vec![String::new()], + ), + ] { + assert!(backend_json("run", Some(&handle), &metadata).is_err()); + } + } +} diff --git a/src/engine/legacy.rs b/src/engine/legacy.rs new file mode 100644 index 000000000..1faa03a52 --- /dev/null +++ b/src/engine/legacy.rs @@ -0,0 +1,192 @@ +//! Runner-1 rows remain read-only until engine adoption is enabled and their launch has settled. + +use super::bus::RunEvent; +use super::{handle_of, phase_of, Engine}; +use crate::error::Result; +use crate::jobs::ssh::ContainerRun; +use crate::jobs::BackendDescriptor; +use crate::store::{Contact, SeenRow, StoredRun, ATTENTION, RECOVERED, TERMINAL}; + +/// 0.2.x launched without wrapper or tags, so `CancelLegacy` only reaches the recorded group. +const LEGACY_CANCEL_NOTE: &str = "Cancelled. This run was launched by orx 0.2.x, so only its \ + process group was stopped; workers it started in new sessions are not covered (OR-469)."; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Adoption { + /// An old supervisor holds the run: read its row until terminal, never write it. + Watch, + /// `ssh_job`: `InspectLegacy` for state, `CancelLegacy` with the shipped container step. + Inspect { + dir: String, + container: Option, + }, + /// `openresearch_job`: `LegacyLoop` behind a `RunSink`. + Loop, + /// Other kinds: the native adapter reading the old descriptor fields. + Native { kind: String }, +} + +fn adoption(descriptor: BackendDescriptor) -> Option { + Some(match descriptor.kind.as_str() { + "ssh_job" => Adoption::Inspect { + dir: descriptor.job_id?, + container: descriptor.ssh_container, + }, + "openresearch_job" => Adoption::Loop, + kind if matches!(kind, "slurm_job" | "local_job" | "tinker_job") + || super::adapters::api::provider(kind).is_ok() => + { + Adoption::Native { + kind: descriptor.kind, + } + } + _ => return None, + }) +} + +pub(super) fn cancel_note(run: &StoredRun) -> Option { + match handle_of(run)? { + super::Handle::Legacy { descriptor } if descriptor.kind == "ssh_job" => { + Some(LEGACY_CANCEL_NOTE.into()) + } + _ => None, + } +} + +impl Engine { + pub fn scan_legacy(&self, adopt: bool) -> Result> { + let candidates: Vec<(StoredRun, Adoption)> = { + let store = self.store(); + let mut candidates = Vec::new(); + for run in store.list_active_runs()? { + let Ok(descriptor) = BackendDescriptor::parse(&run.backend_json) else { + continue; + }; + // Without a handle a 0.2.x CLI may still be submitting it. + if descriptor.kind == "engine" + || descriptor.job_id.is_none() + || store.get_local_experiment(&run.experiment_id)?.is_none() + { + continue; + } + if let Some(adoption) = adoption(descriptor) { + candidates.push((run, adoption)); + } + } + candidates + }; + + #[cfg(test)] + { + let hook = self.memory().after_legacy_snapshot.take(); + if let Some(hook) = hook { + hook(); + } + } + + let mut decisions = Vec::new(); + for (run, adoption) in candidates { + if self.memory().locks.holds(&run.id) { + continue; + } + if !adopt + || self.clock.wall_ms() - run.updated_at < super::ORPHANED_RUN_SETTLE_MS + || !self.own(&run.id)? + { + self.store().watch_legacy_run(&run.id, None)?; + decisions.push((run.id, Adoption::Watch)); + } else if self.reread_watch(&run.id, None, true)?.is_some() { + decisions.push((run.id, adoption)); + } else { + // Its supervisor finished it between the snapshot and the lock. + self.memory().locks.release(&run.id); + } + } + let watches = self.store().legacy_watches()?; + for (id, seen) in watches { + self.reread_watch(&id, seen.as_ref(), false)?; + } + Ok(decisions) + } + + /// Rereads a watched run and records what it found in one transaction: a finished run's + /// chat results are queued as its watch ends. Returns the row while it is still active; + /// `adopting` ends the watch of an active run too. + fn reread_watch( + &self, + id: &str, + seen: Option<&SeenRow>, + adopting: bool, + ) -> Result> { + let now = self.clock.wall_ms(); + let (run, chats, terminal, changed) = { + let store = self.store(); + let tx = store.begin_immediate()?; + let Some(run) = store.get_run(id)? else { + store.unwatch_legacy_run(id)?; + tx.commit()?; + return Ok(None); + }; + let terminal = phase_of(&run)?.is_terminal(); + let mut chats = Vec::new(); + if terminal { + let body = store.terminal_notice_body(&run)?; + for chat in store.run_subscribers(id)? { + if store.insert_run_notice(id, &chat, TERMINAL, TERMINAL, &body, now)? { + chats.push(chat); + } + } + } else if !adopting { + let descriptor = BackendDescriptor::parse(&run.backend_json)?; + for chat in store.run_subscribers(id)? { + let (kind, body) = if descriptor.monitoring_error.is_some() { + let body = format!( + "[orx] orx can no longer monitor these live runs:\n\ + - run `{id}` of experiment `{}` (still **{}**)\n\ + Run `orx exp status ` for the reason and tell the user so they \ + can fix it. orx wakes you once it can see a run finish; until then \ + each run keeps its current status.", + run.experiment_id, run.status + ); + (ATTENTION, body) + } else if store.settle_outage_notice(id, &chat)? { + ( + RECOVERED, + format!( + "[orx] Run `{id}` is reachable again; status {}.", + run.status + ), + ) + } else { + continue; + }; + let dedupe = store.outage_dedupe(id, &chat, kind)?; + if store.insert_run_notice(id, &chat, kind, &dedupe, &body, now)? { + chats.push(chat); + } + } + } + let changed = seen != Some(&(run.status.clone(), run.updated_at)); + if terminal || adopting { + store.unwatch_legacy_run(id)?; + } else if changed { + store.watch_legacy_run(id, Some((&run.status, run.updated_at)))?; + } + tx.commit()?; + (run, chats, terminal, changed) + }; + if terminal || (changed && !adopting) { + let phase = phase_of(&run)?; + self.bus.publish(RunEvent::Changed { + run_id: id.into(), + phase, + contact: Contact::Live, + cancelling: run.cancel_requested && !terminal, + }); + } + if !chats.is_empty() { + self.bus.publish(RunEvent::Notices { chats }); + } + Ok((!terminal).then_some(run)) + } +} diff --git a/src/engine/locks.rs b/src/engine/locks.rs new file mode 100644 index 000000000..1689bac99 --- /dev/null +++ b/src/engine/locks.rs @@ -0,0 +1,50 @@ +use std::collections::HashMap; +use std::fs::{File, OpenOptions, TryLockError}; +use std::path::PathBuf; + +use crate::error::Result; + +/// The per-run `.supervisor.lock` + `.supervisor.shared-ssh.lock` pairs the engine owns. +/// Holding both is what makes 0.2.x startup, `orx supervise` and `ssh-service` leave a run alone; +/// dropping the files releases them. +#[derive(Default)] +pub struct RunLocks(HashMap); + +impl RunLocks { + pub fn holds(&self, run_id: &str) -> bool { + self.0.contains_key(run_id) + } + + /// False when another process (an old supervisor, or a momentary probe) holds either lock. + pub fn acquire(&mut self, run_id: &str, paths: [PathBuf; 2]) -> Result { + if self.holds(run_id) { + return Ok(true); + } + let [supervisor, shared] = paths.map(|path| -> Result { + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent)?; + } + Ok(OpenOptions::new() + .create(true) + .truncate(false) + .write(true) + .open(path)?) + }); + // Supervisor first, as `orx supervise` takes them: whoever holds it owns the run. + let supervisor = supervisor?; + let shared = shared?; + for file in [&supervisor, &shared] { + match file.try_lock() { + Ok(()) => {} + Err(TryLockError::WouldBlock) => return Ok(false), + Err(TryLockError::Error(error)) => return Err(error.into()), + } + } + self.0.insert(run_id.to_string(), [supervisor, shared]); + Ok(true) + } + + pub fn release(&mut self, run_id: &str) { + self.0.remove(run_id); + } +} diff --git a/src/engine/mod.rs b/src/engine/mod.rs new file mode 100644 index 000000000..be9806004 --- /dev/null +++ b/src/engine/mod.rs @@ -0,0 +1,497 @@ +pub mod adapters; +pub mod bus; +pub mod clock; +pub mod handle; +pub mod legacy; +pub mod locks; +pub mod notify; +pub mod process; +pub mod reconcile; +pub mod runtime; +pub mod ssh_config_cleanup; +pub mod submit; +pub mod transport; + +use std::collections::{HashMap, HashSet}; +use std::sync::{Arc, Mutex, MutexGuard, Weak}; +use std::time::Duration; + +use async_trait::async_trait; +use tokio::sync::OwnedMutexGuard; + +use crate::error::{anyhow, Result}; +use crate::jobs::BackendDescriptor; +use crate::store::{Contact, EngineRunState, LaunchSpec, Store, StoredRun, SubmissionFence}; +use bus::Bus; +use clock::Clock; +use handle::Handle; +use locks::RunLocks; +pub use orx_host_proto::{ByteRange, FileIdent, LogFile, LogPage}; + +/// `runs.status`. Phase only moves forward: Submitting → Starting → Running → one terminal. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Phase { + Submitting, + Starting, + Running, + Done, + Failed, + Cancelled, + Lost, +} + +impl Phase { + pub fn parse(status: &str) -> Option { + Some(match status { + "submitting" => Self::Submitting, + "starting" => Self::Starting, + "running" => Self::Running, + "done" => Self::Done, + "failed" => Self::Failed, + "cancelled" => Self::Cancelled, + "lost" => Self::Lost, + _ => return None, + }) + } + + pub fn as_str(self) -> &'static str { + match self { + Self::Submitting => "submitting", + Self::Starting => "starting", + Self::Running => "running", + Self::Done => "done", + Self::Failed => "failed", + Self::Cancelled => "cancelled", + Self::Lost => "lost", + } + } + + fn rank(self) -> u8 { + match self { + Self::Submitting => 0, + Self::Starting => 1, + Self::Running => 2, + Self::Done | Self::Failed | Self::Cancelled | Self::Lost => 3, + } + } + + pub fn is_terminal(self) -> bool { + self.rank() == 3 + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Observation { + NotFound, + Gone { + reason: String, + }, + Queued { + detail: String, + }, + Running { + started_at: Option, + }, + Exited { + finished_at: Option, + code: Option, + signal: Option, + }, + Cancelled { + finished_at: Option, + code: Option, + signal: Option, + }, + CancelReceipt { + finished_at: Option, + code: Option, + remaining: usize, + note: Option>, + }, + Failed { + finished_at: Option, + reason: String, + }, + Lost { + reason: String, + }, + Unreachable { + cause: String, + }, + NeedsAuth { + cause: String, + }, + Unreconciled { + detail: String, + }, + Notify { + len: u64, + }, + /// The log length of a followed or local run. + Log { + len: u64, + }, + /// Latest process proof; an empty list settles a tombstone. + Lingering { + pids: Vec, + }, +} + +impl Observation { + pub fn ends_run(&self) -> bool { + matches!( + self, + Self::Exited { .. } + | Self::Cancelled { .. } + | Self::CancelReceipt { .. } + | Self::Failed { .. } + | Self::Lost { .. } + | Self::Gone { .. } + ) + } +} + +#[derive(Debug)] +pub enum Recovery { + Found(Handle), + /// Proven: no job exists for this attempt and none can appear. + Absent, + Unknown { + detail: String, + }, +} + +#[derive(Debug)] +pub enum CancelOutcome { + Verified, + Survivors { + count: usize, + }, + /// Accepted; the outcome arrives as an observation. + Pending, + /// No acknowledgement; retain the intent for another delivery attempt. + Undelivered { + detail: String, + }, +} + +#[derive(Debug)] +pub enum LaunchError { + /// Proven: nothing was created. + Rejected { reason: String }, + /// No launch was sent; contact must recover before retrying. + Blocked { contact: crate::store::Contact }, + /// The outcome is unknown; recovery decides. + Interrupted { detail: String }, +} + +#[derive(Debug)] +pub struct RunIntent { + pub run: StoredRun, + pub launch: LaunchSpec, + pub spec_digest: String, + /// Lets fakes report which attempt they were asked to launch or recover. + #[cfg(test)] + pub attempt: u32, +} + +impl RunIntent { + fn new(run: StoredRun, state: &EngineRunState) -> Result { + let launch = state + .launch + .clone() + .ok_or_else(|| anyhow!("Run {} has no launch intent", run.id))?; + Ok(Self { + run, + launch, + spec_digest: state.spec_digest.clone().unwrap_or_default(), + #[cfg(test)] + attempt: state.submission_attempt, + }) + } +} + +#[derive(Debug, Clone)] +pub struct WatchedRun { + pub id: String, + pub handle: Handle, +} + +/// The outstanding submitter of one attempt, recorded before its side effect. +pub struct Fence<'a> { + store: &'a Mutex, + run_id: &'a str, + attempt: u32, + taken_at: i64, +} + +impl Fence<'_> { + /// Whether a cancel was accepted for the run; a launch checks before each step it takes. + pub fn cancelled(&self) -> bool { + lock(self.store) + .engine_run_state(self.run_id) + .ok() + .flatten() + .is_some_and(|state| state.cancel_accepted_at.is_some()) + } + + /// For a launch done by a child process. Record it before the child can act (e.g. have it + /// wait on stdin), so recovery after a crash waits for it instead of racing it. + pub fn record_submitter(&self, pid: u32) -> Result<()> { + let submitter = process::identity(pid) + .ok_or_else(|| anyhow!("Could not read submitter {pid}'s identity"))?; + let fence = SubmissionFence { + taken_at: self.taken_at, + submitter: Some(submitter), + }; + if lock(self.store).record_submitter(self.run_id, self.attempt, &fence)? { + Ok(()) + } else { + Err(anyhow!( + "Run {} no longer awaits attempt {}", + self.run_id, + self.attempt + )) + } + } +} + +#[async_trait] +pub trait Backend: Send + Sync { + async fn launch(&self, intent: &RunIntent, fence: &Fence<'_>) -> Result; + async fn recover(&self, intent: &RunIntent) -> Recovery; + async fn recover_with_cancel( + &self, + intent: &RunIntent, + _cancelled: &(dyn Fn() -> bool + Sync), + ) -> Recovery { + self.recover(intent).await + } + + async fn observe(&self, runs: &[WatchedRun], budget: Duration) -> Vec<(String, Observation)>; + async fn cancel(&self, run: &WatchedRun) -> CancelOutcome; + async fn cleanup(&self, run: &WatchedRun) -> CancelOutcome { + self.cancel(run).await + } + /// Releases provider resources after output is kept; failures retry with collection. + async fn finish(&self, _run: &WatchedRun) -> Result<()> { + Ok(()) + } + async fn unwatch(&self, _run: &WatchedRun) {} + /// Releases what is held for reading the logs of runs `forgotten` names, such as deleted + /// ones. + fn forget_logs(&self, _forgotten: &dyn Fn(&str) -> bool) {} + /// Before a finished run's log is kept: fetch it through its end where reads are cached. + async fn drain_log(&self, _run: &WatchedRun) -> Result<()> { + Ok(()) + } + async fn read_log( + &self, + run: &WatchedRun, + file: LogFile, + range: ByteRange, + ident: Option<&FileIdent>, + ) -> Result; +} + +pub(crate) const ORPHANED_RUN_SETTLE_MS: i64 = 5 * 60 * 1000; + +/// Process-local facts; everything durable lives in the store. +#[derive(Default)] +struct Memory { + locks: RunLocks, + /// Serializes submission, recovery and notify delivery per run; dropping a future releases it. + gates: HashMap>>, + /// Monotonic start of each Unreachable outage seen by this process. + outages: HashMap, + /// Failed recoveries and when the next one is due. + retries: HashMap, + /// Cancels delivered on the current connection; cleared when contact is lost. + cancels_sent: HashSet, + /// Cancels awaiting the backend's verdict, alive while their delivery is; the verdict, not + /// a death seen meanwhile, ends the run. + verifying: HashMap>, + #[cfg(test)] + after_legacy_snapshot: Option>, + #[cfg(test)] + before_observed_commit: Option>, + /// Notify-file lengths reported but not yet turned into a notice. + notify: HashMap, + /// Last published log length per run. + logs: HashMap, +} + +pub struct Engine { + store: Mutex, + clock: Arc, + pub bus: Bus, + memory: Mutex, +} + +fn lock(mutex: &Mutex) -> MutexGuard<'_, T> { + mutex + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) +} + +impl Engine { + pub fn new(store: Store, clock: Arc) -> Self { + Self { + store: Mutex::new(store), + clock, + bus: Bus::new(), + memory: Mutex::default(), + } + } + + fn store(&self) -> MutexGuard<'_, Store> { + lock(&self.store) + } + + fn memory(&self) -> MutexGuard<'_, Memory> { + lock(&self.memory) + } + + fn gate(&self, run_id: &str) -> Arc> { + self.memory() + .gates + .entry(run_id.into()) + .or_default() + .clone() + } + + /// None while another task is submitting, recovering or notifying for this run. + fn try_gate(&self, run_id: &str) -> Option> { + self.gate(run_id).try_lock_owned().ok() + } + + /// Takes both per-run locks unless already held. Every action on a run goes through here, + /// so a run an old supervisor holds is never written. + fn own(&self, run_id: &str) -> Result { + let paths = self.store().supervisor_lock_paths(run_id)?; + self.memory().locks.acquire(run_id, paths) + } + + /// True while this engine holds the run's supervisor locks. + pub fn holds(&self, run_id: &str) -> bool { + self.memory().locks.holds(run_id) + } + + #[cfg(test)] + pub async fn observe_runs( + &self, + backend: &dyn Backend, + runs: &[WatchedRun], + budget: Duration, + ) -> Result<()> { + let observations = backend.observe(runs, budget).await; + self.apply_observations(backend, runs, observations).await + } + + /// Applies what `Backend::observe` reported and delivers pending cancels. + pub async fn apply_observations( + &self, + backend: &dyn Backend, + runs: &[WatchedRun], + observations: Vec<(String, Observation)>, + ) -> Result<()> { + for (id, observation) in observations { + self.observe(&id, observation)?; + } + for watched in runs { + let (run, state) = self.load(&watched.id)?; + let phase = phase_of(&run)?; + let tombstone = reconcile::is_tombstone(phase, &state.contact); + if phase.is_terminal() && !tombstone { + self.memory().logs.remove(&watched.id); + } else if run.cancel_requested || state.cancel_accepted_at.is_some() || tombstone { + self.deliver_cancel(backend, &watched.id).await?; + } + } + Ok(()) + } + + /// Delivers a pending stop once per connection; rented boxes can be released without SSH. + pub async fn deliver_cancel(&self, backend: &dyn Backend, run_id: &str) -> Result<()> { + if !self.own(run_id)? { + return Ok(()); + } + let (run, state) = self.load(run_id)?; + let phase = phase_of(&run)?; + // Intent is read under `cancel.lock`, accepting a legacy `cancel_requested` for good. + let wanted = reconcile::is_tombstone(phase, &state.contact) + || (matches!(phase, Phase::Starting | Phase::Running) + && self.store().accept_run_cancel(run_id, None)?.is_some()); + let Some(handle) = handle_of(&run) else { + return Ok(()); + }; + let deliverable = matches!( + state.contact, + Contact::Live | Contact::Unreconciled { .. } | Contact::Stopping { .. } + ) || matches!(&handle, Handle::Legacy { descriptor } if descriptor.kind == "openresearch_job"); + if !wanted || !deliverable || self.memory().cancels_sent.contains(run_id) { + return Ok(()); + } + let watched = WatchedRun { + id: run.id.clone(), + handle, + }; + let verifying = Arc::new(()); + { + // Serialized with terminal decisions, which commit under the store lock. + let _decisions = self.store(); + let mut memory = self.memory(); + memory.cancels_sent.insert(run_id.to_string()); + memory + .verifying + .insert(run_id.to_string(), Arc::downgrade(&verifying)); + } + let outcome = if reconcile::is_tombstone(phase, &state.contact) { + backend.cleanup(&watched).await + } else { + backend.cancel(&watched).await + }; + if matches!(outcome, CancelOutcome::Undelivered { .. }) { + self.memory().cancels_sent.remove(run_id); + } + self.apply_cancel(&run, outcome) + } + + fn load(&self, run_id: &str) -> Result<(StoredRun, EngineRunState)> { + load(&self.store(), run_id) + } +} + +fn load(store: &Store, run_id: &str) -> Result<(StoredRun, EngineRunState)> { + let missing = || anyhow!("Run {run_id} not found"); + let run = store.get_run(run_id)?.ok_or_else(missing)?; + let state = store.engine_run_state(run_id)?.ok_or_else(missing)?; + Ok((run, state)) +} + +fn phase_of(run: &StoredRun) -> Result { + Phase::parse(&run.status).ok_or_else(|| anyhow!("Unknown run status: {}", run.status)) +} + +/// Rows the engine created, as opposed to rows orx 0.2.x left behind. +pub fn is_engine_row(run: &StoredRun) -> bool { + serde_json::from_str::(&run.backend_json) + .is_ok_and(|value| value["kind"] == "engine") +} + +/// Runner-2 rows carry `handle`; an adopted runner-1 row is its whole old descriptor. +pub fn handle_of(run: &StoredRun) -> Option { + let value: serde_json::Value = serde_json::from_str(&run.backend_json).ok()?; + if value["kind"] == "engine" { + return serde_json::from_value(value.get("handle")?.clone()).ok(); + } + let descriptor = BackendDescriptor::parse(&run.backend_json).ok()?; + descriptor.job_id.is_some().then(|| Handle::Legacy { + descriptor: Box::new(descriptor), + }) +} + +#[cfg(test)] +mod fake; +#[cfg(test)] +mod tests; diff --git a/src/engine/notify.rs b/src/engine/notify.rs new file mode 100644 index 000000000..13d6bd6bb --- /dev/null +++ b/src/engine/notify.rs @@ -0,0 +1,182 @@ +//! §7 `notify` notices: new bytes of a run's `$ORX_NOTIFY_FILE`, at most one per run per +//! 10 minutes. Bytes coalesce inside the window; final collection bypasses it. + +use std::time::Duration; + +use super::bus::RunEvent; +use super::{handle_of, phase_of, Backend, ByteRange, Engine, LogFile, LogPage, WatchedRun}; +use crate::error::{anyhow, Result}; +use crate::store::{NotifyCursor, NOTIFY}; + +const NOTIFY_INTERVAL: Duration = Duration::from_secs(10 * 60); +/// A notice carries at most this tail of the new bytes; the file itself keeps the rest. +const NOTIFY_BYTES: u64 = 4 * 1024; + +impl Engine { + fn notify_window_open(&self, run_id: &str) -> Result { + let interval = i64::try_from(NOTIFY_INTERVAL.as_millis())?; + let last = self.store().last_notice_at(run_id, NOTIFY)?; + Ok(last.is_none_or(|last| self.clock.wall_ms() - last >= interval)) + } + + /// Runs with reported notify bytes whose rate window is open. + pub fn notify_due(&self) -> Result> { + let pending: Vec = self.memory().notify.keys().cloned().collect(); + let mut due = Vec::new(); + for run_id in pending { + if self.notify_window_open(&run_id)? { + due.push(run_id); + } + } + Ok(due) + } + + /// Turns the bytes past the run's notify cursor into one notice per subscribed chat, then + /// advances the cursor in the same transaction. + pub async fn deliver_notify(&self, backend: &dyn Backend, run_id: &str) -> Result { + let Some(_gate) = self.try_gate(run_id) else { + return Ok(false); + }; + let (run, state) = self.load(run_id)?; + let terminal = phase_of(&run)?.is_terminal(); + if !terminal && (!self.notify_window_open(run_id)? || !self.own(run_id)?) { + return Ok(false); + } + let Some(handle) = handle_of(&run) else { + return Ok(true); + }; + let reported = self.memory().notify.get(run_id).copied(); + if !terminal && reported.is_none() { + return Ok(false); + } + let watched = WatchedRun { + id: run.id.clone(), + handle, + }; + let mut len = if terminal { + match backend + .read_log( + &watched, + LogFile::Notify, + ByteRange { + start: u64::MAX - 1, + end: u64::MAX, + }, + None, + ) + .await + { + Err(error) + if error + .downcast_ref::() + .is_some_and(|error| error.kind() == std::io::ErrorKind::Unsupported) => + { + return Ok(true) + } + Err(error) => return Err(error), + Ok(LogPage::Reset { info: Some(info) }) => info.len, + Ok(LogPage::Reset { info: None }) => { + self.memory().notify.remove(run_id); + return Ok(true); + } + Ok(LogPage::Data { .. }) => { + return Err(anyhow!("The host answered a notify length probe with data")) + } + } + } else { + reported.unwrap() + }; + let tail = |from: u64, end: u64| ByteRange { + start: from.max(end.saturating_sub(NOTIFY_BYTES)), + end, + }; + + // A file now shorter than the cursor was truncated or replaced, whatever its identity. + let old = state.notify_cursor; + let continued = old.as_ref().filter(|cursor| cursor.offset <= len); + let mut offset = continued.map_or(0, |cursor| cursor.offset); + let mut same_file = continued.is_some(); + let ident = continued.map(|cursor| &cursor.ident); + let mut page = backend + .read_log(&watched, LogFile::Notify, tail(offset, len), ident) + .await?; + if let LogPage::Reset { info } = page { + let Some(info) = info else { + self.memory().notify.remove(run_id); + return Ok(true); + }; + (offset, same_file) = (0, false); + len = info.len; + page = backend + .read_log( + &watched, + LogFile::Notify, + tail(0, info.len), + Some(&info.ident), + ) + .await?; + } + let LogPage::Data { + ident, + start, + bytes, + eof, + .. + } = page + else { + return Err(anyhow!("The notify file changed during collection")); + }; + let end = start + bytes.len() as u64; + let generation = match &old { + Some(old) if same_file => old.generation, + Some(old) => old.generation + 1, + None => 0, + }; + let cursor = NotifyCursor { + ident, + offset: end, + generation, + }; + + let mut chats = Vec::new(); + if old.as_ref() != Some(&cursor) { + let omitted = start.saturating_sub(offset); + let text = String::from_utf8_lossy(&bytes); + let mut body = format!("[orx] Run `{run_id}` wrote to its notify file:\n{text}"); + if omitted > 0 { + body.push_str(&format!( + "\n({omitted} earlier bytes omitted; see the file.)" + )); + } + let now = self.clock.wall_ms(); + let dedupe = format!("{NOTIFY}:{generation}:{end}"); + let store = self.store(); + let tx = store.begin_immediate()?; + store.set_notify_cursor(run_id, &cursor)?; + for chat in store.run_subscribers(run_id)? { + if !bytes.is_empty() + && store.insert_run_notice(run_id, &chat, NOTIFY, &dedupe, &body, now)? + { + chats.push(chat); + } + } + tx.commit()?; + } + { + let mut memory = self.memory(); + // The length this read started from is consumed even if the file has since shrunk; + // a newer report stays pending. + if memory + .notify + .get(run_id) + .is_some_and(|pending| *pending == reported.unwrap_or(len) || *pending <= end) + { + memory.notify.remove(run_id); + } + } + if !chats.is_empty() { + self.bus.publish(RunEvent::Notices { chats }); + } + Ok(end >= len && (!terminal || eof)) + } +} diff --git a/src/engine/process.rs b/src/engine/process.rs new file mode 100644 index 000000000..49ecfba7d --- /dev/null +++ b/src/engine/process.rs @@ -0,0 +1,212 @@ +//! Identity of a local submitter subprocess (§2 fence): pid plus the OS start stamp, so a +//! reused pid never passes for the process that was recorded. + +use std::io; +use std::time::Duration; + +use crate::store::SubmitterIdentity; + +pub fn identity(pid: u32) -> Option { + start_stamp(pid) + .ok() + .flatten() + .map(|starttime| SubmitterIdentity { pid, starttime }) +} + +/// Kills the submitter if it is still the recorded process; true once it is provably gone. +pub async fn ensure_gone(submitter: &SubmitterIdentity) -> bool { + for _ in 0..50 { + match start_stamp(submitter.pid) { + Ok(Some(starttime)) if starttime == submitter.starttime => {} + Ok(_) => return true, + Err(_) => return false, + } + kill(submitter); + tokio::time::sleep(Duration::from_millis(100)).await; + } + false +} + +#[cfg(target_os = "linux")] +fn start_stamp(pid: u32) -> io::Result> { + if pid == 0 || libc::pid_t::try_from(pid).is_err() { + return Err(io::Error::from(io::ErrorKind::InvalidInput)); + } + let stat = match std::fs::read_to_string(format!("/proc/{pid}/stat")) { + Ok(stat) => stat, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None), + Err(error) => return Err(error), + }; + let (_, fields) = stat + .rsplit_once(')') + .ok_or_else(|| io::Error::from(io::ErrorKind::InvalidData))?; + let fields: Vec<&str> = fields.split_whitespace().collect(); + // Field 3 is the state and field 22 the start time; a zombie has already exited. + if fields.first() == Some(&"Z") { + return Ok(None); + } + let stamp = fields + .get(19) + .and_then(|stamp| stamp.parse().ok()) + .ok_or_else(|| io::Error::from(io::ErrorKind::InvalidData))?; + Ok(Some(stamp)) +} + +#[cfg(target_os = "macos")] +fn start_stamp(pid: u32) -> io::Result> { + let pid = libc::c_int::try_from(pid) + .ok() + .filter(|pid| *pid > 0) + .ok_or_else(|| io::Error::from(io::ErrorKind::InvalidInput))?; + let mut info: libc::proc_bsdinfo = unsafe { std::mem::zeroed() }; + let size = std::mem::size_of::() as libc::c_int; + // SAFETY: `info` is a writable proc_bsdinfo of exactly `size` bytes. + let written = unsafe { + libc::proc_pidinfo( + pid, + libc::PROC_PIDTBSDINFO, + 0, + (&mut info as *mut libc::proc_bsdinfo).cast(), + size, + ) + }; + if written != size { + let error = io::Error::last_os_error(); + return if error.raw_os_error() == Some(libc::ESRCH) { + Ok(None) + } else { + Err(error) + }; + } + if info.pbi_status == libc::SZOMB { + return Ok(None); + } + Ok(Some( + info.pbi_start_tvsec * 1_000_000 + info.pbi_start_tvusec, + )) +} + +#[cfg(unix)] +fn kill(submitter: &SubmitterIdentity) { + let Ok(pid) = libc::pid_t::try_from(submitter.pid) else { + return; + }; + if identity(submitter.pid).as_ref() == Some(submitter) { + // The stat→kill race is accepted on Unix, where no portable handle pins the PID. + unsafe { libc::kill(pid, libc::SIGKILL) }; + } +} + +#[cfg(windows)] +fn with_process( + pid: u32, + access: u32, + f: impl FnOnce(*mut std::ffi::c_void) -> T, +) -> io::Result> { + use windows_sys::Win32::Foundation::CloseHandle; + use windows_sys::Win32::System::Threading::OpenProcess; + + // SAFETY: plain syscalls; the handle is closed before returning. + unsafe { + let process = OpenProcess(access, 0, pid); + if process.is_null() { + let error = io::Error::last_os_error(); + return if error.raw_os_error() == Some(87) { + Ok(None) + } else { + Err(error) + }; + } + let result = f(process); + CloseHandle(process); + Ok(Some(result)) + } +} + +#[cfg(windows)] +fn start_stamp(pid: u32) -> io::Result> { + use windows_sys::Win32::Foundation::{FILETIME, STILL_ACTIVE}; + use windows_sys::Win32::System::Threading::{ + GetExitCodeProcess, GetProcessTimes, PROCESS_QUERY_LIMITED_INFORMATION, + }; + + with_process(pid, PROCESS_QUERY_LIMITED_INFORMATION, |process| { + // SAFETY: `process` is a live handle and every out-pointer is a local. + unsafe { + let mut code = 0u32; + if GetExitCodeProcess(process, &mut code) == 0 { + return Err(io::Error::last_os_error()); + } + if code != STILL_ACTIVE as u32 { + return Ok(None); + } + let mut times: [FILETIME; 4] = std::mem::zeroed(); + let [created, exited, kernel, user] = &mut times; + if GetProcessTimes(process, created, exited, kernel, user) == 0 { + return Err(io::Error::last_os_error()); + } + Ok(Some( + u64::from(created.dwHighDateTime) << 32 | u64::from(created.dwLowDateTime), + )) + } + })? + .unwrap_or(Ok(None)) +} + +#[cfg(windows)] +fn kill(submitter: &SubmitterIdentity) { + use windows_sys::Win32::System::Threading::{ + TerminateProcess, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_TERMINATE, + }; + + // The handle pins the process, so the identity check and the kill name the same one. + let _ = with_process( + submitter.pid, + PROCESS_TERMINATE | PROCESS_QUERY_LIMITED_INFORMATION, + |process| { + if identity(submitter.pid).as_ref() == Some(submitter) { + // SAFETY: `process` is a live handle opened with PROCESS_TERMINATE. + unsafe { TerminateProcess(process, 1) }; + } + }, + ); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[cfg(unix)] + #[tokio::test] + async fn an_unreadable_identity_does_not_release_the_fence() { + let unreadable = SubmitterIdentity { + pid: u32::MAX, + starttime: 1, + }; + assert!(start_stamp(unreadable.pid).is_err()); + assert!(!ensure_gone(&unreadable).await); + } + + #[tokio::test] + async fn a_live_submitter_is_killed_and_a_reused_pid_is_not_mistaken_for_it() { + let mut child = if cfg!(windows) { + crate::process::command("ping") + .args(["-n", "60", "127.0.0.1"]) + .stdout(std::process::Stdio::null()) + .spawn() + .unwrap() + } else { + crate::process::command("sleep").arg("60").spawn().unwrap() + }; + let recorded = identity(child.id()).unwrap(); + let impostor = SubmitterIdentity { + starttime: recorded.starttime + 1, + ..recorded.clone() + }; + assert!(ensure_gone(&impostor).await); + assert_eq!(identity(child.id()), Some(recorded.clone())); + assert!(ensure_gone(&recorded).await); + assert!(child.wait().is_ok()); + assert!(identity(child.id()).is_none()); + } +} diff --git a/src/engine/reconcile.rs b/src/engine/reconcile.rs new file mode 100644 index 000000000..ca7d22ec8 --- /dev/null +++ b/src/engine/reconcile.rs @@ -0,0 +1,659 @@ +use std::mem::discriminant; +use std::time::Duration; + +use super::bus::RunEvent; +use super::{load, phase_of, CancelOutcome, Engine, Handle, Observation, Phase}; +use crate::error::Result; +use crate::store::{Contact, EngineRunState, StoredRun, ATTENTION, RECOVERED, TERMINAL}; + +const OUTAGE_ATTENTION: Duration = Duration::from_secs(10 * 60); + +pub(crate) const ABANDONED: &str = + "Abandoned; the cancel stays pending until the job is confirmed gone."; + +/// What one fact does to a run. The phase applies only if it moves forward. +#[derive(Debug, Default)] +pub(super) struct Change { + pub phase: Option, + /// Records the launched job; the only way out of Submitting other than a terminal phase. + pub handle: Option<(u32, Handle)>, + pub exit_code: Option, + pub finished_at: Option, + pub started_at: Option, + pub reason: Option, + pub cancel_unconfirmed: Option>>, + pub contact: Option, + /// Raise the outage's attention notice even though the contact did not change. + pub attention: bool, +} + +impl Change { + pub fn contact(contact: Contact) -> Self { + Self { + contact: Some(contact), + ..Self::default() + } + } + + pub fn terminal(phase: Phase, reason: Option) -> Self { + Self { + phase: Some(phase), + reason, + contact: Some(Contact::Live), + ..Self::default() + } + } +} + +/// A terminal run with non-Live contact keeps its kill pending. +pub(crate) fn is_tombstone(phase: Phase, contact: &Contact) -> bool { + phase.is_terminal() && *contact != Contact::Live +} + +fn observed(phase: Phase, contact: &Contact, observation: Observation, now: i64) -> Change { + use Observation::*; + + if let CancelReceipt { + finished_at, + code, + remaining, + note, + } = observation + { + if phase == Phase::Submitting || (phase.is_terminal() && !is_tombstone(phase, contact)) { + return Change::default(); + } + let contact = if remaining == 0 { + Contact::Live + } else { + Contact::Stopping { + since: now, + count: remaining, + } + }; + return Change { + phase: Some(Phase::Cancelled), + finished_at, + exit_code: code.map(i64::from), + reason: note.as_ref().map(|unreadable| { + if unreadable.is_empty() { + crate::plane::LABELS["run_notice_cancel_uncovered"].clone() + } else { + let pids = unreadable + .iter() + .map(u32::to_string) + .collect::>() + .join(", "); + crate::plane::LABELS["run_notice_cancel_unreadable"].replace("{pids}", &pids) + } + }), + cancel_unconfirmed: Some(note), + contact: Some(contact), + ..Change::default() + }; + } + if phase.is_terminal() { + if !is_tombstone(phase, contact) { + return Change::default(); + } + let finished_at = match &observation { + Exited { finished_at, .. } + | Cancelled { finished_at, .. } + | Failed { finished_at, .. } => *finished_at, + _ => None, + }; + let mut change = match observation { + Cancelled { .. } | Gone { .. } | NotFound => Change::contact(Contact::Live), + _ if phase == Phase::Cancelled => Change::default(), + Unreachable { cause } => Change::contact(Contact::Unreachable { since: now, cause }), + NeedsAuth { cause } => Change::contact(Contact::NeedsAuth { since: now, cause }), + Queued { .. } + | Running { .. } + | Exited { .. } + | Failed { .. } + | Lost { .. } + | Unreconciled { .. } => Change::contact(Contact::Unreconciled { + since: now, + detail: ABANDONED.into(), + }), + Notify { .. } | Log { .. } | Lingering { .. } | CancelReceipt { .. } => { + Change::default() + } + }; + change.finished_at = finished_at; + return change; + } + // Until it has a handle, a run moves only through the submission protocol. + if phase == Phase::Submitting { + return Change::default(); + } + let cancelled = matches!(observation, Cancelled { .. }); + let progressed = |to| Change { + phase: Some(to), + contact: Some(Contact::Live), + ..Change::default() + }; + match observation { + Queued { .. } => progressed(Phase::Starting), + Running { started_at } => Change { + started_at: Some(started_at.unwrap_or(now)), + ..progressed(Phase::Running) + }, + Exited { + code, + signal, + finished_at, + } + | Cancelled { + code, + signal, + finished_at, + } => Change { + finished_at, + exit_code: code.map(i64::from), + ..Change::terminal( + if cancelled { + Phase::Cancelled + } else if code == Some(0) && signal.is_none() { + Phase::Done + } else { + Phase::Failed + }, + signal.map(|signal| format!("Killed by signal {signal}.")), + ) + }, + Failed { + reason, + finished_at, + } => Change { + finished_at, + ..Change::terminal(Phase::Failed, Some(reason)) + }, + Lost { reason } | Gone { reason } => Change::terminal(Phase::Lost, Some(reason)), + Unreachable { cause } => Change::contact(Contact::Unreachable { since: now, cause }), + NeedsAuth { cause } => Change::contact(Contact::NeedsAuth { since: now, cause }), + Unreconciled { detail } => Change::contact(Contact::Unreconciled { since: now, detail }), + NotFound => Change::contact(Contact::Unreconciled { + since: now, + detail: "The backend reports no such job.".into(), + }), + Notify { .. } | Log { .. } | Lingering { .. } | CancelReceipt { .. } => Change::default(), + } +} + +/// A continuing outage keeps its start; its cause or detail follows the latest report. +fn merged(old: &Contact, new: Contact) -> Contact { + match (old, new) { + (Contact::Unreachable { since, .. }, Contact::Unreachable { cause, .. }) => { + Contact::Unreachable { + since: *since, + cause, + } + } + (Contact::NeedsAuth { since, .. }, Contact::NeedsAuth { cause, .. }) => { + Contact::NeedsAuth { + since: *since, + cause, + } + } + (Contact::Unreconciled { since, .. }, Contact::Unreconciled { detail, .. }) => { + Contact::Unreconciled { + since: *since, + detail, + } + } + (Contact::Stopping { since, .. }, Contact::Stopping { count, .. }) => Contact::Stopping { + since: *since, + count, + }, + (_, new) => new, + } +} + +fn attention_body(run_id: &str, contact: &Contact) -> String { + match contact { + Contact::Unreachable { since, cause } => format!( + "[orx] Run `{run_id}` has been unreachable since {} ({cause}). Its status is unchanged and orx keeps retrying.", + crate::telemetry::iso8601_utc(*since) + ), + Contact::NeedsAuth { cause, .. } => format!( + "[orx] Run `{run_id}` needs authentication ({cause}). Its status is unchanged." + ), + Contact::Unreconciled { detail, .. } => { + format!("[orx] Run `{run_id}` needs attention: {detail}") + } + Contact::Stopping { .. } | Contact::Live => unreachable!("terminal contact is not an outage"), + } +} + +impl Engine { + pub fn observe(&self, run_id: &str, observation: Observation) -> Result<()> { + if let Observation::Notify { len } = observation { + self.memory().notify.insert(run_id.into(), len); + self.bus.publish(RunEvent::Grew { + file: super::LogFile::Notify, + run_id: run_id.into(), + len, + }); + return Ok(()); + } + if let Observation::Log { len } = observation { + if self.memory().logs.insert(run_id.into(), len) != Some(len) { + self.bus.publish(RunEvent::Grew { + file: super::LogFile::Log, + run_id: run_id.into(), + len, + }); + } + return Ok(()); + } + if let Observation::Lingering { pids } = observation { + if !self.own(run_id)? { + return Ok(()); + } + if pids.is_empty() { + return self.commit(run_id, |phase, state| { + if is_tombstone(phase, &state.contact) { + Change::contact(Contact::Live) + } else { + Change::default() + } + }); + } + let body = format!("[orx] Run `{run_id}` finished with lingering processes {pids:?}. Cleanup can stop them."); + return self.attention(run_id, "lingering", &body); + } + if !self.own(run_id)? { + return Ok(()); + } + #[cfg(test)] + { + let hook = self.memory().before_observed_commit.take(); + if let Some(hook) = hook { + hook(); + } + } + let hosted = match super::handle_of(&load(&self.store(), run_id)?.0) { + Some(Handle::Api { .. }) => true, + Some(Handle::Legacy { descriptor }) => { + super::adapters::api::provider(&descriptor.kind).is_ok() + } + _ => false, + }; + let now = self.clock.wall_ms(); + // Decided under the store lock that cancel registration also takes. + self.commit(run_id, |phase, state| { + let verifying = self + .memory() + .verifying + .get(run_id) + .is_some_and(|cancel| cancel.strong_count() > 0); + if verifying && observation.ends_run() { + return Change::default(); + } + let observation = match observation { + Observation::Exited { + finished_at, + code, + signal, + } if hosted + && matches!(phase, Phase::Starting | Phase::Running) + && state.cancel_accepted_at.is_some() + && (code.is_some_and(|code| code != 0) || signal.is_some()) => + { + Observation::Cancelled { + finished_at, + code, + signal, + } + } + Observation::Gone { .. } if state.cancel_accepted_at.is_some() => { + Observation::Cancelled { + finished_at: None, + code: None, + signal: None, + } + } + observation => observation, + }; + if phase == Phase::Cancelled + && matches!( + observation, + Observation::Unreachable { .. } | Observation::NeedsAuth { .. } + ) + { + self.memory().cancels_sent.remove(run_id); + } + observed(phase, &state.contact, observation, now) + }) + } + + /// A live run whose adapter cannot be built is surfaced, never skipped. + pub fn unreconciled(&self, run_id: &str, error: &crate::error::Error) -> Result<()> { + if !self.own(run_id)? { + return Ok(()); + } + let since = self.clock.wall_ms(); + let detail = format!("{error:#}"); + self.commit(run_id, |phase, _| { + if phase.is_terminal() { + return Change::default(); + } + Change::contact(Contact::Unreconciled { since, detail }) + }) + } + + /// One attention notice per subscribed chat and `dedupe` key. + pub fn attention(&self, run_id: &str, dedupe: &str, body: &str) -> Result<()> { + let chats = { + let store = self.store(); + let tx = store.begin_immediate()?; + let mut chats = Vec::new(); + for chat in store.run_subscribers(run_id)? { + if store.insert_run_notice( + run_id, + &chat, + ATTENTION, + dedupe, + body, + self.clock.wall_ms(), + )? { + chats.push(chat); + } + } + tx.commit()?; + chats + }; + if !chats.is_empty() { + self.bus.publish(RunEvent::Notices { chats }); + } + Ok(()) + } + + pub(super) fn apply_cancel(&self, run: &StoredRun, outcome: CancelOutcome) -> Result<()> { + let now = self.clock.wall_ms(); + let legacy_note = super::legacy::cancel_note(run); + self.commit(&run.id, |phase, _| match outcome { + CancelOutcome::Verified if phase.is_terminal() => Change::contact(Contact::Live), + CancelOutcome::Verified => Change::terminal(Phase::Cancelled, legacy_note), + CancelOutcome::Survivors { count } => Change { + contact: Some(Contact::Stopping { since: now, count }), + ..Change::terminal(Phase::Cancelled, legacy_note) + }, + CancelOutcome::Undelivered { detail } => { + eprintln!("Cancel pending for {}: {detail}", run.id); + Change::default() + } + CancelOutcome::Pending => Change::default(), + }) + } + + /// Raises the attention notice for every outage that has lasted long enough. + pub fn check_outages(&self) -> Result<()> { + let now = self.clock.monotonic(); + let due: Vec = self + .memory() + .outages + .iter() + .filter(|(_, start)| now.saturating_sub(**start) >= OUTAGE_ATTENTION) + .map(|(run_id, _)| run_id.clone()) + .collect(); + for run_id in due { + self.commit(&run_id, |_, _| Change { + attention: true, + ..Change::default() + })?; + } + Ok(()) + } + + /// Writes a change and its notices in one transaction, then publishes it. + pub(super) fn commit( + &self, + run_id: &str, + decide: impl FnOnce(Phase, &EngineRunState) -> Change, + ) -> Result<()> { + let now = self.clock.wall_ms(); + let (phase, contact, cancelling, chats, changed) = { + let store = self.store(); + let tx = store.begin_immediate()?; + let (run, state) = load(&store, run_id)?; + let old_phase = phase_of(&run)?; + let change = decide(old_phase, &state); + + let recorded = match &change.handle { + Some((attempt, handle)) => store.record_run_handle(run_id, *attempt, handle)?, + None => false, + }; + let phase = if recorded && old_phase == Phase::Submitting { + Phase::Starting + } else { + change + .phase + .filter(|to| to.rank() > old_phase.rank()) + .filter(|to| old_phase != Phase::Submitting || to.is_terminal()) + .unwrap_or(old_phase) + }; + let moved = phase != old_phase; + if moved || (old_phase == Phase::Cancelled && is_tombstone(old_phase, &state.contact)) { + if change.cancel_unconfirmed.is_some() + || old_phase == Phase::Cancelled && change.contact == Some(Contact::Live) + { + let unconfirmed = change + .cancel_unconfirmed + .as_ref() + .and_then(Option::as_ref) + .map(serde_json::to_string) + .transpose()?; + tx.execute( + "UPDATE runs SET cancel_unconfirmed = ?2 WHERE id = ?1", + rusqlite::params![run_id, unconfirmed], + )?; + } + if let Some(reason) = &change.reason { + store.set_result_markdown(run_id, reason)?; + } + } + let ended_at = phase.is_terminal().then(|| { + change + .finished_at + .unwrap_or(now) + .min(now) + .max(run.created_at) + }); + if moved && !recorded { + let started_at = change + .started_at + .filter(|_| phase == Phase::Running && super::is_engine_row(&run)); + if phase.is_terminal() && super::handle_of(&run).is_some() { + store.queue_log_collection(run_id)?; + } + store.set_engine_phase( + run_id, + old_phase.as_str(), + phase.as_str(), + ended_at, + change.exit_code, + started_at, + )?; + } else if is_tombstone(old_phase, &state.contact) && change.finished_at.is_some() { + tx.execute( + "UPDATE runs SET ended_at = ?2, exit_code = COALESCE(?3, exit_code) WHERE id = ?1", + rusqlite::params![run_id, ended_at, change.exit_code], + )?; + } + + let settled = phase.is_terminal() && !moved && state.contact == Contact::Live; + let contact = match change.contact { + Some(new) if !settled => merged(&state.contact, new), + _ => state.contact.clone(), + }; + let contact_changed = contact != state.contact; + if contact_changed { + store.set_run_contact(run_id, &contact)?; + } + + let terminal_body = match moved && phase.is_terminal() { + true => Some(store.terminal_notice_body(&load(&store, run_id)?.0)?), + false => None, + }; + let mut chats = Vec::new(); + for chat in store.run_subscribers(run_id)? { + let notice = if let Some(body) = &terminal_body { + Some((TERMINAL, body.clone())) + } else if phase == Phase::Cancelled && contact_changed && contact == Contact::Live { + if store.queue_cancel_settled_notice(run_id, &chat, now)? { + chats.push(chat); + } + continue; + } else if phase.is_terminal() { + None + } else if contact == Contact::Live { + (contact_changed && store.settle_outage_notice(run_id, &chat)?).then(|| { + let status = phase.as_str(); + let body = + format!("[orx] Run `{run_id}` is reachable again; status {status}."); + (RECOVERED, body) + }) + } else { + let raise = change.attention + || (discriminant(&contact) != discriminant(&state.contact) + && !matches!(contact, Contact::Unreachable { .. })); + raise.then(|| { + let mut body = attention_body(run_id, &contact); + if matches!(contact, Contact::NeedsAuth { .. } | Contact::Unreachable { .. }) + && matches!(super::handle_of(&run), Some(Handle::Legacy { descriptor }) if descriptor.kind == "openresearch_job") + { + body.push(' '); + body.push_str(&crate::plane::LABELS["run_notice_rental_billing"]); + } + (ATTENTION, body) + }) + }; + let Some((kind, body)) = notice else { + continue; + }; + let dedupe = if kind == TERMINAL { + TERMINAL.to_string() + } else { + store.outage_dedupe(run_id, &chat, kind)? + }; + if store.insert_run_notice(run_id, &chat, kind, &dedupe, &body, now)? { + chats.push(chat); + } + } + tx.commit()?; + let cancelling = (run.cancel_requested || state.cancel_accepted_at.is_some()) + && !phase.is_terminal(); + ( + phase, + contact, + cancelling, + chats, + moved || contact_changed || recorded, + ) + }; + + { + let mut memory = self.memory(); + if matches!(contact, Contact::Unreachable { .. }) && !phase.is_terminal() { + let now = self.clock.monotonic(); + memory.outages.entry(run_id.into()).or_insert(now); + } else { + memory.outages.remove(run_id); + } + if matches!( + contact, + Contact::Unreachable { .. } | Contact::NeedsAuth { .. } + ) { + memory.cancels_sent.remove(run_id); + } + let tombstone = is_tombstone(phase, &contact); + if phase != Phase::Submitting && !tombstone { + memory.retries.remove(run_id); + } + if phase.is_terminal() && !tombstone { + memory.cancels_sent.remove(run_id); + memory.verifying.remove(run_id); + memory.locks.release(run_id); + } + } + if changed { + self.bus.publish(RunEvent::Changed { + run_id: run_id.into(), + phase, + contact, + cancelling, + }); + } + if !chats.is_empty() { + self.bus.publish(RunEvent::Notices { chats }); + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn contact_observations_never_move_the_phase() { + for phase in [Phase::Starting, Phase::Running] { + for observation in [ + Observation::Unreachable { + cause: "eof".into(), + }, + Observation::NeedsAuth { + cause: "denied".into(), + }, + Observation::Unreconciled { detail: "?".into() }, + Observation::NotFound, + Observation::Notify { len: 3 }, + ] { + assert_eq!(observed(phase, &Contact::Live, observation, 1).phase, None); + } + } + } + + #[test] + fn submitting_runs_ignore_observations_and_settled_runs_ignore_everything() { + for observation in [ + Observation::Running { started_at: None }, + Observation::Cancelled { + finished_at: None, + code: None, + signal: None, + }, + ] { + for phase in [Phase::Submitting, Phase::Done] { + let change = observed(phase, &Contact::Live, observation.clone(), 1); + assert!(change.phase.is_none() && change.contact.is_none()); + } + } + } + + #[test] + fn a_continuing_outage_keeps_its_start() { + let old = Contact::Unreachable { + since: 1, + cause: "eof".into(), + }; + let next = Contact::Unreachable { + since: 9, + cause: "timeout".into(), + }; + assert_eq!( + merged(&old, next), + Contact::Unreachable { + since: 1, + cause: "timeout".into() + } + ); + let auth = Contact::NeedsAuth { + since: 9, + cause: "denied".into(), + }; + assert_eq!(merged(&old, auth.clone()), auth); + } +} diff --git a/src/engine/runtime.rs b/src/engine/runtime.rs new file mode 100644 index 000000000..e717f92a9 --- /dev/null +++ b/src/engine/runtime.rs @@ -0,0 +1,2292 @@ +//! The engine as `orx up` runs it: one adapter per host or account, a loop observing each, +//! a 5 s supervision tick (0.2.x adoption, submission recovery, outage and notify notices), +//! final log collection, and the commands behind API v2. + +use std::collections::HashMap; +use std::io::{Seek, SeekFrom}; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex, MutexGuard, Weak}; +use std::time::Duration; + +use async_trait::async_trait; +use once_cell::sync::OnceCell; +use serde_json::{json, Value}; +use sha2::{Digest, Sha256}; +use tokio::sync::{watch, Notify}; + +use super::adapters::openresearch::LegacyTransport; +use super::adapters::{api, local::Local, openresearch, slurm::Slurm, ssh::Ssh}; +use super::clock::Clock; +use super::handle::ApiAccount; +use super::transport::{Auth, Config, HostConn, Prompt, Status}; +use super::{ + handle_of, is_engine_row, Backend, ByteRange, Engine, FileIdent, Handle, LogFile, LogPage, + Observation, Phase, WatchedRun, +}; +use crate::commands::up::api_v2::{Commands, KeptRange}; +use crate::error::{anyhow, bail, Result}; +use crate::jobs::ssh::SshTarget; +use crate::store::{LaunchSpec, Store, StoredRun, SubmittingRun}; +use orx_host_proto::LogInfo; + +const DEFAULT_ROOT: &str = "~/.orx/engine"; +/// Logs up to this size are kept whole; larger ones keep the head and the tail. +const KEEP_WHOLE: u64 = 1 << 30; +const KEEP_HEAD: u64 = 64 << 20; +const KEEP_TAIL: u64 = 256 << 20; +const COLLECTION_BUDGET: Duration = Duration::from_secs(120); +/// How long finishing runs' logs may hold up an adapter's observations so their notices can +/// quote them. +const EARLY_COLLECTION_BUDGET: Duration = Duration::from_secs(3); +const PREPARATION_BUDGET: Duration = Duration::from_secs(10 * 60); + +/// Engine run directories live beside, never inside, the 0.2.x `/runs`. +pub fn engine_root(remote_root: Option<&str>) -> String { + remote_root.map_or_else(|| DEFAULT_ROOT.into(), |root| format!("{root}/engine")) +} + +/// What one adapter instance serves. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +enum Key { + Ssh { + host: String, + root: String, + }, + Slurm { + host: String, + root: String, + }, + Local, + Api { + provider: String, + account: ApiAccount, + }, + OpenResearch, +} + +impl Key { + /// The adapter serving runs of `kind` on `target`: their host, namespace or address. + fn of_kind( + kind: &str, + target: Option, + root: String, + context: Option, + ) -> Result { + let required_target = || { + target + .clone() + .ok_or_else(|| anyhow!("The {kind} run has no target")) + }; + Ok(match kind { + "ssh_job" => Self::Ssh { + host: required_target()?, + root, + }, + "slurm_job" => Self::Slurm { + host: required_target()?, + root, + }, + "local_job" | "tinker_job" => Self::Local, + "openresearch_job" => Self::OpenResearch, + kind => { + api::provider(kind)?; + Self::Api { + provider: kind.into(), + account: ApiAccount { target, context }, + } + } + }) + } + + fn of_launch(launch: &LaunchSpec) -> Result { + let root = launch.options["root"].as_str().unwrap_or(DEFAULT_ROOT); + let context = launch.options["context"].as_str().map(str::to_owned); + Self::of_kind(&launch.kind, launch.target.clone(), root.into(), context) + } + + fn of_handle(handle: &Handle) -> Result { + Ok(match handle { + Handle::Ssh { host, root } => Self::Ssh { + host: host.clone(), + root: root.clone(), + }, + Handle::Slurm { host, root, .. } => Self::Slurm { + host: host.clone(), + root: root.clone(), + }, + Handle::Local { .. } | Handle::Tinker { .. } => Self::Local, + Handle::Api { + provider, account, .. + } => Self::Api { + provider: provider.clone(), + account: account.clone(), + }, + Handle::Legacy { descriptor } => Self::of_kind( + &descriptor.kind, + descriptor.namespace.clone(), + engine_root(descriptor.remote_root.as_deref()), + descriptor.context.clone(), + )?, + }) + } + + /// How long one `observe` may wait: host feeds long-poll, API accounts pace themselves. + fn budget(&self) -> Duration { + match self { + Self::Ssh { .. } | Self::Slurm { .. } => Duration::from_secs(25), + Self::Local => Duration::from_secs(1), + _ => Duration::from_secs(10), + } + } +} + +fn lock(mutex: &Mutex) -> MutexGuard<'_, T> { + mutex + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) +} + +type HostCell = Arc>; + +pub struct Runtime { + engine: Arc, + clock: Arc, + data_dir: PathBuf, + store: OnceCell>, + /// `ssh -F` for every configured host; tests point it at a hermetic sshd. + ssh_config: Option, + me: Weak, + conns: Mutex>, + auth: Mutex>>, + hosts: Mutex>>, + backends: Mutex>>, + boxes: Mutex>>, + watched: Mutex>>>, + changed: Notify, + collect_now: Notify, +} + +impl Runtime { + pub fn new( + engine: Arc, + clock: Arc, + data_dir: PathBuf, + ssh_config: Option, + ) -> Arc { + Arc::new_cyclic(|me| Self { + engine, + clock, + data_dir, + store: OnceCell::new(), + ssh_config, + me: me.clone(), + conns: Mutex::default(), + auth: Mutex::default(), + hosts: Mutex::default(), + backends: Mutex::default(), + boxes: Mutex::default(), + watched: Mutex::default(), + changed: Notify::new(), + collect_now: Notify::new(), + }) + } + + pub fn start(self: &Arc) { + tokio::spawn(self.clone().supervise()); + tokio::spawn(self.clone().collect_pending()); + } + + fn store(&self) -> Result> { + let store = self + .store + .get_or_try_init(|| Store::open_at(self.data_dir.clone()).map(Mutex::new))?; + Ok(lock(store)) + } + + fn conn(&self, alias: &str, root: &str, ssh_config: Option) -> Result { + let key = (alias.to_owned(), root.to_owned()); + let cell = lock(&self.conns).entry(key).or_default().clone(); + cell.get_or_try_init(|| { + let auth = { + let mut aliases = lock(&self.auth); + match aliases.entry(alias.into()) { + std::collections::hash_map::Entry::Occupied(entry) => entry.get().clone(), + std::collections::hash_map::Entry::Vacant(entry) => { + entry.insert(Auth::new(&*self.store()?, alias)?).clone() + } + } + }; + let conn = HostConn::start_shared( + Config { + alias: alias.into(), + root: root.into(), + ssh_config, + #[cfg(unix)] + control_dir: control_dir(&self.data_dir), + binary_dir: None, + #[cfg(unix)] + sharing_home: dirs::home_dir(), + askpass_executable: crate::paths::spawnable_exe()?, + }, + Store::open_at(self.data_dir.clone())?, + self.clock.clone(), + auth, + )?; + let mut state = conn.state(); + let engine = self.engine.clone(); + let me = self.me.clone(); + let alias = alias.to_owned(); + let root = root.to_owned(); + tokio::spawn(async move { + let mut live = false; + loop { + let snapshot = state.borrow_and_update().clone(); + let now = snapshot.status == Status::Live; + if now && !live { + if let Some(Err(error)) = + me.upgrade().map(|me| me.host_returned(&alias, &root)) + { + eprintln!("orx up: {alias}: log collection: {error:#}"); + } + } + live = now; + engine.bus.publish(super::bus::RunEvent::Host { + alias: alias.clone(), + root: root.clone(), + state: snapshot, + }); + if state.changed().await.is_err() { + break; + } + } + }); + Ok::<_, crate::error::Error>(conn) + }) + .cloned() + } + + /// Ssh and Slurm keep separate feeds over the one connection to a host. + fn ssh(&self, key: &Key) -> Result> { + let (Key::Ssh { host, root } | Key::Slurm { host, root }) = key else { + bail!("{key:?} is not an SSH host"); + }; + if let Some(ssh) = lock(&self.hosts).get(key) { + return Ok(ssh.clone()); + } + let conn = self.conn(host, root, self.ssh_config.clone())?; + let ssh = Arc::new(Ssh::new(host.clone(), root.clone(), conn)); + Ok(lock(&self.hosts).entry(key.clone()).or_insert(ssh).clone()) + } + + fn backend_for(&self, key: &Key) -> Result> { + if let Some(backend) = lock(&self.backends).get(key) { + return Ok(backend.clone()); + } + let clock = self.clock.clone(); + let spools = self.data_dir.join("run-logs"); + let backend: Arc = match key { + Key::Ssh { .. } => self.ssh(key)?, + Key::Slurm { .. } => Arc::new(Slurm::new(self.ssh(key)?, clock)), + Key::Local => Arc::new(Local::new(self.data_dir.join("local-runs"))), + Key::Api { provider, account } => { + (api::provider(provider)?.build)(account, clock, spools)? + } + Key::OpenResearch => { + let me = self.me.clone(); + Arc::new(openresearch::OpenResearch::new( + self.engine.clone(), + Arc::new(move |target: &SshTarget| { + me.upgrade() + .ok_or_else(|| anyhow!("The run engine stopped"))? + .box_transport(target) + }), + )) + } + }; + Ok(lock(&self.backends) + .entry(key.clone()) + .or_insert(backend) + .clone()) + } + + fn key(&self, run: &StoredRun) -> Result { + if let Some(handle) = handle_of(run) { + return Key::of_handle(&handle); + } + let launch = self + .store()? + .engine_run_state(&run.id)? + .and_then(|state| state.launch) + .ok_or_else(|| anyhow!("Run {} has neither a handle nor a launch intent", run.id))?; + Key::of_launch(&launch) + } + + /// An OpenResearch box is reached through a generated `ssh -F` file that layers its + /// endpoint over the user's own configuration. + fn box_transport(&self, target: &SshTarget) -> Result> { + let identity = + serde_json::to_vec(&(&target.dest, &target.extra_opts, &target.managed_generation))?; + let alias = format!("orx-box-{}", &hex(&Sha256::digest(identity))[..16]); + if let Some(transport) = lock(&self.boxes).get(&alias) { + return Ok(transport.clone()); + } + let (user, hostname) = target + .dest + .split_once('@') + .ok_or_else(|| anyhow!("Box endpoint {} has no user", target.dest))?; + let mut config = format!("Host {alias}\n HostName {hostname}\n User {user}\n"); + let mut options = target.extra_opts.iter(); + while let Some(flag) = options.next() { + let value = options + .next() + .ok_or_else(|| anyhow!("Box SSH option {flag} has no value"))?; + match flag.as_str() { + "-p" => config.push_str(&format!(" Port {value}\n")), + "-o" => { + let (name, value) = value + .split_once('=') + .ok_or_else(|| anyhow!("Unexpected box SSH option {value}"))?; + config.push_str(&format!(" {name} {value}\n")); + } + _ => bail!("Unexpected box SSH option {flag}"), + } + } + if dirs::home_dir().is_some_and(|home| home.join(".ssh/config").is_file()) { + config.push_str("Host *\n Include ~/.ssh/config\n"); + } + let directory = self.data_dir.join("engine-ssh"); + std::fs::create_dir_all(&directory)?; + let path = directory.join(format!("{alias}.config")); + crate::local::git::atomic_write_with_mode(&path, config.as_bytes(), Some(0o600))?; + let conn = self.conn(&alias, DEFAULT_ROOT, Some(path))?; + let ssh = Arc::new(Ssh::new(alias.clone(), DEFAULT_ROOT.into(), conn)); + let transport = Arc::new(LegacyTransport::new(ssh, self.data_dir.join("run-logs"))); + Ok(lock(&self.boxes).entry(alias).or_insert(transport).clone()) + } + + async fn supervise(self: Arc) { + let home = dirs::home_dir(); + let mut retired = home.is_none(); + let mut retire_after = tokio::time::Instant::now(); + loop { + if !retired && tokio::time::Instant::now() >= retire_after { + match self + .engine + .retire_ssh_config(home.as_deref().unwrap_or(Path::new("/"))) + { + Ok(done) => retired = done, + Err(error) => { + retire_after = tokio::time::Instant::now() + Duration::from_secs(300); + eprintln!( + "orx up: could not retire the 0.2.x SSH configuration: {error:#}" + ); + } + } + } + if let Err(error) = self.tick() { + eprintln!("orx up: run engine: {error:#}"); + } + tokio::select! { + _ = tokio::time::sleep(Duration::from_secs(5)) => {} + _ = self.changed.notified() => {} + } + } + } + + fn tick(self: &Arc) -> Result<()> { + self.engine + .scan_legacy(crate::config::run_engine_settings()?.0)?; + self.engine.check_outages()?; + let store = self.store()?; + // Deleted from the dashboard or the CLI alike. + let deleted = |run: &str| store.get_run(run).is_ok_and(|row| row.is_none()); + let backends: Vec<_> = lock(&self.backends).values().cloned().collect(); + for backend in backends { + backend.forget_logs(&deleted); + } + let runs = store.list_engine_runs()?; + drop(store); + let mut watch: HashMap> = HashMap::new(); + for run in runs { + // 0.2.x rows are touched only once adoption holds their locks. + if !is_engine_row(&run) && !self.engine.holds(&run.id) { + continue; + } + let key = match self.key(&run) { + Ok(key) => key, + Err(error) => { + self.engine.unreconciled(&run.id, &error)?; + continue; + } + }; + match handle_of(&run) { + Some(handle) => watch + .entry(key) + .or_default() + .push(WatchedRun { id: run.id, handle }), + None => { + let me = self.clone(); + tokio::spawn(async move { + let result = match me.backend_for(&key) { + Ok(backend) => me.engine.recover(backend.as_ref(), &run.id).await, + Err(error) => me.engine.unreconciled(&run.id, &error), + }; + if let Err(error) = result { + eprintln!("orx up: run {}: recovery: {error:#}", run.id); + } + }); + } + } + } + for run_id in self.engine.notify_due()? { + let row = self.store()?.get_run(&run_id)?; + let Some(key) = row.and_then(|run| self.key(&run).ok()) else { + continue; + }; + let me = self.clone(); + tokio::spawn(async move { + let result = match me.backend_for(&key) { + Ok(backend) => me + .engine + .deliver_notify(backend.as_ref(), &run_id) + .await + .map(|_| ()), + Err(error) => Err(error), + }; + if let Err(error) = result { + eprintln!("orx up: run {run_id}: notify: {error:#}"); + } + }); + } + + let mut senders = lock(&self.watched); + for (key, sender) in senders.iter() { + if !watch.contains_key(key) { + sender.send_if_modified(|runs| !std::mem::take(runs).is_empty()); + } + } + for (key, runs) in watch { + let ids = + |runs: &[WatchedRun]| runs.iter().map(|run| run.id.clone()).collect::>(); + match senders.get(&key) { + Some(sender) => { + sender.send_if_modified(|current| { + let modified = ids(current) != ids(&runs); + *current = runs; + modified + }); + } + None => { + let (sender, receiver) = watch::channel(runs); + tokio::spawn(self.clone().observe(key.clone(), receiver)); + senders.insert(key, sender); + } + } + } + + drop(senders); + self.engine.store().migrate_run_wakeups() + } + + /// One loop per adapter. A changed watch set interrupts a pending long poll. + async fn observe(self: Arc, key: Key, mut runs: watch::Receiver>) { + loop { + let watched = runs.borrow_and_update().clone(); + if watched.is_empty() { + if runs.changed().await.is_err() { + return; + } + continue; + } + let backend = match self.backend_for(&key) { + Ok(backend) => backend, + Err(error) => { + for run in &watched { + if let Err(error) = self.engine.unreconciled(&run.id, &error) { + eprintln!("orx up: run {}: {error:#}", run.id); + } + } + tokio::time::sleep(Duration::from_secs(30)).await; + continue; + } + }; + let started = tokio::time::Instant::now(); + let observations = tokio::select! { + observations = backend.observe(&watched, key.budget()) => observations, + changed = runs.changed() => { + if changed.is_err() { + return; + } + continue; + } + }; + let finished = observations + .iter() + .any(|(_, observation)| observation.ends_run()); + if finished { + let collecting = self.collect_logs(backend.as_ref(), &watched, &observations); + // Other runs' phases wait on this; what is left resumes in `collect_pending`. + let _ = tokio::time::timeout(EARLY_COLLECTION_BUDGET, collecting).await; + } + if let Err(error) = self + .engine + .apply_observations(backend.as_ref(), &watched, observations) + .await + { + eprintln!("orx up: {key:?}: {error:#}"); + } + if finished { + self.changed.notify_one(); + } + // Adapters that are not yet due answer at once; never spin on them. + tokio::time::sleep_until(started + Duration::from_secs(1)).await; + } + } + + /// Starts keeping the log of every run about to become terminal, so later reads need no + /// host. What the early budget leaves is finished by [`Self::collect_pending`]. + async fn collect_logs( + &self, + backend: &dyn Backend, + watched: &[WatchedRun], + observations: &[(String, Observation)], + ) { + for run in watched { + if !observations + .iter() + .any(|(id, observation)| *id == run.id && observation.ends_run()) + { + continue; + } + let terminal = self + .store() + .and_then(|store| store.get_run(&run.id)) + .ok() + .flatten() + .and_then(|row| Phase::parse(&row.status)) + .is_none_or(Phase::is_terminal); + if terminal { + continue; + } + if let Err(error) = self.collect(backend, run, COLLECTION_BUDGET).await { + eprintln!("orx up: run {}: log collection: {error:#}", run.id); + } + } + } + + /// Retries, across restarts, the logs of finished runs that could not be kept in time. + /// A starting engine retries them all at once. + async fn collect_pending(self: Arc) { + if let Err(error) = self + .store() + .and_then(|store| store.retry_log_collections_now(None)) + { + eprintln!("orx up: log collection: {error:#}"); + } + loop { + match self.store().and_then(|store| store.due_log_collections(10)) { + Ok(due) => { + let full = due.len() == 10; + for run_id in &due { + if let Err(error) = self.collect_finished(run_id).await { + eprintln!("orx up: run {run_id}: log collection: {error:#}"); + } + } + if full + && self + .store() + .and_then(|store| store.due_log_collections(10)) + .is_ok_and(|next| due.iter().any(|id| !next.contains(id))) + { + continue; + } + } + Err(error) => eprintln!("orx up: log collection: {error:#}"), + } + tokio::select! { + _ = tokio::time::sleep(Duration::from_secs(30)) => {} + _ = self.collect_now.notified() => {} + } + } + } + + async fn collect_finished(&self, run_id: &str) -> Result<()> { + let Some(run) = self.store()?.get_run(run_id)? else { + return Ok(()); + }; + let collected = async { + let Some(handle) = handle_of(&run) else { + return self.store()?.finish_log_collection(run_id); + }; + let run = WatchedRun { id: run.id, handle }; + let backend = self.backend_for(&Key::of_handle(&run.handle)?)?; + if !self.store()?.log_output_collected(run_id)? { + if !self + .collect(backend.as_ref(), &run, COLLECTION_BUDGET) + .await? + { + return Ok(()); + } + let (_, state) = self.engine.load(run_id)?; + if state.contact != crate::store::Contact::Live { + return Ok(()); + } + if !self.engine.deliver_notify(backend.as_ref(), run_id).await? { + bail!("Final notify collection is still pending"); + } + self.store()?.checkpoint_log_collection(run_id)?; + } + backend.finish(&run).await?; + { + let store = self.store()?; + let tx = store.begin_immediate()?; + store.finish_log_collection(run_id)?; + store.queue_finished_remote_cleanup(run_id)?; + tx.commit()?; + } + backend.unwatch(&run).await; + Ok(()) + } + .await; + if let Err(error) = &collected { + let error = format!("{error:#}"); + if self.store()?.defer_log_collection(run_id, &error)? { + let body = format!( + "[orx] Run `{run_id}`'s output collection could not finish ({error}). orx keeps retrying hourly, and at once when its host reconnects." + ); + self.engine.attention(run_id, "log-collection", &body)?; + } + } + self.engine + .bus + .publish(super::bus::RunEvent::LogCollection { + run_id: run_id.into(), + }); + collected + } + + fn host_returned(&self, alias: &str, root: &str) -> Result<()> { + let store = self.store()?; + for run_id in store.pending_log_collections()? { + let on_host = store + .get_run(&run_id)? + .and_then(|run| handle_of(&run)) + .and_then(|handle| Key::of_handle(&handle).ok()) + .is_some_and(|key| { + matches!(&key, Key::Ssh { host, root: r } | Key::Slurm { host, root: r } + if host == alias && r == root) + }); + if on_host { + store.retry_log_collections_now(Some(&run_id))?; + self.collect_now.notify_one(); + } + } + Ok(()) + } + + /// OpenResearch boxes keep their logs through the 0.2.x loop that drives them. + async fn collect( + &self, + backend: &dyn Backend, + run: &WatchedRun, + budget: Duration, + ) -> Result { + let mirrored = matches!(&run.handle, Handle::Legacy { descriptor } if descriptor.kind == "openresearch_job"); + if !mirrored { + let mut progressed = false; + let collected = async { + backend.drain_log(run).await?; + self.collect_log(backend, run, &mut progressed).await + }; + match tokio::time::timeout(budget, collected).await { + Ok(result) => result?, + Err(_) if progressed => return Ok(false), + Err(_) => bail!("timed out without keeping more log bytes"), + } + } + Ok(true) + } + + /// Keeps the log by the keep policy, up to the length the host reported when collection + /// started. A partial range resumes from the length its marker records as synced, when it + /// was started for this generation at this offset; every page checks the generation. + async fn collect_log( + &self, + backend: &dyn Backend, + run: &WatchedRun, + progressed: &mut bool, + ) -> Result<()> { + let Some(info) = Self::log_info(backend, run).await? else { + return Ok(()); + }; + let ident = info.ident; + let ranges = if info.len > KEEP_WHOLE { + vec![ + (0, KEEP_HEAD, "log"), + (info.len - KEEP_TAIL, info.len, "tail.log"), + ] + } else { + vec![(0, info.len, "log")] + }; + let last = ranges.len() - 1; + let directory = self.data_dir.join("run-logs"); + std::fs::create_dir_all(&directory)?; + let mut kept = Vec::new(); + for (index, (start, end, suffix)) in ranges.into_iter().enumerate() { + let path = directory.join(format!("{}.{suffix}", run.id)); + let part = directory.join(format!("{}.{suffix}.part", run.id)); + let marker = directory.join(format!("{}.{suffix}.part.json", run.id)); + let mut file = std::fs::OpenOptions::new() + .create(true) + .truncate(false) + .write(true) + .open(&part)?; + let recorded = std::fs::read(&marker) + .ok() + .and_then(|bytes| serde_json::from_slice::<(FileIdent, u64, u64)>(&bytes).ok()) + .filter(|(kept, at, synced)| { + *kept == ident && *at == start && *synced <= end - start + }); + let synced = recorded.map_or(0, |(_, _, synced)| synced); + let synced = synced.min(file.metadata()?.len()); + file.set_len(synced)?; + file.seek(SeekFrom::Start(synced))?; + let mut cursor = start + synced; + let mut eof; + loop { + let range = ByteRange { + start: cursor, + end: end.min(cursor + orx_host_proto::MAX_PAGE_LEN), + }; + match backend + .read_log(run, LogFile::Log, range, Some(&ident)) + .await? + { + LogPage::Data { + start: at, + bytes, + eof: at_end, + .. + } if at == cursor => { + if !bytes.is_empty() { + std::io::Write::write_all(&mut file, &bytes)?; + file.sync_data()?; + cursor += bytes.len() as u64; + let progress = serde_json::to_vec(&(&ident, start, cursor - start))?; + crate::local::git::atomic_write_with_mode( + &marker, + &progress, + Some(0o600), + )?; + *progressed = true; + } + eof = at_end; + } + page => bail!("The log changed during collection: {page:?}"), + } + if cursor >= end || eof { + break; + } + } + if cursor < end { + bail!("The log ended at byte {cursor} of {end}"); + } + drop(file); + std::fs::rename(&part, &path)?; + match std::fs::remove_file(&marker) { + Err(error) if error.kind() != std::io::ErrorKind::NotFound => { + return Err(error.into()) + } + _ => {} + } + kept.push(KeptRange { + offset: start, + len: cursor - start, + file: path, + ident: ident.clone(), + eof: index == last && eof, + }); + } + crate::commands::up::api_v2::keep_ranges(&self.data_dir, &run.id, kept) + } + + async fn log_info(backend: &dyn Backend, run: &WatchedRun) -> Result> { + let probe = ByteRange { + start: u64::MAX - 1, + end: u64::MAX, + }; + match backend.read_log(run, LogFile::Log, probe, None).await? { + LogPage::Reset { info } => Ok(info), + LogPage::Data { .. } => bail!("The host answered a length probe with data"), + } + } + + /// The connection a host's runs use: SSH and Slurm keep their own engine roots. + fn host_key(host: &str, slurm: bool) -> Result { + Ok(if slurm { + let settings = crate::jobs::slurm::load_settings()?.unwrap_or_default(); + Key::Slurm { + host: host.into(), + root: engine_root(settings.remote_root.as_deref()), + } + } else { + let saved = crate::config::ssh_settings()?.hosts.remove(host); + Key::Ssh { + host: host.into(), + root: engine_root(saved.and_then(|saved| saved.remote_root).as_deref()), + } + }) + } + + fn target(&self, key: &Key) -> Result { + let ssh = self.ssh(key)?; + let mut target = SshTarget::alias(&ssh.host); + target.transport = Some(Arc::new(LegacyTransport::new( + ssh, + self.data_dir.join("run-logs"), + ))); + Ok(target) + } +} + +#[async_trait] +impl Commands for Runtime { + async fn run(&self, args: crate::ExpRunArgs, admission: Box) -> Result { + let chat_session = args.launching_chat_session(); + let (durable, inserted) = tokio::sync::oneshot::channel::<()>(); + let submitted = crate::compute::submit(&args, |mut submission| async move { + // A saved container is resolved over the engine's own connection, so first + // contact follows the engine's authentication rules. + if submission.launch.kind == "ssh_job" { + let mut options: super::adapters::ssh::LaunchOptions = + serde_json::from_value(submission.launch.options.clone())?; + if let Some(reference) = options.container_reference.take() { + let target = self.target(&Key::of_launch(&submission.launch)?)?; + let container = + crate::jobs::ssh::resolve_container(&target, &reference).await?; + options.container = Some(container.for_run(&submission.run_id)); + submission.launch.options = serde_json::to_value(options)?; + } + } + let backend = self.backend_for(&Key::of_launch(&submission.launch)?)?; + let mut metadata = crate::jobs::BackendDescriptor::parse(r#"{"kind":"engine"}"#)?; + submission.source.apply_to_descriptor(&mut metadata); + let digest = hex(&Sha256::digest( + serde_json::to_vec(&json!([ + submission.launch, + submission.command, + submission.source.digest, + ]))? + .as_slice(), + )); + self.engine.insert(SubmittingRun { + id: &submission.run_id, + experiment_id: &submission.experiment.id, + project_id: &submission.experiment.project_id, + metadata: &metadata, + command: &submission.command, + created_at: crate::store::now_ms(), + commit_sha: Some(&submission.source.revision), + chat_session_id: chat_session.as_deref(), + spec_digest: &digest, + launch: &submission.launch, + })?; + drop(admission); + let _ = durable.send(()); + self.engine + .launch_inserted(backend.as_ref(), &submission.run_id) + .await + }); + // Only preparation is bounded; once the run is durable, recovery owns its launch. + let unprepared = async { + if tokio::time::timeout(PREPARATION_BUDGET, inserted) + .await + .is_ok() + { + std::future::pending::<()>().await; + } + }; + let run_id = tokio::select! { + run_id = submitted => run_id?, + () = unprepared => bail!( + "Preparing the run took over {} minutes; check the compute backend and retry.", + PREPARATION_BUDGET.as_secs() / 60 + ), + }; + self.changed.notify_one(); + Ok(run_id) + } + + fn backend(&self, run: &StoredRun) -> Result> { + self.backend_for(&self.key(run)?) + } + + /// Accepts a cancel for a run the engine owns, or records it for the 0.2.x supervisor + /// that does. + async fn cancel(&self, run: &StoredRun, reason: &str) -> Result<()> { + if !is_engine_row(run) + && !self.engine.holds(&run.id) + && !crate::local::is_terminal(&run.status) + { + return crate::commands::exp::request_legacy_run_cancel( + &*self.store()?, + &run.id, + reason, + ); + } + let backend = self.backend_for(&self.key(run)?)?; + self.engine + .cancel(backend.as_ref(), &run.id, reason) + .await?; + Ok(()) + } + + async fn cleanup(&self, run: &WatchedRun) -> Result { + if matches!(run.handle, Handle::Local { .. } | Handle::Tinker { .. }) { + return Ok(serde_json::to_value( + Local::new(self.data_dir.join("local-runs")).cleanup(run)?, + )?); + } + let key = Key::of_handle(&run.handle)?; + let ssh = self.ssh(&key)?; + Ok(serde_json::to_value(ssh.cleanup(run).await?)?) + } + + async fn compute(&self, action: &str, args: Value, prompt: Option) -> Result { + let backend = args["backend"].as_str().unwrap_or_default(); + let host = args["host"].as_str().map(str::to_owned); + if action == "connect" && matches!(backend, "ssh" | "slurm") { + let slurm = backend == "slurm"; + let host = match &host { + Some(host) => host.clone(), + None if slurm => crate::jobs::slurm::load_settings()? + .unwrap_or_default() + .host + .ok_or_else(|| anyhow!("Pass --host or configure a default host."))?, + None => crate::config::ssh_settings()? + .default_host + .ok_or_else(|| anyhow!("Pass --host or configure a default host."))?, + }; + let supervised = crate::compute::supervised_ssh_needed( + crate::config::run_engine_settings()?.0, + &self.store()?.list_active_runs()?, + &host, + ); + let target = SshTarget::alias(&host); + #[cfg(unix)] + if supervised && prompt.is_some() { + drop(crate::jobs::ssh::prepare_interactive_connection(&target, None, None).await?); + } + self.ssh(&Self::host_key(&host, slurm)?)?; + let connections: Vec<_> = lock(&self.conns) + .iter() + .filter(|((alias, _), _)| alias == &host) + .filter_map(|(_, cell)| cell.get().cloned()) + .collect(); + let mut worst: Option<(u8, anyhow::Error)> = None; + for conn in connections { + let result = match &prompt { + Some(prompt) => conn.connect_interactive(prompt.clone(), supervised).await, + None => conn.retry().await, + }; + if let Err(error) = result { + let severity = conn.state().borrow().status.severity(); + if worst.as_ref().is_none_or(|(worst, _)| severity > *worst) { + worst = Some((severity, error)); + } + } + } + if let Err(error) = crate::jobs::ssh::service::reset_existing_backoff(&target).await { + eprintln!("Host {host}: could not reset supervisor SSH backoff: {error:#}"); + } + let connected = worst.map_or(Ok(()), |(_, error)| Err(error)); + #[cfg(windows)] + let connected = if supervised { + connect_supervised(connected, prompt.as_ref(), |operation| { + crate::jobs::ssh::service::request(&target, operation) + }) + .await + } else { + connected + }; + connected?; + } + crate::commands::up::compute_settings::check( + backend, + host, + args["container"].as_str().map(str::to_owned), + args["noContainer"] == true, + args["address"].as_str().map(str::to_owned), + ) + .await + } + + fn host_states(&self, alias: &str) -> Vec<(String, super::transport::HostState)> { + let mut states: Vec<_> = lock(&self.conns) + .iter() + .filter(|((host, _), _)| host == alias) + .filter_map(|((_, root), cell)| { + cell.get() + .map(|conn| (root.clone(), conn.state().borrow().clone())) + }) + .collect(); + states.sort_by(|a, b| a.0.cmp(&b.0)); + states + } + + async fn retry_host(&self, alias: &str) { + let connections: Vec<_> = lock(&self.conns) + .iter() + .filter(|((host, _), _)| host == alias) + .filter_map(|(_, cell)| cell.get().cloned()) + .collect(); + futures::future::join_all(connections.iter().map(|conn| conn.retry_key())).await; + } + + fn host_target(&self, host: &str, slurm: bool) -> Result { + self.target(&Self::host_key(host, slurm)?) + } + + fn follow_log(&self, run: &str) -> Result> { + let row = self + .store()? + .get_run(run)? + .ok_or_else(|| anyhow!("Run {run} not found"))?; + let key = self.key(&row)?; + Ok(match key { + Key::Ssh { .. } | Key::Slurm { .. } => Box::new(self.ssh(&key)?.follow_logs(run)), + _ => Box::new(()), + }) + } +} + +#[cfg(any(windows, test))] +async fn connect_supervised( + connected: Result<()>, + prompt: Option<&Prompt>, + mut request: F, +) -> Result<()> +where + F: FnMut(Value) -> Fut, + Fut: std::future::Future>, +{ + let login = async { + if request(json!({"op": "status"})).await?["connected"] == true { + return Ok(()); + } + let prompt = prompt.ok_or_else(|| { + anyhow!("SSH disconnected. Use Connect to authenticate; background login is disabled.") + })?; + let start = request(json!({"op": "connect_start"})).await?; + let attempt = start["attempt"].as_str().ok_or_else(|| { + anyhow!("SSH Connect returned no authentication attempt. Retry Connect.") + })?; + let result = async { + loop { + let status = request(json!({"op": "connect_status", "attempt": attempt})).await?; + if status["done"] == true { + if let Some(error) = status["error"].as_str() { + bail!("{error}"); + } + return Ok(()); + } + if let Some(question) = status["prompt"].as_str() { + let answer = prompt(question.to_owned()) + .await? + .ok_or_else(|| anyhow!("SSH authentication cancelled."))?; + request(json!({"op": "connect_answer", "attempt": attempt, "answer": answer})) + .await?; + } + tokio::time::sleep(Duration::from_millis(150)).await; + } + } + .await; + let _ = request(json!({"op": "connect_cancel", "attempt": attempt})).await; + result + } + .await; + connected.and(login) +} + +pub(crate) fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|byte| format!("{byte:02x}")).collect() +} + +/// Master sockets need a short path; `/tmp` keeps them under the Unix socket limit. +#[cfg(unix)] +fn control_dir(data_dir: &Path) -> PathBuf { + let uid = unsafe { libc::geteuid() }; + let digest = hex(&Sha256::digest(data_dir.as_os_str().as_encoded_bytes())); + PathBuf::from("/tmp").join(format!("orx-cm-{uid}-{}", &digest[..8])) +} + +#[cfg(all(test, unix))] +pub(crate) mod chaos; + +#[cfg(test)] +mod tests { + use super::*; + use crate::engine::clock::TestClock; + + #[tokio::test] + async fn supervisor_connect_skips_a_live_service_and_relays_each_authentication_prompt() { + use std::collections::VecDeque; + let mut calls = Vec::new(); + connect_supervised(Ok(()), None, |request| { + calls.push(request); + std::future::ready(Ok(json!({"connected": true}))) + }) + .await + .unwrap(); + assert_eq!(calls, [json!({"op": "status"})]); + + let prompt: Prompt = + Arc::new(|question| Box::pin(async move { Ok(Some(format!("answer: {question}"))) })); + let mut replies = VecDeque::from([ + json!({"connected": false}), + json!({"attempt": "login"}), + json!({"prompt": "Password"}), + json!({}), + json!({"prompt": "MFA code"}), + json!({}), + json!({"done": true}), + json!({}), + ]); + calls.clear(); + connect_supervised(Ok(()), Some(&prompt), |request| { + calls.push(request); + std::future::ready(Ok(replies.pop_front().unwrap())) + }) + .await + .unwrap(); + assert!(replies.is_empty()); + assert_eq!( + calls + .iter() + .map(|call| call["op"].as_str().unwrap()) + .collect::>(), + [ + "status", + "connect_start", + "connect_status", + "connect_answer", + "connect_status", + "connect_answer", + "connect_status", + "connect_cancel", + ] + ); + assert_eq!(calls[3]["answer"], "answer: Password"); + assert_eq!(calls[5]["answer"], "answer: MFA code"); + assert!(calls[2..].iter().all(|call| call["attempt"] == "login")); + } + + #[tokio::test] + async fn supervisor_connect_attempts_login_after_the_engine_fails() { + let prompt: Prompt = Arc::new(|_| Box::pin(async { Ok(Some("answer".into())) })); + let mut replies = std::collections::VecDeque::from([ + json!({"connected": false}), + json!({"attempt": "login"}), + json!({"done": true}), + json!({}), + ]); + let mut calls = Vec::new(); + let error = + connect_supervised(Err(anyhow!("Unsupported host")), Some(&prompt), |request| { + calls.push(request); + std::future::ready(Ok(replies.pop_front().unwrap())) + }) + .await + .unwrap_err(); + assert_eq!(error.to_string(), "Unsupported host"); + assert!(calls.iter().any(|call| call["op"] == "connect_start")); + assert!(replies.is_empty()); + } + + #[tokio::test] + async fn supervisor_connect_cancels_the_attempt_after_errors_or_cancelled_prompts() { + let prompt: Prompt = Arc::new(|_| Box::pin(async { Ok(None) })); + for status in [ + Ok(json!({"done": true, "error": "Login rejected"})), + Ok(json!({"prompt": "Password"})), + Err(anyhow!("Service unavailable")), + ] { + let mut replies = std::collections::VecDeque::from([ + Ok(json!({"connected": false})), + Ok(json!({"attempt": "login"})), + status, + Ok(json!({})), + ]); + let mut calls = Vec::new(); + assert!(connect_supervised(Ok(()), Some(&prompt), |request| { + calls.push(request); + std::future::ready(replies.pop_front().unwrap()) + }) + .await + .is_err()); + assert_eq!( + calls.last().unwrap(), + &json!({"op": "connect_cancel", "attempt": "login"}) + ); + assert!(replies.is_empty()); + } + } + + use crate::engine::fake::{FakeBackend, HostFile}; + + /// A host log that counts the bytes collection pages from it and, when `grows`, grows + /// before answering each page. + #[derive(Default)] + struct Host { + log: FakeBackend, + paged: std::sync::atomic::AtomicU64, + grows: std::sync::atomic::AtomicBool, + destroyed: std::sync::atomic::AtomicBool, + fail_finish: std::sync::atomic::AtomicBool, + stall_after: Option, + } + + #[async_trait] + impl Backend for Host { + async fn launch( + &self, + _: &super::super::RunIntent, + _: &super::super::Fence<'_>, + ) -> std::result::Result { + unreachable!() + } + async fn recover(&self, _: &super::super::RunIntent) -> super::super::Recovery { + unreachable!() + } + async fn observe(&self, _: &[WatchedRun], _: Duration) -> Vec<(String, Observation)> { + unreachable!() + } + async fn cancel(&self, _: &WatchedRun) -> super::super::CancelOutcome { + unreachable!() + } + async fn finish(&self, _: &WatchedRun) -> Result<()> { + use std::sync::atomic::Ordering; + self.destroyed.store(true, Ordering::SeqCst); + if self.fail_finish.load(Ordering::SeqCst) { + bail!("provider destroyed the sandbox but its response was lost"); + } + Ok(()) + } + async fn read_log( + &self, + run: &WatchedRun, + file: LogFile, + range: ByteRange, + ident: Option<&FileIdent>, + ) -> Result { + use std::sync::atomic::Ordering; + if self.destroyed.load(Ordering::SeqCst) { + bail!("sandbox was destroyed"); + } + let probe = range.start == u64::MAX - 1; + if !probe + && self + .stall_after + .is_some_and(|limit| self.paged.load(Ordering::SeqCst) >= limit) + { + std::future::pending::<()>().await; + } + if !probe && self.grows.load(Ordering::SeqCst) { + let mut log = self.log.log.lock().unwrap(); + log.bytes.extend_from_slice(b"more\n"); + } + let page = self.log.read_log(run, file, range, ident).await?; + if let LogPage::Data { bytes, .. } = &page { + self.paged.fetch_add(bytes.len() as u64, Ordering::SeqCst); + } + Ok(page) + } + } + + fn collector(dir: &Path) -> Arc { + let clock = Arc::new(TestClock::new()); + let engine = Arc::new(Engine::new( + Store::open_at(dir.to_owned()).unwrap(), + clock.clone(), + )); + Runtime::new(engine, clock, dir.to_owned(), None) + } + + #[tokio::test] + async fn legacy_wakeups_accepted_while_running_are_imported_once() { + let dir = std::env::temp_dir().join(format!("orx-live-wakeups-{}", uuid::Uuid::new_v4())); + let runtime = collector(&dir); + runtime.tick().unwrap(); + let store = Store::open_at(dir.clone()).unwrap(); + let legacy = rusqlite::Connection::open(dir.join("orx.db")).unwrap(); + legacy + .execute_batch( + "INSERT INTO runs + (id, experiment_id, project_id, status, backend_json, created_at, updated_at) + VALUES ('legacy', 'exp', 'project', 'done', '{\"kind\":\"ssh_job\",\"jobId\":\"old\"}', 1, 2);", + ) + .unwrap(); + store.register_run_wakeup("legacy", "chat").unwrap(); + runtime.tick().unwrap(); + let notices = store.run_notice_batch("chat").unwrap(); + assert_eq!(notices.len(), 1); + assert_eq!(notices[0].run_id, "legacy"); + assert_eq!(notices[0].kind, crate::store::TERMINAL); + runtime.tick().unwrap(); + assert_eq!(store.run_notice_batch("chat").unwrap(), notices); + drop(legacy); + drop(store); + drop(runtime); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[cfg(unix)] + #[tokio::test(start_paused = true)] + async fn ssh_retirement_failures_wait_five_minutes_before_retrying() { + const CHILD: &str = "ORX_TEST_RETIREMENT_BACKOFF"; + if std::env::var_os(CHILD).is_none() { + let server = orx_test_support::Sshd::start().unwrap(); + let output = crate::process::command(std::env::current_exe().unwrap()) + .args([ + "--exact", + "engine::runtime::tests::ssh_retirement_failures_wait_five_minutes_before_retrying", + "--nocapture", + ]) + .env(CHILD, "1") + .env("HOME", server.home()) + .env("ORX_DATA_DIR", server.directory().join("store")) + .env("ORX_NO_TELEMETRY", "1") + .output() + .unwrap(); + assert!( + output.status.success(), + "{}\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!( + String::from_utf8_lossy(&output.stderr) + .matches("could not retire the 0.2.x SSH configuration") + .count(), + 2 + ); + return; + } + let home = dirs::home_dir().unwrap(); + let ssh = home.join(".ssh"); + std::fs::create_dir_all(&ssh).unwrap(); + let registry = ssh.join("openresearch_connections.json"); + std::fs::write(®istry, b"malformed").unwrap(); + let marker = ssh.join(".orx-config.lock"); + let runtime = collector(&crate::store::data_dir()); + let supervisor = tokio::spawn(runtime.clone().supervise()); + tokio::task::yield_now().await; + assert!(marker.exists()); + std::fs::remove_file(&marker).unwrap(); + for _ in 0..3 { + runtime.changed.notify_one(); + tokio::task::yield_now().await; + assert!(!marker.exists()); + } + for attempt in 0..2 { + tokio::time::advance(Duration::from_secs(299)).await; + runtime.changed.notify_one(); + tokio::task::yield_now().await; + assert!(!marker.exists()); + if attempt == 1 { + std::fs::write(®istry, b"{}").unwrap(); + } + tokio::time::advance(Duration::from_secs(1)).await; + runtime.changed.notify_one(); + tokio::task::yield_now().await; + assert!(marker.exists()); + std::fs::remove_file(&marker).unwrap(); + } + tokio::time::advance(Duration::from_secs(600)).await; + runtime.changed.notify_one(); + tokio::task::yield_now().await; + assert!(!marker.exists()); + supervisor.abort(); + } + + fn local_run() -> WatchedRun { + WatchedRun { + id: "run".into(), + handle: Handle::Local { + dir: "/fake".into(), + }, + } + } + + fn kept_ranges(dir: &Path) -> Vec { + serde_json::from_slice(&std::fs::read(dir.join("run-logs/run.ranges.json")).unwrap()) + .unwrap() + } + + #[tokio::test] + async fn collection_budget_yields_only_after_durable_progress() { + for stall_after in [0, 1] { + let dir = std::env::temp_dir() + .join(format!("orx-collection-budget-{}", uuid::Uuid::new_v4())); + let runtime = collector(&dir); + let host = Host { + stall_after: Some(stall_after), + ..Host::default() + }; + host.log.log.lock().unwrap().bytes = + vec![b'x'; 2 * orx_host_proto::MAX_PAGE_LEN as usize]; + runtime + .store() + .unwrap() + .queue_log_collection("run") + .unwrap(); + let result = runtime + .collect(&host, &local_run(), Duration::from_millis(100)) + .await; + if stall_after > 0 { + assert!(!result.unwrap()); + } else { + assert!(result.is_err()); + } + assert_eq!( + runtime.store().unwrap().log_collection("run").unwrap(), + Some((false, None)) + ); + assert!(!dir.join("run-logs/run.ranges.json").exists()); + if stall_after > 0 { + let marker: (FileIdent, u64, u64) = serde_json::from_slice( + &std::fs::read(dir.join("run-logs/run.log.part.json")).unwrap(), + ) + .unwrap(); + assert!(marker.2 > 0); + let resumed = Host::default(); + resumed.log.log.lock().unwrap().bytes = host.log.log.lock().unwrap().bytes.clone(); + assert!(runtime + .collect(&resumed, &local_run(), Duration::from_secs(1)) + .await + .unwrap()); + assert_eq!( + resumed.paged.load(std::sync::atomic::Ordering::SeqCst), + orx_host_proto::MAX_PAGE_LEN + ); + assert!(runtime + .store() + .unwrap() + .log_collection_pending("run") + .unwrap()); + assert_eq!( + std::fs::metadata(dir.join("run-logs/run.log")) + .unwrap() + .len(), + 2 * orx_host_proto::MAX_PAGE_LEN + ); + } + drop(runtime); + std::fs::remove_dir_all(dir).unwrap(); + } + } + + #[test] + fn runtime_reuses_its_store_without_reopening_migrations() { + let dir = + std::env::temp_dir().join(format!("orx-collection-budget-{}", uuid::Uuid::new_v4())); + let runtime = collector(&dir); + drop(runtime.store().unwrap()); + let db = rusqlite::Connection::open(dir.join("orx.db")).unwrap(); + db.execute_batch( + "CREATE TRIGGER fail_ui_insert BEFORE INSERT ON ui_state + BEGIN SELECT RAISE(FAIL, 'store reopened'); END;", + ) + .unwrap(); + assert!(Store::open_at(dir.clone()).is_err()); + assert!(runtime + .store() + .unwrap() + .list_engine_runs() + .unwrap() + .is_empty()); + drop(db); + drop(runtime); + std::fs::remove_dir_all(dir).unwrap(); + } + + /// A partial range resumes from the length its marker records as synced, so only the + /// rest is paged from the host again. + #[tokio::test] + async fn a_partial_range_resumes_from_its_synced_length() { + use std::sync::atomic::Ordering; + let dir = std::env::temp_dir().join(format!("orx-collect-{}", uuid::Uuid::new_v4())); + let runtime = collector(&dir); + let host = Host::default(); + let log: Vec = (0..3 * 4096).map(|i| (i % 251) as u8).collect(); + host.log.log.lock().unwrap().bytes = log.clone(); + let run = local_run(); + let info = Runtime::log_info(&host, &run).await.unwrap().unwrap(); + let logs = dir.join("run-logs"); + std::fs::create_dir_all(&logs).unwrap(); + // Bytes past the synced length may not have reached the disk. + let mut partial = log[..9000].to_vec(); + partial[8500] ^= 1; + std::fs::write(logs.join("run.log.part"), &partial).unwrap(); + std::fs::write( + logs.join("run.log.part.json"), + serde_json::to_vec(&(&info.ident, 0u64, 8192u64)).unwrap(), + ) + .unwrap(); + runtime.collect_log(&host, &run, &mut false).await.unwrap(); + assert_eq!(std::fs::read(logs.join("run.log")).unwrap(), log); + assert_eq!(host.paged.load(Ordering::SeqCst), 4096); + drop(runtime); + std::fs::remove_dir_all(dir).unwrap(); + } + + /// A log is kept to the length it had when collection started; growth since then leaves + /// it short of the end, so readers ask the host for the rest. + #[tokio::test] + async fn a_log_growing_during_collection_is_kept_to_its_starting_length() { + use std::sync::atomic::Ordering; + let dir = std::env::temp_dir().join(format!("orx-collect-{}", uuid::Uuid::new_v4())); + let runtime = collector(&dir); + let host = Host::default(); + host.log.log.lock().unwrap().bytes = b"start\n".to_vec(); + host.grows.store(true, Ordering::SeqCst); + runtime + .collect_log(&host, &local_run(), &mut false) + .await + .unwrap(); + let kept = std::fs::read(dir.join("run-logs/run.log")).unwrap(); + assert_eq!(kept, b"start\n"); + let range = &kept_ranges(&dir)[0]; + assert_eq!((range.len, range.eof), (6, false)); + + host.grows.store(false, Ordering::SeqCst); + runtime + .collect_log(&host, &local_run(), &mut false) + .await + .unwrap(); + let range = &kept_ranges(&dir)[0]; + assert_eq!((range.len, range.eof), (11, true)); + drop(runtime); + std::fs::remove_dir_all(dir).unwrap(); + } + + /// Once a log is kept, what the adapter held for reading it goes; runs deleted by any path + /// are forgotten on the next tick. + #[tokio::test] + async fn kept_and_deleted_runs_release_their_logs() { + let dir = std::env::temp_dir().join(format!("orx-collect-{}", uuid::Uuid::new_v4())); + let clock = Arc::new(TestClock::new()); + let store = Store::open_at(dir.clone()).unwrap(); + let run = StoredRun { + id: "kept".into(), + experiment_id: "exp".into(), + project_id: "project".into(), + status: "done".into(), + backend_json: + r#"{"kind":"engine","jobId":"/fake","handle":{"type":"Local","dir":"/fake"}}"# + .into(), + command: "train".into(), + created_at: 1, + updated_at: 1, + ended_at: Some(1), + exit_code: Some(0), + commit_sha: None, + result_markdown: None, + cancel_requested: false, + cancel_reason: None, + chat_session_id: None, + }; + store.upsert_run(&run).unwrap(); + let engine = Arc::new(Engine::new(store, clock.clone())); + let runtime = Runtime::new(engine, clock, dir.clone(), None); + let backend = Arc::new(FakeBackend::default()); + backend.log.lock().unwrap().bytes = b"output\n".to_vec(); + *backend.held.lock().unwrap() = vec!["kept".into(), "deleted".into()]; + lock(&runtime.backends).insert(Key::Local, backend.clone()); + + runtime + .store() + .unwrap() + .queue_log_collection("kept") + .unwrap(); + runtime + .store() + .unwrap() + .set_run_contact( + "kept", + &crate::store::Contact::Unreconciled { + since: 1, + detail: "kill pending".into(), + }, + ) + .unwrap(); + for _ in 0..10 { + runtime.collect_finished("kept").await.unwrap(); + } + assert_eq!( + runtime.store().unwrap().log_collection("kept").unwrap(), + Some((false, None)) + ); + let failures: i64 = runtime + .store() + .unwrap() + .begin() + .unwrap() + .query_row( + "SELECT attempts FROM log_collections WHERE run_id = 'kept'", + [], + |row| row.get(0), + ) + .unwrap(); + assert_eq!(failures, 0); + assert!(backend.unwatched.lock().unwrap().is_empty()); + runtime + .store() + .unwrap() + .set_run_contact("kept", &crate::store::Contact::Live) + .unwrap(); + runtime.collect_finished("kept").await.unwrap(); + assert_eq!(*backend.unwatched.lock().unwrap(), ["kept"]); + runtime.tick().unwrap(); + assert_eq!(*backend.held.lock().unwrap(), ["kept"]); + drop(runtime); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[tokio::test] + async fn finalization_retries_after_restart_without_reopening_destroyed_logs() { + use std::sync::atomic::Ordering; + let dir = std::env::temp_dir().join(format!("orx-finalize-{}", uuid::Uuid::new_v4())); + let runtime = collector(&dir); + let metadata = crate::jobs::BackendDescriptor::parse(r#"{"kind":"local_job"}"#).unwrap(); + runtime + .engine + .insert(SubmittingRun { + id: "run", + experiment_id: "exp", + project_id: "project", + metadata: &metadata, + command: "true", + created_at: 1, + commit_sha: None, + chat_session_id: None, + spec_digest: "digest", + launch: &LaunchSpec { + kind: "local_job".into(), + target: None, + options: json!({}), + }, + }) + .unwrap(); + { + let store = runtime.store().unwrap(); + store + .set_submission_fence( + "run", + 1, + &crate::store::SubmissionFence { + taken_at: 1, + submitter: None, + }, + ) + .unwrap(); + store + .record_run_handle("run", 1, &local_run().handle) + .unwrap(); + } + runtime + .engine + .observe( + "run", + Observation::Exited { + finished_at: None, + code: Some(0), + signal: None, + }, + ) + .unwrap(); + let backend = Arc::new(Host::default()); + backend.log.log.lock().unwrap().bytes = b"final output\n".to_vec(); + backend.fail_finish.store(true, Ordering::SeqCst); + lock(&runtime.backends).insert(Key::Local, backend.clone()); + assert!(runtime.collect_finished("run").await.is_err()); + assert!(runtime + .store() + .unwrap() + .log_output_collected("run") + .unwrap()); + assert!(runtime + .store() + .unwrap() + .log_collection_pending("run") + .unwrap()); + assert!(backend.destroyed.load(Ordering::SeqCst)); + drop(runtime); + + let runtime = collector(&dir); + let backend = Arc::new(Host::default()); + backend.destroyed.store(true, Ordering::SeqCst); + lock(&runtime.backends).insert(Key::Local, backend); + runtime.collect_finished("run").await.unwrap(); + assert!(!runtime + .store() + .unwrap() + .log_collection_pending("run") + .unwrap()); + assert_eq!( + std::fs::read(dir.join("run-logs/run.log")).unwrap(), + b"final output\n" + ); + drop(runtime); + std::fs::remove_dir_all(dir).unwrap(); + } + + /// A partial range resumes only for the log generation and offset it was started for. + #[tokio::test] + async fn partial_collection_restarts_for_a_new_generation_or_offset() { + let dir = std::env::temp_dir().join(format!("orx-collect-{}", uuid::Uuid::new_v4())); + let clock = Arc::new(TestClock::new()); + let engine = Arc::new(Engine::new( + Store::open_at(dir.clone()).unwrap(), + clock.clone(), + )); + let runtime = Runtime::new(engine, clock, dir.clone(), None); + let backend = FakeBackend::default(); + let run = WatchedRun { + id: "run".into(), + handle: Handle::Local { + dir: "/fake".into(), + }, + }; + let probe = ByteRange { + start: u64::MAX - 1, + end: u64::MAX, + }; + let logs = dir.join("run-logs"); + std::fs::create_dir_all(&logs).unwrap(); + + backend.log.lock().unwrap().bytes = b"OLD:tail\n".to_vec(); + let LogPage::Reset { info: Some(old) } = backend + .read_log(&run, LogFile::Log, probe.clone(), None) + .await + .unwrap() + else { + panic!("no length probe") + }; + std::fs::write(logs.join("run.log.part"), "OLD:").unwrap(); + std::fs::write( + logs.join("run.log.part.json"), + serde_json::to_vec(&(&old.ident, 0u64, 4u64)).unwrap(), + ) + .unwrap(); + *backend.log.lock().unwrap() = HostFile { + bytes: b"NEW:tail\n".to_vec(), + ino: 1, + }; + runtime + .collect_log(&backend, &run, &mut false) + .await + .unwrap(); + assert_eq!(std::fs::read(logs.join("run.log")).unwrap(), b"NEW:tail\n"); + assert!(!logs.join("run.log.part.json").exists()); + + // The same generation recorded for another offset starts over too. + let LogPage::Reset { info: Some(new) } = backend + .read_log(&run, LogFile::Log, probe.clone(), None) + .await + .unwrap() + else { + panic!("no length probe") + }; + std::fs::write(logs.join("run.log.part"), "tail\n").unwrap(); + std::fs::write( + logs.join("run.log.part.json"), + serde_json::to_vec(&(&new.ident, 4u64, 5u64)).unwrap(), + ) + .unwrap(); + runtime + .collect_log(&backend, &run, &mut false) + .await + .unwrap(); + assert_eq!(std::fs::read(logs.join("run.log")).unwrap(), b"NEW:tail\n"); + drop(runtime); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[tokio::test] + async fn early_collection_and_failed_final_notify_do_not_finish_output_debt() { + let dir = std::env::temp_dir().join(format!("orx-final-notify-{}", uuid::Uuid::new_v4())); + let runtime = collector(&dir); + let local = dir.join("local-runs/run"); + std::fs::create_dir_all(&local).unwrap(); + std::fs::write(local.join("log"), "finished\n").unwrap(); + std::fs::create_dir(local.join("notify")).unwrap(); + let metadata = crate::jobs::BackendDescriptor::parse(r#"{"kind":"local_job"}"#).unwrap(); + runtime + .engine + .insert(SubmittingRun { + id: "run", + experiment_id: "exp", + project_id: "project", + metadata: &metadata, + command: "true", + created_at: 1, + commit_sha: None, + chat_session_id: Some("chat"), + spec_digest: "spec", + launch: &LaunchSpec { + kind: "local_job".into(), + target: None, + options: json!({}), + }, + }) + .unwrap(); + let store = Store::open_at(dir.clone()).unwrap(); + store + .set_submission_fence( + "run", + 1, + &crate::store::SubmissionFence { + taken_at: 1, + submitter: None, + }, + ) + .unwrap(); + let handle = Handle::Local { + dir: local.to_string_lossy().into_owned(), + }; + store.record_run_handle("run", 1, &handle).unwrap(); + let watched = WatchedRun { + id: "run".into(), + handle, + }; + let backend = Local::new(dir.clone()); + runtime + .collect(&backend, &watched, COLLECTION_BUDGET) + .await + .unwrap(); + assert!(store.log_collection("run").unwrap().is_none()); + runtime + .engine + .observe( + "run", + Observation::Exited { + finished_at: None, + code: Some(0), + signal: None, + }, + ) + .unwrap(); + assert!(store.log_collection_pending("run").unwrap()); + assert!(runtime.collect_finished("run").await.is_err()); + assert!(store.log_collection_pending("run").unwrap()); + drop(runtime); + let runtime = collector(&dir); + assert_eq!(store.pending_log_collections().unwrap(), ["run"]); + std::fs::remove_dir(local.join("notify")).unwrap(); + std::fs::write(local.join("notify"), "final evaluation\n").unwrap(); + runtime.collect_finished("run").await.unwrap(); + assert!(!store.log_collection_pending("run").unwrap()); + let notices = store.run_notice_batch("chat").unwrap(); + assert!(notices + .iter() + .any(|notice| notice.kind == crate::store::NOTIFY + && notice.body.ends_with("final evaluation\n"))); + drop(runtime); + drop(store); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[tokio::test] + async fn a_provider_without_notify_input_completes_that_obligation() { + let dir = std::env::temp_dir().join(format!("orx-no-notify-{}", uuid::Uuid::new_v4())); + let runtime = collector(&dir); + let store = Store::open_at(dir.clone()).unwrap(); + store + .upsert_run(&StoredRun { + id: "run".into(), + experiment_id: "exp".into(), + project_id: "project".into(), + status: "done".into(), + backend_json: r#"{"kind":"engine","handle":{"type":"Api","provider":"hf_job","account":{"target":"test","context":null},"ids":["job"]}}"# + .into(), + command: "true".into(), + created_at: 1, + updated_at: 1, + ended_at: Some(1), + exit_code: Some(0), + commit_sha: None, + result_markdown: None, + cancel_requested: false, + cancel_reason: None, + chat_session_id: None, + }) + .unwrap(); + let backend = runtime + .backend_for(&Key::Api { + provider: "hf_job".into(), + account: ApiAccount { + target: Some("test".into()), + context: None, + }, + }) + .unwrap(); + assert!(runtime + .engine + .deliver_notify(backend.as_ref(), "run") + .await + .unwrap()); + drop(runtime); + drop(store); + std::fs::remove_dir_all(dir).unwrap(); + } + + /// A run no adapter can be built for is surfaced as unreconciled, with one notice, rather + /// than skipped every tick. + #[tokio::test] + async fn a_run_without_an_adapter_is_unreconciled_and_told_once() { + let dir = std::env::temp_dir().join(format!("orx-adapter-{}", uuid::Uuid::new_v4())); + let runtime = collector(&dir); + runtime + .engine + .insert(crate::store::SubmittingRun { + id: "run", + experiment_id: "exp", + project_id: "project", + metadata: &crate::jobs::BackendDescriptor::parse(r#"{"kind":"local"}"#).unwrap(), + command: "train", + created_at: 1, + commit_sha: None, + chat_session_id: None, + spec_digest: "digest", + launch: &LaunchSpec { + kind: "retired_job".into(), + target: None, + options: json!({}), + }, + }) + .unwrap(); + let store = Store::open_at(dir.clone()).unwrap(); + store.subscribe_run("run", "chat", 1).unwrap(); + for _ in 0..2 { + runtime.tick().unwrap(); + } + let state = store.engine_run_state("run").unwrap().unwrap(); + assert!( + matches!(&state.contact, crate::store::Contact::Unreconciled { detail, .. } if detail.contains("retired_job")), + "{:?}", + state.contact + ); + let notices = store.run_notice_batch("chat").unwrap(); + assert_eq!(notices.len(), 1); + assert_eq!(notices[0].kind, crate::store::ATTENTION); + drop(runtime); + drop(store); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[tokio::test] + async fn collection_failures_tell_the_chat_once_and_reconnect_retries_owed_logs() { + let dir = std::env::temp_dir().join(format!("orx-collect-{}", uuid::Uuid::new_v4())); + let clock = Arc::new(TestClock::new()); + let store = Store::open_at(dir.clone()).unwrap(); + let descriptor = r#"{"kind":"vanished_job","jobId":"j"}"#; + store + .upsert_run(&StoredRun { + id: "run".into(), + experiment_id: "exp".into(), + project_id: "project".into(), + status: "done".into(), + backend_json: descriptor.into(), + command: "train".into(), + created_at: 1, + updated_at: 1, + ended_at: Some(1), + exit_code: Some(0), + commit_sha: None, + result_markdown: None, + cancel_requested: false, + cancel_reason: None, + chat_session_id: Some("chat".into()), + }) + .unwrap(); + store.subscribe_run("run", "chat", 1).unwrap(); + store.queue_log_collection("run").unwrap(); + let engine = Arc::new(Engine::new(store, clock.clone())); + let runtime = Runtime::new(engine, clock, dir.clone(), None); + let attention = || { + runtime + .store() + .unwrap() + .run_notice_batch("chat") + .unwrap() + .into_iter() + .filter(|notice| notice.kind == crate::store::ATTENTION) + .count() + }; + let mut events = runtime.engine.bus.subscribe(); + for attempt in 1..=10 { + assert!(runtime.collect_finished("run").await.is_err()); + let mut updates = 0; + while let Ok(event) = events.try_recv() { + if matches!(event, super::super::bus::RunEvent::LogCollection { run_id } if run_id == "run") + { + updates += 1; + } + } + assert_eq!(updates, 1); + let (failed, error) = runtime + .store() + .unwrap() + .log_collection("run") + .unwrap() + .unwrap(); + assert_eq!(failed, attempt >= 7, "attempt {attempt}"); + assert!(error.unwrap().contains("vanished_job")); + assert_eq!(attention(), usize::from(attempt >= 7), "attempt {attempt}"); + } + + // Reconnecting a host retries its runs' collections at once. + let store = Store::open_at(dir.clone()).unwrap(); + let mut on_host = store.get_run("run").unwrap().unwrap(); + on_host.id = "on-host".into(); + on_host.backend_json = + r#"{"kind":"engine","jobId":"x","handle":{"type":"Ssh","host":"lab","root":"/r"}}"# + .into(); + store.upsert_run(&on_host).unwrap(); + store.queue_log_collection("on-host").unwrap(); + for _ in 0..3 { + store + .defer_log_collection("on-host", "unreachable") + .unwrap(); + } + runtime.host_returned("other", "/r").unwrap(); + runtime.host_returned("lab", "/elsewhere").unwrap(); + assert!(store.due_log_collections(10).unwrap().is_empty()); + runtime.host_returned("lab", "/r").unwrap(); + assert_eq!(store.due_log_collections(10).unwrap(), ["on-host"]); + for _ in 3..7 { + store + .defer_log_collection("on-host", "unreachable") + .unwrap(); + } + assert!(store.due_log_collections(10).unwrap().is_empty()); + runtime.host_returned("other", "/r").unwrap(); + runtime.host_returned("lab", "/elsewhere").unwrap(); + assert!(store.due_log_collections(10).unwrap().is_empty()); + runtime.host_returned("lab", "/r").unwrap(); + assert_eq!(store.due_log_collections(10).unwrap(), ["on-host"]); + drop(runtime); + drop(store); + std::fs::remove_dir_all(dir).unwrap(); + } + #[tokio::test] + async fn rented_boxes_keep_separate_transports_for_ports_and_rental_generations() { + let directory = + std::env::temp_dir().join(format!("orx-rental-transports-{}", uuid::Uuid::new_v4())); + let clock = Arc::new(TestClock::new()); + let engine = Arc::new(Engine::new( + Store::open_at(directory.clone()).unwrap(), + clock.clone(), + )); + let runtime = Runtime::new( + engine, + clock, + directory.clone(), + Some(directory.join("missing-config")), + ); + let mut first = SshTarget::host_port( + "root@shared".into(), + 2200, + crate::jobs::ssh::HostKeyPolicy::Ephemeral, + ); + first.managed_generation = Some("first-rental".into()); + let transport = runtime.box_transport(&first).unwrap(); + assert!(Arc::ptr_eq( + &transport, + &runtime.box_transport(&first).unwrap() + )); + + let mut other_port = SshTarget::host_port( + "root@shared".into(), + 2201, + crate::jobs::ssh::HostKeyPolicy::Ephemeral, + ); + other_port.managed_generation = first.managed_generation.clone(); + assert!(!Arc::ptr_eq( + &transport, + &runtime.box_transport(&other_port).unwrap() + )); + + let mut next_rental = first; + next_rental.managed_generation = Some("next-rental".into()); + assert!(!Arc::ptr_eq( + &transport, + &runtime.box_transport(&next_rental).unwrap() + )); + assert_eq!(lock(&runtime.auth).len(), 3); + let events = runtime.engine.bus.subscribe(); + drop(transport); + drop(runtime); + engine_released(events).await; + std::fs::remove_dir_all(directory).unwrap(); + } + + /// Windows cannot remove the data directory while a host watcher still holds the store. + async fn engine_released( + mut events: tokio::sync::broadcast::Receiver, + ) { + tokio::time::timeout(Duration::from_secs(10), async { + while !matches!( + events.recv().await, + Err(tokio::sync::broadcast::error::RecvError::Closed) + ) {} + }) + .await + .expect("host watchers retained the engine after its runtime stopped"); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn concurrent_host_initialization_shares_one_cell_per_alias_and_root() { + let directory = + std::env::temp_dir().join(format!("orx-host-cells-{}", uuid::Uuid::new_v4())); + let clock = Arc::new(super::super::clock::SystemClock::new()); + let engine = Arc::new(Engine::new( + Store::open_at(directory.clone()).unwrap(), + clock.clone(), + )); + let runtime = Runtime::new( + engine, + clock, + directory.clone(), + Some(directory.join("missing-config")), + ); + let barrier = Arc::new(std::sync::Barrier::new(8)); + let handle = tokio::runtime::Handle::current(); + let connections = std::thread::scope(|scope| { + let threads: Vec<_> = (0..8) + .map(|_| { + let (runtime, barrier, handle) = + (runtime.clone(), barrier.clone(), handle.clone()); + scope.spawn(move || { + let _entered = handle.enter(); + barrier.wait(); + runtime + .conn("host", "/first", runtime.ssh_config.clone()) + .unwrap() + }) + }) + .collect(); + threads + .into_iter() + .map(|thread| thread.join().unwrap()) + .collect::>() + }); + for conn in &connections { + assert!(connections[0].state().same_channel(&conn.state())); + } + let other = runtime + .conn("host", "/second", runtime.ssh_config.clone()) + .unwrap(); + assert!(!other.state().same_channel(&connections[0].state())); + assert_eq!(runtime.store().unwrap().engine_hosts().unwrap().len(), 2); + assert_eq!(runtime.host_states("host").len(), 2); + assert!(runtime.host_states("unused").is_empty()); + runtime.retry_host("unused").await; + assert_eq!(lock(&runtime.conns).len(), 2); + assert_eq!(lock(&runtime.auth).len(), 1); + let events = runtime.engine.bus.subscribe(); + drop(other); + drop(connections); + drop(runtime); + engine_released(events).await; + std::fs::remove_dir_all(directory).unwrap(); + } + + #[tokio::test] + async fn owed_collections_without_progress_wait_instead_of_spinning() { + let dir = std::env::temp_dir().join(format!("orx-owed-stalled-{}", uuid::Uuid::new_v4())); + let store = Store::open_at(dir.clone()).unwrap(); + for n in 0..10 { + store.queue_log_collection(&format!("missing-{n}")).unwrap(); + } + let clock = Arc::new(super::super::clock::TestClock::new()); + let runtime = Runtime::new( + Arc::new(Engine::new( + Store::open_at(dir.clone()).unwrap(), + clock.clone(), + )), + clock, + dir.clone(), + None, + ); + let task = tokio::spawn(runtime.collect_pending()); + tokio::time::sleep(Duration::from_millis(1)).await; + assert_eq!(store.due_log_collections(10).unwrap().len(), 10); + task.abort(); + let _ = task.await; + drop(store); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[tokio::test] + async fn owed_collections_drain_full_batches_without_sleeping() { + let dir = std::env::temp_dir().join(format!("orx-owed-{}", uuid::Uuid::new_v4())); + let store = Store::open_at(dir.clone()).unwrap(); + for n in 0..37 { + let id = format!("owed-{n}"); + store + .upsert_run(&StoredRun { + id: id.clone(), + experiment_id: "exp".into(), + project_id: "p".into(), + status: "done".into(), + backend_json: r#"{"kind":"engine"}"#.into(), + command: "true".into(), + created_at: 1, + updated_at: 1, + ended_at: Some(1), + exit_code: Some(0), + commit_sha: None, + result_markdown: None, + cancel_requested: false, + cancel_reason: None, + chat_session_id: None, + }) + .unwrap(); + store.queue_log_collection(&id).unwrap(); + } + let clock = Arc::new(super::super::clock::TestClock::new()); + let runtime = Runtime::new( + Arc::new(Engine::new( + Store::open_at(dir.clone()).unwrap(), + clock.clone(), + )), + clock, + dir.clone(), + None, + ); + let task = tokio::spawn(runtime.clone().collect_pending()); + tokio::time::timeout(Duration::from_secs(3), async { + loop { + if store.due_log_collections(40).unwrap().is_empty() { + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + for n in 0..37 { + assert!(store + .log_collection(&format!("owed-{n}")) + .unwrap() + .is_none()); + } + task.abort(); + let _ = task.await; + drop(runtime); + drop(store); + std::fs::remove_dir_all(dir).unwrap(); + } +} diff --git a/src/engine/runtime/chaos.rs b/src/engine/runtime/chaos.rs new file mode 100644 index 000000000..a51577b39 --- /dev/null +++ b/src/engine/runtime/chaos.rs @@ -0,0 +1,855 @@ +use super::*; +use crate::commands::up::api_v2::KeptRange; +use crate::engine::transport::Status; +use crate::jobs::BackendDescriptor; +use crate::local::model::LocalExperiment; +use orx_test_support::{Faults, Process, Sshd, SshdBuilder}; +use std::collections::BTreeMap; +use std::fs; +use std::io::{Read, Seek, SeekFrom}; +use std::num::NonZeroU64; +use std::time::Instant; + +pub(crate) mod rng; +use rng::Rng; + +const RECONCILE_BUDGET: Duration = Duration::from_secs(60); + +// A process-local clock reads atomically replaced offsets; wall and monotonic move independently. +struct ChaosClock { + origin: Instant, + path: PathBuf, +} +impl Clock for ChaosClock { + fn monotonic(&self) -> Duration { + self.origin.elapsed() + Duration::from_millis(self.offsets().0) + } + fn wall_ms(&self) -> i64 { + crate::store::now_ms() + self.offsets().1 + } +} +impl ChaosClock { + fn offsets(&self) -> (u64, i64) { + fs::read(&self.path) + .ok() + .and_then(|bytes| serde_json::from_slice(&bytes).ok()) + .unwrap_or_default() + } +} + +fn set_clock(directory: &Path, offsets: (u64, i64)) { + let pending = directory.join("clock.tmp"); + fs::write(&pending, serde_json::to_vec(&offsets).unwrap()).unwrap(); + fs::rename(pending, directory.join("clock.json")).unwrap(); +} + +pub(crate) fn crash_point(name: &str) { + if std::env::var("ORX_TEST_CRASH_AT").as_deref() == Ok(name) { + let directory = + PathBuf::from(std::env::var_os("ORX_CHAOS_WORKER").expect("crash worker directory")); + fs::write(directory.join("crashed"), name).unwrap(); + unsafe { + libc::kill(libc::getpid(), libc::SIGKILL); + } + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[ignore = "chaos subprocess entry point"] +async fn chaos_engine_worker() { + let Some(directory) = std::env::var_os("ORX_CHAOS_WORKER") else { + return; + }; + let directory = PathBuf::from(directory); + let parent: libc::pid_t = std::env::var("ORX_CHAOS_PARENT").unwrap().parse().unwrap(); + let _payloads = Payloads(directory.join("home/chaos-root/runs")); + let clock = Arc::new(ChaosClock { + origin: Instant::now(), + path: directory.join("clock.json"), + }); + let data = directory.join("store"); + let engine = Arc::new(Engine::new( + Store::open_at(data.clone()).unwrap(), + clock.clone(), + )); + let runtime = Runtime::new( + engine.clone(), + clock, + data, + Some(directory.join("ssh_config")), + ); + let live = directory.join("host-live"); + let _ = fs::remove_file(&live); + fs::write(directory.join("worker-ready"), b"ready").unwrap(); + if let Ok(point) = std::env::var("ORX_TEST_CRASH_AT") { + let runtime = runtime.clone(); + tokio::spawn(async move { + let backend = runtime + .backend_for(&Key::Ssh { + host: "orx-test".into(), + root: "~/chaos-root".into(), + }) + .unwrap(); + let deadline = Instant::now() + Duration::from_secs(20); + while !lock(&runtime.conns) + .values() + .filter_map(|cell| cell.get()) + .any(|conn| conn.state().borrow().status == Status::Live) + { + assert!(Instant::now() < deadline, "crash hook host not live"); + tokio::time::sleep(Duration::from_millis(20)).await; + } + let id = format!("hook-{point}"); + let script = "printf 'start\\n' >> payload-starts; sleep 1"; + engine + .submit( + backend.as_ref(), + submission( + &id, + script, + &orx_host::sha(script.as_bytes()), + "exp", + &BackendDescriptor::parse(r#"{"kind":"ssh_job"}"#).unwrap(), + &LaunchSpec { + kind: "ssh_job".into(), + target: Some("orx-test".into()), + options: json!({"root":"~/chaos-root"}), + }, + ), + ) + .await + .unwrap(); + panic!("crash hook did not fire: {point}"); + }); + } else { + runtime.clone().start(); + } + while unsafe { libc::getppid() } == parent { + let connected = lock(&runtime.conns).iter().any(|((alias, _), conn)| { + alias == "orx-test" + && conn + .get() + .is_some_and(|conn| conn.state().borrow().status == Status::Live) + }); + if connected { + if !live.exists() { + fs::write(&live, b"live").unwrap(); + } + } else { + let _ = fs::remove_file(&live); + } + tokio::time::sleep(Duration::from_millis(100)).await; + } +} + +fn worker(server: &Sshd, hook: Option<&str>) -> Process { + let ready = server.directory().join("worker-ready"); + let _ = fs::remove_file(&ready); + let mut command = crate::process::command(std::env::current_exe().unwrap()); + command + .args([ + "--exact", + "engine::runtime::chaos::chaos_engine_worker", + "--ignored", + "--nocapture", + ]) + .env("ORX_CHAOS_WORKER", server.directory()) + .env("ORX_CHAOS_PARENT", std::process::id().to_string()) + .env("HOME", server.home()) + .env("XDG_CONFIG_HOME", server.home().join("config")) + .env("ORX_DATA_DIR", server.directory().join("store")) + .env("ORX_HOST_BIN_DIR", orx_test_support::host_binaries()); + if let Some(point) = hook { + command.env("ORX_TEST_CRASH_AT", point); + } else { + command.env_remove("ORX_TEST_CRASH_AT"); + } + let mut process = Process::spawn(&mut command).unwrap(); + let deadline = Instant::now() + Duration::from_secs(15); + while !ready.exists() { + if let Ok(output) = process.wait(Duration::from_millis(20)) { + panic!("worker exited: {output:?}"); + } + assert!(Instant::now() < deadline, "engine worker did not start"); + } + process +} + +fn kill_worker(process: &mut Process) { + assert_eq!( + unsafe { libc::kill(process.pid() as i32, libc::SIGKILL) }, + 0 + ); + assert!(!process + .wait(Duration::from_secs(5)) + .unwrap() + .status + .success()); +} + +fn submission<'a>( + id: &'a str, + script: &'a str, + digest: &'a str, + experiment: &'a str, + metadata: &'a BackendDescriptor, + launch: &'a LaunchSpec, +) -> SubmittingRun<'a> { + SubmittingRun { + id, + experiment_id: experiment, + project_id: "proj", + metadata, + command: script, + created_at: crate::store::now_ms(), + commit_sha: None, + chat_session_id: Some("chaos"), + spec_digest: digest, + launch, + } +} + +fn insert(store: &Store, alias: &str, experiment: &str, id: &str, script: &str) { + let metadata = BackendDescriptor::parse(r#"{"kind":"ssh_job"}"#).unwrap(); + let launch = LaunchSpec { + kind: "ssh_job".into(), + target: Some(alias.into()), + options: json!({"root":"~/chaos-root"}), + }; + store + .insert_submitting_run(submission( + id, + script, + &orx_host::sha(script.as_bytes()), + experiment, + &metadata, + &launch, + )) + .unwrap(); +} + +struct Payloads(PathBuf); +impl Drop for Payloads { + fn drop(&mut self) { + let Ok(runs) = fs::read_dir(&self.0) else { + return; + }; + for run in runs.flatten() { + let directory = run.path(); + let identity = orx_host::read_json::( + &directory.join("wrapper.json"), + ) + .ok(); + if let Ok(tag) = fs::read_to_string(directory.join("started")) { + if let Ok(scan) = orx_host::platform::scan(identity.as_ref(), tag.trim(), false) { + for child in scan.processes { + let _ = orx_host::platform::signal(&child, libc::SIGKILL); + } + } + } + if let Some(identity) = identity { + if let Ok(wrapper) = orx_host::platform::process(identity.pid) { + if wrapper.starttime == identity.starttime { + let _ = orx_host::platform::signal(&wrapper, libc::SIGKILL); + } + } + } + } + } +} + +fn assert_step( + server: &Sshd, + worker: &Process, + starts: &mut BTreeMap, + reachable_since: Option, +) -> usize { + use std::os::unix::fs::MetadataExt; + let db = rusqlite::Connection::open(server.directory().join("store/orx.db")).unwrap(); + let mut query = db.prepare("SELECT id, status, (SELECT count(*) FROM run_notices n WHERE n.run_id=runs.id AND n.kind='terminal' AND n.chat_session_id='chaos') FROM runs WHERE experiment_id='exp'").unwrap(); + let runs = query + .query_map([], |row| { + Ok(( + row.get::<_, String>(0)?, + row.get::<_, String>(1)?, + row.get::<_, usize>(2)?, + )) + }) + .unwrap() + .collect::, _>>() + .unwrap(); + let mut statement = db + .prepare("SELECT run,phase FROM chaos_phases ORDER BY rowid") + .unwrap(); + let mut phases = BTreeMap::::new(); + for row in statement + .query_map([], |row| { + Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)) + }) + .unwrap() + { + let (id, phase) = row.unwrap(); + let phase = Phase::parse(&phase).unwrap(); + if let Some(before) = phases.insert(id.clone(), phase) { + assert!( + phase.rank() >= before.rank(), + "phase history regressed: {id}" + ); + if before.is_terminal() { + assert_eq!(before, phase); + } + } + } + let mut terminal = 0; + for (id, status, notices) in runs { + let phase = Phase::parse(&status).unwrap(); + assert_eq!( + notices, + usize::from(phase.is_terminal()), + "terminal notices: {}", + id + ); + let remote = server.home().join("chaos-root/runs").join(&id); + if let Ok(metadata) = fs::metadata(remote.join("started")) { + if let Some(inode) = starts.insert(id.clone(), metadata.ino()) { + assert_eq!(inode, metadata.ino(), "started replaced: {}", id); + } + } + let settled = |path: PathBuf| { + fs::metadata(path) + .and_then(|m| m.modified()) + .ok() + .and_then(|t| t.elapsed().ok()) + .is_some_and(|age| age > Duration::from_secs(35)) + }; + if reachable_since.is_some_and(|since| since.elapsed() > Duration::from_secs(35)) + && settled(server.directory().join("host-live")) + && settled(remote.join("exit.json")) + { + assert!( + phase.is_terminal(), + "host returned but receipt stayed nonterminal: {id}" + ); + } + if phase == Phase::Lost { + assert_eq!(id, "boot-swap", "unexpected Lost run without receipt: {id}"); + assert!( + matches!(orx_host::wrapper::state(&remote).unwrap(), orx_host_proto::RunState::Lost {reason} if reason == "host rebooted") + ); + } else if phase.is_terminal() { + let receipt = orx_host::wrapper::receipt(&remote) + .unwrap_or_else(|error| panic!("receipt unreadable for {id} ({phase:?}): {error}")) + .unwrap_or_else(|| panic!("terminal {id} ({phase:?}) has no receipt")); + let expected = if receipt.code == Some(0) && receipt.signal.is_none() { + Phase::Done + } else { + Phase::Failed + }; + assert_eq!(phase, expected, "receipt disagrees with phase: {id}"); + } + let launch_count = fs::read_to_string(remote.join("payload-starts")) + .unwrap_or_default() + .lines() + .count(); + assert!(launch_count <= 1, "duplicate payload: {}", id); + let manifest = server + .directory() + .join("store/run-logs") + .join(format!("{}.ranges.json", id)); + if let Ok(bytes) = fs::read(manifest) { + let kept: Vec = serde_json::from_slice(&bytes).unwrap(); + for range in kept { + let local = fs::read(range.file).unwrap(); + let mut file = fs::File::open(remote.join("log")).unwrap(); + file.seek(SeekFrom::Start(range.offset)).unwrap(); + let mut remote_bytes = vec![0; range.len as usize]; + file.read_exact(&mut remote_bytes).unwrap(); + assert_eq!(local.len() as u64, range.len); + assert_eq!( + local, remote_bytes, + "log mismatch: {} @{}", + id, range.offset + ); + } + } else if phase.is_terminal() && phase != Phase::Lost { + // A finished run may wait for its log, but then owes it. + let owed: bool = db + .query_row( + "SELECT done = 0 FROM log_collections WHERE run_id = ?1", + [&id], + |row| row.get(0), + ) + .unwrap_or(false); + assert!( + owed, + "terminal without kept log: {id}\n{}", + worker.stderr().unwrap() + ); + } + terminal += usize::from(phase.is_terminal()); + } + let output = crate::process::command("ps") + .args(["-axo", "comm=,args="]) + .output() + .unwrap(); + let config = server.config_path(); + let count = String::from_utf8_lossy(&output.stdout) + .lines() + .filter(|line| { + let comm = line.split_whitespace().next().unwrap_or_default(); + comm.ends_with("ssh") + && line.contains(config.to_str().unwrap()) + && !line.contains(" -G ") + }) + .count(); + assert!(count <= 2, "{count} SSH processes for one host"); + terminal +} + +fn receipt_overdue(reconnected: Duration, receipt_age: Option) -> bool { + receipt_age.is_some_and(|age| reconnected.min(age) > RECONCILE_BUDGET) +} + +#[test] +fn final_deadline_waits_for_the_natural_exit_receipt() { + for (reconnected, receipt, expected) in [ + (120, None, false), + (120, Some(1), false), + (1, Some(120), false), + (120, Some(60), false), + (120, Some(61), true), + (61, Some(120), true), + ] { + assert_eq!( + receipt_overdue( + Duration::from_secs(reconnected), + receipt.map(Duration::from_secs) + ), + expected, + "reconnect age={reconnected}, receipt age={receipt:?}" + ); + } +} + +#[test] +fn held_outage_does_not_make_an_old_live_marker_prove_receipt_reconciliation() { + let server = Sshd::start().unwrap(); + let store = Store::open_at(server.directory().join("store")).unwrap(); + insert(&store, server.alias(), "exp", "outage", "true"); + let db = rusqlite::Connection::open(server.directory().join("store/orx.db")).unwrap(); + db.execute_batch("CREATE TABLE chaos_phases(run TEXT, phase TEXT);") + .unwrap(); + let backend = json!({ + "kind": "engine", + "handle": Handle::Ssh { + host: server.alias().into(), + root: "~/chaos-root".into(), + }, + }); + db.execute( + "UPDATE runs SET status = 'running', backend_json = ?1", + [backend.to_string()], + ) + .unwrap(); + let remote = server.home().join("chaos-root/runs/outage"); + fs::create_dir_all(&remote).unwrap(); + let receipt = orx_host_proto::ExitReceipt { + finished_at: None, + code: Some(0), + signal: None, + reason: orx_host_proto::ExitReason::Exited, + processes: vec![], + outcome: orx_host_proto::CancelOutcome::Verified, + }; + orx_host::publish(&remote.join("exit.json"), &receipt).unwrap(); + let live = server.directory().join("host-live"); + fs::write(&live, "live").unwrap(); + let age = Duration::from_secs(60); + let old = std::time::SystemTime::now() - age; + for path in [live, remote.join("exit.json")] { + fs::File::options() + .write(true) + .open(path) + .unwrap() + .set_times(fs::FileTimes::new().set_modified(old)) + .unwrap(); + } + let worker = Process::spawn(&mut crate::process::command("true")).unwrap(); + let mut starts = BTreeMap::new(); + assert_eq!(assert_step(&server, &worker, &mut starts, None), 0); + let healthy = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + assert_step(&server, &worker, &mut starts, Some(Instant::now() - age)) + })); + assert!(healthy.is_err()); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[ignore = "real SSH seeded chaos and soak"] +async fn chaos_seeded_soak() { + let parent = unsafe { libc::getppid() }; + tokio::select! { + _ = schedule() => {}, + _ = tokio::signal::ctrl_c() => panic!("chaos interrupted; owned processes cleaned up"), + _ = async { + while unsafe { libc::getppid() } == parent { + tokio::time::sleep(Duration::from_millis(100)).await; + } + } => panic!("cargo exited; owned processes cleaned up"), + } +} + +async fn schedule() { + let replay = std::env::var("CHAOS_SEED").unwrap_or_else(|_| "8030613221891662191".into()); + let parts: Vec<_> = replay.split(':').collect(); + let seed = parts[0].parse().expect("CHAOS_SEED must start with a u64"); + let (seconds, runs): (u64, usize) = match parts.as_slice() { + [_] => ( + std::env::var("CHAOS_DURATION") + .map(|s| s.parse().expect("CHAOS_DURATION must be seconds")) + .unwrap_or(120), + std::env::var("CHAOS_RUNS") + .map(|s| s.parse().expect("CHAOS_RUNS must be a count")) + .unwrap_or(32), + ), + [_, seconds, runs] => ( + seconds.parse().expect("seed duration"), + runs.parse().expect("seed run count"), + ), + _ => panic!("CHAOS_SEED must be u64 or u64:seconds:runs"), + }; + assert!(seconds >= 30 && runs > 0); + eprintln!("CHAOS_SEED={seed}:{seconds}:{runs}"); + let mut rng = Rng(seed); + let mut server = Sshd::start().unwrap(); + let _payloads = Payloads(server.home().join("chaos-root/runs")); + let store = Store::open_at(server.directory().join("store")).unwrap(); + store + .create_local_experiment(&LocalExperiment { + id: "exp".into(), + project_id: "proj".into(), + parent_experiment_id: None, + slug: "exp".into(), + branch_name: "chaos".into(), + title: None, + description: None, + run_command: "true".into(), + agent_status: "idle".into(), + created_at: 1, + updated_at: 1, + chat_session_id: None, + archived: false, + }) + .unwrap(); + // Record every phase in SQLite too, so sub-second transitions and killed workers cannot hide regressions. + let db = rusqlite::Connection::open(server.directory().join("store/orx.db")).unwrap(); + db.execute_batch("CREATE TABLE chaos_phases(run TEXT, phase TEXT); CREATE TRIGGER chaos_phase AFTER UPDATE OF status ON runs BEGIN INSERT INTO chaos_phases VALUES(NEW.id,NEW.status); END;").unwrap(); + let auth = SshdBuilder { + identity_files: vec!["host_key".into()], + ..SshdBuilder::default() + } + .start() + .unwrap(); + let rejected = fs::read_to_string(auth.config_path()) + .unwrap() + .replace("Host orx-test", "Host chaos-rejected"); + let mut config = fs::read_to_string(server.config_path()).unwrap(); + config.push_str(&rejected); + fs::write(server.config_path(), config).unwrap(); + let mut experiment = store.get_local_experiment("exp").unwrap().unwrap(); + experiment.id = "auth-exp".into(); + experiment.slug = "auth-exp".into(); + store.create_local_experiment(&experiment).unwrap(); + insert( + &store, + "chaos-rejected", + "auth-exp", + "auth-rejected", + "true", + ); + let mut process = worker(&server, None); + let deadline = Instant::now() + Duration::from_secs(20); + while !store + .engine_host("chaos-rejected", "~/chaos-root") + .unwrap() + .is_some_and(|host| host.status == Status::NeedsAuth) + { + assert!( + Instant::now() < deadline, + "Runtime did not open auth breaker: {}", + process.stderr().unwrap() + ); + tokio::time::sleep(Duration::from_millis(50)).await; + } + tokio::time::sleep(Duration::from_millis(200)).await; + let auth_attempts = auth.auth_attempts().unwrap(); + assert_eq!(auth_attempts.values().sum::(), 1); + let mut offsets = ( + 1_800_000u64, + if rng.next() & 1 == 0 { + 3_600_000i64 + } else { + -3_600_000i64 + }, + ); + set_clock(server.directory(), offsets); + tokio::time::sleep(Duration::from_millis(300)).await; + assert_eq!( + auth.auth_attempts().unwrap(), + auth_attempts, + "Runtime retried auth after clock jump" + ); + kill_worker(&mut process); + for point in [ + "engine_intent", + "engine_fence", + "engine_response", + "engine_handle", + ] { + let _ = fs::remove_file(server.directory().join("crashed")); + let mut crashing = worker(&server, Some(point)); + let output = crashing.wait(Duration::from_secs(30)).unwrap(); + use std::os::unix::process::ExitStatusExt; + assert_eq!( + output.status.signal(), + Some(libc::SIGKILL), + "crash {point}: {output:?}" + ); + assert_eq!( + fs::read_to_string(server.directory().join("crashed")).unwrap(), + point + ); + } + process = worker(&server, None); + insert( + &store, + server.alias(), + "exp", + "boot-swap", + "printf 'start\\n' >> payload-starts; sleep 20", + ); + let boot = server.home().join("chaos-root/runs/boot-swap"); + let deadline = Instant::now() + Duration::from_secs(20); + while !boot.join("payload-starts").exists() { + assert!( + Instant::now() < deadline, + "boot probe did not start: {}", + process.stderr().unwrap() + ); + tokio::time::sleep(Duration::from_millis(50)).await; + } + let mut identity: orx_host_proto::ProcessIdentity = + orx_host::read_json(&boot.join("wrapper.json")).unwrap(); + let wrapper = orx_host::platform::process(identity.pid).unwrap(); + orx_host::platform::signal(&wrapper, libc::SIGKILL).unwrap(); + let tag = fs::read_to_string(boot.join("started")).unwrap(); + for child in orx_host::platform::scan(Some(&identity), tag.trim(), false) + .unwrap() + .processes + { + let _ = orx_host::platform::signal(&child, libc::SIGKILL); + } + identity.boot_id.push_str("-chaos-reboot"); + orx_host::publish(&boot.join("wrapper.json"), &identity).unwrap(); + let mut starts = BTreeMap::new(); + let started = Instant::now(); + let mut reachable_since = Some(started); + let mut faults: Vec<_> = (0..9).collect(); + for launched in 0..runs { + let id = format!("chaos-{seed:016x}-{launched:04}"); + let choice = rng.next() % 7; + let delay = 1 + rng.next() % (seconds - 20); + let payload = match choice { + 0 => format!("sleep {delay}; exit {}",rng.next()%4), + 1 => format!("sleep {delay}; kill -KILL $$"), + 2 | 3 => format!("python3 -c 'import os,time; p=os.fork(); os._exit(0) if p else None; os.setsid(); p=os.fork(); os._exit(0) if p else None; time.sleep({delay}+4)'\nsleep {delay}"), + 4 => format!("python3 - <<'PYCPU'\nimport os,time\nend=time.monotonic()+{delay}\nchildren=[]\nfor _ in range(os.cpu_count() or 1):\n pid=os.fork()\n if pid==0:\n while time.monotonic() format!("head -c {} /dev/zero | tr '\\000' x; printf '\\n'; sleep {delay}",2*1024*1024+rng.next()%(6*1024*1024)), + }; + let script = + format!("printf 'start\\n' >> payload-starts\nprintf 'run {id}\\n'\n{payload}\n"); + insert(&store, server.alias(), "exp", &id, &script); + } + let mut elapsed = 0; + let mut step = 0; + while elapsed < seconds { + if step % faults.len() == 0 { + for index in (1..faults.len()).rev() { + let swap = rng.next() as usize % (index + 1); + faults.swap(index, swap); + } + } + let fault = faults[step % faults.len()]; + let hold = 1 + rng.next() % 60; + eprintln!("seed={seed} step={step} fault={fault} hold={hold}s runs={runs}"); + match fault { + 0 => server + .proxy() + .set(Faults { + black_hole: true, + ..Faults::default() + }) + .unwrap(), + 1 => server + .proxy() + .set(Faults { + paused: true, + ..Faults::default() + }) + .unwrap(), + 2 => server + .proxy() + .set(Faults { + latency: Duration::from_millis(50 + rng.next() % 150), + ..Faults::default() + }) + .unwrap(), + 3 => server + .proxy() + .set(Faults { + bytes_per_second: NonZeroU64::new(4096 + rng.next() % 32768), + ..Faults::default() + }) + .unwrap(), + 4 => server.proxy().reset().unwrap(), + 5 => { + server + .proxy() + .set(Faults { + refuse_new: true, + ..Faults::default() + }) + .unwrap(); + server.proxy().reset().unwrap(); + } + 6 => server.restart().unwrap(), + 7 => { + kill_worker(&mut process); + process = worker(&server, None); + } + 8 => { + offsets.0 += 1_800_000; + offsets.1 += if rng.next() & 1 == 0 { + 3_600_000 + } else { + -3_600_000 + }; + set_clock(server.directory(), offsets); + } + _ => unreachable!(), + } + if matches!(fault, 0 | 1 | 5) { + reachable_since = None; + } else if matches!(fault, 4 | 6 | 7 | 8) { + reachable_since = Some(Instant::now()); + } + let hold_started = Instant::now(); + for second in 1..=hold { + tokio::time::sleep_until((hold_started + Duration::from_secs(second)).into()).await; + assert_step(&server, &process, &mut starts, reachable_since); + if matches!(fault, 0 | 1 | 5) && second >= 37 { + assert_ne!( + store + .engine_host(server.alias(), "~/chaos-root") + .unwrap() + .unwrap() + .status, + Status::Live, + "host stayed Live during a held outage" + ); + } + assert_eq!( + auth.auth_attempts().unwrap(), + auth_attempts, + "Runtime login after auth failure, seed={seed} step={step}" + ); + assert_eq!( + store + .engine_host("chaos-rejected", "~/chaos-root") + .unwrap() + .unwrap() + .status, + Status::NeedsAuth + ); + } + server.proxy().clear().unwrap(); + if fault == 0 { + server.proxy().reset().unwrap(); + } + reachable_since.get_or_insert_with(Instant::now); + assert_step(&server, &process, &mut starts, reachable_since); + elapsed += hold; + step += 1; + } + server.proxy().clear().unwrap(); + kill_worker(&mut process); + process = worker(&server, None); + let reconnected = Instant::now(); + // Payload delays reserve 20 seconds for setup and output. + let deadline = reconnected + Duration::from_secs(seconds) + RECONCILE_BUDGET; + while assert_step(&server, &process, &mut starts, None) != runs + 5 { + for run in store.list_runs_by_experiment("exp").unwrap() { + if Phase::parse(&run.status).unwrap().is_terminal() { + continue; + } + let receipt_age = fs::metadata( + server + .home() + .join("chaos-root/runs") + .join(&run.id) + .join("exit.json"), + ) + .and_then(|metadata| metadata.modified()) + .ok() + .and_then(|published| published.elapsed().ok()); + assert!( + !receipt_overdue(reconnected.elapsed(), receipt_age), + "receipt stayed nonterminal after reconnect, seed={seed}, run={}, reconnect_age={:?}, receipt_age={receipt_age:?}", + run.id, + reconnected.elapsed(), + ); + } + assert!( + Instant::now() < deadline, + "payload lifetime plus reconciliation grace exceeded, seed={seed}: {:?}", + store.list_runs_by_experiment("exp").unwrap() + ); + tokio::time::sleep(Duration::from_millis(200)).await; + } + // A restarted engine retries every log still owed, and a clean host keeps them. + let owed = || -> i64 { + let db = rusqlite::Connection::open(server.directory().join("store/orx.db")).unwrap(); + db.query_row( + "SELECT count(*) FROM log_collections WHERE done = 0", + [], + |row| row.get(0), + ) + .unwrap() + }; + let deadline = Instant::now() + Duration::from_secs(120); + while owed() != 0 { + assert!( + Instant::now() < deadline, + "logs still owed after the host returned, seed={seed}" + ); + tokio::time::sleep(Duration::from_millis(500)).await; + } + assert_step(&server, &process, &mut starts, None); + for run in store.list_runs_by_experiment("exp").unwrap() { + let id = &run.id; + let remote = server.home().join("chaos-root/runs").join(id); + assert!(remote.join("started").exists(), "never started: {id}"); + assert_eq!( + fs::read_to_string(remote.join("payload-starts")) + .unwrap() + .lines() + .count(), + 1, + "{id}" + ); + } + kill_worker(&mut process); + eprintln!( + "CHAOS PASS seed={seed}:{seconds}:{runs} steps={step} elapsed={:?}", + started.elapsed() + ); +} diff --git a/src/engine/runtime/chaos/rng.rs b/src/engine/runtime/chaos/rng.rs new file mode 100644 index 000000000..5cd1bbe24 --- /dev/null +++ b/src/engine/runtime/chaos/rng.rs @@ -0,0 +1,10 @@ +pub(crate) struct Rng(pub(crate) u64); +impl Rng { + pub(crate) fn next(&mut self) -> u64 { + self.0 = self.0.wrapping_add(0x9e3779b97f4a7c15); + let mut z = self.0; + z = (z ^ (z >> 30)).wrapping_mul(0xbf58476d1ce4e5b9); + z = (z ^ (z >> 27)).wrapping_mul(0x94d049bb133111eb); + z ^ (z >> 31) + } +} diff --git a/src/engine/ssh_config_cleanup.rs b/src/engine/ssh_config_cleanup.rs new file mode 100644 index 000000000..7e9cad31d --- /dev/null +++ b/src/engine/ssh_config_cleanup.rs @@ -0,0 +1,274 @@ +use std::fs::OpenOptions; +use std::io::ErrorKind; +use std::path::Path; + +use super::{phase_of, Engine}; +use crate::error::Result; +use crate::jobs::BackendDescriptor; + +impl Engine { + /// Refresh sharing only after this store's legacy supervisors release ownership. + pub fn retire_ssh_config(&self, home: &Path) -> Result { + let store = self.store(); + let transaction = store.begin_immediate()?; + // LIMIT -1 also includes terminal rows whose legacy supervisor may still be exiting. + for run in store.list_runs(usize::MAX)? { + if self.memory().locks.holds(&run.id) { + continue; + } + let descriptor = BackendDescriptor::parse(&run.backend_json); + if descriptor.as_ref().is_ok_and(|descriptor| { + !matches!( + descriptor.kind.as_str(), + "ssh_job" | "slurm_job" | "openresearch_job" + ) + }) { + continue; + } + if descriptor.is_ok() && phase_of(&run).is_ok_and(|phase| !phase.is_terminal()) { + return Ok(false); + } + for path in store.supervisor_lock_paths(&run.id)? { + let file = match OpenOptions::new().write(true).open(path) { + Ok(file) => file, + Err(error) if error.kind() == ErrorKind::NotFound => continue, + Err(error) => return Err(error.into()), + }; + match file.try_lock() { + Ok(()) => {} + Err(std::fs::TryLockError::WouldBlock) => return Ok(false), + Err(std::fs::TryLockError::Error(error)) => return Err(error.into()), + } + } + } + + #[cfg(unix)] + crate::jobs::ssh::sharing::retire_legacy(home)?; + #[cfg(not(unix))] + let _ = home; + transaction.commit()?; + Ok(true) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::engine::clock::TestClock; + use crate::store::{Store, StoredRun}; + use std::fs; + use std::path::PathBuf; + use std::sync::Arc; + + const MANAGED_FILES: [&str; 3] = [ + "openresearch_config", + "openresearch_match", + "openresearch_connections.json", + ]; + + const FOOTER: &[u8] = b"\nHost *\nInclude openresearch_config\n"; + + struct Fixture { + home: PathBuf, + engine: Engine, + } + + impl Fixture { + fn new(config: &[u8]) -> Self { + let home = + std::env::temp_dir().join(format!("orx-ssh-retirement-{}", uuid::Uuid::new_v4())); + fs::create_dir_all(home.join(".ssh")).unwrap(); + fs::write(home.join(".ssh/config"), config).unwrap(); + for name in MANAGED_FILES { + fs::write(home.join(".ssh").join(name), b"legacy").unwrap(); + } + fs::write(home.join(".ssh/openresearch_connections.json"), b"{}").unwrap(); + let store = Store::open_at(home.join("data")).unwrap(); + Self { + home, + engine: Engine::new(store, Arc::new(TestClock::new())), + } + } + + fn retire(&self) -> Result { + for _ in 0..20 { + if self.engine.retire_ssh_config(&self.home)? { + return Ok(true); + } + std::thread::sleep(std::time::Duration::from_millis(10)); + } + Ok(false) + } + + fn config(&self) -> Vec { + fs::read(self.home.join(".ssh/config")).unwrap() + } + + fn assert_managed(&self) { + for name in MANAGED_FILES { + assert!(self.home.join(".ssh").join(name).try_exists().unwrap()); + } + } + + fn legacy(&self, status: &str) { + self.engine + .store() + .upsert_run(&StoredRun { + id: "legacy".into(), + experiment_id: "exp".into(), + project_id: "proj".into(), + status: status.into(), + backend_json: r#"{"kind":"ssh_job","jobId":"/old/run"}"#.into(), + command: "train".into(), + created_at: 1, + updated_at: 1, + ended_at: None, + exit_code: None, + commit_sha: None, + result_markdown: None, + cancel_requested: false, + cancel_reason: None, + chat_session_id: None, + }) + .unwrap(); + } + + fn cleanup(self) { + drop(self.engine); + fs::remove_dir_all(self.home).unwrap(); + } + } + + #[test] + fn config_and_its_metadata_are_untouched() { + let config = [b"Host example\n HostName example.org\n".as_slice(), FOOTER].concat(); + let f = Fixture::new(&config); + let path = f.home.join(".ssh/config"); + let before = fs::metadata(&path).unwrap(); + assert!(f.retire().unwrap()); + assert!(f.retire().unwrap()); + assert_eq!(f.config(), config); + assert_eq!( + fs::metadata(&path).unwrap().modified().unwrap(), + before.modified().unwrap() + ); + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + let after = fs::metadata(&path).unwrap(); + assert_eq!( + (after.ino(), after.mode(), after.uid()), + (before.ino(), before.mode(), before.uid()) + ); + } + f.assert_managed(); + f.cleanup(); + } + + #[cfg(unix)] + #[test] + fn symlinked_config_and_target_are_untouched() { + use std::os::unix::fs::symlink; + let f = Fixture::new(FOOTER); + let target = f.home.join("user-config"); + fs::rename(f.home.join(".ssh/config"), &target).unwrap(); + symlink(&target, f.home.join(".ssh/config")).unwrap(); + assert!(f.retire().unwrap()); + assert!(fs::symlink_metadata(f.home.join(".ssh/config")) + .unwrap() + .is_symlink()); + assert_eq!(fs::read(target).unwrap(), FOOTER); + f.assert_managed(); + f.cleanup(); + } + + #[test] + fn missing_files_and_ssh_directory_are_noops() { + let f = Fixture::new(FOOTER); + for name in MANAGED_FILES { + fs::remove_file(f.home.join(".ssh").join(name)).unwrap(); + } + assert!(f.retire().unwrap()); + assert!(!f.home.join(".ssh/.orx-config.lock").exists()); + assert_eq!(f.config(), FOOTER); + fs::remove_dir_all(f.home.join(".ssh")).unwrap(); + assert!(f.retire().unwrap()); + assert!(!f.home.join(".ssh").exists()); + f.cleanup(); + } + + #[test] + fn malformed_rows_only_block_while_either_supervisor_lock_is_held() { + for malformed_backend in [false, true] { + for lock_index in 0..2 { + let f = Fixture::new(FOOTER); + f.legacy("running"); + let db = rusqlite::Connection::open(f.home.join("data/orx.db")).unwrap(); + if malformed_backend { + db.execute( + "UPDATE runs SET backend_json = 'invalid' WHERE id = 'legacy'", + [], + ) + .unwrap(); + } else { + db.execute("UPDATE runs SET status = 'unknown' WHERE id = 'legacy'", []) + .unwrap(); + } + let paths = f.engine.store().supervisor_lock_paths("legacy").unwrap(); + fs::create_dir_all(paths[lock_index].parent().unwrap()).unwrap(); + let file = OpenOptions::new() + .write(true) + .create(true) + .truncate(false) + .open(&paths[lock_index]) + .unwrap(); + let mut lock = fd_lock::RwLock::new(file); + let guard = lock.try_write().unwrap(); + assert!(!f.retire().unwrap()); + assert_eq!(f.config(), FOOTER); + drop(guard); + assert!(f.retire().unwrap()); + f.assert_managed(); + drop(lock); + drop(db); + f.cleanup(); + } + } + } + + #[test] + fn legacy_runs_block_until_adopted_or_finished_and_locks_released() { + for lock_index in 0..2 { + let f = Fixture::new(FOOTER); + f.legacy("running"); + assert!(!f.retire().unwrap()); + let paths = f.engine.store().supervisor_lock_paths("legacy").unwrap(); + fs::create_dir_all(paths[lock_index].parent().unwrap()).unwrap(); + let file = OpenOptions::new() + .write(true) + .create(true) + .truncate(false) + .open(&paths[lock_index]) + .unwrap(); + let mut lock = fd_lock::RwLock::new(file); + let guard = lock.try_write().unwrap(); + assert!(!f.retire().unwrap()); + f.legacy("done"); + assert!(!f.retire().unwrap()); + assert_eq!(f.config(), FOOTER); + assert_eq!( + fs::read(f.home.join(".ssh/openresearch_config")).unwrap(), + b"legacy" + ); + drop(guard); + assert!(f.retire().unwrap()); + drop(lock); + f.cleanup(); + } + let f = Fixture::new(FOOTER); + f.legacy("running"); + assert!(f.engine.own("legacy").unwrap()); + assert!(f.retire().unwrap()); + f.cleanup(); + } +} diff --git a/src/engine/submit.rs b/src/engine/submit.rs new file mode 100644 index 000000000..6ecc6cccb --- /dev/null +++ b/src/engine/submit.rs @@ -0,0 +1,300 @@ +//! §2: submission with fences and recovery, cancel at every point of it, and Abandon. + +use super::clock::backoff; +use super::reconcile::{is_tombstone, Change, ABANDONED}; +use super::{ + handle_of, phase_of, process, Backend, Engine, Fence, Handle, LaunchError, Phase, Recovery, + RunIntent, +}; +use crate::error::{anyhow, Result}; +use crate::store::{Contact, EngineRunState, SubmissionFence, SubmittingRun}; + +/// Ends `attempt` if it is still the current one: Cancelled when a cancel was accepted, else +/// Failed with `rejected`. A superseded attempt's result changes nothing. +fn end_attempt( + attempt: u32, + phase: Phase, + state: &EngineRunState, + rejected: Option, +) -> Change { + if phase != Phase::Submitting || state.submission_attempt != attempt { + return Change::default(); + } + match (state.cancel_accepted_at, rejected) { + (Some(_), _) => Change::terminal(Phase::Cancelled, None), + (None, Some(reason)) => Change::terminal(Phase::Failed, Some(reason)), + (None, None) => Change::default(), + } +} + +impl Engine { + /// Commits the intent before any side effect, then launches attempt 1. + #[cfg(test)] + pub async fn submit(&self, backend: &dyn Backend, run: SubmittingRun<'_>) -> Result<()> { + let run_id = run.id.to_string(); + self.insert(run)?; + self.launch_inserted(backend, &run_id).await + } + + /// The durable half of [`Self::submit`]: from here recovery owns the run. + pub fn insert(&self, run: SubmittingRun<'_>) -> Result<()> { + self.store().insert_submitting_run(run)?; + #[cfg(all(test, unix))] + super::runtime::chaos::crash_point("engine_intent"); + Ok(()) + } + + pub async fn launch_inserted(&self, backend: &dyn Backend, run_id: &str) -> Result<()> { + let run_id = run_id.to_string(); + if !self.own(&run_id)? { + return Err(anyhow!("Run {run_id} is locked by another process")); + } + let _gate = self.gate(&run_id).lock_owned().await; + if let Some(error) = self.launch(backend, &run_id, 1).await? { + self.recover_gated(backend, &run_id, Some(error)).await?; + } + Ok(()) + } + + /// Fences and launches one attempt; the launch error when its outcome is unknown and needs + /// recovery. + async fn launch( + &self, + backend: &dyn Backend, + run_id: &str, + attempt: u32, + ) -> Result> { + let taken_at = self.clock.wall_ms(); + let fence = SubmissionFence { + taken_at, + submitter: None, + }; + if !self.store().set_submission_fence(run_id, attempt, &fence)? { + // Refused before any side effect; an accepted cancel ends the attempt. + self.commit(run_id, |phase, state| { + end_attempt(attempt, phase, state, None) + })?; + return Ok(None); + } + #[cfg(all(test, unix))] + super::runtime::chaos::crash_point("engine_fence"); + let (run, state) = self.load(run_id)?; + let intent = RunIntent::new(run, &state)?; + let fence = Fence { + store: &self.store, + run_id, + attempt, + taken_at, + }; + match backend.launch(&intent, &fence).await { + Ok(handle) => { + #[cfg(all(test, unix))] + super::runtime::chaos::crash_point("engine_response"); + self.found(backend, run_id, attempt, handle).await?; + } + Err(LaunchError::Rejected { reason }) => { + self.commit(run_id, |phase, state| { + end_attempt(attempt, phase, state, Some(reason)) + })?; + } + Err(LaunchError::Blocked { contact }) => { + if self.store().clear_submission_fence(run_id, attempt)? { + self.commit(run_id, |phase, state| { + if phase != Phase::Submitting || state.submission_attempt != attempt { + return Change::default(); + } + if state.cancel_accepted_at.is_some() { + end_attempt(attempt, phase, state, None) + } else { + Change::contact(contact) + } + })?; + } + } + Err(LaunchError::Interrupted { detail }) => return Ok(Some(detail)), + } + Ok(None) + } + + async fn found( + &self, + backend: &dyn Backend, + run_id: &str, + attempt: u32, + handle: Handle, + ) -> Result<()> { + self.commit(run_id, |phase, state| Change { + handle: Some((attempt, handle)), + contact: (!is_tombstone(phase, &state.contact)).then_some(Contact::Live), + ..Change::default() + })?; + #[cfg(all(test, unix))] + super::runtime::chaos::crash_point("engine_handle"); + self.deliver_cancel(backend, run_id).await + } + + /// §2 recovery a–c for a submitting run, or an abandoned one that never got a handle. + /// Unknown leaves it Unreconciled and retries with backoff; it is never failed for it. + /// A run another task is already working on is left to it. + pub async fn recover(&self, backend: &dyn Backend, run_id: &str) -> Result<()> { + let Some(_gate) = self.try_gate(run_id) else { + return Ok(()); + }; + self.recover_gated(backend, run_id, None).await + } + + /// A relaunch after Absent that is interrupted again backs off rather than looping. + async fn recover_gated( + &self, + backend: &dyn Backend, + run_id: &str, + mut launch_error: Option, + ) -> Result<()> { + if !self.own(run_id)? { + return Ok(()); + } + loop { + let now = self.clock.monotonic(); + let backing_off = self + .memory() + .retries + .get(run_id) + .is_some_and(|(_, due)| *due > now); + if backing_off { + return Ok(()); + } + let (run, state) = self.load(run_id)?; + let phase = phase_of(&run)?; + let tombstone = is_tombstone(phase, &state.contact) && handle_of(&run).is_none(); + if phase != Phase::Submitting && !tombstone { + return Ok(()); + } + let attempt = state.submission_attempt; + + let Some(fence) = &state.submission_fence else { + // The fence precedes every side effect, so this attempt never launched. + if tombstone { + return self.commit(run_id, |_, _| Change::contact(Contact::Live)); + } + launch_error = self.launch(backend, run_id, attempt).await?; + if launch_error.is_none() { + return Ok(()); + } + continue; + }; + if let Some(submitter) = &fence.submitter { + if !process::ensure_gone(submitter).await { + return self.unknown(run_id, "The previous submitter could not be stopped."); + } + } + let intent = RunIntent::new(run, &state)?; + let recovery_fence = Fence { + store: &self.store, + run_id, + attempt, + taken_at: fence.taken_at, + }; + match backend + .recover_with_cancel(&intent, &|| recovery_fence.cancelled()) + .await + { + Recovery::Found(handle) => { + return self.found(backend, run_id, attempt, handle).await + } + Recovery::Absent if tombstone => { + return self.commit(run_id, |_, _| Change::contact(Contact::Live)) + } + Recovery::Absent => { + if !self.store().advance_submission_attempt(run_id, attempt)? { + return self.commit(run_id, |phase, state| { + end_attempt(attempt, phase, state, None) + }); + } + return match self.launch(backend, run_id, attempt + 1).await? { + Some(error) => self.unknown(run_id, format!("The launch failed: {error}")), + None => Ok(()), + }; + } + Recovery::Unknown { detail } => { + let detail = match launch_error { + Some(error) => format!("{detail}; the launch failed: {error}"), + None => detail, + }; + return self.unknown(run_id, detail); + } + } + } + } + + fn unknown(&self, run_id: &str, detail: impl Into) -> Result<()> { + { + let mut memory = self.memory(); + let failures = memory.retries.get(run_id).map_or(0, |(n, _)| *n) + 1; + let due = self.clock.monotonic() + backoff(failures); + memory.retries.insert(run_id.into(), (failures, due)); + } + let now = self.clock.wall_ms(); + let detail = detail.into(); + self.commit(run_id, |phase, state| { + if is_tombstone(phase, &state.contact) { + return Change::default(); + } + Change::contact(Contact::Unreconciled { since: now, detail }) + }) + } + + /// Before the fence cancel is immediate; after it, the backend's stop proof decides the result. + pub async fn cancel(&self, backend: &dyn Backend, run_id: &str, reason: &str) -> Result { + if !self.own(run_id)? + || self + .store() + .accept_run_cancel(run_id, Some(reason))? + .is_none() + { + return Ok(false); + } + // A busy gate means a launch or recovery is running; it will see the accepted cancel. + if let Some(_gate) = self.try_gate(run_id) { + self.commit(run_id, |phase, state| { + if phase == Phase::Submitting && state.submission_fence.is_none() { + Change::terminal(Phase::Cancelled, None) + } else { + Change::default() + } + })?; + } + let (run, state) = self.load(run_id)?; + let phase = phase_of(&run)?; + if !phase.is_terminal() { + self.bus.publish(super::bus::RunEvent::Changed { + run_id: run_id.into(), + phase, + contact: state.contact, + cancelling: true, + }); + } + self.deliver_cancel(backend, run_id).await?; + Ok(true) + } + + /// Lost now, with the chat told; the fence and the cancel stay alive for if the job returns. + pub fn abandon(&self, run_id: &str) -> Result { + if !self.own(run_id)? + || self + .store() + .accept_run_cancel(run_id, Some("Abandoned."))? + .is_none() + { + return Ok(false); + } + let now = self.clock.wall_ms(); + self.commit(run_id, |_, _| Change { + contact: Some(Contact::Unreconciled { + since: now, + detail: ABANDONED.into(), + }), + ..Change::terminal(Phase::Lost, Some(ABANDONED.into())) + })?; + Ok(true) + } +} diff --git a/src/engine/tests.rs b/src/engine/tests.rs new file mode 100644 index 000000000..e6b5e207c --- /dev/null +++ b/src/engine/tests.rs @@ -0,0 +1,2241 @@ +use std::path::PathBuf; +use std::sync::Arc; +use std::time::Duration; + +use tokio::sync::broadcast::Receiver; + +use super::bus::RunEvent; +use super::clock::TestClock; +use super::fake::{FakeBackend, HostFile}; +use super::legacy::Adoption; +use super::*; +use crate::local::model::LocalExperiment; +use crate::store::{ + LaunchSpec, RunNotice, StoredRun, SubmissionFence, SubmittingRun, ATTENTION, NOTIFY, RECOVERED, + TERMINAL, +}; + +const CHAT: &str = "chat"; + +struct Fixture { + dir: PathBuf, + clock: Arc, + engine: Engine, + backend: FakeBackend, + events: Receiver, +} + +impl Fixture { + fn new() -> Self { + let dir = std::env::temp_dir().join(format!("orx-engine-{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&dir).unwrap(); + let store = Store::open_at(dir.clone()).unwrap(); + store + .create_local_experiment(&LocalExperiment { + id: "exp".into(), + project_id: "proj".into(), + parent_experiment_id: None, + slug: "exp".into(), + branch_name: "orx/exp".into(), + title: None, + description: None, + run_command: "train".into(), + agent_status: "idle".into(), + created_at: 1, + updated_at: 1, + chat_session_id: None, + archived: false, + }) + .unwrap(); + let clock = Arc::new(TestClock::new()); + let engine = Engine::new(store, clock.clone()); + let events = engine.bus.subscribe(); + Self { + dir, + clock, + engine, + backend: FakeBackend::default(), + events, + } + } + + /// A second connection, as another process would have. + fn store(&self) -> Store { + Store::open_at(self.dir.clone()).unwrap() + } + + /// Simulates a crash: a fresh engine over the same data, with nothing in memory, once the + /// old one's locks are gone as they would be with its process. + fn restart(&mut self) { + let held: Vec = std::fs::read_dir(self.dir.join("run-logs")) + .into_iter() + .flatten() + .filter_map(|entry| { + let name = entry.unwrap().file_name().into_string().unwrap(); + name.strip_suffix(".supervisor.lock").map(str::to_owned) + }) + .filter(|id| self.engine.holds(id)) + .collect(); + let engine = Engine::new(self.store(), self.clock.clone()); + self.events = engine.bus.subscribe(); + self.engine = engine; + for id in held { + self.released(&id); + } + } + + async fn submit(&self, id: &str) -> Result<()> { + let metadata = BackendDescriptor::parse(r#"{"kind":"ssh_job","sourceDigest":"abc"}"#)?; + self.engine + .submit( + &self.backend, + SubmittingRun { + id, + experiment_id: "exp", + project_id: "proj", + metadata: &metadata, + command: "train", + created_at: 1, + commit_sha: None, + chat_session_id: Some(CHAT), + spec_digest: "spec", + launch: &ssh_launch(), + }, + ) + .await + } + + async fn running(&self, id: &str) { + self.backend.then_launch(Ok(handle())); + self.submit(id).await.unwrap(); + self.engine + .observe(id, Observation::Running { started_at: None }) + .unwrap(); + assert_eq!(self.status(id), "running"); + } + + fn status(&self, id: &str) -> String { + self.store().get_run(id).unwrap().unwrap().status + } + + fn contact(&self, id: &str) -> Contact { + self.store().engine_run_state(id).unwrap().unwrap().contact + } + + /// Freezes, reads and acknowledges the chat's next notice batch. + fn deliver(&self) -> Vec { + let store = self.store(); + let batch = store.run_notice_batch(CHAT).unwrap(); + if let Some(first) = batch.first() { + store + .mark_run_notice_batch_delivered(CHAT, &first.client_turn_id, 1) + .unwrap(); + } + batch + } + + fn kinds(&self) -> Vec { + self.deliver() + .into_iter() + .map(|notice| notice.kind) + .collect() + } + + fn events(&mut self) -> Vec { + std::iter::from_fn(|| self.events.try_recv().ok()).collect() + } + + fn phases(&mut self) -> Vec { + self.events() + .into_iter() + .filter_map(|event| match event { + RunEvent::Changed { phase, .. } => Some(phase), + _ => None, + }) + .collect() + } + + /// Waits until no process holds the run's locks. A dropped lock lingers in any child a + /// parallel test forked meanwhile, until that child execs, which load can stretch. + fn released(&self, id: &str) { + released(&self.store().supervisor_lock_paths(id).unwrap()); + } + + fn locked(&self, id: &str) -> bool { + self.store() + .supervisor_lock_paths(id) + .unwrap() + .iter() + .all(|path| { + matches!( + lock_file(path).try_lock(), + Err(std::fs::TryLockError::WouldBlock) + ) + }) + } + + fn legacy_run(&self, id: &str, backend_json: &str) { + self.store() + .upsert_run(&StoredRun { + id: id.into(), + experiment_id: "exp".into(), + project_id: "proj".into(), + status: "running".into(), + backend_json: backend_json.into(), + command: "train".into(), + created_at: 1, + updated_at: 1, + ended_at: None, + exit_code: None, + commit_sha: None, + result_markdown: None, + cancel_requested: false, + cancel_reason: None, + chat_session_id: Some(CHAT.into()), + }) + .unwrap(); + } +} + +impl Drop for Fixture { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.dir); + } +} + +fn released(paths: &[PathBuf]) { + let free = || paths.iter().all(|path| lock_file(path).try_lock().is_ok()); + let deadline = std::time::Instant::now() + Duration::from_secs(10); + while !free() { + assert!( + std::time::Instant::now() < deadline, + "{paths:?} stayed locked" + ); + std::thread::sleep(Duration::from_millis(1)); + } +} + +fn lock_file(path: &std::path::Path) -> std::fs::File { + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::OpenOptions::new() + .create(true) + .truncate(false) + .write(true) + .open(path) + .unwrap() +} + +fn ssh_launch() -> LaunchSpec { + LaunchSpec { + kind: "ssh_job".into(), + target: Some("lab".into()), + options: serde_json::json!({ "root": "/orx", "container": null }), + } +} + +fn handle() -> Handle { + Handle::Ssh { + host: "lab".into(), + root: "/orx".into(), + } +} + +fn unreconciled(contact: &Contact) -> bool { + matches!(contact, Contact::Unreconciled { .. }) +} + +#[tokio::test] +async fn phase_moves_only_forward_and_one_terminal_notice_survives_a_crash() { + let mut f = Fixture::new(); + f.backend.then_launch(Ok(handle())); + f.submit("run").await.unwrap(); + assert_eq!(f.status("run"), "starting"); + assert!(f.locked("run")); + let row = f.store().get_run("run").unwrap().unwrap(); + assert!(matches!(handle_of(&row), Some(Handle::Ssh { .. }))); + + f.engine + .observe("run", Observation::Running { started_at: None }) + .unwrap(); + f.engine + .observe( + "run", + Observation::Queued { + detail: "late".into(), + }, + ) + .unwrap(); + assert_eq!(f.status("run"), "running"); + f.engine + .observe( + "run", + Observation::Exited { + finished_at: None, + code: Some(3), + signal: None, + }, + ) + .unwrap(); + f.engine + .observe("run", Observation::Running { started_at: None }) + .unwrap(); + f.engine + .observe( + "run", + Observation::Cancelled { + finished_at: None, + code: None, + signal: None, + }, + ) + .unwrap(); + let row = f.store().get_run("run").unwrap().unwrap(); + assert_eq!((row.status.as_str(), row.exit_code), ("failed", Some(3))); + assert_eq!(f.phases(), [Phase::Starting, Phase::Running, Phase::Failed]); + f.released("run"); + + // Crash after the transition committed, before the notice was delivered. + f.restart(); + f.engine + .observe( + "run", + Observation::Exited { + finished_at: None, + code: Some(0), + signal: None, + }, + ) + .unwrap(); + let batch = f.store().run_notice_batch(CHAT).unwrap(); + assert_eq!(batch.len(), 1); + assert_eq!(batch[0].kind, TERMINAL); + assert!(batch[0].body.contains("**failed**")); + // Crash after the batch was frozen and sent, before it was marked delivered. + f.restart(); + f.engine + .observe("run", Observation::Lost { reason: "?".into() }) + .unwrap(); + assert_eq!(f.deliver(), batch); + assert!(f.deliver().is_empty()); + assert!(f.phases().is_empty()); +} + +#[tokio::test] +async fn a_frozen_batch_keeps_its_members_and_later_notices_wait_for_the_next() { + let f = Fixture::new(); + f.running("a").await; + f.running("b").await; + f.engine + .observe( + "a", + Observation::Exited { + finished_at: None, + code: Some(0), + signal: None, + }, + ) + .unwrap(); + let store = f.store(); + let frozen = store.run_notice_batch(CHAT).unwrap(); + f.engine + .observe( + "b", + Observation::Exited { + finished_at: None, + code: Some(0), + signal: None, + }, + ) + .unwrap(); + assert_eq!(store.run_notice_batch(CHAT).unwrap(), frozen); + assert_eq!(f.deliver(), frozen); + let next = f.deliver(); + assert_eq!(next.len(), 1); + assert_eq!(next[0].run_id, "b"); +} + +#[tokio::test] +async fn contact_never_moves_the_phase_and_raises_one_attention_per_outage() { + let f = Fixture::new(); + f.running("run").await; + let start = f.clock.wall_ms(); + f.engine + .observe( + "run", + Observation::Unreachable { + cause: "eof".into(), + }, + ) + .unwrap(); + f.clock.advance(Duration::from_secs(9 * 60)); + f.engine + .observe( + "run", + Observation::Unreachable { + cause: "timeout".into(), + }, + ) + .unwrap(); + f.engine.check_outages().unwrap(); + assert_eq!( + f.contact("run"), + Contact::Unreachable { + since: start, + cause: "timeout".into() + } + ); + assert!(f.kinds().is_empty()); + f.clock.advance(Duration::from_secs(60)); + f.engine.check_outages().unwrap(); + f.engine.check_outages().unwrap(); + f.engine + .observe( + "run", + Observation::NeedsAuth { + cause: "denied".into(), + }, + ) + .unwrap(); + assert_eq!(f.status("run"), "running"); + assert_eq!(f.kinds(), [ATTENTION]); + + f.engine + .observe("run", Observation::Running { started_at: None }) + .unwrap(); + assert_eq!(f.contact("run"), Contact::Live); + assert_eq!(f.kinds(), [RECOVERED]); + + // The next outage is a new one; an attention resolved before it was sent is withdrawn. + f.engine + .observe( + "run", + Observation::NeedsAuth { + cause: "denied".into(), + }, + ) + .unwrap(); + f.engine + .observe("run", Observation::Running { started_at: None }) + .unwrap(); + assert!(f.kinds().is_empty()); + f.engine + .observe( + "run", + Observation::Unreconciled { + detail: "wrapper died".into(), + }, + ) + .unwrap(); + let attention = f.deliver(); + assert_eq!(attention.len(), 1); + assert!(attention[0].body.contains("wrapper died")); + assert_eq!(f.status("run"), "running"); +} + +#[tokio::test] +async fn cancel_before_any_side_effect_is_immediate() { + let f = Fixture::new(); + let metadata = BackendDescriptor::parse(r#"{"kind":"ssh_job"}"#).unwrap(); + for id in ["api", "refused"] { + f.store() + .insert_submitting_run(SubmittingRun { + id, + experiment_id: "exp", + project_id: "proj", + metadata: &metadata, + command: "train", + created_at: 1, + commit_sha: None, + chat_session_id: Some(CHAT), + spec_digest: "spec", + launch: &ssh_launch(), + }) + .unwrap(); + } + assert!(f.engine.cancel(&f.backend, "api", "user").await.unwrap()); + assert_eq!(f.status("api"), "cancelled"); + // An engine restarting between the intent and the fence finds the cancel and never launches. + f.store() + .accept_run_cancel("refused", Some("user")) + .unwrap(); + f.engine.recover(&f.backend, "refused").await.unwrap(); + assert_eq!(f.status("refused"), "cancelled"); + assert!(f.backend.calls().is_empty()); + assert!(!f.engine.cancel(&f.backend, "api", "again").await.unwrap()); +} + +#[tokio::test] +async fn cancel_during_submission_rides_the_launch() { + let f = Fixture::new(); + let dir = f.dir.clone(); + *f.backend.during_launch.lock().unwrap() = Some(Box::new(move || { + let store = Store::open_at(dir).unwrap(); + store + .accept_run_cancel("run", Some("user")) + .unwrap() + .unwrap(); + })); + f.backend + .then_launch(Ok(handle())) + .then_cancel(CancelOutcome::Pending); + f.submit("run").await.unwrap(); + assert_eq!(f.status("run"), "starting"); + assert_eq!(f.backend.calls(), ["launch run #1", "cancel run Ssh"]); + f.engine + .observe( + "run", + Observation::Cancelled { + finished_at: None, + code: None, + signal: None, + }, + ) + .unwrap(); + assert_eq!(f.status("run"), "cancelled"); +} + +#[tokio::test] +async fn an_unknown_submission_stays_unreconciled_with_backoff_until_recovery_decides() { + let f = Fixture::new(); + f.backend + .then_launch(Err(LaunchError::Interrupted { + detail: "lost".into(), + })) + .then_recover(Recovery::Unknown { + detail: "host down".into(), + }); + f.submit("run").await.unwrap(); + assert_eq!(f.status("run"), "submitting"); + assert!(unreconciled(&f.contact("run"))); + assert_eq!(f.kinds(), [ATTENTION]); + + assert!(f.engine.cancel(&f.backend, "run", "user").await.unwrap()); + f.engine.recover(&f.backend, "run").await.unwrap(); + assert_eq!(f.backend.calls().len(), 2); + f.clock.advance(Duration::from_secs(5)); + f.backend.then_recover(Recovery::Unknown { + detail: "still down".into(), + }); + f.engine.recover(&f.backend, "run").await.unwrap(); + f.clock.advance(Duration::from_secs(14)); + f.engine.recover(&f.backend, "run").await.unwrap(); + assert_eq!(f.backend.calls().len(), 3); + assert_eq!(f.status("run"), "submitting"); + + f.clock.advance(Duration::from_secs(1)); + f.backend + .then_recover(Recovery::Found(handle())) + .then_cancel(CancelOutcome::Verified); + f.engine.recover(&f.backend, "run").await.unwrap(); + assert_eq!(f.status("run"), "cancelled"); + assert_eq!(f.contact("run"), Contact::Live); + assert_eq!( + f.backend.calls(), + [ + "launch run #1", + "recover run #1", + "recover run #1", + "recover run #1", + "cancel run Ssh" + ] + ); +} + +#[tokio::test] +async fn absent_relaunches_the_next_attempt_unless_cancelled() { + let f = Fixture::new(); + f.backend + .then_launch(Err(LaunchError::Interrupted { + detail: "lost".into(), + })) + .then_recover(Recovery::Absent) + .then_launch(Ok(handle())); + f.submit("relaunched").await.unwrap(); + assert_eq!(f.status("relaunched"), "starting"); + assert_eq!( + f.backend.calls(), + [ + "launch relaunched #1", + "recover relaunched #1", + "launch relaunched #2" + ] + ); + + f.backend + .then_launch(Err(LaunchError::Interrupted { + detail: "lost".into(), + })) + .then_recover(Recovery::Unknown { detail: "?".into() }); + f.submit("cancelled").await.unwrap(); + f.engine + .cancel(&f.backend, "cancelled", "user") + .await + .unwrap(); + f.clock.advance(Duration::from_secs(5)); + f.backend.then_recover(Recovery::Absent); + f.engine.recover(&f.backend, "cancelled").await.unwrap(); + assert_eq!(f.status("cancelled"), "cancelled"); + + f.backend.then_launch(Err(LaunchError::Rejected { + reason: "no such host".into(), + })); + f.submit("rejected").await.unwrap(); + let row = f.store().get_run("rejected").unwrap().unwrap(); + assert_eq!(row.status, "failed"); + assert_eq!(row.result_markdown.as_deref(), Some("no such host")); + assert_eq!( + f.backend + .calls() + .iter() + .filter(|c| c.starts_with("launch")) + .count(), + 4 + ); +} + +#[tokio::test] +async fn a_relaunch_interrupted_again_waits_out_the_backoff_with_the_launch_error() { + let f = Fixture::new(); + let interrupted = || { + Err(LaunchError::Interrupted { + detail: "disk full".into(), + }) + }; + f.backend + .then_launch(interrupted()) + .then_recover(Recovery::Absent) + .then_launch(interrupted()); + f.submit("run").await.unwrap(); + assert!( + matches!(f.contact("run"), Contact::Unreconciled { detail, .. } if detail == "The launch failed: disk full") + ); + assert_eq!(f.kinds(), [ATTENTION]); + + f.engine.recover(&f.backend, "run").await.unwrap(); + assert_eq!(f.backend.calls().len(), 3); + + f.clock.advance(Duration::from_secs(5)); + f.backend + .then_recover(Recovery::Absent) + .then_launch(Ok(handle())); + f.engine.recover(&f.backend, "run").await.unwrap(); + assert_eq!(f.status("run"), "starting"); + assert_eq!( + f.backend.calls(), + [ + "launch run #1", + "recover run #1", + "launch run #2", + "recover run #2", + "launch run #3" + ] + ); +} + +#[cfg(unix)] +#[tokio::test] +async fn recovery_waits_out_a_recorded_submitter_before_asking_the_backend() { + let f = Fixture::new(); + let mut child = crate::process::command("sleep").arg("60").spawn().unwrap(); + *f.backend.submitter.lock().unwrap() = Some(child.id()); + f.backend + .then_launch(Err(LaunchError::Interrupted { + detail: "lost".into(), + })) + .then_recover(Recovery::Found(handle())); + f.submit("run").await.unwrap(); + let fence = f + .store() + .engine_run_state("run") + .unwrap() + .unwrap() + .submission_fence; + assert_eq!(fence.unwrap().submitter.unwrap().pid, child.id()); + assert!(child.try_wait().unwrap().is_some()); + assert_eq!(f.status("run"), "starting"); +} + +#[tokio::test] +async fn a_death_seen_while_a_cancel_is_verified_waits_for_the_verdict() { + let f = Fixture::new(); + f.running("run").await; + let mut events = f.engine.bus.subscribe(); + f.backend.then_cancel(CancelOutcome::Verified); + let cancel = f.engine.cancel(&f.backend, "run", "user"); + tokio::pin!(cancel); + assert!(futures::poll!(&mut cancel).is_pending()); + // Dashboards see the accepted cancel before the verdict. + assert!(matches!( + events.try_recv(), + Ok(RunEvent::Changed { + phase: Phase::Running, + cancelling: true, + .. + }) + )); + let died = Observation::Failed { + finished_at: None, + reason: "process died without an exit code".into(), + }; + f.engine.observe("run", died.clone()).unwrap(); + assert_eq!(f.status("run"), "running"); + assert!(cancel.await.unwrap()); + assert_eq!(f.status("run"), "cancelled"); + + // A delivery dropped before its verdict leaves observation in charge. + f.running("dropped").await; + f.backend.then_cancel(CancelOutcome::Verified); + { + let cancel = f.engine.cancel(&f.backend, "dropped", "user"); + tokio::pin!(cancel); + assert!(futures::poll!(&mut cancel).is_pending()); + } + f.engine.observe("dropped", died).unwrap(); + assert_eq!(f.status("dropped"), "failed"); +} + +/// A cancel registered between an observation's arrival and its terminal decision still wins. +#[tokio::test] +async fn a_cancel_registered_just_before_a_terminal_commit_is_honored() { + use futures::FutureExt; + let f = Fixture::new(); + f.running("run").await; + f.backend.then_cancel(CancelOutcome::Verified); + let (arrived, at_commit) = std::sync::mpsc::channel(); + let (proceed, go) = std::sync::mpsc::channel::<()>(); + f.engine.memory().before_observed_commit = Some(Box::new(move || { + arrived.send(()).unwrap(); + go.recv().unwrap(); + })); + let cancel = f.engine.cancel(&f.backend, "run", "user"); + tokio::pin!(cancel); + std::thread::scope(|scope| { + let observer = scope.spawn(|| { + let died = Observation::Failed { + finished_at: None, + reason: "process died without an exit code".into(), + }; + f.engine.observe("run", died).unwrap() + }); + at_commit.recv().unwrap(); + // The cancel registers and parks in the backend while the observation waits to commit. + assert!(cancel.as_mut().now_or_never().is_none()); + proceed.send(()).unwrap(); + observer.join().unwrap(); + }); + assert_eq!(f.status("run"), "running"); + assert!(cancel.await.unwrap()); + assert_eq!(f.status("run"), "cancelled"); +} + +#[tokio::test] +async fn cancel_while_unreachable_is_held_until_reconnect_and_sent_once_per_connection() { + let mut f = Fixture::new(); + f.running("run").await; + f.engine + .observe( + "run", + Observation::Unreachable { + cause: "eof".into(), + }, + ) + .unwrap(); + f.events(); + assert!(f.engine.cancel(&f.backend, "run", "user").await.unwrap()); + f.engine.deliver_cancel(&f.backend, "run").await.unwrap(); + assert!(f + .backend + .calls() + .iter() + .all(|call| !call.starts_with("cancel"))); + + f.engine + .observe("run", Observation::Running { started_at: None }) + .unwrap(); + assert!(f.events().iter().any(|event| matches!( + event, + RunEvent::Changed { + cancelling: true, + contact: Contact::Live, + .. + } + ))); + f.backend.then_cancel(CancelOutcome::Survivors { count: 1 }); + f.engine.deliver_cancel(&f.backend, "run").await.unwrap(); + f.engine.deliver_cancel(&f.backend, "run").await.unwrap(); + assert_eq!(f.status("run"), "cancelled"); + assert!(matches!( + f.contact("run"), + Contact::Stopping { count: 1, .. } + )); + assert_eq!(f.kinds(), [TERMINAL]); + + f.engine + .observe( + "run", + Observation::Unreachable { + cause: "eof".into(), + }, + ) + .unwrap(); + f.engine + .observe("run", Observation::Running { started_at: None }) + .unwrap(); + f.backend.then_cancel(CancelOutcome::Verified); + f.engine.deliver_cancel(&f.backend, "run").await.unwrap(); + assert_eq!(f.status("run"), "cancelled"); + let cancels = f + .backend + .calls() + .iter() + .filter(|c| c.starts_with("cancel")) + .count(); + assert_eq!(cancels, 2); + assert_eq!(f.kinds(), [ATTENTION]); +} + +#[tokio::test] +async fn a_verified_cancel_receipt_keeps_its_exit_code() { + let f = Fixture::new(); + f.running("run").await; + f.backend.then_cancel(CancelOutcome::Pending); + f.engine + .cancel(&f.backend, "run", "Cancel requested with `orx exp cancel`.") + .await + .unwrap(); + f.engine + .observe( + "run", + Observation::Cancelled { + finished_at: None, + code: Some(0), + signal: None, + }, + ) + .unwrap(); + let row = f.store().get_run("run").unwrap().unwrap(); + assert_eq!((row.status.as_str(), row.exit_code), ("cancelled", Some(0))); + let body = &f.deliver()[0].body; + assert!(body.contains("Exit code: 0\n")); + assert!(body.contains("Reason: Cancel requested with `orx exp cancel`.\n")); +} + +#[tokio::test] +async fn accepted_cancels_classify_nonzero_exits_after_restart() { + for handle in [ + super::adapters::api::test_handle("ray_job", None, None, vec!["job".into()]), + Handle::Legacy { + descriptor: Box::new( + BackendDescriptor::parse(r#"{"kind":"ray_job","jobId":"job"}"#).unwrap(), + ), + }, + ] { + for (requested, code, signal, status) in [ + (true, Some(137), None, "cancelled"), + (false, Some(137), None, "failed"), + (true, Some(0), None, "done"), + (true, None, Some(9), "cancelled"), + ] { + let mut f = Fixture::new(); + f.backend.then_launch(Ok(handle.clone())); + f.submit("run").await.unwrap(); + f.engine + .observe("run", Observation::Running { started_at: None }) + .unwrap(); + if requested { + assert!(f + .store() + .accept_run_cancel("run", Some("Dashboard stop")) + .unwrap() + .is_some()); + } + f.restart(); + f.engine + .observe( + "run", + Observation::Exited { + finished_at: Some(123), + code, + signal, + }, + ) + .unwrap(); + + let row = f.store().get_run("run").unwrap().unwrap(); + assert_eq!(row.status, status); + assert_eq!(row.exit_code, code.map(i64::from)); + assert_eq!(row.ended_at, Some(123)); + } + } +} + +#[tokio::test] +async fn accepted_cancels_do_not_replace_wrapper_or_legacy_stop_proof() { + for legacy in [false, true] { + let f = Fixture::new(); + if legacy { + f.legacy_run("run", r#"{"kind":"ssh_job","jobId":"/orx/run"}"#); + } else { + f.running("run").await; + } + f.store().accept_run_cancel("run", Some("stop")).unwrap(); + f.engine + .observe("run", Observation::Lingering { pids: vec![42] }) + .unwrap(); + f.engine + .observe( + "run", + Observation::Exited { + finished_at: None, + code: Some(137), + signal: None, + }, + ) + .unwrap(); + assert_eq!(f.status("run"), "failed"); + let notices = f.deliver(); + assert_eq!(notices.len(), 2); + assert!(notices + .iter() + .any(|notice| notice.body.contains("lingering processes [42]"))); + assert!(notices + .iter() + .all(|notice| !notice.body.contains("Cancelled"))); + } +} + +#[tokio::test] +async fn nonzero_exit_after_abandon_keeps_cleanup_pending() { + let mut f = Fixture::new(); + f.running("run").await; + assert!(f.engine.abandon("run").unwrap()); + f.restart(); + f.engine + .observe( + "run", + Observation::Exited { + finished_at: None, + code: Some(137), + signal: None, + }, + ) + .unwrap(); + + assert_eq!(f.status("run"), "lost"); + assert!(unreconciled(&f.contact("run"))); +} + +#[tokio::test] +async fn an_unreconciled_run_keeps_its_since_across_a_restart() { + let mut f = Fixture::new(); + f.running("run").await; + let unverified = || Observation::Unreconciled { + detail: "wrapper gone".into(), + }; + f.engine.observe("run", unverified()).unwrap(); + let before = f.contact("run"); + assert!(unreconciled(&before)); + f.clock.advance(Duration::from_secs(60)); + f.restart(); + f.engine.observe("run", unverified()).unwrap(); + assert_eq!(f.contact("run"), before); +} + +#[tokio::test] +async fn abandon_tells_the_chat_once_and_keeps_the_kill_pending_until_the_job_is_gone() { + let f = Fixture::new(); + f.backend + .then_launch(Err(LaunchError::Interrupted { + detail: "lost".into(), + })) + .then_recover(Recovery::Unknown { + detail: "host down".into(), + }); + f.submit("unsubmitted").await.unwrap(); + f.deliver(); + assert!(f.engine.abandon("unsubmitted").unwrap()); + assert!(!f.engine.abandon("unsubmitted").unwrap()); + assert_eq!(f.status("unsubmitted"), "lost"); + let abandoned = f.store().get_run("unsubmitted").unwrap().unwrap(); + assert_eq!( + abandoned.result_markdown.as_deref(), + Some("Abandoned; the cancel stays pending until the job is confirmed gone.") + ); + assert!(f + .store() + .terminal_notice_body(&abandoned) + .unwrap() + .contains("Reason: Abandoned; the cancel stays pending until the job is confirmed gone.")); + assert!(f.locked("unsubmitted")); + f.clock.advance(Duration::from_secs(5)); + f.backend + .then_recover(Recovery::Found(handle())) + .then_cancel(CancelOutcome::Verified); + f.engine.recover(&f.backend, "unsubmitted").await.unwrap(); + assert_eq!(f.contact("unsubmitted"), Contact::Live); + f.released("unsubmitted"); + + f.running("submitted").await; + assert!(f.engine.abandon("submitted").unwrap()); + f.backend.then_cancel(CancelOutcome::Undelivered { + detail: "environ unreadable".into(), + }); + f.engine + .deliver_cancel(&f.backend, "submitted") + .await + .unwrap(); + assert!( + matches!(f.contact("submitted"), Contact::Unreconciled { detail, .. } if detail == super::reconcile::ABANDONED) + ); + // Terminal evidence is not proof of absence: exits and failures keep the kill pending. + for observation in [ + Observation::Running { started_at: None }, + Observation::Exited { + finished_at: None, + code: Some(0), + signal: None, + }, + Observation::Failed { + finished_at: None, + reason: "receipt unreadable".into(), + }, + Observation::Lost { + reason: "no receipt".into(), + }, + ] { + f.engine.observe("submitted", observation).unwrap(); + assert!(unreconciled(&f.contact("submitted"))); + assert!(f.locked("submitted")); + } + f.engine + .observe( + "submitted", + Observation::Cancelled { + finished_at: None, + code: None, + signal: None, + }, + ) + .unwrap(); + let row = f.store().get_run("submitted").unwrap().unwrap(); + assert_eq!(row.status, "lost"); + assert_eq!(f.contact("submitted"), Contact::Live); + f.released("submitted"); + + let terminal: Vec<_> = f + .deliver() + .into_iter() + .map(|notice| notice.run_id) + .collect(); + assert_eq!(terminal, ["unsubmitted", "submitted"]); +} + +#[tokio::test] +async fn runs_an_old_supervisor_holds_are_watched_and_never_written() { + let f = Fixture::new(); + f.legacy_run("held", r#"{"kind":"ssh_job","jobId":"/orx/runs/held"}"#); + let [supervisor, shared] = f.store().supervisor_lock_paths("held").unwrap(); + let old_supervisor = [supervisor, shared].map(|path| { + let file = lock_file(&path); + file.try_lock().unwrap(); + file + }); + f.legacy_run( + "ssh", + r#"{"kind":"ssh_job","jobId":"/orx/runs/ssh","sshContainer":{"reference":"img","id":"c1","startedAt":"t","runDir":"/orx/runs/ssh"}}"#, + ); + f.legacy_run( + "box", + r#"{"kind":"openresearch_job","namespace":"org","jobId":"sb"}"#, + ); + f.legacy_run("hf", r#"{"kind":"hf_job","namespace":"lab","jobId":"j"}"#); + f.legacy_run("submitting", r#"{"kind":"modal_job"}"#); + f.legacy_run("mystery", r#"{"kind":"future_job","jobId":"x"}"#); + f.running("engine").await; + + let mut decisions = f.engine.scan_legacy(true).unwrap(); + decisions.sort_by(|a, b| a.0.cmp(&b.0)); + let container = match &decisions[3].1 { + Adoption::Inspect { container, .. } => container.clone(), + other => panic!("{other:?}"), + }; + assert_eq!( + decisions, + [ + ("box".to_string(), Adoption::Loop), + ("held".to_string(), Adoption::Watch), + ( + "hf".to_string(), + Adoption::Native { + kind: "hf_job".into() + } + ), + ( + "ssh".to_string(), + Adoption::Inspect { + dir: "/orx/runs/ssh".into(), + container + } + ), + ] + ); + assert!(f.locked("ssh") && f.locked("box") && f.locked("hf")); + assert!(f + .engine + .scan_legacy(true) + .unwrap() + .iter() + .all(|(id, _)| id == "held")); + + let before = f.store().get_run("held").unwrap().unwrap(); + f.engine + .observe( + "held", + Observation::Exited { + finished_at: None, + code: Some(0), + signal: None, + }, + ) + .unwrap(); + assert!(!f.engine.abandon("held").unwrap()); + f.store().request_cancel("held", "old CLI").unwrap(); + f.engine.deliver_cancel(&f.backend, "held").await.unwrap(); + let after = f.store().get_run("held").unwrap().unwrap(); + assert_eq!(after.status, before.status); + assert!(f + .store() + .engine_run_state("held") + .unwrap() + .unwrap() + .cancel_accepted_at + .is_none()); + assert!(f.backend.calls().iter().all(|call| !call.contains("held"))); + + // The old supervisor finishes the run; the engine only tells the chat. + f.store() + .update_status("held", crate::store::RunStatus::Done, Some(5), Some(0)) + .unwrap(); + drop(old_supervisor); + f.released("held"); + f.engine.scan_legacy(true).unwrap(); + let notices = f.deliver(); + assert_eq!(notices.len(), 1); + assert_eq!( + (notices[0].run_id.as_str(), notices[0].kind.as_str()), + ("held", TERMINAL) + ); + f.engine.scan_legacy(true).unwrap(); + assert!(f.deliver().is_empty()); + f.released("held"); +} + +#[tokio::test] +async fn an_old_cli_cancel_is_accepted_once_under_its_lock_and_survives_withdrawal() { + let f = Fixture::new(); + for id in ["pending", "verified"] { + f.legacy_run( + id, + &format!(r#"{{"kind":"ssh_job","jobId":"/orx/runs/{id}"}}"#), + ); + } + f.engine.scan_legacy(true).unwrap(); + let old_cli = |id: &str, act: &dyn Fn(&Store)| { + let path = f.dir.join(format!("run-logs/{id}.cancel.lock")); + let mut lock = crate::store::open_lifecycle_lock_at(&path).unwrap(); + let _guard = lock.write().unwrap(); + act(&f.store()); + }; + + old_cli("pending", &|store| { + assert!(store.request_cancel("pending", "old CLI").unwrap()); + }); + f.backend.then_cancel(CancelOutcome::Pending); + f.engine + .deliver_cancel(&f.backend, "pending") + .await + .unwrap(); + // The old CLI's supervisor spawn failed, so it withdraws; the engine already started. + old_cli("pending", &|store| { + store.withdraw_cancel("pending").unwrap() + }); + for _ in 0..3 { + f.engine + .deliver_cancel(&f.backend, "pending") + .await + .unwrap(); + } + assert_eq!(f.backend.calls(), ["cancel pending Legacy"]); + f.engine + .observe( + "pending", + Observation::Cancelled { + finished_at: None, + code: None, + signal: None, + }, + ) + .unwrap(); + assert_eq!(f.status("pending"), "cancelled"); + + old_cli("verified", &|store| { + assert!(store.request_cancel("verified", "old CLI").unwrap()); + }); + f.backend.then_cancel(CancelOutcome::Verified); + f.engine + .deliver_cancel(&f.backend, "verified") + .await + .unwrap(); + let row = f.store().get_run("verified").unwrap().unwrap(); + assert_eq!(row.status, "cancelled"); + assert!(row.result_markdown.unwrap().contains("OR-469")); +} + +#[tokio::test] +async fn reordered_feed_reports_never_move_a_phase_backwards() { + let f = Fixture::new(); + f.running("run").await; + f.running("other").await; + f.backend.feed.lock().unwrap().extend([ + ( + "run".to_string(), + Observation::Exited { + finished_at: None, + code: Some(0), + signal: None, + }, + ), + ( + "unwatched".to_string(), + Observation::Running { started_at: None }, + ), + ("run".to_string(), Observation::Running { started_at: None }), + ( + "other".to_string(), + Observation::Failed { + finished_at: None, + reason: "OOM".into(), + }, + ), + ( + "run".to_string(), + Observation::Queued { + detail: "stale".into(), + }, + ), + ]); + let watched: Vec<_> = ["run", "other"] + .iter() + .map(|id| WatchedRun { + id: id.to_string(), + handle: handle_of(&f.store().get_run(id).unwrap().unwrap()).unwrap(), + }) + .collect(); + let feed = f.backend.observe(&watched, Duration::from_secs(25)).await; + assert_eq!(feed.len(), 4); + for (id, observation) in feed { + f.engine.observe(&id, observation).unwrap(); + } + assert_eq!(f.status("run"), "done"); + let other = f.store().get_run("other").unwrap().unwrap(); + assert_eq!( + (other.status.as_str(), other.result_markdown.as_deref()), + ("failed", Some("OOM")) + ); +} + +#[tokio::test] +async fn a_restart_between_fence_and_launch_recovers_from_the_persisted_intent() { + let mut f = Fixture::new(); + let metadata = BackendDescriptor::parse(r#"{"kind":"ssh_job"}"#).unwrap(); + let store = f.store(); + store + .insert_submitting_run(SubmittingRun { + id: "run", + experiment_id: "exp", + project_id: "proj", + metadata: &metadata, + command: "train", + created_at: 1, + commit_sha: None, + chat_session_id: Some(CHAT), + spec_digest: "spec", + launch: &ssh_launch(), + }) + .unwrap(); + let fence = SubmissionFence { + taken_at: 1, + submitter: None, + }; + assert!(store.set_submission_fence("run", 1, &fence).unwrap()); + + f.restart(); + f.backend + .then_recover(Recovery::Absent) + .then_launch(Ok(handle())); + f.engine.recover(&f.backend, "run").await.unwrap(); + assert_eq!(f.backend.calls(), ["recover run #1", "launch run #2"]); + assert_eq!( + *f.backend.intents.lock().unwrap(), + [ssh_launch(), ssh_launch()] + ); + assert_eq!(f.status("run"), "starting"); +} + +#[tokio::test] +async fn notify_bytes_become_at_most_one_notice_per_ten_minutes_and_coalesce() { + let mut f = Fixture::new(); + f.running("run").await; + let write = |f: &Fixture, text: &str| { + let mut notify = f.backend.notify.lock().unwrap(); + notify.bytes.extend_from_slice(text.as_bytes()); + let len = notify.bytes.len() as u64; + drop(notify); + f.engine + .observe("run", Observation::Notify { len }) + .unwrap(); + }; + + write(&f, "epoch 1: loss 0.9"); + assert_eq!(f.engine.notify_due().unwrap(), ["run"]); + f.engine.deliver_notify(&f.backend, "run").await.unwrap(); + write(&f, "\nepoch 2: loss 0.5"); + f.engine.deliver_notify(&f.backend, "run").await.unwrap(); + f.clock.advance(Duration::from_secs(9 * 60)); + write(&f, "\nepoch 3: loss 0.2"); + assert!(f.engine.notify_due().unwrap().is_empty()); + f.engine.deliver_notify(&f.backend, "run").await.unwrap(); + let first = f.deliver(); + assert_eq!(first.len(), 1); + assert_eq!(first[0].kind, NOTIFY); + assert!(first[0].body.ends_with("epoch 1: loss 0.9")); + + f.clock.advance(Duration::from_secs(60)); + assert_eq!(f.engine.notify_due().unwrap(), ["run"]); + f.engine.deliver_notify(&f.backend, "run").await.unwrap(); + let coalesced = f.deliver(); + assert_eq!(coalesced.len(), 1); + assert!(coalesced[0] + .body + .ends_with("wrote to its notify file:\n\nepoch 2: loss 0.5\nepoch 3: loss 0.2")); + + // The cursor is durable: a restarted engine re-reported the same length sends nothing. + f.restart(); + f.clock.advance(Duration::from_secs(10 * 60)); + let len = f.backend.notify.lock().unwrap().bytes.len() as u64; + f.engine + .observe("run", Observation::Notify { len }) + .unwrap(); + f.engine.deliver_notify(&f.backend, "run").await.unwrap(); + assert!(f.engine.notify_due().unwrap().is_empty()); + + // A replaced file starts over, and only its tail is quoted. + let long = "x".repeat(5000) + "tail"; + *f.backend.notify.lock().unwrap() = HostFile { + bytes: Vec::new(), + ino: 1, + }; + write(&f, &long); + f.engine.deliver_notify(&f.backend, "run").await.unwrap(); + let restarted = f.deliver(); + assert_eq!(restarted.len(), 1); + assert!(restarted[0] + .body + .contains("tail\n(908 earlier bytes omitted; see the file.)")); + + // A same-size replacement and a truncation below the cursor are both new files. + let replaced = "y".repeat(5000) + "tail"; + f.clock.advance(Duration::from_secs(10 * 60)); + *f.backend.notify.lock().unwrap() = HostFile { + bytes: Vec::new(), + ino: 2, + }; + write(&f, &replaced); + f.engine.deliver_notify(&f.backend, "run").await.unwrap(); + let same_size = f.deliver(); + assert_eq!(same_size.len(), 1); + assert!(same_size[0].body.contains("yyyytail")); + assert_ne!(same_size[0].dedupe, restarted[0].dedupe); + + f.clock.advance(Duration::from_secs(10 * 60)); + *f.backend.notify.lock().unwrap() = HostFile { + bytes: Vec::new(), + ino: 3, + }; + write(&f, "short"); + f.engine.deliver_notify(&f.backend, "run").await.unwrap(); + let truncated = f.deliver(); + assert_eq!(truncated.len(), 1); + assert!(truncated[0].body.ends_with("notify file:\nshort")); + assert!(f.deliver().is_empty()); +} + +#[tokio::test] +async fn concurrent_notify_deliveries_send_one_notice() { + let f = Fixture::new(); + f.running("run").await; + f.backend.notify.lock().unwrap().bytes = b"done".to_vec(); + f.engine + .observe("run", Observation::Notify { len: 4 }) + .unwrap(); + let (a, b) = tokio::join!( + f.engine.deliver_notify(&f.backend, "run"), + f.engine.deliver_notify(&f.backend, "run"), + ); + a.unwrap(); + b.unwrap(); + f.backend + .notify + .lock() + .unwrap() + .bytes + .extend_from_slice(b" again"); + f.engine + .observe("run", Observation::Notify { len: 10 }) + .unwrap(); + f.engine.deliver_notify(&f.backend, "run").await.unwrap(); + assert_eq!(f.deliver().len(), 1); + let cursor = f + .store() + .engine_run_state("run") + .unwrap() + .unwrap() + .notify_cursor; + assert_eq!(cursor.unwrap().offset, 4); +} + +#[tokio::test] +async fn concurrent_recoveries_never_act_on_a_stale_attempt() { + let f = Fixture::new(); + f.backend + .then_launch(Err(LaunchError::Interrupted { + detail: "lost".into(), + })) + .then_recover(Recovery::Unknown { detail: "?".into() }); + f.submit("run").await.unwrap(); + f.clock.advance(Duration::from_secs(5)); + let dir = f.dir.clone(); + *f.backend.during_launch.lock().unwrap() = Some(Box::new(move || { + let store = Store::open_at(dir).unwrap(); + store + .accept_run_cancel("run", Some("user")) + .unwrap() + .unwrap(); + })); + f.backend + .then_recover(Recovery::Absent) + .then_recover(Recovery::Absent) + .then_launch(Ok(handle())) + .then_cancel(CancelOutcome::Pending); + let (a, b) = tokio::join!( + f.engine.recover(&f.backend, "run"), + f.engine.recover(&f.backend, "run"), + ); + a.unwrap(); + b.unwrap(); + assert_eq!(f.status("run"), "starting"); + assert!(handle_of(&f.store().get_run("run").unwrap().unwrap()).is_some()); + assert_eq!( + f.backend.calls(), + [ + "launch run #1", + "recover run #1", + "recover run #1", + "launch run #2", + "cancel run Ssh" + ] + ); +} + +#[tokio::test] +async fn a_dropped_launch_leaves_the_run_recoverable() { + let f = Fixture::new(); + f.backend + .hang_launch + .store(true, std::sync::atomic::Ordering::SeqCst); + let dropped = tokio::time::timeout(Duration::from_millis(50), f.submit("run")).await; + assert!(dropped.is_err()); + assert_eq!(f.status("run"), "submitting"); + f.backend.then_recover(Recovery::Found(handle())); + f.engine.recover(&f.backend, "run").await.unwrap(); + assert_eq!(f.status("run"), "starting"); +} + +#[test] +fn legacy_adoption_waits_for_the_launch_to_settle_and_respects_the_current_mode() { + let f = Fixture::new(); + f.legacy_run("recent", r#"{"kind":"local_job","jobId":"job"}"#); + let mut run = f.store().get_run("recent").unwrap().unwrap(); + run.updated_at = f.clock.wall_ms(); + f.store().upsert_run(&run).unwrap(); + for enabled in [false, true] { + assert_eq!( + f.engine.scan_legacy(enabled).unwrap(), + [("recent".into(), Adoption::Watch)] + ); + assert!(!f.engine.holds("recent")); + } + f.clock.advance(Duration::from_millis( + u64::try_from(ORPHANED_RUN_SETTLE_MS).unwrap() - 1, + )); + assert_eq!( + f.engine.scan_legacy(true).unwrap(), + [("recent".into(), Adoption::Watch)] + ); + f.clock.advance(Duration::from_millis(1)); + assert_eq!( + f.engine.scan_legacy(false).unwrap(), + [("recent".into(), Adoption::Watch)] + ); + assert!(!f.engine.holds("recent")); + assert_eq!( + f.engine.scan_legacy(true).unwrap(), + [( + "recent".into(), + Adoption::Native { + kind: "local_job".into() + } + )] + ); + assert!(f.engine.holds("recent")); + assert!(f.engine.scan_legacy(false).unwrap().is_empty()); + assert!(f.engine.holds("recent")); +} + +#[tokio::test] +async fn an_old_supervisor_finishing_while_the_engine_is_down_still_reaches_the_chat() { + let mut f = Fixture::new(); + f.legacy_run("held", r#"{"kind":"ssh_job","jobId":"/orx/runs/held"}"#); + let old_supervisor = f + .store() + .supervisor_lock_paths("held") + .unwrap() + .map(|path| { + let file = lock_file(&path); + file.try_lock().unwrap(); + file + }); + assert_eq!( + f.engine.scan_legacy(true).unwrap(), + [("held".to_string(), Adoption::Watch)] + ); + + f.restart(); + f.store() + .update_status("held", crate::store::RunStatus::Failed, Some(5), Some(1)) + .unwrap(); + drop(old_supervisor); + f.released("held"); + assert!(f.engine.scan_legacy(true).unwrap().is_empty()); + let notices = f.deliver(); + assert_eq!(notices.len(), 1); + assert!(notices[0].body.contains("**failed**")); + f.restart(); + f.engine.scan_legacy(true).unwrap(); + assert!(f.deliver().is_empty()); +} + +#[tokio::test] +async fn a_supervisor_finishing_between_snapshot_and_adoption_still_reaches_the_chat() { + let f = Fixture::new(); + f.legacy_run("held", r#"{"kind":"ssh_job","jobId":"/orx/runs/held"}"#); + let old_supervisor = f + .store() + .supervisor_lock_paths("held") + .unwrap() + .map(|path| { + let file = lock_file(&path); + file.try_lock().unwrap(); + file + }); + assert_eq!( + f.engine.scan_legacy(true).unwrap(), + [("held".to_string(), Adoption::Watch)] + ); + + let dir = f.dir.clone(); + let paths = f.store().supervisor_lock_paths("held").unwrap(); + f.engine.memory().after_legacy_snapshot = Some(Box::new(move || { + Store::open_at(dir) + .unwrap() + .update_status("held", crate::store::RunStatus::Done, Some(5), Some(0)) + .unwrap(); + drop(old_supervisor); + released(&paths); + })); + assert!(f.engine.scan_legacy(true).unwrap().is_empty()); + let notices = f.deliver(); + assert_eq!(notices.len(), 1); + assert!(notices[0].body.contains("**done**")); + assert!(f.store().legacy_watches().unwrap().is_empty()); + f.released("held"); + f.engine.scan_legacy(true).unwrap(); + assert!(f.deliver().is_empty()); +} + +/// `echo msg > $ORX_NOTIFY_FILE` rewrites the file under the same inode: the shorter file is +/// read from its start, never as a tail of the old one, and nothing stays pending. +#[tokio::test] +async fn a_shorter_rewrite_in_place_is_read_from_its_start() { + let f = Fixture::new(); + f.running("run").await; + for text in ["epoch 1: loss 0.9\n", "done\n"] { + f.backend.notify.lock().unwrap().bytes = text.as_bytes().to_vec(); + let len = text.len() as u64; + f.engine + .observe("run", Observation::Notify { len }) + .unwrap(); + f.engine.deliver_notify(&f.backend, "run").await.unwrap(); + assert!(f.engine.notify_due().unwrap().is_empty()); + f.clock.advance(Duration::from_secs(10 * 60)); + } + let bodies: Vec<_> = f.deliver().into_iter().map(|notice| notice.body).collect(); + assert_eq!(bodies.len(), 2); + assert!(bodies[1].ends_with("notify file:\ndone\n"), "{}", bodies[1]); +} + +#[tokio::test] +async fn a_truncation_after_a_long_report_is_sent_once() { + let f = Fixture::new(); + f.running("run").await; + f.backend.notify.lock().unwrap().bytes = vec![b'x'; 5004]; + f.engine + .observe("run", Observation::Notify { len: 5004 }) + .unwrap(); + f.engine.deliver_notify(&f.backend, "run").await.unwrap(); + f.clock.advance(Duration::from_secs(10 * 60)); + f.engine + .observe("run", Observation::Notify { len: 5004 }) + .unwrap(); + // Shrinks after the report and before the read. + f.backend.notify.lock().unwrap().bytes = b"short".to_vec(); + f.engine.deliver_notify(&f.backend, "run").await.unwrap(); + for _ in 0..3 { + f.clock.advance(Duration::from_secs(10 * 60)); + assert!(f.engine.notify_due().unwrap().is_empty()); + f.engine.deliver_notify(&f.backend, "run").await.unwrap(); + } + let bodies: Vec<_> = f.deliver().into_iter().map(|notice| notice.body).collect(); + assert_eq!(bodies.len(), 2); + assert!(bodies[1].ends_with("notify file:\nshort")); +} + +#[tokio::test] +async fn a_cancel_without_acknowledgement_can_be_delivered_again() { + let f = Fixture::new(); + f.running("run").await; + f.backend.then_cancel(CancelOutcome::Undelivered { + detail: "scheduler unavailable".into(), + }); + f.engine.cancel(&f.backend, "run", "user").await.unwrap(); + assert_eq!(f.status("run"), "running"); + assert_eq!(f.contact("run"), Contact::Live); + f.backend.then_cancel(CancelOutcome::Verified); + f.engine.deliver_cancel(&f.backend, "run").await.unwrap(); + assert_eq!(f.status("run"), "cancelled"); + assert_eq!( + f.backend + .calls() + .iter() + .filter(|call| call.starts_with("cancel")) + .count(), + 2 + ); +} + +#[tokio::test] +async fn observing_a_run_without_cancel_intent_does_not_take_the_cancel_lock() { + let f = Fixture::new(); + f.running("run").await; + let path = f.dir.join("run-logs/run.cancel.lock"); + let (ready, locked) = std::sync::mpsc::channel(); + let (release, released) = std::sync::mpsc::channel(); + let holder = std::thread::spawn(move || { + let mut lock = crate::store::open_lifecycle_lock_at(&path).unwrap(); + let _guard = lock.write().unwrap(); + ready.send(()).unwrap(); + let _ = released.recv_timeout(Duration::from_secs(1)); + }); + locked.recv().unwrap(); + let began = std::time::Instant::now(); + f.engine + .observe_runs( + &f.backend, + &[WatchedRun { + id: "run".into(), + handle: handle(), + }], + Duration::ZERO, + ) + .await + .unwrap(); + let elapsed = began.elapsed(); + let _ = release.send(()); + holder.join().unwrap(); + assert!( + elapsed < Duration::from_millis(500), + "cancel lock blocked observation for {elapsed:?}" + ); +} + +#[tokio::test] +async fn launch_blocked_before_send_keeps_contact_and_retries_without_recovery() { + for contact in [ + Contact::NeedsAuth { + since: 1, + cause: "Permission denied (publickey)".into(), + }, + Contact::Unreachable { + since: 1, + cause: "Connection refused".into(), + }, + ] { + let mut f = Fixture::new(); + f.backend.then_launch(Err(LaunchError::Blocked { + contact: contact.clone(), + })); + f.submit("blocked").await.unwrap(); + assert_eq!(f.status("blocked"), "submitting"); + assert_eq!(f.contact("blocked"), contact); + assert!(f + .store() + .engine_run_state("blocked") + .unwrap() + .unwrap() + .submission_fence + .is_none()); + assert_eq!(f.backend.calls(), ["launch blocked #1"]); + f.restart(); + f.backend.then_launch(Ok(handle())); + f.engine.recover(&f.backend, "blocked").await.unwrap(); + assert_eq!(f.status("blocked"), "starting"); + assert_eq!(f.contact("blocked"), Contact::Live); + assert_eq!( + f.backend.calls(), + ["launch blocked #1", "launch blocked #1"] + ); + } +} + +#[tokio::test] +async fn cancelling_a_launch_blocked_before_send_needs_no_backend_confirmation() { + let f = Fixture::new(); + f.backend.then_launch(Err(LaunchError::Blocked { + contact: Contact::NeedsAuth { + since: 1, + cause: "Permission denied (publickey)".into(), + }, + })); + f.submit("blocked").await.unwrap(); + f.engine + .cancel(&f.backend, "blocked", "user") + .await + .unwrap(); + assert_eq!(f.status("blocked"), "cancelled"); + assert_eq!(f.backend.calls(), ["launch blocked #1"]); +} + +#[tokio::test] +async fn final_notify_survives_a_restart_inside_the_rate_window() { + let mut f = Fixture::new(); + f.running("run").await; + f.backend.notify.lock().unwrap().bytes = b"epoch 1\n".to_vec(); + f.engine + .observe("run", Observation::Notify { len: 8 }) + .unwrap(); + assert!(f.engine.deliver_notify(&f.backend, "run").await.unwrap()); + assert_eq!(f.kinds(), [NOTIFY]); + f.backend + .notify + .lock() + .unwrap() + .bytes + .extend_from_slice(b"final score 0.93\n"); + f.engine + .observe( + "run", + Observation::Exited { + finished_at: None, + code: Some(0), + signal: None, + }, + ) + .unwrap(); + assert!(f.store().log_collection_pending("run").unwrap()); + f.restart(); + assert!(f.engine.memory().notify.is_empty()); + assert!(f.engine.deliver_notify(&f.backend, "run").await.unwrap()); + let notices = f.deliver(); + assert_eq!( + notices + .iter() + .filter(|notice| notice.kind == TERMINAL) + .count(), + 1 + ); + let final_notice = notices.iter().find(|notice| notice.kind == NOTIFY).unwrap(); + assert!(final_notice.body.ends_with("final score 0.93\n")); + assert!(f.engine.deliver_notify(&f.backend, "run").await.unwrap()); + assert!(f.deliver().is_empty()); +} + +#[cfg(unix)] +#[tokio::test] +async fn a_submitter_without_a_readable_identity_cannot_cross_the_fence() { + let f = Fixture::new(); + let metadata = BackendDescriptor::parse(r#"{"kind":"ssh_job"}"#).unwrap(); + f.engine + .insert(SubmittingRun { + id: "run", + experiment_id: "exp", + project_id: "proj", + metadata: &metadata, + command: "train", + created_at: 1, + commit_sha: None, + chat_session_id: None, + spec_digest: "spec", + launch: &ssh_launch(), + }) + .unwrap(); + let fence = SubmissionFence { + taken_at: 1, + submitter: None, + }; + f.store().set_submission_fence("run", 1, &fence).unwrap(); + let fence = Fence { + store: &f.engine.store, + run_id: "run", + attempt: 1, + taken_at: 1, + }; + assert!(fence.record_submitter(u32::MAX).is_err()); + assert!(f + .store() + .engine_run_state("run") + .unwrap() + .unwrap() + .submission_fence + .unwrap() + .submitter + .is_none()); +} + +#[tokio::test] +async fn running_records_its_first_source_or_observation_time_durably() { + let mut f = Fixture::new(); + for (id, source) in [("source", Some(1234)), ("fallback", None)] { + f.backend.then_launch(Ok(handle())); + f.submit(id).await.unwrap(); + let expected = source.unwrap_or_else(|| f.clock.wall_ms()); + f.engine + .observe(id, Observation::Running { started_at: source }) + .unwrap(); + assert_eq!( + f.store().engine_run_state(id).unwrap().unwrap().started_at, + Some(expected) + ); + f.clock.advance(Duration::from_secs(10)); + f.engine + .observe( + id, + Observation::Running { + started_at: Some(expected + 5000), + }, + ) + .unwrap(); + assert_eq!( + f.store().engine_run_state(id).unwrap().unwrap().started_at, + Some(expected) + ); + f.restart(); + assert_eq!( + f.store().engine_run_state(id).unwrap().unwrap().started_at, + Some(expected) + ); + } + f.legacy_run("legacy", r#"{"kind":"local_job","jobId":"job"}"#); + f.engine + .observe( + "legacy", + Observation::Running { + started_at: Some(1234), + }, + ) + .unwrap(); + assert_eq!( + f.store() + .engine_run_state("legacy") + .unwrap() + .unwrap() + .started_at, + None + ); +} + +#[tokio::test] +async fn receipt_time_uses_the_source_clock_and_falls_back_to_observation_time() { + let f = Fixture::new(); + let now = f.clock.wall_ms(); + for (id, finished_at, expected) in [ + ("dated", Some(1234), 1234), + ("old", None, now), + ("past", Some(-100), 1), + ("future", Some(now + 1000), now), + ] { + f.running(id).await; + f.engine + .observe( + id, + Observation::Exited { + code: Some(0), + signal: None, + finished_at, + }, + ) + .unwrap(); + assert_eq!( + f.store().get_run(id).unwrap().unwrap().ended_at, + Some(expected) + ); + } + f.running("provider-failed").await; + f.engine + .observe( + "provider-failed", + Observation::Failed { + finished_at: Some(5678), + reason: "provider failure".into(), + }, + ) + .unwrap(); + assert_eq!( + f.store() + .get_run("provider-failed") + .unwrap() + .unwrap() + .ended_at, + Some(5678) + ); + f.running("abandoned").await; + f.engine.abandon("abandoned").unwrap(); + f.engine + .observe( + "abandoned", + Observation::CancelReceipt { + finished_at: Some(2468), + code: Some(0), + remaining: 0, + note: None, + }, + ) + .unwrap(); + assert_eq!( + f.store().get_run("abandoned").unwrap().unwrap().ended_at, + Some(2468) + ); + f.running("rollback").await; + f.clock.jump_wall(100 - now); + f.engine + .observe( + "rollback", + Observation::Exited { + code: Some(0), + signal: None, + finished_at: Some(-100), + }, + ) + .unwrap(); + assert_eq!( + f.store().get_run("rollback").unwrap().unwrap().ended_at, + Some(1) + ); +} + +#[tokio::test] +async fn vanished_job_is_lost_unless_cancellation_was_requested() { + let f = Fixture::new(); + for (id, cancel) in [("expired", false), ("deleted", true)] { + f.running(id).await; + if cancel { + f.backend.then_cancel(CancelOutcome::Pending); + f.engine.cancel(&f.backend, id, "test").await.unwrap(); + } + f.engine + .observe( + id, + Observation::Gone { + reason: "Job deleted before its outcome was recorded".into(), + }, + ) + .unwrap(); + assert_eq!(f.status(id), if cancel { "cancelled" } else { "lost" }); + if !cancel { + assert!(f + .store() + .get_run(id) + .unwrap() + .unwrap() + .result_markdown + .unwrap() + .contains("Job deleted")); + } + } +} + +#[tokio::test] +async fn cancelled_survivors_settle_once_after_a_restart_and_only_notify_affected_chats() { + let mut f = Fixture::new(); + f.running("survivors").await; + let proof = |remaining| Observation::CancelReceipt { + finished_at: Some(1234), + code: None, + remaining, + note: None, + }; + f.engine.observe("survivors", proof(2)).unwrap(); + assert_eq!(f.status("survivors"), "cancelled"); + assert_eq!( + f.store().get_run("survivors").unwrap().unwrap().ended_at, + Some(1234) + ); + assert!(matches!( + f.contact("survivors"), + Contact::Stopping { count: 2, .. } + )); + let terminal = f.deliver(); + assert_eq!(terminal.len(), 1); + let known = f.contact("survivors"); + for observation in [ + Observation::Unreachable { + cause: "eof".into(), + }, + Observation::NeedsAuth { + cause: "MFA".into(), + }, + ] { + f.engine.observe("survivors", observation).unwrap(); + assert_eq!(f.contact("survivors"), known); + } + + assert!(terminal[0] + .body + .contains("Not fully stopped · 2 processes still running on lab")); + f.store().begin().unwrap().execute( + "UPDATE run_notices SET body = 'Earlier cancellation wording' WHERE run_id = 'survivors' AND kind = ?1", + [TERMINAL], + ).unwrap(); + f.store() + .subscribe_run("survivors", "late-subscriber", 2) + .unwrap(); + f.restart(); + f.engine.observe("survivors", proof(1)).unwrap(); + assert!(f.deliver().is_empty()); + f.engine.observe("survivors", proof(0)).unwrap(); + assert_eq!(f.contact("survivors"), Contact::Live); + assert_eq!( + f.store().get_run("survivors").unwrap().unwrap().ended_at, + Some(1234) + ); + let followup = f.deliver(); + assert_eq!(followup.len(), 1); + assert_eq!(followup[0].dedupe, "cancel-stopped"); + assert!(f + .store() + .run_notice_batch("late-subscriber") + .unwrap() + .is_empty()); + assert_eq!( + followup[0].body, + "[orx] Run `survivors`: Cancelled. All remaining processes have stopped." + ); + f.engine.observe("survivors", proof(0)).unwrap(); + f.restart(); + f.engine.observe("survivors", proof(0)).unwrap(); + assert!(f.deliver().is_empty()); + + f.running("empty").await; + f.engine.observe("empty", proof(0)).unwrap(); + assert_eq!(f.deliver().len(), 1); + f.engine + .observe("empty", Observation::Lingering { pids: vec![] }) + .unwrap(); + assert!(f.deliver().is_empty()); +} + +#[tokio::test] +async fn cancelled_without_containment_proof_is_live_with_an_explicit_note() { + let mut f = Fixture::new(); + for (id, unreadable, note) in [ + ( + "container", + vec![], + "In-container processes or processes outside the host scan couldn't be checked.", + ), + ( + "mac", + vec![789], + "The host couldn't inspect processes 789 to confirm the stop.", + ), + ] { + f.running(id).await; + f.engine + .observe( + id, + Observation::CancelReceipt { + finished_at: None, + code: None, + remaining: 0, + note: Some(unreadable.clone()), + }, + ) + .unwrap(); + assert_eq!(f.status(id), "cancelled"); + assert_eq!(f.contact(id), Contact::Live); + assert_eq!( + f.store() + .get_run(id) + .unwrap() + .unwrap() + .result_markdown + .as_deref(), + Some(note) + ); + assert_eq!( + f.store() + .engine_run_state(id) + .unwrap() + .unwrap() + .cancel_unconfirmed, + Some(unreadable) + ); + assert!(!f + .store() + .list_engine_runs() + .unwrap() + .iter() + .any(|run| run.id == id)); + f.restart(); + let run = f.store().get_run(id).unwrap().unwrap(); + assert_eq!( + crate::plane::Run::from_store(&f.store(), &run) + .unwrap() + .display_status(), + "Cancelled · couldn't confirm" + ); + let notices = f.deliver(); + assert_eq!(notices.len(), 1); + assert!(notices[0] + .body + .contains("status **Cancelled · couldn't confirm**")); + assert!(notices[0].body.contains(note)); + } +} + +#[tokio::test] +async fn emptied_survivors_without_proof_do_not_claim_a_verified_stop_in_the_followup() { + let mut f = Fixture::new(); + f.running("opaque").await; + f.engine + .observe( + "opaque", + Observation::CancelReceipt { + finished_at: Some(10), + code: None, + remaining: 2, + note: None, + }, + ) + .unwrap(); + assert_eq!(f.deliver().len(), 1); + f.restart(); + let uncertain = || Observation::CancelReceipt { + finished_at: Some(10), + code: None, + remaining: 0, + note: Some(vec![]), + }; + f.engine.observe("opaque", uncertain()).unwrap(); + assert_eq!(f.contact("opaque"), Contact::Live); + let notices = f.deliver(); + assert_eq!(notices.len(), 1); + assert_eq!(notices[0].body, "[orx] Run `opaque`: Cancelled · couldn't confirm. In-container processes or processes outside the host scan couldn't be checked."); + f.restart(); + f.engine.observe("opaque", uncertain()).unwrap(); + assert!(f.deliver().is_empty()); +} + +#[tokio::test] +async fn supervised_monitoring_outages_and_recoveries_are_delivered_once() { + let mut f = Fixture::new(); + f.legacy_run("run", r#"{"kind":"ssh_job","jobId":"/orx/run"}"#); + f.engine.scan_legacy(false).unwrap(); + assert!(f.deliver().is_empty()); + for _ in 0..2 { + let mut run = f.store().get_run("run").unwrap().unwrap(); + let mut descriptor = BackendDescriptor::parse(&run.backend_json).unwrap(); + descriptor.monitoring_error = Some("Host unreachable".into()); + run.backend_json = descriptor.to_json(); + f.store().upsert_run(&run).unwrap(); + f.engine.scan_legacy(false).unwrap(); + f.engine.scan_legacy(false).unwrap(); + let notices = f.deliver(); + assert_eq!(notices.len(), 1); + assert_eq!(notices[0].kind, ATTENTION); + assert!(notices[0].body.contains("orx can no longer monitor")); + f.restart(); + f.engine.scan_legacy(false).unwrap(); + assert!(f.deliver().is_empty()); + descriptor.monitoring_error = None; + run.backend_json = descriptor.to_json(); + f.store().upsert_run(&run).unwrap(); + f.engine.scan_legacy(false).unwrap(); + f.engine.scan_legacy(false).unwrap(); + assert_eq!(f.kinds(), [RECOVERED]); + f.restart(); + f.engine.scan_legacy(false).unwrap(); + assert!(f.deliver().is_empty()); + } +} + +#[tokio::test] +async fn tombstone_finish_time_does_not_stage_terminal_effects_again() { + let f = Fixture::new(); + f.running("run").await; + f.store() + .reserve_run_telemetry( + "run", + None, + Some(&( + "terminal".into(), + serde_json::json!({ + "events": [{"eventId": "terminal", "properties": {}}] + }), + )), + ) + .unwrap(); + f.engine.abandon("run").unwrap(); + assert_eq!(f.store().pending_telemetry().unwrap().len(), 1); + f.store().acknowledge_pending_telemetry("terminal").unwrap(); + let updated_at = f.store().get_run("run").unwrap().unwrap().updated_at; + let now = f.clock.wall_ms(); + for (remaining, finished_at, expected) in [(2, now + 1000, now), (1, -100, 1), (0, 1234, 1234)] + { + f.engine + .observe( + "run", + Observation::CancelReceipt { + finished_at: Some(finished_at), + code: Some(137), + remaining, + note: None, + }, + ) + .unwrap(); + let run = f.store().get_run("run").unwrap().unwrap(); + assert_eq!(run.ended_at, Some(expected)); + assert_eq!(run.exit_code, Some(137)); + assert_eq!(run.updated_at, updated_at); + assert!(f.store().pending_telemetry().unwrap().is_empty()); + } +} diff --git a/src/engine/transport/askpass.rs b/src/engine/transport/askpass.rs new file mode 100644 index 000000000..681a6aba3 --- /dev/null +++ b/src/engine/transport/askpass.rs @@ -0,0 +1,104 @@ +use anyhow::{anyhow, bail, Result}; +use std::future::Future; +use std::pin::Pin; +use std::sync::{ + atomic::{AtomicBool, Ordering}, + Arc, +}; +use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader}; +use tokio::net::{TcpListener, TcpStream}; +use tokio::process::Command; +use tokio::task::JoinHandle; + +pub type Prompt = Arc< + dyn Fn(String) -> Pin>> + Send>> + Send + Sync, +>; + +pub(super) struct Askpass { + endpoint: String, + token: String, + task: JoinHandle<()>, + auth_prompted: Arc, +} + +impl Askpass { + pub async fn start(prompt: Prompt) -> Result { + let listener = TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0)).await?; + let endpoint = listener.local_addr()?.to_string(); + let token = uuid::Uuid::new_v4().to_string(); + let expected = token.clone(); + let auth_prompted = Arc::new(AtomicBool::new(false)); + let invoked = auth_prompted.clone(); + let task = tokio::spawn(async move { + while let Ok((stream, _)) = listener.accept().await { + let mut stream = BufReader::new(stream); + let exchange = async { + let mut line = String::new(); + (&mut stream).take(16384).read_line(&mut line).await?; + let (token, question): (String, String) = serde_json::from_str(&line)?; + if token != expected { + bail!("Invalid askpass token"); + } + let host_key = question.contains("continue connecting (yes/no") + || question.starts_with("Please type 'yes' or 'no':") + || question.starts_with("Please type 'yes', 'no' or the fingerprint:") + || question.starts_with("Accept updated hostkeys? (yes/no):"); + if !host_key { + invoked.store(true, Ordering::SeqCst); + } + let answer = prompt(question).await?; + let bytes = serde_json::to_vec(&answer)?; + stream.get_mut().write_all(&bytes).await?; + stream.get_mut().write_all(b"\n").await?; + anyhow::Ok(()) + }; + let _ = tokio::time::timeout(std::time::Duration::from_secs(300), exchange).await; + } + }); + Ok(Self { + endpoint, + token, + task, + auth_prompted, + }) + } + + pub fn auth_prompted(&self) -> bool { + self.auth_prompted.load(Ordering::SeqCst) + } + + pub fn configure(&self, command: &mut Command, executable: &std::path::Path) { + command + .env("SSH_ASKPASS", executable) + .env("SSH_ASKPASS_REQUIRE", "force") + .env("DISPLAY", "orx-engine") + .env("ORX_ENGINE_ASKPASS", &self.endpoint) + .env("ORX_ENGINE_ASKPASS_TOKEN", &self.token) + .stdin(std::process::Stdio::null()); + } +} + +impl Drop for Askpass { + fn drop(&mut self) { + self.task.abort(); + } +} + +pub async fn relay() -> Result<()> { + let stream = TcpStream::connect(std::env::var("ORX_ENGINE_ASKPASS")?).await?; + let mut stream = BufReader::new(stream); + let token = std::env::var("ORX_ENGINE_ASKPASS_TOKEN")?; + let question = std::env::args().nth(1).unwrap_or_default(); + let bytes = serde_json::to_vec(&(token, question))?; + stream.get_mut().write_all(&bytes).await?; + stream.get_mut().write_all(b"\n").await?; + let mut line = String::new(); + (&mut stream).take(16384).read_line(&mut line).await?; + let answer: Option = serde_json::from_str(&line)?; + let answer = answer.ok_or_else(|| anyhow!("SSH authentication cancelled"))?; + if answer.contains(['\n', '\r']) { + bail!("Invalid multiline SSH answer"); + } + println!("{answer}"); + Ok(()) +} diff --git a/src/engine/transport/mod.rs b/src/engine/transport/mod.rs new file mode 100644 index 000000000..a8f77bb81 --- /dev/null +++ b/src/engine/transport/mod.rs @@ -0,0 +1,1043 @@ +pub mod askpass; +mod ssh; + +#[cfg(unix)] +pub(crate) use ssh::local_binary; + +use anyhow::{anyhow, bail, Result}; +use orx_host_proto::{Message, Request, Response}; +use serde::{Deserialize, Serialize}; +use std::collections::{BTreeMap, VecDeque}; +use std::path::PathBuf; +use std::sync::Arc; +use std::time::Duration; + +use crate::engine::clock::{Clock, JumpDetector}; +use tokio::sync::{mpsc, oneshot, watch}; + +use crate::store::Store; +pub use askpass::Prompt; + +const DEADLINE: Duration = Duration::from_secs(35); +const CHUNK: usize = 256 * 1024; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum HostClass { + Key, + Interactive, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub enum Status { + Idle, + Connecting, + Live, + Backoff, + NeedsAuth, +} + +impl Status { + /// Ranks how much a root needs attention when one state stands for an alias. + pub fn severity(&self) -> u8 { + match self { + Status::Idle => 0, + Status::Live => 1, + Status::Connecting => 2, + Status::Backoff => 3, + Status::NeedsAuth => 4, + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct HostState { + pub status: Status, + pub failures: usize, + pub next_retry_ms: Option, + pub since_ms: i64, + pub last_live_ms: Option, + pub cause: Option, +} + +impl Default for HostState { + fn default() -> Self { + Self { + status: Status::Idle, + failures: 0, + next_retry_ms: None, + since_ms: 0, + last_live_ms: None, + cause: None, + } + } +} + +#[derive(Debug)] +pub struct Unavailable { + pub state: HostState, + /// A write was attempted, so the request may have reached the host. + pub sent: bool, +} + +impl std::fmt::Display for Unavailable { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(self.state.cause.as_deref().unwrap_or("Connection closed")) + } +} + +impl std::error::Error for Unavailable {} + +#[derive(Clone)] +pub struct Config { + pub alias: String, + pub root: String, + pub ssh_config: Option, + #[cfg(unix)] + pub control_dir: PathBuf, + #[cfg(unix)] + pub sharing_home: Option, + pub binary_dir: Option, + pub askpass_executable: PathBuf, +} + +#[derive(Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub(crate) struct AuthState { + pub blocked: Option<(i64, String)>, + pub class: Option, + pub route: Option, +} + +pub(crate) struct Auth { + gate: tokio::sync::Mutex<()>, + state: watch::Sender, +} + +impl Auth { + pub(crate) fn new(store: &Store, alias: &str) -> Result> { + Ok(Arc::new(Self { + gate: tokio::sync::Mutex::new(()), + state: watch::channel(store.engine_host_auth(alias)?).0, + })) + } + + /// Failed writes still block peers, but cannot clear their breaker. + fn update( + &self, + store: &Store, + alias: &str, + update: impl FnOnce(&mut AuthState), + ) -> Result<()> { + let mut result = Ok(()); + self.state.send_if_modified(|current| { + let mut next = current.clone(); + update(&mut next); + result = store.save_engine_host_auth(alias, &next); + if result.is_err() && current.blocked.is_some() && next.blocked.is_none() { + return false; + } + let changed = next != *current; + *current = next; + changed + }); + result + } + + fn block(&self, store: &Store, alias: &str, since: i64, cause: String) -> Result<()> { + self.update(store, alias, |state| { + state.blocked.get_or_insert((since, cause)); + }) + } +} + +#[derive(Clone)] +pub struct HostConn { + calls: mpsc::Sender, + actions: mpsc::Sender, + state: watch::Receiver, +} + +struct Action { + key_only: bool, + keep_master: bool, + prompt: Option, + reply: oneshot::Sender>, +} + +struct Call { + body: Request, + reply: oneshot::Sender>, +} +struct Pending { + reply: Reply, + deadline: Duration, +} + +enum Reply { + Call(oneshot::Sender>), + Probe, +} + +impl HostConn { + pub(crate) fn start_shared( + config: Config, + store: Store, + clock: Arc, + auth: Arc, + ) -> Result { + let mut state = store + .engine_root(&config.alias, &config.root)? + .unwrap_or_default(); + let class = auth.state.borrow().class; + if state.status == Status::Connecting && class.is_none() { + state.status = Status::NeedsAuth; + state.cause = Some("First SSH attempt was interrupted; press Connect".into()); + if let Err(error) = auth.block( + &store, + &config.alias, + state.since_ms, + state.cause.clone().unwrap(), + ) { + eprintln!( + "Host {}: could not persist SSH auth state: {error:#}", + config.alias + ); + } + } else if matches!(state.status, Status::Live | Status::Connecting) + || state.status == Status::Backoff && class != Some(HostClass::Interactive) + { + state.status = Status::Idle; + } + if let Some((since, cause)) = auth.state.borrow().blocked.as_ref() { + state.status = Status::NeedsAuth; + state.since_ms = *since; + state.cause = Some(cause.clone()); + state.next_retry_ms = None; + } + if let Err(error) = store.save_engine_host(&config.alias, &config.root, &state) { + eprintln!( + "Host {}: could not persist SSH connection state: {error:#}", + config.alias + ); + } + let (publish, state_rx) = watch::channel(state.clone()); + let (calls, incoming) = mpsc::channel(256); + let (actions, action_rx) = mpsc::channel(8); + let actor = Actor { + auth, + config, + store, + clock, + state, + publish, + incoming, + }; + tokio::spawn(actor.run(action_rx)); + Ok(Self { + calls, + actions, + state: state_rx, + }) + } + + pub fn state(&self) -> watch::Receiver { + self.state.clone() + } + + pub async fn request(&self, body: Request) -> Result { + match &body { + Request::PutBlob { bytes, .. } if bytes.len() > CHUNK => { + bail!("Upload chunks must be at most 256 KiB") + } + Request::ReadLog { range, .. } + if range.end.saturating_sub(range.start) > CHUNK as u64 => + { + bail!("Log chunks must be at most 256 KiB") + } + _ => {} + } + let (reply, receive) = oneshot::channel(); + self.calls.send(Call { body, reply }).await.map_err(|_| { + anyhow!(Unavailable { + state: self.state.borrow().clone(), + sent: false + }) + })?; + receive.await.map_err(|_| { + anyhow!(Unavailable { + state: self.state.borrow().clone(), + sent: true + }) + })? + } + + pub async fn retry(&self) -> Result<()> { + self.action(None, false, false).await + } + + pub async fn retry_key(&self) -> Result<()> { + self.action(None, true, false).await + } + + pub async fn connect_interactive(&self, prompt: Prompt, keep_master: bool) -> Result<()> { + self.action(Some(prompt), false, keep_master).await + } + + async fn action( + &self, + prompt: Option, + key_only: bool, + keep_master: bool, + ) -> Result<()> { + let (reply, receive) = oneshot::channel(); + self.actions + .send(Action { + prompt, + key_only, + keep_master, + reply, + }) + .await + .map_err(|_| anyhow!("Host transport stopped"))?; + receive.await? + } +} + +struct Actor { + auth: Arc, + config: Config, + store: Store, + clock: Arc, + state: HostState, + publish: watch::Sender, + incoming: mpsc::Receiver, +} + +fn lane(body: &Request) -> usize { + match body { + Request::Changes { .. } | Request::SlurmQueue { .. } => 1, + Request::ReadLog { .. } => 2, + Request::PutBlob { .. } | Request::HasBlob { .. } | Request::PinSource { .. } => 3, + _ => 0, + } +} + +#[cfg(unix)] +async fn publish_master(config: &Config, route: &str) { + let result = async { + if let Some(home) = &config.sharing_home { + let path = ssh::socket(config, route)?; + crate::jobs::ssh::sharing::publish_engine( + home, + &config.alias, + config.ssh_config.as_deref(), + &path, + route, + ) + .await?; + } + Ok::<(), anyhow::Error>(()) + } + .await; + if let Err(error) = result { + eprintln!( + "Host {}: connection sharing is unavailable: {error:#}", + config.alias + ); + } +} + +impl Actor { + fn save(&self) { + if let Err(error) = + self.store + .save_engine_host(&self.config.alias, &self.config.root, &self.state) + { + eprintln!( + "Host {}: could not persist SSH connection state: {error:#}", + self.config.alias + ); + } + self.publish.send_replace(self.state.clone()); + } + + fn classify(&mut self, class: HostClass) { + if let Err(error) = self.auth.update(&self.store, &self.config.alias, |state| { + state.class = Some(class) + }) { + eprintln!( + "Host {}: could not persist SSH auth state: {error:#}", + self.config.alias + ); + } + } + + fn failed(&mut self, breaker: bool, cause: String) { + if breaker && self.auth.state.borrow().class.is_none() { + self.classify(HostClass::Interactive); + } + let now = self.clock.wall_ms(); + if self.state.cause.is_none() { + self.state.since_ms = now; + } + self.state.cause = Some(cause); + if breaker + || cfg!(windows) && self.auth.state.borrow().class == Some(HostClass::Interactive) + { + if let Err(error) = self.auth.block( + &self.store, + &self.config.alias, + now, + self.state.cause.clone().unwrap(), + ) { + eprintln!( + "Host {}: could not persist SSH auth breaker: {error:#}", + self.config.alias + ); + } + } + let blocked = self.auth.state.borrow().blocked.clone(); + if let Some((since, cause)) = blocked { + self.state.since_ms = since; + self.state.cause = Some(cause); + self.state.status = Status::NeedsAuth; + self.state.next_retry_ms = None; + } else { + let steps = [5_000, 15_000, 60_000, 300_000, 900_000]; + let base = steps[self.state.failures.min(steps.len() - 1)]; + let noise = + u16::from_le_bytes(uuid::Uuid::new_v4().as_bytes()[..2].try_into().unwrap()) as i64; + let delay = (base * (800 + noise % 401) / 1000).min(900_000); + self.state.failures = self.state.failures.saturating_add(1); + self.state.next_retry_ms = Some(now.saturating_add(delay)); + self.state.status = Status::Backoff; + } + self.save(); + } + + async fn connect( + &mut self, + prompt: Option, + approve_route: bool, + #[cfg_attr(windows, allow(unused_variables))] keep_master: bool, + ) -> Result { + let auth = self.auth.clone(); + let _guard = auth.gate.lock().await; + let blocked = auth.state.borrow().blocked.clone(); + if !approve_route { + if let Some((_, cause)) = blocked { + self.failed(true, cause.clone()); + bail!("{cause}"); + } + } + if approve_route { + let now = self.clock.wall_ms(); + auth.update(&self.store, &self.config.alias, |state| { + state.blocked = None; + })?; + self.state.cause = None; + self.state.since_ms = now; + } + self.state.status = Status::Connecting; + self.store + .save_engine_host(&self.config.alias, &self.config.root, &self.state)?; + self.publish.send_replace(self.state.clone()); + let route = match ssh::route(&self.config).await { + Ok(route) => route, + Err(error) => { + let failure = ssh::failure(&error.to_string(), "", None, false); + self.failed(failure.breaker, failure.cause); + return Err(error); + } + }; + let retry_closure = !route + .lines() + .any(|line| line.starts_with("proxycommand ") || line.starts_with("proxyjump ")); + let pinned = auth.state.borrow().route.clone(); + if !approve_route && pinned.as_ref().is_some_and(|pin| pin != &route) { + #[cfg(unix)] + if let Some(previous) = &pinned { + ssh::withdraw(&self.config, previous).await; + } + self.failed( + true, + "SSH route changed; press Connect to approve it".into(), + ); + bail!("SSH route changed"); + } + #[cfg(unix)] + if let Some(previous) = pinned.filter(|previous| *previous != route) { + ssh::stop_master(&self.config, &previous).await?; + } + auth.update(&self.store, &self.config.alias, |state| { + state.route = Some(route.clone()) + })?; + #[cfg(unix)] + let mut attach = false; + #[cfg(windows)] + let attach = false; + let askpass = if let Some(prompt) = prompt { + let askpass = askpass::Askpass::start(prompt).await?; + #[cfg(unix)] + { + if self.auth.state.borrow().class.is_none() { + ssh::stop_master(&self.config, &route).await?; + } + let result = + ssh::master(&self.config, &ssh::socket(&self.config, &route)?, &askpass).await; + if askpass.auth_prompted() { + self.classify(HostClass::Interactive); + } + match result { + Ok(authenticated) => { + if authenticated && !askpass.auth_prompted() { + self.classify(HostClass::Key); + } + if self.auth.state.borrow().class == Some(HostClass::Key) && !keep_master { + ssh::stop_master(&self.config, &route).await?; + } else { + attach = true; + } + } + Err(error) => { + let failure = ssh::failure( + "SSH connection failed", + &error.to_string(), + None, + retry_closure, + ); + self.failed(failure.breaker, failure.cause); + return Err(error); + } + } + } + Some(askpass) + } else { + #[cfg(unix)] + if self.auth.state.borrow().class == Some(HostClass::Interactive) { + let alive = + ssh::master_alive(&self.config, &ssh::socket(&self.config, &route)?).await?; + if !alive { + ssh::withdraw(&self.config, &route).await; + } + if !alive && !approve_route { + self.failed(true, "SSH master ended; press Connect".into()); + bail!("SSH master ended"); + } + attach = alive; + } + #[cfg(windows)] + if self.auth.state.borrow().class == Some(HostClass::Interactive) && !approve_route { + self.failed(true, "Interactive SSH requires Connect".into()); + bail!("Interactive SSH requires Connect"); + } + None + }; + #[cfg(unix)] + if attach { + publish_master(&self.config, &route).await; + } + let mut session = { + let authorization = auth.state.borrow(); + if !approve_route { + if let Some((_, cause)) = &authorization.blocked { + bail!("{cause}"); + } + } + ssh::spawn(&self.config, attach, &route, askpass.as_ref())? + }; + #[cfg(windows)] + let deadline = if askpass.is_some() { + Duration::from_secs(300) + } else { + DEADLINE + }; + #[cfg(unix)] + let deadline = DEADLINE; + let result = tokio::time::timeout(deadline, async { + let (os, arch) = session.handshake().await?; + if askpass + .as_ref() + .is_some_and(|bridge| bridge.auth_prompted()) + { + self.classify(HostClass::Interactive); + } else if !attach { + self.classify(HostClass::Key); + } + let binary = ssh::binary(self.config.binary_dir.as_deref(), &os, &arch)?; + session.bootstrap(&binary).await + }) + .await + .map_err(|_| anyhow!("SSH did not respond within {} s", deadline.as_secs())) + .and_then(|result| result); + match result { + Ok(()) => { + let blocked = self.auth.state.borrow().blocked.clone(); + if !approve_route { + if let Some((_, cause)) = blocked { + self.failed(true, cause.clone()); + bail!("{cause}"); + } + } + if approve_route { + self.auth.update(&self.store, &self.config.alias, |state| { + state.blocked = None; + })?; + } + self.state.status = Status::Live; + self.state.failures = 0; + self.state.next_retry_ms = None; + self.state.cause = None; + self.state.since_ms = self.clock.wall_ms(); + self.state.last_live_ms = Some(self.state.since_ms); + self.save(); + Ok(session) + } + Err(error) => { + let failure = session.failure(error, retry_closure).await; + if askpass + .as_ref() + .is_some_and(|bridge| bridge.auth_prompted()) + { + self.classify(HostClass::Interactive); + } + self.failed(failure.breaker, failure.cause.clone()); + bail!("{}", failure.cause) + } + } + } + + async fn run(mut self, mut actions: mpsc::Receiver) { + let mut auth = self.auth.state.subscribe(); + auth.borrow_and_update(); + let mut session: Option = None; + let mut reader: Option> = None; + let mut masters: tokio::task::JoinSet<(oneshot::Sender>, Result<()>, bool)> = + tokio::task::JoinSet::new(); + let (events, mut responses) = mpsc::channel(64); + let mut pending: BTreeMap = BTreeMap::new(); + let mut queues: [VecDeque; 4] = std::array::from_fn(|_| VecDeque::new()); + let mut id = 1u64; + let mut jumps = JumpDetector::new(self.clock.as_ref()); + let mut last_reply = self.clock.monotonic(); + let mut tick = tokio::time::interval(Duration::from_millis(100)); + loop { + let mut disconnect: Option = None; + let mut action = None; + tokio::select! { + Some(completed) = masters.join_next(), if !masters.is_empty() => { + if let Ok((reply, result, prompted)) = completed { + if prompted { + self.classify(HostClass::Interactive); + } + let _ = reply.send(result); + } + } + changed = auth.changed() => { + if changed.is_err() { break; } + let authorization = auth.borrow_and_update().clone(); + match authorization.blocked { + Some((_, cause)) => { self.failed(true, cause.clone()); disconnect = Some(cause); } + None => { + if self.state.status == Status::NeedsAuth + && !(cfg!(windows) && authorization.class == Some(HostClass::Interactive)) { + self.state.status = Status::Idle; + self.state.cause = None; + } + self.save(); + } + } + } + next = actions.recv() => { + match next { Some(next) => action = Some(next), None => break } + } + event = responses.recv(), if session.is_some() => { + match event { + Some(Ok(Message { id, body })) => { + last_reply = self.clock.monotonic(); + self.state.last_live_ms = Some(self.clock.wall_ms()); + if let Some(call) = pending.remove(&id) { + if let Reply::Call(reply) = call.reply { let _ = reply.send(Ok(body)); } + } else { disconnect = Some("Unexpected orx-host response id".into()); } + } + Some(Err(_)) => disconnect = Some("Connection closed".into()), + None => disconnect = Some("Connection closed".into()), + } + } + call = self.incoming.recv(), if queues.iter().map(VecDeque::len).sum::() < 256 => { + match call { + Some(call) if session.is_some() || matches!(self.state.status, Status::Idle | Status::Connecting) => queues[lane(&call.body)].push_back(call), + Some(call) => { let _ = call.reply.send(Err(anyhow!(Unavailable { state: self.state.clone(), sent: false }))); } + None => break, + } + } + _ = tick.tick() => { + let now = self.clock.monotonic(); + if jumps.jumped(self.clock.as_ref()) && (session.is_some() || self.auth.state.borrow().class == Some(HostClass::Key) && self.state.status == Status::Backoff) { + disconnect = Some("Clock jump exceeded 30 seconds".into()); + } else if session.is_some() && now >= last_reply + DEADLINE + || pending.values().any(|call| now >= call.deadline) { + disconnect = Some("Connection timed out".into()); + } else if let Some(current) = session.as_mut().filter(|_| now >= last_reply + Duration::from_secs(15) && !pending.values().any(|call| matches!(call.reply, Reply::Probe))) { + let body = Request::Hello { proto: orx_host_proto::PROTOCOL_VERSION }; + let remaining = (last_reply + DEADLINE).saturating_sub(now); + let result = tokio::time::timeout(remaining, ssh::write(&mut current.input, &Message { id, body })).await; + if matches!(result, Ok(Ok(()))) { + pending.insert(id, Pending { reply: Reply::Probe, deadline: now + DEADLINE }); + id += 1; + } else { disconnect = Some("Connection closed".into()); } + } + } + } + if action.as_ref().is_some_and(|action| !action.key_only) + && self.state.status == Status::Live + && self.auth.state.borrow().blocked.is_none() + && ssh::route(&self.config).await.ok().as_ref() + == self.auth.state.borrow().route.as_ref() + { + if let Some(action) = action.take() { + #[cfg(unix)] + if let (true, Some(prompt), Some(route)) = ( + action.keep_master, + action.prompt.clone(), + self.auth.state.borrow().route.clone(), + ) { + let config = self.config.clone(); + let auth = self.auth.clone(); + masters.spawn(async move { + let mut reply = action.reply; + let mut prompted = false; + let connect = async { + let _guard = auth.gate.lock().await; + let askpass = askpass::Askpass::start(prompt).await?; + let result = + ssh::master(&config, &ssh::socket(&config, &route)?, &askpass) + .await; + prompted = askpass.auth_prompted(); + result?; + publish_master(&config, &route).await; + Ok(()) + }; + let result = tokio::select! { + result = connect => result, + _ = reply.closed() => Err(anyhow!("SSH authentication cancelled.")), + }; + (reply, result, prompted) + }); + } else { + let _ = action.reply.send(Ok(())); + } + #[cfg(windows)] + let _ = action.reply.send(Ok(())); + } + } + if action.as_ref().is_some_and(|action| { + action.key_only && matches!(self.state.status, Status::Live | Status::Connecting) + }) { + if let Some(action) = action.take() { + let _ = action.reply.send(Ok(())); + } + } + if action.as_ref().is_some_and(|action| { + action.key_only + && (self.state.status == Status::NeedsAuth + || self.auth.state.borrow().class != Some(HostClass::Key)) + }) { + if let Some(action) = action.take() { + let _ = action.reply.send(Err(anyhow!("Host requires Connect"))); + } + } + if let Some(current) = session + .as_mut() + .filter(|_| disconnect.is_none() && action.is_none()) + { + while pending.len() < 24 { + while queues.iter().map(VecDeque::len).sum::() < 256 { + let Ok(call) = self.incoming.try_recv() else { + break; + }; + queues[lane(&call.body)].push_back(call); + } + let call = queues + .iter_mut() + .zip([24, 20, 16, 8]) + .find_map(|(queue, limit)| { + if pending.len() < limit { + queue.pop_front() + } else { + None + } + }); + let Some(call) = call else { + break; + }; + if call.reply.is_closed() { + continue; + } + let timeout = match &call.body { + Request::Exec { timeout_ms, .. } => { + Duration::from_millis(u64::from(*timeout_ms)) + DEADLINE + } + Request::Changes { wait_ms, .. } => { + Duration::from_millis(u64::from(*wait_ms)) + DEADLINE + } + _ => DEADLINE, + }; + let remaining = pending + .values() + .map(|call| call.deadline.saturating_sub(self.clock.monotonic())) + .min() + .unwrap_or(DEADLINE) + .min((last_reply + DEADLINE).saturating_sub(self.clock.monotonic())); + let result = tokio::time::timeout( + remaining, + ssh::write( + &mut current.input, + &Message { + id, + body: call.body, + }, + ), + ) + .await; + pending.insert( + id, + Pending { + reply: Reply::Call(call.reply), + deadline: self.clock.monotonic() + timeout, + }, + ); + if matches!(result, Ok(Ok(()))) { + id += 1; + } else { + disconnect = Some("Connection closed".into()); + break; + } + } + } + if disconnect.is_some() || action.is_some() { + #[cfg(unix)] + let route = self.auth.state.borrow().route.clone().filter(|_| { + self.config.sharing_home.is_some() + && self.auth.state.borrow().class == Some(HostClass::Interactive) + }); + #[cfg(unix)] + if let Some(route) = route { + if let Ok(path) = ssh::socket(&self.config, &route) { + if !ssh::master_alive(&self.config, &path) + .await + .unwrap_or(false) + { + ssh::withdraw(&self.config, &route).await; + } + } + } + if let Some(mut old) = session.take() { + old.close().await; + } + if let Some(task) = reader.take() { + task.abort(); + let _ = task.await; + } + while responses.try_recv().is_ok() {} + if let Some(cause) = disconnect { + let jump = cause.starts_with("Clock jump"); + self.failed(false, cause); + if jump && self.auth.state.borrow().class == Some(HostClass::Key) { + self.state.next_retry_ms = Some(self.clock.wall_ms()); + self.save(); + } + } + for (_, call) in std::mem::take(&mut pending) { + if let Reply::Call(reply) = call.reply { + let _ = reply.send(Err(anyhow!(Unavailable { + state: self.state.clone(), + sent: true + }))); + } + } + for queue in &mut queues { + for call in queue.drain(..) { + let _ = call.reply.send(Err(anyhow!(Unavailable { + state: self.state.clone(), + sent: false + }))); + } + } + } + let now = self.clock.wall_ms(); + let automatic = matches!(self.state.status, Status::Idle) + || (self.state.status == Status::Backoff + && self.state.next_retry_ms.is_some_and(|at| now >= at)); + if session.is_none() && (automatic || action.is_some()) { + let mut next_action = action; + let mut replies = Vec::new(); + let result = loop { + if next_action.as_ref().is_some_and(|action| action.key_only) { + self.state.failures = 0; + self.state.next_retry_ms = None; + } + let approve_route = next_action.as_ref().is_some_and(|action| !action.key_only); + let keep_master = next_action + .as_ref() + .is_some_and(|action| action.keep_master); + let prompt = next_action.take().and_then(|action| { + replies.push(action.reply); + action.prompt + }); + let mut queued_action = None; + let mut enqueue = |action: Action| { + if !approve_route && queued_action.is_none() { + queued_action = Some(action); + } else { + replies.push(action.reply); + } + }; + let result = { + let attempt = self.connect(prompt, approve_route, keep_master); + tokio::pin!(attempt); + loop { + tokio::select! { + result = &mut attempt => break result, + Some(action) = actions.recv(), if !actions.is_closed() => { + if action.key_only { let _ = action.reply.send(Ok(())); } + else { enqueue(action); } + }, + } + } + }; + while let Ok(action) = actions.try_recv() { + enqueue(action); + } + if queued_action.as_ref().is_some_and(|action| { + action.key_only + && (self.state.status == Status::NeedsAuth + || self.auth.state.borrow().class != Some(HostClass::Key)) + }) { + if let Some(action) = queued_action.take() { + let _ = action.reply.send(Err(anyhow!("Host requires Connect"))); + } + } + if queued_action.is_some() + && (result.is_err() + || cfg!(unix) + && !keep_master + && queued_action + .as_ref() + .is_some_and(|action| action.keep_master)) + { + next_action = queued_action; + continue; + } + if let Some(action) = queued_action { + replies.push(action.reply); + } + break result; + }; + auth.borrow_and_update(); + let error = result.as_ref().err().map(|error| format!("{error:#}")); + match result { + Ok(mut connected) => { + // The reader owns the pipe so cancelling select branches cannot lose frame bytes. + let mut output = connected.output.take().unwrap(); + let sender = events.clone(); + reader = Some(tokio::spawn(async move { + loop { + let result = ssh::read(&mut output).await; + let failed = result.is_err(); + if sender.send(result).await.is_err() || failed { + break; + } + } + })); + session = Some(connected); + last_reply = self.clock.monotonic(); + } + Err(error) => { + if self.state.status != Status::NeedsAuth + && self.state.status != Status::Backoff + { + self.failed(true, format!("{error:#}")); + } + for queue in &mut queues { + for call in queue.drain(..) { + let _ = call.reply.send(Err(anyhow!(Unavailable { + state: self.state.clone(), + sent: false + }))); + } + } + } + } + for reply in replies { + let result = match &error { + Some(error) => Err(anyhow!("{error}")), + None => Ok(()), + }; + let _ = reply.send(result); + } + } + } + if let Some(task) = reader { + task.abort(); + let _ = task.await; + } + } +} + +#[cfg(all(test, unix))] +mod tests; + +#[cfg(test)] +mod state_tests { + use super::*; + + #[tokio::test] + async fn interrupted_first_contact_requires_user_action_even_after_restart() { + let directory = + std::env::temp_dir().join(format!("orx-transport-{}", uuid::Uuid::new_v4())); + let store = Store::open_at(directory.clone()).unwrap(); + store + .seed_engine_host( + "interrupted", + "/unused", + None, + &HostState { + status: Status::Connecting, + ..HostState::default() + }, + ) + .unwrap(); + let config = Config { + alias: "interrupted".into(), + root: "/unused".into(), + ssh_config: Some(directory.join("missing-ssh-config")), + binary_dir: None, + #[cfg(unix)] + sharing_home: None, + askpass_executable: std::env::current_exe().unwrap(), + #[cfg(unix)] + control_dir: directory.join("cm"), + }; + let auth = Auth::new(&store, &config.alias).unwrap(); + let conn = HostConn::start_shared( + config, + store, + Arc::new(crate::engine::clock::SystemClock::new()), + auth, + ) + .unwrap(); + assert_eq!(conn.state().borrow().status, Status::NeedsAuth); + assert!(conn + .request(Request::Hello { + proto: orx_host_proto::PROTOCOL_VERSION + }) + .await + .is_err()); + assert!(conn.retry().await.is_err()); + let prompt: Prompt = Arc::new(|_| Box::pin(async { bail!("unexpected prompt") })); + assert!(conn.connect_interactive(prompt, false).await.is_err()); + drop(conn); + tokio::time::sleep(Duration::from_millis(150)).await; + std::fs::remove_dir_all(directory).unwrap(); + } +} diff --git a/src/engine/transport/ssh.rs b/src/engine/transport/ssh.rs new file mode 100644 index 000000000..896bb81d7 --- /dev/null +++ b/src/engine/transport/ssh.rs @@ -0,0 +1,758 @@ +use super::{askpass::Askpass, Config, DEADLINE}; +use crate::jobs::ssh::sh_quote; +use anyhow::{anyhow, bail, Context, Result}; +use orx_host_proto::{Message, Request, Response, MAX_FRAME_LEN, PROTOCOL_VERSION}; +use sha2::{Digest, Sha256}; +use std::path::{Path, PathBuf}; +use std::process::Stdio; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; +use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, BufReader}; +use tokio::process::{Child, ChildStdin, ChildStdout, Command}; +use tokio::task::JoinHandle; + +pub(super) struct Session { + child: Child, + pub(super) input: ChildStdin, + pub(super) output: Option>, + stderr: JoinHandle<()>, + stderr_tail: Arc>>, + bootstrapped: bool, + authenticated: Arc, +} + +impl Drop for Session { + fn drop(&mut self) { + let _ = self.child.start_kill(); + self.stderr.abort(); + } +} + +pub(super) fn command(config: &Config) -> Command { + let mut command = crate::process::tokio_command("ssh"); + if let Some(path) = &config.ssh_config { + command.arg("-F").arg(path); + } + command + .kill_on_drop(true) + .env("LC_ALL", "C") + .env("ORX_SSH_PROBE", "1") + .env("SSH_ASKPASS", "") + .env("SSH_ASKPASS_REQUIRE", "never"); + // A ProxyJump hop ignores our BatchMode; with no terminal it fails instead of prompting. + #[cfg(unix)] + unsafe { + command.pre_exec(|| { + libc::setsid(); + Ok(()) + }); + } + #[cfg(windows)] + command.creation_flags(windows_sys::Win32::System::Threading::DETACHED_PROCESS); + command +} + +pub(super) async fn route(config: &Config) -> Result { + let output = tokio::time::timeout( + DEADLINE, + command(config).args(["-G", "--", &config.alias]).output(), + ) + .await??; + if !output.status.success() { + bail!("ssh -G failed: {}", String::from_utf8_lossy(&output.stderr)); + } + let output = String::from_utf8(output.stdout)?; + // Legacy route fingerprints are frozen for live 0.2.x supervisors. + let fields: Vec<_> = output + .lines() + .filter(|line| { + let key = line.split_whitespace().next().unwrap_or_default(); + matches!( + key, + "hostname" + | "user" + | "port" + | "proxyjump" + | "proxycommand" + | "identityfile" + | "certificatefile" + | "identityagent" + | "identitiesonly" + | "pubkeyauthentication" + | "passwordauthentication" + | "kbdinteractiveauthentication" + | "preferredauthentications" + | "gssapiauthentication" + | "hostbasedauthentication" + | "hostkeyalias" + | "stricthostkeychecking" + | "userknownhostsfile" + | "globalknownhostsfile" + | "hostkeyalgorithms" + | "pubkeyacceptedalgorithms" + | "proxyusefdpass" + | "bindaddress" + | "bindinterface" + | "canonicalizehostname" + ) + }) + .collect(); + Ok(fields.join("\n")) +} + +#[cfg(unix)] +pub(super) fn socket(config: &Config, route: &str) -> Result { + { + use std::os::unix::fs::{MetadataExt, PermissionsExt}; + std::fs::create_dir_all(&config.control_dir)?; + let metadata = std::fs::symlink_metadata(&config.control_dir)?; + if !metadata.is_dir() || metadata.uid() != unsafe { libc::geteuid() } { + bail!("SSH control directory must be owned by the current user"); + } + std::fs::set_permissions(&config.control_dir, std::fs::Permissions::from_mode(0o700))?; + } + let key = format!("{:x}", Sha256::digest(format!("{}\0{route}", config.alias))); + let path = config.control_dir.join(&key[..16]); + if path.as_os_str().len() > 100 { + bail!("SSH control path exceeds 100 bytes: {}", path.display()); + } + Ok(path) +} + +fn isolation(command: &mut Command) { + command.args([ + "-T", + "-o", + "ClearAllForwardings=yes", + "-o", + "RemoteCommand=none", + "-o", + "ForwardAgent=no", + "-o", + "ForwardX11=no", + "-o", + "PermitLocalCommand=no", + "-o", + "ServerAliveInterval=15", + "-o", + "ServerAliveCountMax=3", + "-o", + "ConnectionAttempts=1", + "-o", + "ConnectTimeout=10", + "-o", + "NumberOfPasswordPrompts=1", + "-o", + "LogLevel=VERBOSE", + ]); +} + +#[cfg(unix)] +pub(super) async fn master_alive(config: &Config, path: &Path) -> Result { + let check = tokio::time::timeout( + Duration::from_secs(5), + command(config) + .arg("-S") + .arg(path) + .args([ + "-O", + "check", + "-o", + "BatchMode=yes", + "-o", + "ProxyCommand=false", + "--", + &config.alias, + ]) + .output(), + ) + .await??; + Ok(check.status.success()) +} + +#[cfg(unix)] +pub(super) async fn master(config: &Config, path: &Path, askpass: &Askpass) -> Result { + if master_alive(config, path).await? { + return Ok(false); + } + if path.exists() { + std::fs::remove_file(path)?; + } + let mut command = command(config); + isolation(&mut command); + command + .args([ + "-M", + "-N", + "-f", + "-o", + "ControlPersist=yes", + "-o", + "BatchMode=no", + ]) + .arg("-S") + .arg(path) + .args(["--", &config.alias]); + askpass.configure(&mut command, &config.askpass_executable); + let output = + tokio::time::timeout(std::time::Duration::from_secs(300), command.output()).await??; + if !output.status.success() { + bail!("{}", String::from_utf8_lossy(&output.stderr).trim()); + } + Ok(true) +} + +#[cfg(unix)] +pub(super) async fn withdraw(config: &Config, route: &str) { + let Some(home) = &config.sharing_home else { + return; + }; + let result = + async { crate::jobs::ssh::sharing::withdraw_engine(home, &socket(config, route)?).await } + .await; + if let Err(error) = result { + eprintln!( + "Host {}: could not withdraw SSH sharing: {error:#}", + config.alias + ); + } +} + +#[cfg(unix)] +pub(super) async fn stop_master(config: &Config, route: &str) -> Result<()> { + let path = socket(config, route)?; + withdraw(config, route).await; + if path.exists() { + let output = tokio::time::timeout( + Duration::from_secs(5), + command(config) + .arg("-S") + .arg(&path) + .args(["-O", "exit", "--", &config.alias]) + .output(), + ) + .await??; + if !output.status.success() && path.exists() { + std::fs::remove_file(path)?; + } + } + Ok(()) +} + +pub(super) fn spawn( + config: &Config, + attach: bool, + route: &str, + askpass: Option<&Askpass>, +) -> Result { + let mut command = command(config); + isolation(&mut command); + command.args(["-o", "ControlMaster=no"]); + #[cfg(unix)] + { + command.args(["-o", "BatchMode=yes"]); + if attach { + command + .arg("-S") + .arg(socket(config, route)?) + .args(["-o", "ProxyCommand=false"]); + } else { + command.args(["-o", "ControlPath=none"]); + } + } + #[cfg(windows)] + { + let _ = attach; + command.args(["-o", "ControlPath=none"]); + if let Some(askpass) = askpass { + command.args(["-o", "BatchMode=no"]); + askpass.configure(&mut command, &config.askpass_executable); + } else { + command.args(["-o", "BatchMode=yes"]); + } + } + #[cfg(unix)] + let _ = askpass; + command + .args(["--", &config.alias]) + .arg(stub(&config.root)) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + let hostname = route + .lines() + .find_map(|line| line.strip_prefix("hostname ")) + .ok_or_else(|| anyhow!("ssh -G did not report a hostname"))?; + let prefix = format!("Authenticated to {hostname} (").into_bytes(); + let authenticated = Arc::new(AtomicBool::new(false)); + let latched = authenticated.clone(); + let mut child = command.spawn().context("start OpenSSH")?; + let input = child.stdin.take().unwrap(); + let output = Some(BufReader::new(child.stdout.take().unwrap())); + let mut stderr = child.stderr.take().unwrap(); + let stderr_tail = Arc::new(Mutex::new(Vec::new())); + let tail = stderr_tail.clone(); + let stderr = tokio::spawn(async move { + let mut bytes = [0; 4096]; + let mut line = Vec::new(); + while let Ok(len @ 1..) = stderr.read(&mut bytes).await { + for &byte in &bytes[..len] { + if byte == b'\n' { + line.clear(); + } else if line.len() < prefix.len() { + line.push(byte); + if line == prefix { + latched.store(true, Ordering::Relaxed); + } + } + } + let mut tail = tail.lock().unwrap(); + tail.extend_from_slice(&bytes[..len]); + if tail.len() > 16 * 1024 { + let excess = tail.len() - 16 * 1024; + tail.drain(..excess); + } + } + }); + Ok(Session { + child, + input, + output, + stderr, + stderr_tail, + bootstrapped: false, + authenticated, + }) +} + +const EMBEDDED_HOSTS: &[(&str, &str, &str, &[u8])] = + include!(concat!(env!("OUT_DIR"), "/host_binaries.rs")); + +pub(super) struct Binary { + sha: String, + bytes: Vec, +} + +#[cfg(unix)] +pub(crate) fn local_binary(root: &Path) -> Result { + use std::os::unix::fs::PermissionsExt; + + let os = if cfg!(target_os = "macos") { + "Darwin" + } else { + "Linux" + }; + #[cfg(test)] + let directory = Some(orx_test_support::host_binaries()); + #[cfg(not(test))] + let directory: Option = None; + let mut native = None; + if cfg!(debug_assertions) + && directory.is_none() + && std::env::var_os("ORX_HOST_BIN_DIR").is_none() + { + let executable = std::env::current_exe()?; + if let Some(parent) = executable.parent() { + let candidate = parent.join("orx-host"); + if candidate.is_file() { + let bytes = std::fs::read(candidate)?; + native = Some(Binary { + sha: format!("{:x}", Sha256::digest(&bytes)), + bytes, + }); + } + } + } + let binary = match native { + Some(binary) => binary, + None => binary(directory.as_deref(), os, std::env::consts::ARCH)?, + }; + let cache = root + .parent() + .ok_or_else(|| anyhow!("Local run root has no parent"))? + .join("host-bin"); + std::fs::create_dir_all(&cache)?; + std::fs::set_permissions(&cache, std::fs::Permissions::from_mode(0o700))?; + let path = cache.join(format!("orx-host-{}", binary.sha)); + if !path.try_exists()? { + orx_host::publish_bytes(&path, &binary.bytes)?; + } + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o700))?; + Ok(path) +} + +pub(super) fn binary(directory: Option<&Path>, os: &str, arch: &str) -> Result { + let os = match os { + "Linux" => "linux", + "Darwin" => "darwin", + _ => bail!("Unsupported SSH host OS: {os}"), + }; + let arch = match arch { + "x86_64" | "amd64" => "x86_64", + "aarch64" | "arm64" => "aarch64", + _ => bail!("Unsupported SSH host architecture: {arch}"), + }; + let Some(directory) = directory + .map(Path::to_path_buf) + .or_else(|| std::env::var_os("ORX_HOST_BIN_DIR").map(PathBuf::from)) + else { + let (_, _, sha, bytes) = EMBEDDED_HOSTS + .iter() + .find(|(host_os, host_arch, _, _)| *host_os == os && *host_arch == arch) + .ok_or_else(|| anyhow!("No orx-host for {os}-{arch}. Release builds embed hosts; for development, run node scripts/build-host.mjs and set ORX_HOST_BIN_DIR to its output directory"))?; + return Ok(Binary { + sha: (*sha).into(), + bytes: bytes.to_vec(), + }); + }; + let universal = directory.join("orx-host-darwin-universal"); + let path = if os == "darwin" && universal.exists() { + universal + } else { + directory.join(format!("orx-host-{os}-{arch}")) + }; + let metadata = std::fs::metadata(&path).with_context(|| { + format!( + "Missing {}; run node scripts/build-host.mjs --out-dir {}", + path.display(), + directory.display() + ) + })?; + if metadata.len() == 0 || metadata.len() > 4 * 1024 * 1024 { + bail!( + "orx-host binary must be between 1 byte and 4 MiB: {}", + path.display() + ); + } + let bytes = std::fs::read(&path)?; + if bytes.len() as u64 != metadata.len() { + bail!("orx-host binary changed while reading {}", path.display()); + } + Ok(Binary { + sha: format!("{:x}", Sha256::digest(&bytes)), + bytes, + }) +} + +impl Session { + pub async fn close(&mut self) { + let _ = self.child.start_kill(); + let _ = self.child.wait().await; + } + + pub async fn handshake(&mut self) -> Result<(String, String)> { + use tokio::io::AsyncBufReadExt; + let mut output = self.output.as_mut().unwrap().take(16 * 1024); + let mut line = Vec::new(); + for _ in 0..64 { + line.clear(); + if output.read_until(b'\n', &mut line).await? == 0 { + bail!("SSH connection closed"); + } + if !line.ends_with(b"\n") { + bail!("SSH bootstrap exceeded 16 KiB"); + } + if !line.starts_with(b"ORX1 ") { + continue; + } + let line = std::str::from_utf8(&line)?; + let fields: Vec<_> = line.split_whitespace().collect(); + if fields.len() != 3 { + bail!("Invalid orx-host bootstrap handshake: {line:?}"); + } + self.bootstrapped = true; + return Ok((fields[1].into(), fields[2].into())); + } + bail!("SSH bootstrap exceeded 64 lines") + } + + pub async fn bootstrap(&mut self, binary: &Binary) -> Result<()> { + use tokio::io::AsyncBufReadExt; + self.input + .write_all(format!("RUN {}\n", binary.sha).as_bytes()) + .await?; + self.input.flush().await?; + let mut ready = String::new(); + self.output + .as_mut() + .unwrap() + .take(256) + .read_line(&mut ready) + .await?; + if ready == "ORX1 missing\n" { + self.input + .write_all(format!("PUT {} {}\n", binary.sha, binary.bytes.len()).as_bytes()) + .await?; + for bytes in binary.bytes.chunks(256 * 1024) { + self.input.write_all(bytes).await?; + } + self.input.flush().await?; + // BSD head can consume trailing pipe bytes; wait before sending Hello. + ready.clear(); + self.output + .as_mut() + .unwrap() + .take(256) + .read_line(&mut ready) + .await?; + } + if ready != "ORX1 ready\n" { + bail!("Invalid bootstrap response: {ready:?}"); + } + write( + &mut self.input, + &Message { + id: 0, + body: Request::Hello { + proto: PROTOCOL_VERSION, + }, + }, + ) + .await?; + let message = read(self.output.as_mut().unwrap()).await?; + match message { + Message { + id: 0, + body: + Response::Hello { + proto: PROTOCOL_VERSION, + binary_sha, + .. + }, + } if binary_sha == binary.sha => Ok(()), + message => bail!("orx-host Hello mismatch: {message:?}"), + } + } + + pub async fn failure(&mut self, error: anyhow::Error, retry_closure: bool) -> Failure { + let status = match tokio::time::timeout(Duration::from_millis(200), self.child.wait()).await + { + Ok(status) => status.ok(), + Err(_) => { + let _ = self.child.start_kill(); + self.child.wait().await.ok() + } + }; + let _ = tokio::time::timeout(Duration::from_secs(1), &mut self.stderr).await; + let tail = self.stderr_tail.lock().unwrap(); + let stderr = String::from_utf8_lossy(&tail); + let code = status.and_then(|status| status.code()); + let retry_closure = retry_closure || self.authenticated.load(Ordering::Relaxed); + let mut failure = failure(&error.to_string(), &stderr, code, retry_closure); + if self.bootstrapped + || self.authenticated.load(Ordering::Relaxed) && matches!(code, Some(95..=98)) + { + failure.breaker = false; + } + failure + } +} + +pub(super) async fn write( + writer: &mut (impl AsyncWrite + Unpin), + message: &Message, +) -> Result<()> { + let mut bytes = Vec::new(); + orx_host_proto::write_frame(&mut bytes, message)?; + writer.write_all(&bytes).await?; + writer.flush().await?; + Ok(()) +} + +pub(super) async fn read(reader: &mut (impl AsyncRead + Unpin)) -> Result> { + let mut prefix = [0; 4]; + reader.read_exact(&mut prefix).await?; + let len = u32::from_be_bytes(prefix) as usize; + if len == 0 || len > MAX_FRAME_LEN { + bail!("Invalid orx-host frame length: {len}"); + } + let mut bytes = vec![0; len + 4]; + bytes[..4].copy_from_slice(&prefix); + reader.read_exact(&mut bytes[4..]).await?; + orx_host_proto::read_frame(&mut bytes.as_slice())?.ok_or_else(|| anyhow!("orx-host EOF")) +} + +pub(super) struct Failure { + pub cause: String, + pub breaker: bool, +} + +pub(super) fn failure( + error: &str, + stderr: &str, + code: Option, + retry_closure: bool, +) -> Failure { + let lines: Vec<_> = stderr + .lines() + .map(str::trim) + .filter(|line| { + !line.is_empty() + && !line.starts_with("Authenticated to ") + && !line.starts_with("Transferred: ") + && !line.starts_with("Bytes per second: ") + && !line.starts_with("Killed by signal ") + }) + .collect(); + let clean = |mut line: &str| { + while let Some((head, rest)) = line.split_once(": ") { + if head.chars().any(char::is_whitespace) + || head.contains(['/', '\\']) + || (head.len() == 1 && head.as_bytes()[0].is_ascii_alphabetic()) + { + break; + } + line = rest; + } + line.to_owned() + }; + let detail = lines.first().map(|first| { + let first = clean(first); + let last = clean(lines.last().unwrap()); + if first == last { + if first.chars().count() > 200 { + format!("{}…", first.chars().take(199).collect::()) + } else { + first + } + } else if first.chars().count() + last.chars().count() + 2 <= 200 { + format!("{first}; {last}") + } else { + format!( + "{}…; {}…", + first.chars().take(98).collect::(), + last.chars().take(98).collect::() + ) + } + }); + let remote = match code { + Some(98) => Some("Could not prepare the remote run directory".into()), + Some(97) => Some("The remote host rejected the bootstrap request".into()), + Some(96) => Some("Could not install or verify the remote host binary".into()), + Some(95) => Some("The remote host binary is missing".into()), + Some(code) if code != 255 => Some(format!("Remote command exited with status {code}")), + _ => None, + }; + let lower = stderr.to_ascii_lowercase(); + for (needle, message) in [ + ( + "remote host identification has changed", + "Host key verification failed", + ), + ( + "host key verification failed", + "Host key verification failed", + ), + ( + "too many authentication failures", + "Too many authentication failures", + ), + ("authentication failed", "Authentication failed"), + ] { + if lower.contains(needle) { + return Failure { + cause: message.into(), + breaker: true, + }; + } + } + if let Some(cause) = lines.iter().find_map(|line| { + let start = line.to_ascii_lowercase().find("permission denied")?; + Some(line[start..].trim_end_matches('.').to_owned()) + }) { + return Failure { + cause, + breaker: true, + }; + } + let first = lines.first().copied().unwrap_or(error); + let lower = first.to_ascii_lowercase(); + for (needle, message) in [ + ("connection refused", Some("Connection refused")), + ("connection timed out", Some("Connection timed out")), + ("operation timed out", Some("Connection timed out")), + ("could not resolve hostname", None), + ("no route to host", Some("No route to host")), + ("network is unreachable", Some("Network is unreachable")), + ("host is down", Some("Host is down")), + ("network is down", Some("Network is down")), + ("connection reset by peer", Some("Connection reset by peer")), + ("connection closed by", None), + ("kex_exchange_identification: connection closed", None), + ("ssh_exchange_identification: connection closed", None), + ] { + if let Some(start) = lower.find(needle) { + return Failure { + cause: message + .map(str::to_owned) + .unwrap_or_else(|| first[start..].trim_end_matches('.').into()), + breaker: !retry_closure && needle.contains("connection closed"), + }; + } + } + let primary = remote.as_deref().unwrap_or(error); + Failure { + cause: detail.map_or_else(|| primary.into(), |detail| format!("{primary}: {detail}")), + breaker: true, + } +} + +pub(super) fn stub(root: &str) -> String { + let home_relative = root + .strip_prefix("~/") + .or_else(|| root.strip_prefix("$HOME/")); + let quoted = sh_quote(home_relative.unwrap_or(root)); + let root = if home_relative.is_some() { + format!("\"$HOME\"/{quoted}") + } else { + quoted + }; + // csh expands history inside single quotes; avoid '!' in the bootstrap syntax. + let script = format!( + r#"umask 077; R={root}; +mkdir -p "$R/bin" "$R/runs" "$R/sources" && chmod 700 "$R" "$R/bin" || exit 98; +printf 'ORX1 %s %s\n' "$(uname -s)" "$(uname -m)"; +read_request() {{ IFS=' ' read -r verb sha len || return 1; [ "$sha" = "$(printf '%s' "$sha" | tr -cd '0-9a-f')" ] && [ "${{#sha}}" -eq 64 ]; }}; +read_request || exit 97; B="$R/bin/orx-host-$sha"; +if [ "$verb" = RUN ]; then + if [ -x "$B" ]; then :; else printf 'ORX1 missing\n'; read_request || exit 97; [ "$verb" = PUT ] || exit 97; B="$R/bin/orx-host-$sha"; fi; +fi; +if [ "$verb" = PUT ]; then + [ "$len" = "$(printf '%s' "$len" | tr -cd '0-9')" ] || exit 97; + [ "$len" -gt 0 ] && [ "$len" -le 4194304 ] || exit 97; + T="$B.$$"; trap 'rm -f "$T"' 0 HUP INT TERM; + head -c "$len" > "$T" && [ "$(wc -c < "$T")" -eq "$len" ] && chmod 700 "$T" && "$T" verify-self "$sha" && mv -f "$T" "$B" || exit 96; + trap - 0 HUP INT TERM; +elif [ "$verb" = RUN ]; then :; else exit 97; fi; +[ -x "$B" ] || exit 95; printf 'ORX1 ready\n'; exec "$B" serve --root "$R""# + ); + format!("exec /bin/sh -c {}", sh_quote(&script.replace('\n', " "))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn embedded_hosts_keep_their_digest_and_allow_directory_overrides() { + for (_, _, sha, bytes) in EMBEDDED_HOSTS { + assert_eq!(*sha, format!("{:x}", Sha256::digest(bytes))); + } + let directory = + std::env::temp_dir().join(format!("orx-host-override-{}", uuid::Uuid::new_v4())); + std::fs::create_dir(&directory).unwrap(); + assert!(binary(Some(&directory), "Linux", "x86_64").is_err()); + std::fs::write(directory.join("orx-host-linux-x86_64"), b"explicit host").unwrap(); + let binary = binary(Some(&directory), "Linux", "x86_64").unwrap(); + assert_eq!(binary.bytes, b"explicit host"); + assert_eq!( + binary.sha, + format!("{:x}", Sha256::digest(b"explicit host")) + ); + std::fs::remove_dir_all(directory).unwrap(); + } +} + +#[cfg(all(test, unix))] +mod properties; diff --git a/src/engine/transport/ssh/properties.rs b/src/engine/transport/ssh/properties.rs new file mode 100644 index 000000000..9c489d81d --- /dev/null +++ b/src/engine/transport/ssh/properties.rs @@ -0,0 +1,218 @@ +use super::*; +use crate::engine::runtime::chaos::rng::Rng; + +fn stub(bytes: &[u8]) -> Session { + let hex: String = bytes.iter().map(|byte| format!("{byte:02x}")).collect(); + let mut child = crate::process::tokio_command("python3") + .args(["-c", "import os,sys; os.write(1,bytes.fromhex(sys.argv[1])); os.close(1); sys.stdin.buffer.read()", &hex]) + .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null()).kill_on_drop(true).spawn().unwrap(); + Session { + input: child.stdin.take().unwrap(), + output: Some(BufReader::new(child.stdout.take().unwrap())), + child, + stderr: tokio::spawn(async {}), + stderr_tail: Arc::new(Mutex::new(Vec::new())), + bootstrapped: false, + authenticated: Arc::new(AtomicBool::new(false)), + } +} + +#[tokio::test] +async fn seeded_bootstrap_stub_responses_are_bounded_and_validated() { + let seed = 0x7b6c9d189f049321; + let mut rng = Rng(seed); + for case in 0..256 { + let bytes = match rng.next() % 4 { + 0 => format!("ORX1 OS-{} arch-{}\n", rng.next(), rng.next()).into_bytes(), + 1 => b"ORX1 Linux x86_64 extra\n".to_vec(), + 2 => vec![b'x'; 300], + _ => (0..rng.next() % 600).map(|_| rng.next() as u8).collect(), + }; + let expected = bytes + .split_inclusive(|&byte| byte == b'\n') + .find(|line| line.starts_with(b"ORX1 ")) + .filter(|line| line.ends_with(b"\n")) + .and_then(|line| std::str::from_utf8(line).ok()) + .and_then(|line| { + let fields: Vec<_> = line.split_whitespace().collect(); + (fields.len() == 3).then(|| (fields[1].to_owned(), fields[2].to_owned())) + }); + let mut session = stub(&bytes); + let actual = tokio::time::timeout(Duration::from_secs(2), session.handshake()) + .await + .expect("handshake hung") + .ok(); + assert_eq!(actual, expected, "seed={seed} case={case}"); + session.close().await; + + let binary = Binary { + sha: "a".repeat(64), + bytes: vec![1, 2, 3], + }; + let mode = rng.next() % 8; + let mut output = match mode { + 0 => b"ORX1 missing\nORX1 ready\n".to_vec(), + 1..=3 => b"ORX1 ready\n".to_vec(), + 4 => b"ORX1 ready \n".to_vec(), + 5 => vec![b'R'; 300], + _ => (0..rng.next() % 600).map(|_| rng.next() as u8).collect(), + }; + orx_host_proto::write_frame( + &mut output, + &Message { + id: 0, + body: Response::Hello { + proto: if mode == 2 { + PROTOCOL_VERSION + 1 + } else { + PROTOCOL_VERSION + }, + binary_sha: if mode == 3 { + "wrong".into() + } else { + binary.sha.clone() + }, + boot_id: "boot".into(), + os: "Linux".into(), + arch: "x86_64".into(), + kernel: "test".into(), + }, + }, + ) + .unwrap(); + let mut session = stub(&output); + let actual = tokio::time::timeout(Duration::from_secs(2), session.bootstrap(&binary)) + .await + .expect("bootstrap hung"); + assert_eq!( + actual.is_ok(), + mode <= 1, + "seed={seed} case={case} mode={mode}: {actual:?}" + ); + session.close().await; + } +} + +#[tokio::test] +async fn seeded_base64_pages_round_trip_through_async_frames() { + let mut rng = Rng(0xef528d041a9bb673); + for case in 0..256 { + let bytes: Vec<_> = (0..rng.next() % 8192).map(|_| rng.next() as u8).collect(); + let page = orx_host_proto::LogPage::Data { + len: None, + ident: orx_host_proto::FileIdent { + dev: rng.next(), + ino: rng.next(), + }, + start: rng.next(), + bytes, + eof: rng.next() & 1 == 0, + }; + let message = Message { + id: rng.next(), + body: Response::ReadLog { page }, + }; + let json = serde_json::to_value(&message).unwrap(); + assert!(json["body"]["page"]["data"].is_string()); + assert!(json["body"]["page"]["ident"].is_string()); + let mut frame = Vec::new(); + orx_host_proto::write_frame(&mut frame, &message).unwrap(); + let actual = read(&mut frame.as_slice()).await.unwrap(); + assert_eq!(actual, message, "case={case}"); + } +} + +#[tokio::test] +async fn bootstrap_banner_limits_count_lines_and_bytes() { + let handshake = b"ORX1 Linux x86_64\n"; + for (banner, expected) in [ + (b"banner\n".repeat(63), true), + (b"banner\n".repeat(64), false), + ( + [vec![b'x'; 16 * 1024 - handshake.len() - 1], b"\n".to_vec()].concat(), + true, + ), + ([vec![b'x'; 16 * 1024], b"\n".to_vec()].concat(), false), + (b"\xff\xfe\n".to_vec(), true), + (b"ORX1 invalid\n".to_vec(), false), + ] { + let mut session = stub(&[banner, handshake.to_vec()].concat()); + let result = tokio::time::timeout(Duration::from_secs(2), session.handshake()) + .await + .unwrap(); + assert_eq!(result.is_ok(), expected, "{result:?}"); + assert_eq!(session.bootstrapped, expected); + session.close().await; + } +} + +#[tokio::test] +async fn inner_proxy_jump_authentication_is_not_target_authentication() { + let jump = orx_test_support::Sshd::start().unwrap(); + let target = orx_test_support::Sshd::start().unwrap(); + let target_config = std::fs::read_to_string(target.config_path()) + .unwrap() + .replace("Host orx-test\n", "Host orx-test\n ProxyJump orx-jump\n") + .replace("HostName 127.0.0.1", "HostName localhost"); + let jump_config = std::fs::read_to_string(jump.config_path()) + .unwrap() + .replace("Host orx-test\n", "Host orx-jump\n LogLevel VERBOSE\n"); + std::fs::write( + target.config_path(), + format!("{target_config}{jump_config}"), + ) + .unwrap(); + let config = Config { + alias: target.alias().into(), + root: "~/engine-root".into(), + ssh_config: Some(target.config_path()), + control_dir: target.directory().join("cm"), + binary_dir: None, + #[cfg(unix)] + sharing_home: None, + askpass_executable: "/unused".into(), + }; + let route = route(&config).await.unwrap(); + let mut session = spawn(&config, false, &route, None).unwrap(); + let error = tokio::time::timeout(Duration::from_secs(5), session.handshake()) + .await + .unwrap() + .unwrap_err(); + let failure = session.failure(error, false).await; + assert!(failure.breaker); + let tail = session.stderr_tail.lock().unwrap(); + let stderr = String::from_utf8_lossy(&tail); + assert!(stderr.contains("Authenticated to 127.0.0.1 ("), "{stderr}"); + assert!(!session.authenticated.load(Ordering::Relaxed)); +} + +#[tokio::test] +async fn target_authentication_latch_survives_diagnostic_tail_eviction() { + let server = orx_test_support::Sshd::start().unwrap(); + std::fs::write(server.directory().join("command"), + "#!/bin/sh\nhead -c 20000 /dev/zero | tr '\\0' '\\n' >&2\nprintf '\\nremote directory unavailable\\n' >&2\nexit 98\n").unwrap(); + let config = Config { + alias: server.alias().into(), + root: "~/engine-root".into(), + ssh_config: Some(server.config_path()), + control_dir: server.directory().join("cm"), + binary_dir: None, + #[cfg(unix)] + sharing_home: None, + askpass_executable: "/unused".into(), + }; + let route = route(&config).await.unwrap(); + let mut session = spawn(&config, false, &route, None).unwrap(); + let error = tokio::time::timeout(Duration::from_secs(5), session.handshake()) + .await + .unwrap() + .unwrap_err(); + let failure = session.failure(error, false).await; + assert!(session.authenticated.load(Ordering::Relaxed)); + assert!(!failure.breaker); + let tail = session.stderr_tail.lock().unwrap(); + assert!(tail.len() <= 16 * 1024); + let stderr = String::from_utf8_lossy(&tail); + assert!(!stderr.contains("Authenticated to ")); + assert!(super::failure("SSH connection closed", &stderr, Some(98), false).breaker); +} diff --git a/src/engine/transport/tests.rs b/src/engine/transport/tests.rs new file mode 100644 index 000000000..2bb1d09c0 --- /dev/null +++ b/src/engine/transport/tests.rs @@ -0,0 +1,2104 @@ +use super::*; +use orx_test_support::{Faults, Sshd, SshdBuilder}; +use std::fs; +use std::sync::atomic::{AtomicI64, AtomicU64, Ordering}; +use std::time::Instant; + +struct TestClock { + start: Instant, + wall: AtomicI64, + mono: AtomicU64, +} + +impl TestClock { + fn new() -> Arc { + Arc::new(Self { + start: Instant::now(), + wall: AtomicI64::new(0), + mono: AtomicU64::new(0), + }) + } + + fn advance(&self, millis: u64) { + self.wall.fetch_add(millis as i64, Ordering::SeqCst); + self.mono.fetch_add(millis, Ordering::SeqCst); + } +} + +impl Clock for TestClock { + fn wall_ms(&self) -> i64 { + 1_700_000_000_000 + + self.start.elapsed().as_millis() as i64 + + self.wall.load(Ordering::SeqCst) + } + fn monotonic(&self) -> Duration { + self.start.elapsed() + Duration::from_millis(self.mono.load(Ordering::SeqCst)) + } +} + +use orx_test_support::host_binaries as binaries; + +fn config(server: &Sshd) -> Config { + Config { + alias: server.alias().into(), + root: "~/engine-root".into(), + ssh_config: Some(server.config_path()), + control_dir: server.directory().join("cm"), + binary_dir: Some(binaries()), + #[cfg(unix)] + sharing_home: None, + askpass_executable: std::env::current_exe() + .unwrap() + .parent() + .unwrap() + .parent() + .unwrap() + .join("orx"), + } +} + +fn start(server: &Sshd, clock: Arc) -> HostConn { + let store = Store::open_at(server.directory().join("store")).unwrap(); + let config = config(server); + let auth = Auth::new(&store, &config.alias).unwrap(); + HostConn::start_shared(config, store, clock, auth).unwrap() +} + +fn alias_auth(server: &Sshd) -> AuthState { + Store::open_at(server.directory().join("store")) + .unwrap() + .engine_host_auth(server.alias()) + .unwrap() +} + +async fn status(conn: &HostConn, wanted: Status) -> HostState { + let mut state = conn.state(); + tokio::time::timeout(Duration::from_secs(45), async { + loop { + let snapshot = state.borrow_and_update().clone(); + if snapshot.status == wanted { + return snapshot; + } + state.changed().await.unwrap(); + } + }) + .await + .unwrap_or_else(|_| panic!("waiting for {wanted:?}: {:?}", *conn.state.borrow())) +} + +fn auth_attempts(server: &Sshd) -> BTreeMap<(String, String), usize> { + server.auth_attempts().unwrap() +} + +async fn logged_attempts(server: &Sshd, count: usize) -> BTreeMap<(String, String), usize> { + tokio::time::timeout(Duration::from_secs(5), async { + loop { + let attempts = auth_attempts(server); + if attempts.values().sum::() >= count { + return attempts; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap_or_else(|_| panic!("Missing auth events: {:?}", auth_attempts(server))) +} + +fn ssh_pids(server: &Sshd) -> Vec { + let output = crate::process::command("ps") + .args(["-axo", "pid=,ppid=,comm=,args="]) + .output() + .unwrap(); + let config = server.config_path(); + String::from_utf8(output.stdout) + .unwrap() + .lines() + .filter_map(|line| { + let mut fields = line.split_whitespace(); + let pid = fields.next()?.parse().ok()?; + let parent: u32 = fields.next()?.parse().ok()?; + let comm = fields.next()?; + (parent == std::process::id() + && comm.ends_with("ssh") + && line.contains(config.to_str().unwrap()) + && !line.contains(" -G ")) + .then_some(pid) + }) + .collect() +} + +async fn exec(conn: &HostConn, command: String) -> orx_host_proto::ExecResult { + let Response::Exec { result } = conn + .request(Request::Exec { + command, + stdin: Vec::new(), + timeout_ms: 10_000, + }) + .await + .unwrap() + else { + panic!("Exec response"); + }; + result +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn key_bootstrap_reuses_binary_and_fifty_requests_share_one_session() { + let server = Sshd::start().unwrap(); + let conn = start(&server, TestClock::new()); + assert_eq!( + { + status(&conn, Status::Live).await; + alias_auth(&server).class + }, + Some(HostClass::Key) + ); + assert!(matches!( + conn.request(Request::Hello { + proto: orx_host_proto::PROTOCOL_VERSION + }) + .await + .unwrap(), + Response::Hello { .. } + )); + let installed: Vec<_> = fs::read_dir(server.home().join("engine-root/bin")) + .unwrap() + .map(|entry| entry.unwrap().path()) + .collect(); + assert_eq!(installed.len(), 1); + use std::os::unix::fs::MetadataExt; + let before = fs::metadata(&installed[0]).unwrap(); + let original = ssh_pids(&server); + assert_eq!(original.len(), 1); + let accepted = ("publickey".into(), "Accepted".into()); + assert_eq!(auth_attempts(&server)[&accepted], 1); + let requests = (0..50).map(|index| { + let conn = conn.clone(); + async move { + assert_eq!( + exec(&conn, format!("printf '{index}'")).await.stdout, + index.to_string().as_bytes() + ); + } + }); + futures::future::join_all(requests).await; + assert_eq!(ssh_pids(&server), original); + conn.retry().await.unwrap(); + status(&conn, Status::Live).await; + let after = fs::metadata(&installed[0]).unwrap(); + assert_eq!( + (before.ino(), before.mtime(), before.mtime_nsec()), + (after.ino(), after.mtime(), after.mtime_nsec()) + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn needs_auth_key_host_makes_no_startup_attempt() { + let server = Sshd::start().unwrap(); + let clock = TestClock::new(); + let store = Store::open_at(server.directory().join("store")).unwrap(); + store + .seed_engine_host( + server.alias(), + "~/engine-root", + Some(HostClass::Key), + &HostState { + status: Status::NeedsAuth, + cause: Some("Authentication failed".into()), + ..HostState::default() + }, + ) + .unwrap(); + let mut pinned = store.engine_host_auth(server.alias()).unwrap(); + pinned.route = Some(ssh::route(&config(&server)).await.unwrap()); + store + .save_engine_host_auth(server.alias(), &pinned) + .unwrap(); + for _ in 0..2 { + let conn = start(&server, clock.clone()); + assert!(conn + .request(Request::Hello { + proto: orx_host_proto::PROTOCOL_VERSION, + }) + .await + .is_err()); + assert_eq!(conn.state().borrow().status, Status::NeedsAuth); + assert_eq!(auth_attempts(&server).values().sum::(), 0); + clock.advance(3_600_000); + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn rejected_first_key_opens_durable_breaker_and_never_retries() { + let server = Sshd::start().unwrap(); + let config = fs::read_to_string(server.config_path()) + .unwrap() + .replace("LogLevel ERROR", "LogLevel QUIET"); + fs::write(server.config_path(), config).unwrap(); + fs::write(server.directory().join("authorized_keys"), "").unwrap(); + let clock = TestClock::new(); + let conn = start(&server, clock.clone()); + assert_eq!( + { + status(&conn, Status::NeedsAuth).await; + alias_auth(&server).class + }, + Some(HostClass::Interactive) + ); + assert!(conn.state().borrow().last_live_ms.is_none()); + assert!(ssh_pids(&server).is_empty()); + let attempts = auth_attempts(&server); + assert_eq!(attempts.values().sum::(), 1, "{attempts:?}"); + clock.wall.fetch_add(30 * 60 * 1000, Ordering::SeqCst); + tokio::time::sleep(Duration::from_millis(250)).await; + assert!(ssh_pids(&server).is_empty()); + assert_eq!(auth_attempts(&server), attempts); + drop(conn); + let restarted = start(&server, clock); + status(&restarted, Status::NeedsAuth).await; + assert_eq!(auth_attempts(&server), attempts); + let key = fs::read(server.directory().join("client_key.pub")).unwrap(); + fs::write(server.directory().join("authorized_keys"), key).unwrap(); + restarted.retry().await.unwrap(); + assert_eq!( + { + status(&restarted, Status::Live).await; + alias_auth(&server).class + }, + Some(HostClass::Key) + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn interactive_dead_master_cannot_login_and_connect_relays_askpass() { + let passphrase = "orx transport 'passphrase'"; + let server = SshdBuilder { + extra_client_keys: vec![Some(passphrase.into()), None], + identity_files: vec!["client_key_1".into()], + ..SshdBuilder::default() + } + .start() + .unwrap(); + interactive_lifecycle(server, 1).await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn interactive_mfa_master_recovers_without_background_logins() { + let server = SshdBuilder { + authentication_methods: "publickey,publickey".into(), + extra_client_keys: vec![Some("orx transport 'passphrase'".into()), None], + identity_files: vec!["client_key".into(), "client_key_1".into()], + ..SshdBuilder::default() + } + .start() + .unwrap(); + interactive_lifecycle(server, 2).await; +} + +async fn interactive_lifecycle(server: Sshd, factors: usize) { + let passphrase = "orx transport 'passphrase'"; + let clock = TestClock::new(); + let mut conn = start(&server, clock.clone()); + status(&conn, Status::NeedsAuth).await; + let prompts = Arc::new(AtomicU64::new(0)); + let fixture = server.askpass(passphrase).unwrap(); + let prompt: Prompt = Arc::new({ + let prompts = prompts.clone(); + move |question| { + let prompts = prompts.clone(); + let fixture = fixture.clone(); + Box::pin(async move { + prompts.fetch_add(1, Ordering::SeqCst); + let answer = crate::process::tokio_command(fixture) + .arg(question) + .output() + .await?; + Ok(Some(String::from_utf8(answer.stdout)?.trim_end().into())) + }) + } + }); + conn.connect_interactive(prompt.clone(), false) + .await + .unwrap(); + status(&conn, Status::Live).await; + assert!(prompts.load(Ordering::SeqCst) > 0); + let authenticated = auth_attempts(&server); + conn.connect_interactive(prompt.clone(), false) + .await + .unwrap(); + assert_eq!(auth_attempts(&server), authenticated); + drop(conn); + tokio::time::sleep(Duration::from_millis(200)).await; + conn = start(&server, clock.clone()); + status(&conn, Status::Live).await; + assert_eq!(auth_attempts(&server), authenticated); + unsafe { + libc::kill(ssh_pids(&server)[0] as i32, libc::SIGKILL); + } + status(&conn, Status::Backoff).await; + clock.advance(6001); + status(&conn, Status::Live).await; + assert_eq!(alias_auth(&server).class, Some(HostClass::Interactive)); + assert_eq!(auth_attempts(&server), authenticated); + clock.wall.fetch_add(31_000, Ordering::SeqCst); + status(&conn, Status::Backoff).await; + clock.advance(6001); + status(&conn, Status::Live).await; + assert_eq!(auth_attempts(&server), authenticated); + let pin = alias_auth(&server).route.unwrap(); + let path = ssh::socket(&config(&server), &pin).unwrap(); + let output = server + .spawn(&["-S", path.to_str().unwrap(), "-O", "exit"], None) + .unwrap() + .wait(Duration::from_secs(5)) + .unwrap(); + assert!(output.status.success()); + status(&conn, Status::Backoff).await; + let attempts = auth_attempts(&server); + clock.advance(6001); + status(&conn, Status::NeedsAuth).await; + assert!(ssh_pids(&server).is_empty()); + assert_eq!(auth_attempts(&server), attempts); + assert!(conn + .request(Request::Hello { + proto: orx_host_proto::PROTOCOL_VERSION + }) + .await + .is_err()); + let retry_error = conn.retry().await.unwrap_err(); + let retried = + logged_attempts(&server, attempts.values().sum::() + factors * 2 - 1).await; + assert_eq!( + retried.values().sum::() - attempts.values().sum::(), + factors * 2 - 1, + "{retry_error:#}; before={attempts:?}, after={retried:?}" + ); + clock.advance(30 * 60 * 1000); + tokio::time::sleep(Duration::from_millis(250)).await; + assert!(ssh_pids(&server).is_empty()); + assert_eq!(auth_attempts(&server), retried); + conn.connect_interactive(prompt, false).await.unwrap(); + status(&conn, Status::Live).await; + assert!(matches!( + conn.request(Request::Hello { + proto: orx_host_proto::PROTOCOL_VERSION + }) + .await + .unwrap(), + Response::Hello { .. } + )); + let original = ssh::socket(&config(&server), &alias_auth(&server).route.unwrap()).unwrap(); + let updated = fs::read_to_string(server.config_path()) + .unwrap() + .replace("client_key_1", "client_key_2"); + fs::write(server.config_path(), updated).unwrap(); + let prompt: Prompt = + Arc::new(|_| Box::pin(async { bail!("Unexpected prompt for unencrypted key") })); + conn.connect_interactive(prompt, false).await.unwrap(); + assert_ne!( + original, + ssh::socket(&config(&server), &alias_auth(&server).route.unwrap()).unwrap() + ); + assert!(!original.exists()); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn user_master_is_ignored_and_route_edits_require_explicit_approval() { + let server = SshdBuilder { + extra_client_keys: vec![None], + ..SshdBuilder::default() + } + .start() + .unwrap(); + let user_socket = server.directory().join("user-master"); + let text = fs::read_to_string(server.config_path()) + .unwrap() + .replace("ControlMaster no", "ControlMaster auto") + .replace( + &format!("{}/control-%C", server.directory().display()), + user_socket.to_str().unwrap(), + ); + fs::write(server.config_path(), &text).unwrap(); + let master = server + .spawn(&["-M", "-N", "-S", user_socket.to_str().unwrap()], None) + .unwrap(); + // The master has authenticated once it answers a control check. + tokio::time::timeout(Duration::from_secs(30), async { + loop { + let check = ["-S", user_socket.to_str().unwrap(), "-O", "check"]; + let output = server + .spawn(&check, None) + .unwrap() + .wait(Duration::from_secs(30)); + if output.unwrap().status.success() { + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + let before = auth_attempts(&server); + let clock = TestClock::new(); + let conn = start(&server, clock.clone()); + status(&conn, Status::Live).await; + assert_eq!(ssh_pids(&server).len(), 2); + let accepted = ("publickey".into(), "Accepted".into()); + assert_eq!(auth_attempts(&server)[&accepted] - before[&accepted], 1); + for (from, to) in [ + ( + "HostName 127.0.0.1".to_owned(), + "HostName localhost".to_owned(), + ), + (format!("Port {}", server.port()), "Port 1".to_owned()), + ("client_key\n".to_owned(), "client_key_1\n".to_owned()), + ] { + let attempts = auth_attempts(&server); + fs::write(server.config_path(), text.replace(&from, &to)).unwrap(); + let session_pid = ssh_pids(&server) + .into_iter() + .find(|pid| *pid != master.pid()) + .unwrap(); + unsafe { + libc::kill(session_pid as i32, libc::SIGKILL); + } + status(&conn, Status::Backoff).await; + clock.advance(6001); + status(&conn, Status::NeedsAuth).await; + assert_eq!(auth_attempts(&server), attempts); + fs::write(server.config_path(), &text).unwrap(); + conn.retry().await.unwrap(); + status(&conn, Status::Live).await; + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn black_hole_is_unreachable_by_deadline_and_recovers_in_one_backoff_step() { + let server = Sshd::start().unwrap(); + let clock = TestClock::new(); + let conn = start(&server, clock.clone()); + status(&conn, Status::Live).await; + server + .proxy() + .set(Faults { + black_hole: true, + ..Faults::default() + }) + .unwrap(); + let began = Instant::now(); + let failed = status(&conn, Status::Backoff).await; + assert!( + began.elapsed() <= Duration::from_secs(36), + "{:?}", + began.elapsed() + ); + assert_eq!(alias_auth(&server).class, Some(HostClass::Key)); + let delay = failed.next_retry_ms.unwrap() - clock.wall_ms(); + assert!((0..=6000).contains(&delay)); + server.proxy().clear().unwrap(); + server.proxy().reset().unwrap(); + clock.advance(delay.max(0) as u64 + 1); + tokio::time::timeout(Duration::from_secs(6), status(&conn, Status::Live)) + .await + .unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn wall_clock_jump_reconnects_key_host_without_backoff() { + let server = Sshd::start().unwrap(); + let clock = TestClock::new(); + let conn = start(&server, clock.clone()); + status(&conn, Status::Live).await; + let before = ssh_pids(&server); + clock.wall.fetch_add(30 * 60 * 1000, Ordering::SeqCst); + tokio::time::timeout(Duration::from_secs(6), async { + loop { + tokio::time::sleep(Duration::from_millis(50)).await; + if conn.state.borrow().status == Status::Live && ssh_pids(&server) != before { + break; + } + } + }) + .await + .unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn restarted_key_host_retries_and_auth_failure_keeps_its_breaker_open() { + let server = Sshd::start().unwrap(); + let config = fs::read_to_string(server.config_path()) + .unwrap() + .replace("LogLevel ERROR", "LogLevel QUIET"); + fs::write(server.config_path(), config).unwrap(); + let clock = TestClock::new(); + let conn = start(&server, clock.clone()); + let live = status(&conn, Status::Live).await; + assert_eq!(live.last_live_ms, Some(live.since_ms)); + server + .proxy() + .set(Faults { + refuse_new: true, + ..Faults::default() + }) + .unwrap(); + unsafe { + libc::kill(ssh_pids(&server)[0] as i32, libc::SIGKILL); + } + let backoff = status(&conn, Status::Backoff).await; + drop(conn); + tokio::time::sleep(Duration::from_millis(200)).await; + let restarted = start(&server, clock.clone()); + let restored = status(&restarted, Status::Backoff).await; + assert_eq!(restored.since_ms, backoff.since_ms); + assert_eq!(restored.failures, backoff.failures + 1); + let attempts = auth_attempts(&server); + server.proxy().clear().unwrap(); + fs::write(server.directory().join("authorized_keys"), "").unwrap(); + let delay = restored.next_retry_ms.unwrap() - clock.wall_ms(); + clock.advance(delay.max(0) as u64 + 1); + let failed = status(&restarted, Status::NeedsAuth).await; + assert_eq!(alias_auth(&server).class, Some(HostClass::Key)); + assert!(failed.last_live_ms >= live.last_live_ms); + assert!(failed.since_ms > backoff.since_ms); + let after = auth_attempts(&server); + assert_eq!( + after.values().sum::() - attempts.values().sum::(), + 1 + ); + drop(restarted); + let restarted = start(&server, clock.clone()); + assert_eq!(status(&restarted, Status::NeedsAuth).await, failed); + clock.advance(30 * 60 * 1000); + tokio::time::sleep(Duration::from_millis(250)).await; + assert!(ssh_pids(&server).is_empty()); + assert_eq!(auth_attempts(&server), after); + assert!(restarted.retry().await.is_err()); + let retried = status(&restarted, Status::NeedsAuth).await; + assert!(retried.since_ms >= failed.since_ms + 30 * 60 * 1000); + assert_eq!(retried.last_live_ms, failed.last_live_ms); +} + +#[test] +fn jittered_cadence_is_persisted_and_capped_at_fifteen_minutes() { + let server = Sshd::start().unwrap(); + let state = HostState::default(); + let (publish, _) = watch::channel(state.clone()); + let (_, incoming) = mpsc::channel(1); + let mut actor = Actor { + auth: Auth::new( + &Store::open_at(server.directory().join("store")).unwrap(), + server.alias(), + ) + .unwrap(), + config: config(&server), + store: Store::open_at(server.directory().join("store")).unwrap(), + clock: TestClock::new(), + state, + publish, + incoming, + }; + actor.classify(HostClass::Key); + let mut since = None; + for base in [5000, 15000, 60000, 300000, 900000, 900000] { + actor.failed(false, "network failure".into()); + let delay = actor.state.next_retry_ms.unwrap() - actor.clock.wall_ms(); + assert!((base * 8 / 10 - 10..=(base * 12 / 10).min(900000)).contains(&delay)); + assert_eq!( + actor + .store + .engine_host(server.alias(), "~/engine-root") + .unwrap() + .unwrap(), + actor.state + ); + assert_eq!( + *since.get_or_insert(actor.state.since_ms), + actor.state.since_ms + ); + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn connect_without_askpass_preserves_key_reconnection() { + let server = Sshd::start().unwrap(); + let clock = TestClock::new(); + let conn = start(&server, clock.clone()); + status(&conn, Status::Live).await; + let prompt: Prompt = Arc::new(|_| Box::pin(async { bail!("Key auth must not prompt") })); + conn.connect_interactive(prompt, false).await.unwrap(); + assert_eq!(alias_auth(&server).class, Some(HostClass::Key)); + let path = ssh::socket(&config(&server), &alias_auth(&server).route.unwrap()).unwrap(); + assert!(!path.exists()); + assert!(!ssh::master_alive(&config(&server), &path).await.unwrap()); + unsafe { + libc::kill(ssh_pids(&server)[0] as i32, libc::SIGKILL); + } + status(&conn, Status::Backoff).await; + clock.advance(6001); + assert_eq!( + { + status(&conn, Status::Live).await; + alias_auth(&server).class + }, + Some(HostClass::Key) + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn queued_retry_and_connect_actions_share_one_attempt() { + let server = Sshd::start().unwrap(); + fs::write(server.directory().join("authorized_keys"), "").unwrap(); + let conn = start(&server, TestClock::new()); + status(&conn, Status::NeedsAuth).await; + let before = auth_attempts(&server); + let retries = (0..30).map(|index| { + let conn = conn.clone(); + async move { + if index % 2 == 0 { + assert!(conn.retry().await.is_err()); + } else { + let prompt: Prompt = Arc::new(|_| Box::pin(async { bail!("Unexpected prompt") })); + assert!(conn.connect_interactive(prompt, false).await.is_err()); + } + } + }); + futures::future::join_all(retries).await; + assert!(ssh_pids(&server).is_empty()); + let after = auth_attempts(&server); + assert_eq!( + after.values().sum::() - before.values().sum::(), + 1 + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn proxy_stderr_is_retained_even_when_a_child_holds_the_pipe_open() { + let server = Sshd::start().unwrap(); + let text = fs::read_to_string(server.config_path()).unwrap(); + fs::write(server.config_path(), format!("ProxyCommand /bin/sh -c 'echo Permission denied sentinel >&2; sleep 3 >/dev/null & exit 1'\n{text}")).unwrap(); + let conn = start(&server, TestClock::new()); + let failed = status(&conn, Status::NeedsAuth).await; + assert!(failed.cause.unwrap().contains("Permission denied sentinel")); + assert!(auth_attempts(&server).is_empty()); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn bootstrap_uses_posix_sh_under_the_available_login_shell() { + let server = Sshd::start().unwrap(); + let shell = if std::path::Path::new("/bin/csh").is_file() { + "/bin/csh" + } else { + "/bin/sh" + }; + let command = server.directory().join("command"); + let text = fs::read_to_string(&command) + .unwrap() + .replace("exec /bin/sh -c", &format!("exec {shell} -f -c")); + fs::write(command, text).unwrap(); + let stub = ssh::stub("~/engine-root"); + assert!(stub.starts_with("exec /bin/sh -c '")); + assert!(!stub.contains('\n')); + let conn = start(&server, TestClock::new()); + status(&conn, Status::Live).await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn quiet_host_key_failure_opens_the_breaker_without_authentication() { + let server = Sshd::start().unwrap(); + let text = fs::read_to_string(server.config_path()) + .unwrap() + .replace("LogLevel ERROR", "LogLevel QUIET"); + fs::write(server.config_path(), text).unwrap(); + let conn = start(&server, TestClock::new()); + status(&conn, Status::Live).await; + let before = auth_attempts(&server); + let wrong = fs::read_to_string(server.directory().join("client_key.pub")).unwrap(); + fs::write( + server.directory().join("known_hosts"), + format!("[127.0.0.1]:{} {wrong}", server.port()), + ) + .unwrap(); + server.proxy().reset().unwrap(); + status(&conn, Status::Backoff).await; + assert!(conn.retry().await.is_err()); + assert_eq!( + status(&conn, Status::NeedsAuth).await.cause.as_deref(), + Some("Host key verification failed") + ); + assert!(ssh_pids(&server).is_empty()); + assert_eq!(auth_attempts(&server), before); +} + +#[test] +fn authentication_errors_win_over_secondary_proxy_disconnects() { + assert!(ssh::failure("closed", "", None, true).breaker); + assert!(ssh::failure("closed", "Permission denied (publickey).\nkex_exchange_identification: Connection closed by UNKNOWN port 65535", None, true).breaker); + assert!( + !ssh::failure( + "closed", + "ssh: connect to host box port 22: Connection refused", + None, + true + ) + .breaker + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn host_key_confirmations_are_relayed_without_classifying_interactive_auth() { + let server = Sshd::start().unwrap(); + let text = fs::read_to_string(server.config_path()) + .unwrap() + .replace("StrictHostKeyChecking yes", "StrictHostKeyChecking ask"); + fs::write(server.config_path(), text).unwrap(); + fs::write(server.directory().join("known_hosts"), "").unwrap(); + let conn = start(&server, TestClock::new()); + status(&conn, Status::NeedsAuth).await; + let questions = Arc::new(std::sync::Mutex::new(Vec::new())); + let prompt: Prompt = Arc::new({ + let questions = questions.clone(); + move |question| { + let mut questions = questions.lock().unwrap(); + questions.push(question); + let answer = if questions.len() == 1 { + "invalid" + } else { + "yes" + }; + Box::pin(async move { Ok(Some(answer.into())) }) + } + }); + conn.connect_interactive(prompt, false).await.unwrap(); + assert_eq!( + { + status(&conn, Status::Live).await; + alias_auth(&server).class + }, + Some(HostClass::Key) + ); + assert_eq!(questions.lock().unwrap().len(), 2); + let path = ssh::socket(&config(&server), &alias_auth(&server).route.unwrap()).unwrap(); + assert!(!path.exists()); + assert!(!ssh::master_alive(&config(&server), &path).await.unwrap()); + assert_eq!(ssh_pids(&server).len(), 1); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn queued_connect_keeps_its_prompt_and_route_approval_after_automatic_failure() { + let passphrase = "queued-connect"; + let server = SshdBuilder { + extra_client_keys: vec![Some(passphrase.into())], + identity_files: vec!["client_key_1".into()], + ..SshdBuilder::default() + } + .start() + .unwrap(); + server + .proxy() + .set(Faults { + paused: true, + ..Faults::default() + }) + .unwrap(); + let conn = start(&server, TestClock::new()); + status(&conn, Status::Connecting).await; + tokio::time::timeout(Duration::from_secs(5), async { + while ssh_pids(&server).is_empty() { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + let text = fs::read_to_string(server.config_path()) + .unwrap() + .replace("HostName 127.0.0.1", "HostName localhost"); + fs::write(server.config_path(), text).unwrap(); + let key = fs::read_to_string(server.directory().join("host_key.pub")).unwrap(); + let mut known = fs::read_to_string(server.directory().join("known_hosts")).unwrap(); + known.push_str(&format!("[localhost]:{} {key}", server.port())); + fs::write(server.directory().join("known_hosts"), known).unwrap(); + let prompts = Arc::new(AtomicU64::new(0)); + let prompt: Prompt = Arc::new({ + let prompts = prompts.clone(); + move |_| { + prompts.fetch_add(1, Ordering::SeqCst); + Box::pin(async { Ok(Some(passphrase.into())) }) + } + }); + let connect = conn.connect_interactive(prompt, false); + tokio::pin!(connect); + assert!(futures::poll!(connect.as_mut()).is_pending()); + server.proxy().clear().unwrap(); + tokio::time::timeout(Duration::from_secs(20), connect) + .await + .unwrap() + .unwrap(); + status(&conn, Status::Live).await; + let pinned = alias_auth(&server); + assert_eq!(pinned.class, Some(HostClass::Interactive)); + assert!(pinned.route.unwrap().contains("hostname localhost")); + assert_eq!(prompts.load(Ordering::SeqCst), 1); + let attempts = logged_attempts(&server, 3).await; + assert_eq!(attempts[&("publickey".into(), "Accepted".into())], 1); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn automatic_success_coalesces_queued_connect_without_another_login() { + let server = Sshd::start().unwrap(); + server + .proxy() + .set(Faults { + paused: true, + ..Faults::default() + }) + .unwrap(); + let conn = start(&server, TestClock::new()); + status(&conn, Status::Connecting).await; + let prompt: Prompt = + Arc::new(|_| Box::pin(async { bail!("Successful key auth must not prompt") })); + let connect = conn.connect_interactive(prompt, false); + tokio::pin!(connect); + assert!(futures::poll!(connect.as_mut()).is_pending()); + server.proxy().clear().unwrap(); + tokio::time::timeout(Duration::from_secs(20), connect) + .await + .unwrap() + .unwrap(); + assert_eq!( + { + status(&conn, Status::Live).await; + alias_auth(&server).class + }, + Some(HostClass::Key) + ); + let attempts = logged_attempts(&server, 2).await; + assert_eq!(attempts[&("publickey".into(), "Accepted".into())], 1); + assert_eq!(ssh_pids(&server).len(), 1); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn delayed_feed_uses_its_wait_budget_while_probes_keep_the_host_live() { + let server = Sshd::start().unwrap(); + let conn = start(&server, TestClock::new()); + status(&conn, Status::Live).await; + let before = ssh_pids(&server); + let attempts = auth_attempts(&server); + server + .proxy() + .set(Faults { + latency: Duration::from_secs(6), + ..Faults::default() + }) + .unwrap(); + tokio::time::sleep(Duration::from_secs(70)).await; + assert_eq!(conn.state.borrow().status, Status::Live); + assert_eq!(ssh_pids(&server), before); + assert_eq!(auth_attempts(&server), attempts); + server.proxy().clear().unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn key_retry_queued_during_auth_failure_cannot_reopen_the_breaker() { + let server = Sshd::start().unwrap(); + fs::write(server.directory().join("authorized_keys"), "").unwrap(); + server + .proxy() + .set(Faults { + latency: Duration::from_millis(100), + ..Faults::default() + }) + .unwrap(); + let store = Store::open_at(server.directory().join("store")).unwrap(); + store + .seed_engine_host( + server.alias(), + "~/engine-root", + Some(HostClass::Key), + &HostState { + ..HostState::default() + }, + ) + .unwrap(); + let conn = { + let config = config(&server); + let auth = Auth::new(&store, &config.alias).unwrap(); + HostConn::start_shared(config, store, TestClock::new(), auth) + } + .unwrap(); + status(&conn, Status::Connecting).await; + conn.retry_key().await.unwrap(); + status(&conn, Status::NeedsAuth).await; + assert_eq!(auth_attempts(&server).values().sum::(), 1); + assert!(conn.retry_key().await.is_err()); + assert_eq!(auth_attempts(&server).values().sum::(), 1); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn key_retry_resets_the_backoff_step_without_prompting() { + let server = Sshd::start().unwrap(); + server + .proxy() + .set(Faults { + refuse_new: true, + ..Faults::default() + }) + .unwrap(); + let clock = TestClock::new(); + let store = Store::open_at(server.directory().join("store")).unwrap(); + store + .seed_engine_host( + server.alias(), + "~/engine-root", + Some(HostClass::Key), + &HostState { + status: Status::Backoff, + failures: 4, + next_retry_ms: Some(clock.wall_ms() + 900_000), + ..HostState::default() + }, + ) + .unwrap(); + let conn = { + let config = config(&server); + let auth = Auth::new(&store, &config.alias).unwrap(); + HostConn::start_shared(config, store, clock.clone(), auth) + } + .unwrap(); + assert!(conn.retry_key().await.is_err()); + let state = status(&conn, Status::Backoff).await; + assert_eq!(state.failures, 1); + let delay = state.next_retry_ms.unwrap() - state.since_ms; + assert!((4000..=6000).contains(&delay), "{delay}"); + assert!(auth_attempts(&server).is_empty()); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn key_retry_cannot_approve_a_changed_route() { + let server = Sshd::start().unwrap(); + let conn = start(&server, TestClock::new()); + status(&conn, Status::Live).await; + let pinned = alias_auth(&server).route; + server + .proxy() + .set(Faults { + refuse_new: true, + ..Faults::default() + }) + .unwrap(); + server.proxy().reset().unwrap(); + status(&conn, Status::Backoff).await; + let config = fs::read_to_string(server.config_path()).unwrap(); + fs::write( + server.config_path(), + format!("{config}\n ProxyCommand false\n"), + ) + .unwrap(); + let attempts = auth_attempts(&server); + assert!(conn.retry_key().await.is_err()); + let failed = status(&conn, Status::NeedsAuth).await; + assert_eq!(alias_auth(&server).route, pinned); + assert_eq!( + failed.cause.as_deref(), + Some("SSH route changed; press Connect to approve it") + ); + assert_eq!(auth_attempts(&server), attempts); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn key_retry_is_a_noop_while_connecting_and_during_live_calls() { + let server = Sshd::start().unwrap(); + server + .proxy() + .set(Faults { + latency: Duration::from_millis(100), + ..Faults::default() + }) + .unwrap(); + let conn = start(&server, TestClock::new()); + status(&conn, Status::Connecting).await; + conn.retry_key().await.unwrap(); + status(&conn, Status::Live).await; + server.proxy().clear().unwrap(); + let pids = ssh_pids(&server); + let attempts = auth_attempts(&server); + assert_eq!(attempts[&("publickey".into(), "Accepted".into())], 1); + let calls = conn.clone(); + let marker = server.home().join("in-flight"); + let call = tokio::spawn(async move { + exec( + &calls, + "touch ~/in-flight; sleep 1; printf completed".into(), + ) + .await + }); + tokio::time::timeout(Duration::from_secs(5), async { + while !marker.exists() { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + conn.retry_key().await.unwrap(); + assert_eq!(call.await.unwrap().stdout, b"completed"); + assert_eq!(ssh_pids(&server), pids); + assert_eq!(auth_attempts(&server), attempts); +} + +#[test] +fn ssh_causes_are_exact_human_diagnostics() { + for (stderr, expected) in [ + ("clo@gpu-box: Permission denied (publickey).\r\n", "Permission denied (publickey)"), + ("ssh: connect to host gpu-box port 22: Connection refused\r\n", "Connection refused"), + ("ssh: connect to host gpu-box port 22: Operation timed out\r\n", "Connection timed out"), + ("ssh: connect to host gpu-box port 22: Connection timed out\r\n", "Connection timed out"), + ("@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @\r\nOffending key in /tmp/known_hosts:1\r\nHost key verification failed.\r\n", "Host key verification failed"), + ("Permission denied (publickey).\nkex_exchange_identification: Connection closed by UNKNOWN port 65535", "Permission denied (publickey)"), + ] { + assert_eq!(ssh::failure("SSH connection closed", stderr, None, true).cause, expected); + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn first_auth_rejection_is_not_a_bootstrap_failure() { + let server = Sshd::start().unwrap(); + fs::write(server.directory().join("authorized_keys"), "").unwrap(); + let conn = start(&server, TestClock::new()); + let failed = status(&conn, Status::NeedsAuth).await; + assert_eq!( + failed.cause.as_deref(), + Some("Permission denied (publickey)") + ); + let error = conn + .request(Request::Hello { + proto: orx_host_proto::PROTOCOL_VERSION, + }) + .await + .unwrap_err(); + assert_eq!(error.to_string(), "Permission denied (publickey)"); + assert!(!error.downcast_ref::().unwrap().sent); +} + +#[test] +fn ssh_diagnostics_preserve_primary_errors_and_proxy_hops() { + for (error, stderr, code, expected, breaker) in [ + ("SSH connection closed", "bash: module: command not found\n", Some(98), "Could not prepare the remote run directory: command not found", true), + ("SSH connection closed", "zsh:1: command not found: cloudflared\n", Some(255), "SSH connection closed: command not found: cloudflared", true), + ("SSH connection closed", "ssh: Could not resolve hostname x: nodename nor servname provided, or not known\n", Some(255), "Could not resolve hostname x: nodename nor servname provided, or not known", false), + ("SSH connection closed", "kex_exchange_identification: read: X\n", Some(255), "SSH connection closed: X", true), + ("SSH connection closed", "user@jump: Permission denied (publickey).\r\nkex_exchange_identification: Connection closed by UNKNOWN port 65535\n", Some(255), "Permission denied (publickey)", true), + ("invalid response", "", Some(97), "The remote host rejected the bootstrap request", true), + ("invalid response", "", Some(96), "Could not install or verify the remote host binary", true), + ("invalid response", "", Some(95), "The remote host binary is missing", true), + ] { + let failure = ssh::failure(error, stderr, code, true); + assert_eq!(failure.cause, expected); + assert_eq!(failure.breaker, breaker); + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn remote_shell_noise_and_stub_failure_do_not_open_the_breaker() { + let server = Sshd::start().unwrap(); + fs::write( + server.directory().join("command"), + "#!/bin/sh\necho 'bash: module: command not found' >&2\nexit 98\n", + ) + .unwrap(); + Store::open_at(server.directory().join("store")) + .unwrap() + .seed_engine_host( + server.alias(), + "~/engine-root", + Some(HostClass::Key), + &HostState::default(), + ) + .unwrap(); + let clock = TestClock::new(); + let conn = start(&server, clock.clone()); + let failed = status(&conn, Status::Backoff).await; + assert_eq!(alias_auth(&server).class, Some(HostClass::Key)); + assert_eq!( + failed.cause.as_deref(), + Some("Could not prepare the remote run directory: command not found") + ); + assert_eq!( + auth_attempts(&server)[&("publickey".into(), "Accepted".into())], + 1 + ); + clock.advance(6001); + logged_attempts(&server, 4).await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn dropped_connection_backs_off_after_authentication() { + let server = Sshd::start().unwrap(); + fs::write( + server.directory().join("command"), + "#!/bin/sh\necho 'Connection closed by 127.0.0.1 port 22' >&2\nexit 255\n", + ) + .unwrap(); + let clock = TestClock::new(); + let conn = start(&server, clock.clone()); + let failed = status(&conn, Status::Backoff).await; + assert_eq!( + failed.cause.as_deref(), + Some("Connection closed by 127.0.0.1 port 22") + ); + assert_eq!( + auth_attempts(&server)[&("publickey".into(), "Accepted".into())], + 1 + ); + clock.advance(6001); + logged_attempts(&server, 4).await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn first_contact_network_allow_list_retries_without_authentication() { + for message in [ + "Connection refused", + "Connection timed out", + "Could not resolve hostname x: unknown host", + "No route to host", + "Network is unreachable", + "Connection reset by peer", + "Host is down", + "Network is down", + ] { + let server = Sshd::start().unwrap(); + let text = fs::read_to_string(server.config_path()).unwrap(); + let marker = server.directory().join("attempts"); + fs::write( + server.config_path(), + format!( + "ProxyCommand /bin/sh -c 'echo x >> {}; echo {} >&2; exit 1'\n{text}", + marker.display(), + message + ), + ) + .unwrap(); + let clock = TestClock::new(); + let conn = start(&server, clock.clone()); + assert_eq!( + { + status(&conn, Status::Backoff).await; + alias_auth(&server).class + }, + None + ); + assert!(auth_attempts(&server).is_empty()); + clock.advance(6001); + tokio::time::timeout(Duration::from_secs(5), async { + while fs::read_to_string(&marker).unwrap().lines().count() < 2 { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + assert!(auth_attempts(&server).is_empty()); + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn auth_breaker_is_shared_across_roots_and_connect_clears_it() { + let server = Sshd::start().unwrap(); + let clock = TestClock::new(); + let store = Store::open_at(server.directory().join("store")).unwrap(); + let auth = Auth::new(&store, server.alias()).unwrap(); + let mut connections = Vec::new(); + for root in ["~/ssh-root", "~/slurm-root"] { + let mut cfg = config(&server); + cfg.root = root.into(); + let conn = HostConn::start_shared( + cfg, + Store::open_at(server.directory().join("store")).unwrap(), + clock.clone(), + auth.clone(), + ) + .unwrap(); + status(&conn, Status::Live).await; + connections.push(conn); + } + fs::write(server.directory().join("authorized_keys"), "").unwrap(); + let before = auth_attempts(&server); + server.proxy().reset().unwrap(); + for conn in &connections { + status(conn, Status::Backoff).await; + } + clock.advance(6001); + for conn in &connections { + status(conn, Status::NeedsAuth).await; + } + let blocked = auth_attempts(&server); + assert_eq!( + blocked.values().sum::() - before.values().sum::(), + 1 + ); + let mut cfg = config(&server); + cfg.root = "~/adopted-root".into(); + connections.push( + HostConn::start_shared( + cfg, + Store::open_at(server.directory().join("store")).unwrap(), + clock.clone(), + auth, + ) + .unwrap(), + ); + status(&connections[2], Status::NeedsAuth).await; + clock.advance(30 * 60 * 1000); + tokio::time::sleep(Duration::from_millis(250)).await; + assert_eq!(auth_attempts(&server), blocked); + fs::write( + server.directory().join("authorized_keys"), + fs::read(server.directory().join("client_key.pub")).unwrap(), + ) + .unwrap(); + connections[0].retry().await.unwrap(); + for conn in &connections { + status(conn, Status::Live).await; + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn connect_with_prompt_on_live_route_preserves_inflight_launch() { + for keep_master in [false, true] { + let server = Sshd::start().unwrap(); + let conn = start(&server, TestClock::new()); + status(&conn, Status::Live).await; + let pids = ssh_pids(&server); + let before = auth_attempts(&server); + server + .proxy() + .set(Faults { + latency: Duration::from_millis(400), + ..Faults::default() + }) + .unwrap(); + let calls = conn.clone(); + let request = tokio::spawn(async move { + calls + .request(Request::Launch(orx_host_proto::LaunchIntent { + run: "connect-inflight".into(), + digest: orx_host::sha(b"connect-inflight"), + run_sh: "true".into(), + env: Default::default(), + source: None, + cancel_sh: None, + })) + .await + }); + tokio::time::timeout(Duration::from_secs(5), async { + while !server + .home() + .join("engine-root/runs/connect-inflight/started") + .exists() + { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + conn.connect_interactive( + Arc::new(|_| Box::pin(async { panic!("Live host prompted") })), + keep_master, + ) + .await + .unwrap(); + assert!(matches!( + request.await.unwrap().unwrap(), + Response::Launch { .. } + )); + assert_eq!(ssh_pids(&server), pids); + if keep_master { + let path = ssh::socket(&config(&server), &alias_auth(&server).route.unwrap()).unwrap(); + assert!(ssh::master_alive(&config(&server), &path).await.unwrap()); + let attempts = auth_attempts(&server); + assert_eq!( + attempts + .get(&("publickey".into(), "Accepted".into())) + .copied() + .unwrap_or(0), + before + .get(&("publickey".into(), "Accepted".into())) + .copied() + .unwrap_or(0) + + 1 + ); + } else { + assert_eq!(auth_attempts(&server), before); + } + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn connect_through_a_peer_root_updates_the_alias_authentication_class() { + let server = Sshd::start().unwrap(); + let key = fs::read(server.directory().join("authorized_keys")).unwrap(); + fs::write(server.directory().join("authorized_keys"), "").unwrap(); + let clock = TestClock::new(); + let store = Store::open_at(server.directory().join("store")).unwrap(); + let auth = Auth::new(&store, server.alias()).unwrap(); + let first = + HostConn::start_shared(config(&server), store, clock.clone(), auth.clone()).unwrap(); + assert_eq!( + { + status(&first, Status::NeedsAuth).await; + alias_auth(&server).class + }, + Some(HostClass::Interactive) + ); + let mut cfg = config(&server); + cfg.root = "~/peer-root".into(); + let peer = HostConn::start_shared( + cfg, + Store::open_at(server.directory().join("store")).unwrap(), + clock, + auth, + ) + .unwrap(); + status(&peer, Status::NeedsAuth).await; + let rejected = auth_attempts(&server) + .get(&("publickey".into(), "Failed".into())) + .copied() + .unwrap_or(0); + fs::write(server.directory().join("authorized_keys"), key).unwrap(); + peer.retry().await.unwrap(); + assert_eq!( + { + status(&peer, Status::Live).await; + alias_auth(&server).class + }, + Some(HostClass::Key) + ); + assert_eq!( + { + status(&first, Status::Live).await; + alias_auth(&server).class + }, + Some(HostClass::Key) + ); + assert_eq!( + auth_attempts(&server) + .get(&("publickey".into(), "Failed".into())) + .copied() + .unwrap_or(0), + rejected + ); +} + +#[test] +fn unmatched_ssh_diagnostics_keep_paths_context_and_bounds() { + for (stderr, expected) in [ + ( + "/bin/bash: module: command not found", + "/bin/bash: module: command not found", + ), + (r"C:\ssh.exe: broken", r"C:\ssh.exe: broken"), + ("C: broken", "C: broken"), + ( + "first useful message\nnoise\nlast useful message", + "first useful message; last useful message", + ), + ] { + let failure = ssh::failure("SSH failed", stderr, Some(255), true); + let expected = format!("SSH failed: {expected}"); + assert_eq!(failure.cause, expected); + assert!(failure.breaker); + } + assert!(ssh::failure("SSH connection failed", "Unclassified ProxyCommand failure\nkex_exchange_identification: Connection closed by remote host", None, true).breaker); + let failure = ssh::failure("SSH failed", "channel 0: open failed: administratively prohibited\nkex_exchange_identification: Connection closed by UNKNOWN port 65535", Some(255), true); + assert!(failure.breaker); + assert_eq!(failure.cause, "SSH failed: channel 0: open failed: administratively prohibited; Connection closed by UNKNOWN port 65535"); + assert!(ssh::failure("SSH failed", "Corrupted MAC on input", None, true).breaker); + for stderr in [ + "Host is down", + "Network is down", + "Connection closed by host", + "kex_exchange_identification: connection closed", + "ssh_exchange_identification: connection closed", + ] { + assert!(!ssh::failure("SSH failed", stderr, None, true).breaker); + } + let failure = ssh::failure("SSH failed", &"x".repeat(400), Some(255), true); + assert_eq!(failure.cause.chars().count(), "SSH failed: ".len() + 200); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn ambiguous_key_failures_open_the_breaker() { + for message in ["Corrupted MAC on input", "Unclassified connection failure"] { + let server = Sshd::start().unwrap(); + let store = Store::open_at(server.directory().join("store")).unwrap(); + store + .seed_engine_host( + server.alias(), + "~/engine-root", + Some(HostClass::Key), + &HostState { + ..HostState::default() + }, + ) + .unwrap(); + fs::write( + server.directory().join("command"), + format!("#!/bin/sh\necho '{message}' >&2\nexit 255\n"), + ) + .unwrap(); + let clock = TestClock::new(); + let conn = start(&server, clock.clone()); + let failed = status(&conn, Status::NeedsAuth).await; + assert_eq!( + failed.cause.unwrap(), + format!("SSH connection closed: {message}") + ); + assert!(store + .engine_host_auth(server.alias()) + .unwrap() + .blocked + .is_some()); + let attempts = auth_attempts(&server).values().sum::(); + clock.advance(30 * 60 * 1000); + tokio::time::sleep(Duration::from_millis(250)).await; + assert_eq!(auth_attempts(&server).values().sum::(), attempts); + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn alias_authorization_survives_lazy_roots_and_restarts() { + let server = Sshd::start().unwrap(); + let store = Store::open_at(server.directory().join("store")).unwrap(); + for root in ["~/engine-root", "~/slurm-root"] { + store + .seed_engine_host( + server.alias(), + root, + Some(HostClass::Key), + &HostState { + status: Status::NeedsAuth, + cause: Some("Permission denied (publickey)".into()), + ..HostState::default() + }, + ) + .unwrap(); + } + for _ in 0..2 { + let conn = start(&server, TestClock::new()); + status(&conn, Status::NeedsAuth).await; + tokio::time::sleep(Duration::from_millis(100)).await; + assert!(auth_attempts(&server).is_empty()); + drop(conn); + tokio::time::sleep(Duration::from_millis(100)).await; + } + let conn = start(&server, TestClock::new()); + conn.retry().await.unwrap(); + status(&conn, Status::Live).await; + assert!(store + .engine_host_auth(server.alias()) + .unwrap() + .blocked + .is_none()); + drop(conn); + tokio::time::sleep(Duration::from_millis(150)).await; + let auth = Auth::new(&store, server.alias()).unwrap(); + let mut peers = Vec::new(); + for root in ["~/engine-root", "~/slurm-root"] { + let mut cfg = config(&server); + cfg.root = root.into(); + let conn = HostConn::start_shared( + cfg, + Store::open_at(server.directory().join("store")).unwrap(), + TestClock::new(), + auth.clone(), + ) + .unwrap(); + status(&conn, Status::Live).await; + peers.push(conn); + } + drop(peers); + tokio::time::sleep(Duration::from_millis(150)).await; + let auth = Auth::new(&store, server.alias()).unwrap(); + let primary = HostConn::start_shared( + config(&server), + Store::open_at(server.directory().join("store")).unwrap(), + TestClock::new(), + auth.clone(), + ) + .unwrap(); + status(&primary, Status::Live).await; + let old = fs::read_to_string(server.config_path()).unwrap(); + fs::write( + server.config_path(), + old.replace("HostName 127.0.0.1", "HostName localhost"), + ) + .unwrap(); + let key = fs::read_to_string(server.directory().join("host_key.pub")).unwrap(); + let mut known = fs::read_to_string(server.directory().join("known_hosts")).unwrap(); + known.push_str(&format!("[localhost]:{} {key}", server.port())); + fs::write(server.directory().join("known_hosts"), known).unwrap(); + primary.retry().await.unwrap(); + let pids = ssh_pids(&server); + let mut cfg = config(&server); + cfg.root = "~/slurm-root".into(); + let lazy = HostConn::start_shared( + cfg, + Store::open_at(server.directory().join("store")).unwrap(), + TestClock::new(), + auth, + ) + .unwrap(); + status(&lazy, Status::Live).await; + assert_eq!(primary.state().borrow().status, Status::Live); + assert!(pids.iter().all(|pid| ssh_pids(&server).contains(pid))); + assert!(store + .engine_host_auth(server.alias()) + .unwrap() + .blocked + .is_none()); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn broken_config_during_connect_leaves_the_actor_alive() { + let server = Sshd::start().unwrap(); + let conn = start(&server, TestClock::new()); + status(&conn, Status::Live).await; + let original = fs::read_to_string(server.config_path()).unwrap(); + fs::write(server.config_path(), "InvalidOrxOption yes\n").unwrap(); + assert!(conn + .connect_interactive(Arc::new(|_| Box::pin(async { Ok(None) })), false) + .await + .is_err()); + assert!(!conn.actions.is_closed()); + assert_eq!(conn.state().borrow().status, Status::NeedsAuth); + fs::write(server.config_path(), original).unwrap(); + conn.retry().await.unwrap(); + status(&conn, Status::Live).await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn automatic_first_success_cannot_clear_a_concurrent_breaker() { + let server = Sshd::start().unwrap(); + server + .proxy() + .set(Faults { + latency: Duration::from_millis(100), + ..Faults::default() + }) + .unwrap(); + let store = Store::open_at(server.directory().join("store")).unwrap(); + let auth = Auth::new(&store, server.alias()).unwrap(); + let conn = HostConn::start_shared( + config(&server), + Store::open_at(server.directory().join("store")).unwrap(), + TestClock::new(), + auth.clone(), + ) + .unwrap(); + status(&conn, Status::Connecting).await; + logged_attempts(&server, 2).await; + auth.block( + &store, + server.alias(), + 123, + "Peer root requires Connect".into(), + ) + .unwrap(); + status(&conn, Status::NeedsAuth).await; + assert_eq!( + store.engine_host_auth(server.alias()).unwrap().blocked, + Some((123, "Peer root requires Connect".into())) + ); + assert_eq!(alias_auth(&server).class, Some(HostClass::Key)); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn silent_proxy_failure_stays_behind_the_breaker_until_connect() { + let server = Sshd::start().unwrap(); + let original = fs::read_to_string(server.config_path()).unwrap(); + let counter = server.directory().join("proxy-attempts"); + fs::write( + server.config_path(), + format!( + "ProxyCommand /bin/sh -c 'echo attempt >> {}; exit 1'\n{original}", + counter.display() + ), + ) + .unwrap(); + let clock = TestClock::new(); + let conn = start(&server, clock.clone()); + status(&conn, Status::NeedsAuth).await; + assert_eq!(fs::read_to_string(&counter).unwrap().lines().count(), 1); + clock.advance(30 * 60 * 1000); + tokio::time::sleep(Duration::from_millis(250)).await; + assert_eq!(fs::read_to_string(&counter).unwrap().lines().count(), 1); + assert!(conn + .connect_interactive( + Arc::new(|_| Box::pin(async { panic!("Silent proxy prompted") })), + false + ) + .await + .is_err()); + assert_eq!(conn.state().borrow().status, Status::NeedsAuth); + assert_eq!(fs::read_to_string(&counter).unwrap().lines().count(), 2); + assert!(auth_attempts(&server).is_empty()); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn post_key_mfa_deadline_opens_the_breaker_without_a_reconnect_storm() { + let server = Sshd::start().unwrap(); + let store = Store::open_at(server.directory().join("store")).unwrap(); + store + .seed_engine_host( + server.alias(), + "~/engine-root", + Some(HostClass::Key), + &HostState::default(), + ) + .unwrap(); + fs::write( + server.directory().join("command"), + "#!/bin/sh\nprintf 'Approve MFA push: ' >&2\nexec sleep 60\n", + ) + .unwrap(); + let clock = TestClock::new(); + let conn = start(&server, clock.clone()); + let failed = status(&conn, Status::NeedsAuth).await; + assert!(failed + .cause + .as_deref() + .unwrap() + .contains("Approve MFA push")); + assert_eq!( + auth_attempts(&server)[&("publickey".into(), "Accepted".into())], + 1 + ); + let attempts = auth_attempts(&server); + clock.advance(30 * 60 * 1000); + tokio::time::sleep(Duration::from_millis(250)).await; + assert_eq!(auth_attempts(&server), attempts); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn proxy_jump_second_factor_fails_without_prompting() { + let jump = SshdBuilder { + authentication_methods: "publickey,publickey".into(), + extra_client_keys: vec![Some("orx transport 'passphrase'".into())], + identity_files: vec!["client_key".into(), "client_key_1".into()], + ..SshdBuilder::default() + } + .start() + .unwrap(); + let server = Sshd::start().unwrap(); + let target = fs::read_to_string(server.config_path()) + .unwrap() + .replace("Host orx-test\n", "Host orx-test\n ProxyJump orx-jump\n"); + let hop = fs::read_to_string(jump.config_path()) + .unwrap() + .replace("Host orx-test\n", "Host orx-jump\n") + .replace(" BatchMode yes\n", ""); + fs::write(server.config_path(), format!("{target}{hop}")).unwrap(); + let clock = TestClock::new(); + let conn = start(&server, clock.clone()); + let failed = status(&conn, Status::NeedsAuth).await; + assert!( + failed + .cause + .as_deref() + .unwrap() + .contains("Permission denied"), + "{failed:?}" + ); + let attempts = auth_attempts(&jump); + assert!(!attempts.is_empty()); + clock.advance(30 * 60 * 1000); + tokio::time::sleep(Duration::from_millis(250)).await; + assert_eq!(auth_attempts(&jump), attempts); + assert!(auth_attempts(&server).is_empty()); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn unpersisted_breaker_still_blocks_every_root() { + let server = Sshd::start().unwrap(); + let clock = TestClock::new(); + let store = Store::open_at(server.directory().join("store")).unwrap(); + let auth = Auth::new(&store, server.alias()).unwrap(); + let mut connections = Vec::new(); + for root in ["~/ssh-root", "~/slurm-root"] { + let mut cfg = config(&server); + cfg.root = root.into(); + let conn = HostConn::start_shared( + cfg, + Store::open_at(server.directory().join("store")).unwrap(), + clock.clone(), + auth.clone(), + ) + .unwrap(); + status(&conn, Status::Live).await; + connections.push(conn); + } + rusqlite::Connection::open(server.directory().join("store/orx.db")) + .unwrap() + .execute_batch( + "CREATE TRIGGER fail_insert BEFORE INSERT ON engine_host_auth + BEGIN SELECT RAISE(FAIL, 'injected write failure'); END; + CREATE TRIGGER fail_update BEFORE UPDATE ON engine_host_auth + BEGIN SELECT RAISE(FAIL, 'injected write failure'); END;", + ) + .unwrap(); + fs::write(server.directory().join("authorized_keys"), "").unwrap(); + let before = auth_attempts(&server).values().sum::(); + server.proxy().reset().unwrap(); + for conn in &connections { + status(conn, Status::Backoff).await; + } + clock.advance(6001); + for conn in &connections { + status(conn, Status::NeedsAuth).await; + } + assert!(store + .engine_host_auth(server.alias()) + .unwrap() + .blocked + .is_none()); + let blocked = auth_attempts(&server); + clock.advance(30 * 60 * 1000); + tokio::time::sleep(Duration::from_millis(250)).await; + assert_eq!(auth_attempts(&server), blocked); + assert_eq!(blocked.values().sum::(), before); +} + +/// Pins and log reads wait in the upload and log lanes, so a host slow to answer them still +/// hears a cancel at once. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn slow_pins_and_log_reads_cannot_delay_a_cancel() { + let server = Sshd::start().unwrap(); + let command = server.directory().join("command"); + let text = fs::read_to_string(&command).unwrap(); + fs::write( + &command, + text.replace("export HOME", "export HOME\nexport ORX_TEST_SLOW_RPC=3000"), + ) + .unwrap(); + let conn = start(&server, TestClock::new()); + status(&conn, Status::Live).await; + let mut slow = Vec::new(); + for index in 0..30 { + let pin = conn.clone(); + slow.push(tokio::spawn(async move { + let _ = pin + .request(Request::PinSource { + run: format!("pin-{index}"), + sha: "0".repeat(64), + }) + .await; + })); + let conn = conn.clone(); + slow.push(tokio::spawn(async move { + let _ = conn + .request(Request::ReadLog { + target: orx_host_proto::LogTarget::Run(format!("read-{index}")), + file: orx_host_proto::LogFile::Log, + ident: None, + range: orx_host_proto::ByteRange { start: 0, end: 1 }, + anchor: None, + }) + .await; + })); + } + tokio::time::sleep(Duration::from_millis(500)).await; + let asked = Instant::now(); + conn.request(Request::Cancel { run: "r1".into() }) + .await + .unwrap(); + assert!( + asked.elapsed() < Duration::from_millis(1500), + "the cancel waited {:?} behind slow requests", + asked.elapsed() + ); + for task in slow { + task.abort(); + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn bashrc_banner_before_bootstrap_is_ignored() { + let server = Sshd::start().unwrap(); + fs::write( + server.home().join(".bashrc"), + "printf 'Welcome to the cluster\\nLoading modules\\n'\n", + ) + .unwrap(); + let path = server.directory().join("command"); + let original = fs::read_to_string(&path).unwrap(); + fs::write( + &path, + original.replace("export HOME", "export HOME\n. \"$HOME/.bashrc\""), + ) + .unwrap(); + let conn = start(&server, TestClock::new()); + status(&conn, Status::Live).await; + assert_eq!(alias_auth(&server).class, Some(HostClass::Key)); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn connection_actor_recovers_after_store_writes_fail() { + for table in ["engine_hosts", "engine_host_auth"] { + let server = Sshd::start().unwrap(); + let clock = TestClock::new(); + let conn = start(&server, clock.clone()); + status(&conn, Status::Live).await; + let db = rusqlite::Connection::open(server.directory().join("store/orx.db")).unwrap(); + db.execute_batch(&format!( + "CREATE TRIGGER fail_write BEFORE INSERT ON {table} + BEGIN SELECT RAISE(FAIL, 'injected write failure'); END;" + )) + .unwrap(); + let attempts = logged_attempts(&server, 2).await; + server.proxy().reset().unwrap(); + status(&conn, Status::Backoff).await; + clock.advance(6001); + status(&conn, Status::NeedsAuth).await; + assert!(!conn.actions.is_closed()); + assert!(conn.retry().await.is_err()); + assert_eq!(auth_attempts(&server), attempts); + db.execute_batch("DROP TRIGGER fail_write").unwrap(); + conn.retry().await.unwrap(); + status(&conn, Status::Live).await; + assert!(alias_auth(&server).blocked.is_none()); + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn failed_breaker_clear_stays_blocked_in_memory() { + let server = Sshd::start().unwrap(); + let store = Store::open_at(server.directory().join("store")).unwrap(); + let auth = Auth::new(&store, server.alias()).unwrap(); + auth.block(&store, server.alias(), 1, "needs Connect".into()) + .unwrap(); + let db = rusqlite::Connection::open(server.directory().join("store/orx.db")).unwrap(); + db.execute_batch( + "CREATE TRIGGER fail_clear BEFORE INSERT ON engine_host_auth + WHEN json_extract(NEW.state_json, '$.blocked') IS NULL BEGIN SELECT RAISE(FAIL, 'injected write failure'); END;", + ) + .unwrap(); + assert!(auth + .update(&store, server.alias(), |state| state.blocked = None) + .is_err()); + assert!(auth.state.borrow().blocked.is_some()); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn breaker_opened_during_route_resolution_prevents_login() { + let server = Sshd::start().unwrap(); + let entered = server.directory().join("route-entered"); + let release = server.directory().join("route-release"); + let script = server.directory().join("route-gate"); + fs::write( + &script, + format!( + "touch {}; while [ ! -e {} ]; do sleep 0.01; done\n", + entered.display(), + release.display() + ), + ) + .unwrap(); + let original = fs::read_to_string(server.config_path()).unwrap(); + fs::write( + server.config_path(), + format!("Match exec \"/bin/sh {}\"\n{original}", script.display()), + ) + .unwrap(); + let store = Store::open_at(server.directory().join("store")).unwrap(); + let auth = Auth::new(&store, server.alias()).unwrap(); + let conn = HostConn::start_shared( + config(&server), + Store::open_at(server.directory().join("store")).unwrap(), + TestClock::new(), + auth.clone(), + ) + .unwrap(); + tokio::time::timeout(Duration::from_secs(5), async { + while !entered.exists() { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + auth.block(&store, server.alias(), 1, "Peer needs Connect".into()) + .unwrap(); + fs::write(release, "").unwrap(); + status(&conn, Status::NeedsAuth).await; + assert!(conn.retry_key().await.is_err()); + assert!(auth_attempts(&server).is_empty()); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn engine_sharing_reuses_mfa_without_authentication() { + if std::env::var_os("ORX_TEST_SHARING_CHILD").is_none() { + use std::os::unix::fs::PermissionsExt; + let temp = crate::local::git::TemporaryDirectory::new("orx-sharing-client").unwrap(); + let bin = temp.path().join("bin"); + fs::create_dir_all(&bin).unwrap(); + let shim = bin.join("ssh"); + fs::write(&shim, r#"#!/bin/sh +if [ -f "$HOME/.ssh/config" ]; then + config="$HOME/.ssh/probe-$$" + sed "s|^Include openresearch_config$|Include $HOME/.ssh/openresearch_config|" "$HOME/.ssh/config" > "$config" + exec /usr/bin/ssh -F "$config" "$@" +else + exec /usr/bin/ssh -F /dev/null "$@" +fi +"#).unwrap(); + fs::set_permissions(&shim, fs::Permissions::from_mode(0o700)).unwrap(); + let mut command = crate::process::command(std::env::current_exe().unwrap()); + command + .args([ + "--exact", + "engine::transport::tests::engine_sharing_reuses_mfa_without_authentication", + "--nocapture", + ]) + .env_remove("CLAUDE_CONFIG_DIR") + .env_remove("CODEX_HOME") + .env("ORX_TEST_SHARING_CHILD", "1") + .env("HOME", temp.path()) + .env("XDG_CONFIG_HOME", temp.path().join(".config")) + .env("XDG_CACHE_HOME", temp.path().join(".cache")) + .env("XDG_DATA_HOME", temp.path().join(".local/share")) + .env( + "PATH", + format!("{}:{}", bin.display(), std::env::var("PATH").unwrap()), + ); + let output = orx_test_support::Process::spawn(&mut command) + .unwrap() + .wait(Duration::from_secs(180)) + .unwrap(); + assert!( + output.status.success(), + "{}\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + return; + } + + let passphrase = "orx sharing passphrase"; + let server = SshdBuilder { + authentication_methods: "publickey,publickey".into(), + extra_client_keys: vec![Some(passphrase.into())], + identity_files: vec!["client_key".into(), "client_key_1".into()], + ..SshdBuilder::default() + } + .start() + .unwrap(); + let home = dirs::home_dir().unwrap(); + fs::create_dir_all(home.join(".ssh")).unwrap(); + let user_config = fs::read_to_string(server.config_path()) + .unwrap() + .lines() + .filter(|line| !line.trim_start().starts_with("ControlPath ")) + .collect::>() + .join("\n") + + "\n"; + fs::write(home.join(".ssh/config"), &user_config).unwrap(); + let clock = TestClock::new(); + let store = Store::open_at(server.directory().join("store")).unwrap(); + let mut cfg = config(&server); + cfg.sharing_home = Some(home.clone()); + let auth = Auth::new(&store, &cfg.alias).unwrap(); + let conn = HostConn::start_shared(cfg, store, clock.clone(), auth).unwrap(); + status(&conn, Status::NeedsAuth).await; + let prompt: Prompt = Arc::new(move |_| Box::pin(async move { Ok(Some(passphrase.into())) })); + conn.connect_interactive(prompt.clone(), false) + .await + .unwrap(); + status(&conn, Status::Live).await; + let attempts = auth_attempts(&server); + let registry = home.join(".ssh/openresearch_connections.json"); + assert!(fs::read_to_string(®istry).unwrap().contains("engine:")); + let installed = fs::read_to_string(home.join(".ssh/config")).unwrap(); + assert_eq!( + installed.matches("Include openresearch_config\n").count(), + 1 + ); + + let plain = |scoped: bool| { + let mut command = crate::process::tokio_command("ssh"); + command + .args([ + "-oBatchMode=yes", + "-oIdentityAgent=none", + "-oIdentityFile=none", + "-oIdentitiesOnly=yes", + server.alias(), + "true", + ]) + .env_remove("SSH_AUTH_SOCK") + .env("SSH_ASKPASS", "") + .env("SSH_ASKPASS_REQUIRE", "never"); + if scoped { + crate::jobs::ssh::prepare_sharing_env(&mut command); + } else { + command.env_remove("ORX_SSH_CONTROL_DIR"); + } + command + }; + for scoped in [true, false] { + let output = plain(scoped).output().await.unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + } + assert_eq!(auth_attempts(&server), attempts); + + let pin = alias_auth(&server).route.unwrap(); + let path = ssh::socket(&config(&server), &pin).unwrap(); + let output = server + .spawn(&["-S", path.to_str().unwrap(), "-O", "exit"], None) + .unwrap() + .wait(Duration::from_secs(5)) + .unwrap(); + assert!(output.status.success()); + status(&conn, Status::Backoff).await; + tokio::time::timeout(Duration::from_secs(5), async { + while fs::read_to_string(®istry).unwrap().contains("engine:") { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + let fallback = plain(true).output().await.unwrap(); + assert!(!fallback.status.success()); + assert!(String::from_utf8_lossy(&fallback.stderr).contains("Permission denied")); + clock.advance(6001); + status(&conn, Status::NeedsAuth).await; + let before = auth_attempts(&server); + tokio::time::sleep(Duration::from_millis(200)).await; + assert_eq!(auth_attempts(&server), before); + assert_eq!( + fs::read_to_string(home.join(".ssh/config")).unwrap(), + installed + ); + + conn.connect_interactive(prompt, false).await.unwrap(); + let changed = installed.replace("IdentitiesOnly yes", "IdentitiesOnly no"); + fs::write(home.join(".ssh/config"), &changed).unwrap(); + let engine_config = fs::read_to_string(server.config_path()) + .unwrap() + .replace("IdentitiesOnly yes", "IdentitiesOnly no"); + fs::write(server.config_path(), engine_config).unwrap(); + assert!(!plain(true).output().await.unwrap().status.success()); + unsafe { + libc::kill(ssh_pids(&server)[0] as i32, libc::SIGKILL); + } + status(&conn, Status::Backoff).await; + clock.advance(6001); + status(&conn, Status::NeedsAuth).await; + assert!(!fs::read_to_string(®istry).unwrap().contains("engine:")); + assert_eq!( + fs::read_to_string(home.join(".ssh/config")).unwrap(), + changed + ); + let mut cfg = config(&server); + cfg.sharing_home = Some(home); + ssh::stop_master(&cfg, &pin).await.unwrap(); +} diff --git a/src/jobs/huggingface.rs b/src/jobs/huggingface.rs index 657d2004c..3cc9f26f3 100644 --- a/src/jobs/huggingface.rs +++ b/src/jobs/huggingface.rs @@ -138,10 +138,10 @@ async fn check(res: reqwest::Response, what: &str) -> Result if status.is_success() { return Ok(res); } - if status.as_u16() == 401 { + if matches!(status.as_u16(), 401 | 403) { res.error_for_status_ref().map_err(|error| { anyhow!(error).context(format!( - "Hugging Face rejected the token (HTTP 401) during {what}. Check HF_TOKEN." + "Hugging Face rejected the token (HTTP {status}) during {what}. Check HF_TOKEN." )) })?; } @@ -222,11 +222,14 @@ pub async fn whoami_details(token: &str) -> Result { Ok(WhoamiDetails { name, jobs_write }) } +#[derive(serde::Serialize, serde::Deserialize)] pub struct JobSubmission { pub command: Vec, pub docker_image: String, pub flavor: String, + #[serde(default)] pub environment: HashMap, + #[serde(default)] pub secrets: HashMap, pub timeout_seconds: u64, pub labels: HashMap, @@ -241,6 +244,7 @@ pub async fn run_job_with_source( spec: &JobSubmission, archive: &Path, digest: &str, + fence: Option<&crate::engine::Fence<'_>>, ) -> Result { let python = CLIENT_ENV.ensure().await?; let source_dir = archive @@ -272,6 +276,18 @@ pub async fn run_job_with_source( .stdout(Stdio::piped()) .stderr(Stdio::piped()) .spawn()?; + if let Some(fence) = fence { + let recorded = fence.record_submitter( + child + .id() + .ok_or_else(|| anyhow!("HF launcher exited before fencing"))?, + ); + if let Err(error) = recorded { + let _ = child.kill().await; + let _ = child.wait().await; + return Err(error); + } + } use tokio::io::AsyncWriteExt as _; child .stdin @@ -339,7 +355,7 @@ pub async fn stream_logs( namespace: &str, job_id: &str, skip: u64, - idle_timeout: Duration, + idle_timeout: Option, sink: &mut (dyn FnMut(&str) + Send), ) -> Result { #[derive(Deserialize)] @@ -362,7 +378,11 @@ pub async fn stream_logs( let mut seen = 0u64; let mut buf: Vec = Vec::new(); loop { - let chunk = match tokio::time::timeout(idle_timeout, res.chunk()).await { + let next = match idle_timeout { + Some(idle) => tokio::time::timeout(idle, res.chunk()).await, + None => Ok(res.chunk().await), + }; + let chunk = match next { Err(_) => break, // idle — likely end of buffered history Ok(Err(e)) => return Err(anyhow!("Hugging Face log stream failed: {}", e)), Ok(Ok(None)) => break, // server closed @@ -416,9 +436,47 @@ pub fn parse_timeout(value: &str) -> Result { }) } -/// Where to watch the job on huggingface.co. -pub fn job_url(namespace: &str, job_id: &str) -> String { - format!("{}/jobs/{}/{}", endpoint(), namespace, job_id) +pub async fn find_run(token: &str, namespace: &str, run: &str) -> Result> { + let base = reqwest::Url::parse(&endpoint())?; + let mut url = base.join(&format!("/api/jobs/{namespace}"))?; + url.query_pairs_mut() + .append_pair("labels", &format!("or_run={run}")); + let mut visited = std::collections::HashSet::new(); + let mut found = Vec::new(); + loop { + if url.origin() != base.origin() || !visited.insert(url.clone()) { + return Err(anyhow!("Invalid HF pagination link")); + } + let response = check( + http().get(url.clone()).bearer_auth(token).send().await?, + "job lookup", + ) + .await?; + let next = response + .headers() + .get("link") + .and_then(|header| header.to_str().ok()) + .and_then(|links| links.split(',').find(|link| link.contains("rel=\"next\""))) + .map(|link| -> Result { + let target = link + .trim() + .strip_prefix('<') + .and_then(|link| link.split_once('>').map(|(target, _)| target)) + .ok_or_else(|| anyhow!("Invalid HF pagination link"))?; + Ok(url.join(target)?) + }) + .transpose()?; + let jobs: Vec = response.json().await?; + for job in jobs { + if job["labels"]["or_run"].as_str() == Some(run) { + found.push(serde_json::from_value(job)?); + } + } + match next { + Some(next) => url = next, + None => return Ok(found), + } + } } #[cfg(test)] @@ -427,7 +485,7 @@ mod settings_tests { #[tokio::test] async fn invalid_token_retains_http_status() { - for status in [401, 503] { + for status in [401, 403, 503] { let response = axum::http::Response::builder() .status(status) .body("") @@ -437,7 +495,7 @@ mod settings_tests { error .downcast_ref::() .and_then(|e| e.status()), - (status == 401).then_some(reqwest::StatusCode::UNAUTHORIZED) + matches!(status, 401 | 403).then(|| reqwest::StatusCode::from_u16(status).unwrap()) ); } } diff --git a/src/jobs/kubernetes.rs b/src/jobs/kubernetes.rs index 448ae351b..580825db5 100644 --- a/src/jobs/kubernetes.rs +++ b/src/jobs/kubernetes.rs @@ -111,7 +111,20 @@ pub fn save_settings(settings: &K8sSettings) -> Result<()> { /// Run kubectl with the given args (plus `--context` when set), feeding /// `stdin` if provided. Non-zero exit → Err carrying stderr. -async fn kubectl(context: Option<&str>, args: &[&str], stdin: Option<&str>) -> Result { +pub(crate) async fn kubectl( + context: Option<&str>, + args: &[&str], + stdin: Option<&str>, +) -> Result { + kubectl_fenced(context, args, stdin, None).await +} + +async fn kubectl_fenced( + context: Option<&str>, + args: &[&str], + stdin: Option<&str>, + fence: Option<&crate::engine::Fence<'_>>, +) -> Result { let mut cmd = crate::process::tokio_command("kubectl"); if let Some(ctx) = context { cmd.arg("--context").arg(ctx); @@ -131,6 +144,18 @@ async fn kubectl(context: Option<&str>, args: &[&str], stdin: Option<&str>) -> R anyhow!("Could not run kubectl: {}", e) } })?; + if let Some(fence) = fence { + let recorded = fence.record_submitter( + child + .id() + .ok_or_else(|| anyhow!("kubectl exited before fencing"))?, + ); + if let Err(error) = recorded { + let _ = child.kill().await; + let _ = child.wait().await; + return Err(error); + } + } if let Some(body) = stdin { let mut pipe = child.stdin.take().expect("piped stdin"); pipe.write_all(body.as_bytes()).await?; @@ -228,6 +253,7 @@ pub async fn preflight(context: Option<&str>, namespace: &str) -> Preflight { // --- manifest submission -------------------------------------------------------- +#[derive(serde::Serialize, serde::Deserialize)] pub struct ManifestSpec { /// Raw manifest text as committed on the experiment branch (YAML or JSON, /// multi-document fine). @@ -238,11 +264,13 @@ pub struct ManifestSpec { /// Run-unique DNS-safe token substituted for `{{ORX_RUN}}`. pub run_token: String, /// Synced into the `orx-env` Secret. + #[serde(default)] pub env: HashMap, /// Injected as `activeDeadlineSeconds` when the manifest doesn't set one. pub timeout_seconds: u64, pub labels: HashMap, /// Set on the primary Job's containers, not in the shared `orx-env` Secret. + #[serde(default)] pub pod_env: Vec<(String, String)>, pub source_archive: PathBuf, } @@ -256,10 +284,11 @@ pub struct Submitted { /// Sync the env Secret, then validate and create the manifest's resources. /// On a partial failure everything already created is rolled back. -pub async fn run_manifest( +pub(crate) async fn run_manifest( context: Option<&str>, namespace: &str, spec: &ManifestSpec, + fence: Option<&crate::engine::Fence<'_>>, ) -> Result { if !spec.env.is_empty() { // stringData via stdin — values never appear on a command line. @@ -274,6 +303,47 @@ pub async fn run_manifest( kubectl(context, &["apply", "-f", "-"], Some(&secret.to_string())).await?; } + let (docs, job_name) = prepared_manifest(context, namespace, spec).await?; + + // Create one resource at a time so a failure can roll back exactly what + // exists so far (a multi-doc `kubectl create` stops mid-way but doesn't + // undo). + let mut created: Vec = Vec::new(); + for doc in &docs { + let handle = resource_handle(doc); + if let Err(e) = kubectl_fenced( + context, + &["create", "-f", "-"], + Some(&doc.to_string()), + fence, + ) + .await + { + for r in created.iter().rev() { + let _ = delete_resources(context, namespace, std::slice::from_ref(r)).await; + } + return Err(anyhow!("could not create {handle}: {e}")); + } + created.push(handle); + } + let staged = stage_source(context, namespace, &job_name, &spec.source_archive).await; + if let Err(error) = staged { + for resource in created.iter().rev() { + let _ = delete_resources(context, namespace, std::slice::from_ref(resource)).await; + } + return Err(error); + } + Ok(Submitted { + job_name, + resources: created, + }) +} + +pub(crate) async fn prepared_manifest( + context: Option<&str>, + namespace: &str, + spec: &ManifestSpec, +) -> Result<(Vec, String)> { let rendered = spec.manifest.replace("{{ORX_RUN}}", &spec.run_token); // YAML → JSON plus schema sanity in one step, without touching the // cluster and without a YAML dependency. @@ -309,34 +379,10 @@ pub async fn run_manifest( &spec.pod_env, )?; - // Create one resource at a time so a failure can roll back exactly what - // exists so far (a multi-doc `kubectl create` stops mid-way but doesn't - // undo). - let mut created: Vec = Vec::new(); - for doc in &docs { - let handle = resource_handle(doc); - if let Err(e) = kubectl(context, &["create", "-f", "-"], Some(&doc.to_string())).await { - for r in created.iter().rev() { - let _ = delete_resources(context, namespace, std::slice::from_ref(r)).await; - } - return Err(anyhow!("could not create {handle}: {e}")); - } - created.push(handle); - } - let staged = stage_source(context, namespace, &job_name, &spec.source_archive).await; - if let Err(error) = staged { - for resource in created.iter().rev() { - let _ = delete_resources(context, namespace, std::slice::from_ref(resource)).await; - } - return Err(error); - } - Ok(Submitted { - job_name, - resources: created, - }) + Ok((docs, job_name)) } -async fn stage_source( +pub(crate) async fn stage_source( context: Option<&str>, namespace: &str, job_name: &str, @@ -364,20 +410,33 @@ async fn stage_source( .unwrap_or_default(); let pod = pod.trim(); if !pod.is_empty() { + if kubectl( + context, + &[ + "exec", + "-n", + namespace, + pod, + "--", + "test", + "-f", + "/tmp/orx-source/source.tar.ready", + ], + None, + ) + .await + .is_ok() + { + return Ok(()); + } let local = archive.to_string_lossy().into_owned(); - let remote = format!("{namespace}/{pod}:/tmp/orx-source/source.tar"); + let remote = format!("{namespace}/{pod}:/tmp/orx-source/source.tar.part"); + let size = tokio::fs::metadata(archive).await?.len(); + let publish = format!("set -e; cd /tmp/orx-source; test -f source.tar.ready && exit 0; test $(wc -c < source.tar.part) -eq {size}; mv source.tar.part source.tar; touch source.tar.ready"); match kubectl(context, &["cp", &local, &remote], None).await { Ok(_) => match kubectl( context, - &[ - "exec", - "-n", - namespace, - pod, - "--", - "touch", - "/tmp/orx-source/source.tar.ready", - ], + &["exec", "-n", namespace, pod, "--", "sh", "-c", &publish], None, ) .await @@ -456,7 +515,7 @@ fn pod_exit(pod: &Value) -> Option<(String, String)> { )) } -fn resource_handle(doc: &Value) -> String { +pub(crate) fn resource_handle(doc: &Value) -> String { format!( "{}/{}", doc["kind"].as_str().unwrap_or("").to_lowercase(), @@ -694,6 +753,7 @@ fn prepare_docs( pub struct JobState { pub stage: String, pub message: Option, + pub exit_code: Option, } pub async fn inspect_job(context: Option<&str>, namespace: &str, name: &str) -> Result { @@ -705,12 +765,11 @@ pub async fn inspect_job(context: Option<&str>, namespace: &str, name: &str) -> .await { Ok(raw) => raw, - // A deleted Job is how cancel manifests (and how TTL cleanup looks - // long after terminal — supervise has exited by then). Err(e) if e.to_string().contains("NotFound") => { return Ok(JobState { stage: "DELETED".to_string(), message: None, + exit_code: None, }) } Err(e) => return Err(e), @@ -731,24 +790,9 @@ pub async fn inspect_job(context: Option<&str>, namespace: &str, name: &str) -> return Ok(JobState { stage: "COMPLETED".to_string(), message: None, + exit_code: Some(0), }); } - if let Some(failed) = condition("Failed") { - let reason = failed["reason"].as_str().unwrap_or(""); - let msg = failed["message"].as_str().unwrap_or(""); - return Ok(JobState { - stage: "ERROR".to_string(), - message: Some( - format!("{reason}: {msg}") - .trim_matches([':', ' ']) - .to_string(), - ), - }); - } - - // Live: RUNNING once every expected pod runs (the whole gang for Indexed - // jobs), SCHEDULING before that (surfacing pod waiting reasons like - // ImagePullBackOff so "stuck" is diagnosable). let pods_raw = kubectl( context, &[ @@ -765,7 +809,40 @@ pub async fn inspect_job(context: Option<&str>, namespace: &str, name: &str) -> ) .await .unwrap_or_default(); - let pods: Value = serde_json::from_str(&pods_raw).unwrap_or_else(|_| json!({"items": []})); + let pods: Value = serde_json::from_str(&pods_raw).unwrap_or_default(); + if let Some(failed) = condition("Failed") { + let reason = failed["reason"].as_str().unwrap_or(""); + let msg = failed["message"].as_str().unwrap_or(""); + return Ok(JobState { + stage: "ERROR".to_string(), + exit_code: pods["items"] + .as_array() + .unwrap_or(&empty) + .iter() + .find_map(|pod| { + let script = pod["metadata"]["annotations"] + ["kubectl.kubernetes.io/default-container"] + .as_str()?; + pod["status"]["containerStatuses"] + .as_array()? + .iter() + .find(|container| container["name"] == script)?["state"]["terminated"] + ["exitCode"] + .as_i64() + .and_then(|code| i32::try_from(code).ok()) + .filter(|code| *code != 0) + }), + message: Some( + format!("{reason}: {msg}") + .trim_matches([':', ' ']) + .to_string(), + ), + }); + } + + // Live: RUNNING once every expected pod runs (the whole gang for Indexed + // jobs), SCHEDULING before that (surfacing pod waiting reasons like + // ImagePullBackOff so "stuck" is diagnosable). let mut waiting_msg = None; let mut live = 0u64; for pod in pods["items"].as_array().unwrap_or(&empty) { @@ -786,11 +863,13 @@ pub async fn inspect_job(context: Option<&str>, namespace: &str, name: &str) -> return Ok(JobState { stage: "RUNNING".to_string(), message: None, + exit_code: None, }); } Ok(JobState { stage: "SCHEDULING".to_string(), message: waiting_msg, + exit_code: None, }) } @@ -820,7 +899,12 @@ pub async fn delete_resources( /// The pod whose stdout is the run log: the completion-index-0 pod for /// Indexed jobs (the annotation exists on any cluster with Indexed jobs), /// else the job's first pod by name. `None` while no pod exists yet. -async fn leader_pod(context: Option<&str>, namespace: &str, job_name: &str) -> Option { +/// `None` while no pod is scheduled; a failed lookup is an error, never "no pod". +async fn leader_pod( + context: Option<&str>, + namespace: &str, + job_name: &str, +) -> Result> { let raw = kubectl( context, &[ @@ -835,22 +919,22 @@ async fn leader_pod(context: Option<&str>, namespace: &str, job_name: &str) -> O ], None, ) - .await - .ok()?; - let pods: Value = serde_json::from_str(&raw).ok()?; + .await?; + let pods: Value = serde_json::from_str(&raw)?; + let unexpected = || anyhow!("Unexpected kubectl pod listing"); let mut names: Vec<&str> = Vec::new(); - for pod in pods["items"].as_array()? { - let name = pod["metadata"]["name"].as_str()?; + for pod in pods["items"].as_array().ok_or_else(unexpected)? { + let name = pod["metadata"]["name"].as_str().ok_or_else(unexpected)?; let index = pod["metadata"]["annotations"]["batch.kubernetes.io/job-completion-index"] .as_str() .unwrap_or(""); if index == "0" { - return Some(name.to_string()); + return Ok(Some(name.to_string())); } names.push(name); } names.sort_unstable(); - names.first().map(|n| n.to_string()) + Ok(names.first().map(|n| n.to_string())) } /// RFC3339Nano with trailing zeros trimmed doesn't sort as text; pad the @@ -873,7 +957,7 @@ fn sort_key(ts: &str) -> Option { /// Where the run log left off: the newest kubelet timestamp written and the /// lines that carried it, so a reconnect resumes there even after log rotation. -#[derive(Default)] +#[derive(Default, Clone)] pub struct LogResume { key: String, tied: Vec, @@ -929,7 +1013,8 @@ impl LogResume { /// not line count: kubelet serves only the current log file, so after /// rotation a replay from the start is shorter than what was already written. /// Ends when kubectl exits (pod gone/finished) or after `idle` silence; the -/// supervisor re-checks job state and reconnects if still live. +/// supervisor re-checks job state and reconnects if still live. True only when +/// kubectl's stream closed, never for an unscheduled pod or an idle stop. /// /// Only the leader pod is captured: a stable single stream keeps the resume /// point sound, and the leader is where the driver's output lives. Other pods @@ -939,15 +1024,15 @@ pub async fn stream_logs( namespace: &str, job_name: &str, resume: &mut LogResume, - idle: Duration, + idle: Option, sink: &mut (dyn FnMut(&str) + Send), -) -> Result<()> { +) -> Result { use tokio::io::{AsyncBufReadExt as _, BufReader}; - let target = match leader_pod(context, namespace, job_name).await { + let target = match leader_pod(context, namespace, job_name).await? { Some(pod) => format!("pod/{pod}"), // Not scheduled yet — let the supervisor's retry loop come back. - None => return Ok(()), + None => return Ok(false), }; let mut cmd = crate::process::tokio_command("kubectl"); @@ -972,15 +1057,19 @@ pub async fn stream_logs( let mut lines = BufReader::new(stdout).lines(); let mut pass = Pass::default(); loop { - match tokio::time::timeout(idle, lines.next_line()).await { - Err(_) => break, // idle — let the caller re-check state + let next = match idle { + Some(idle) => tokio::time::timeout(idle, lines.next_line()).await, + None => Ok(lines.next_line().await), + }; + match next { + Err(_) => return Ok(false), // idle — let the caller re-check state Ok(Err(e)) => return Err(anyhow!("Could not read kubectl logs output: {}", e)), Ok(Ok(None)) => { let status = child.wait().await?; if !status.success() { return Err(anyhow!("kubectl logs exited with {}", status)); } - break; + return Ok(true); } Ok(Ok(Some(line))) => { if let Some(text) = resume.admit(&mut pass, &line) { @@ -989,8 +1078,6 @@ pub async fn stream_logs( } } } - let _ = child.kill().await; - Ok(()) } #[cfg(test)] diff --git a/src/jobs/localbox.rs b/src/jobs/localbox.rs index 8473df97b..2087ae549 100644 --- a/src/jobs/localbox.rs +++ b/src/jobs/localbox.rs @@ -1,24 +1,20 @@ -//! Local backend — run an experiment as a detached process on this machine. -//! -//! The no-transport twin of `jobs/ssh.rs`: same run-dir layout -//! run.sh the launcher (clone-and-run payload) -//! log merged stdout/stderr -//! pid the detached process-group leader -//! exit_code written when the payload finishes -//! but under the orx data dir (`/local-runs//`) instead of a -//! remote `~/.orx/runs/`. A restarted `orx supervise` reattaches purely from -//! that directory. - use std::collections::HashMap; use std::path::{Path, PathBuf}; use crate::error::{anyhow, Result}; -use crate::jobs::ssh::{sh_quote, JobState}; +use crate::jobs::ssh::sh_quote; + +#[derive(Debug, Clone)] +pub struct JobState { + pub stage: String, + pub message: Option, + pub exit_code: Option, +} #[cfg(windows)] -mod python; +pub(crate) mod python; #[cfg(windows)] -mod windows; +pub(crate) mod windows; /// The run's working directory: `/local-runs/`. pub fn run_dir(run_id: &str) -> PathBuf { @@ -41,9 +37,8 @@ pub struct LocalJobSpec { pub secret_env: HashMap, } -/// Submit the job: write run.sh, launch it detached in its own process group -/// (pid == pgid, so cancel can TERM the whole tree), record the pid. Returns -/// the run dir — the reattach handle stored on the descriptor. +/// A run as orx 0.2.x launched it: run.sh detached in its own process group (pid == pgid), +/// with its pid recorded. pub fn run_job(spec: &LocalJobSpec) -> Result { let dir = run_dir(&spec.run_id); std::fs::create_dir_all(&dir) @@ -226,11 +221,13 @@ fn exit_code_state(dir: &Path) -> Option { JobState { stage: "COMPLETED".into(), message: None, + exit_code: Some(code), } } else { JobState { stage: "ERROR".into(), message: Some(format!("exited with code {code}")), + exit_code: Some(code), } }) } @@ -246,6 +243,7 @@ pub fn inspect_job(dir: &Path) -> JobState { Ok(pid) if run_alive(dir, pid.trim()) => JobState { stage: "RUNNING".into(), message: None, + exit_code: None, }, // Dead pid: run.sh may have written exit_code and exited between the // check above and the ps probe — re-read before calling it killed. @@ -264,17 +262,20 @@ pub fn inspect_job(dir: &Path) -> JobState { return JobState { stage: "RUNNING".into(), message: None, + exit_code: None, }; } JobState { stage: "ERROR".into(), message: Some("process died without an exit code (killed?)".into()), + exit_code: None, } } // pid not written yet — just starting. Err(_) => JobState { stage: "RUNNING".into(), message: None, + exit_code: None, }, } } @@ -284,6 +285,14 @@ const LINGERING_GROUP_WINDOW: std::time::Duration = std::time::Duration::from_se /// Whether the run may still have live processes, including a group lingering after exit_code. /// Called only while submission is excluded and a supervisor lock is checked separately. pub fn orphaned_job_is_running(dir: &Path) -> Result { + #[cfg(unix)] + if dir.join("launch.json").try_exists()? || dir.join("wrapper.json").try_exists()? { + return Ok(orx_host::wrapper::has_live_processes(dir)?); + } + #[cfg(windows)] + if dir.join("windows_job").try_exists()? { + return Ok(windows::job_is_running(dir)?); + } if exit_code_state(dir).is_some() { // Children may outlive exit_code briefly; after the window a live PGID is likely reused. let age = std::fs::metadata(dir.join("exit_code"))? @@ -328,7 +337,7 @@ pub fn orphaned_job_is_running(dir: &Path) -> Result { /// Whether any process remains in the run's group (pgid == recorded pid). #[cfg(not(windows))] -fn process_group_alive(dir: &Path) -> bool { +pub(crate) fn process_group_alive(dir: &Path) -> bool { let Ok(pid) = std::fs::read_to_string(dir.join("pid")) else { return false; }; @@ -341,8 +350,12 @@ fn process_group_alive(dir: &Path) -> bool { /// Windows cancel waits for an empty job object; deleting files a survivor holds open fails and is retried. #[cfg(windows)] -fn process_group_alive(_dir: &Path) -> bool { - false +pub(crate) fn process_group_alive(dir: &Path) -> bool { + if dir.join("windows_job").exists() { + windows::job_is_running(dir).unwrap_or(true) + } else { + false + } } /// One poll of the log past `skip` lines (the supervisor loops every ~2s). @@ -367,15 +380,15 @@ pub fn stream_logs( /// TERM the process group (pid == pgid), else the pid alone; on Windows, the process tree. pub fn cancel_job(dir: &Path) -> Result<()> { - let pid = std::fs::read_to_string(dir.join("pid")) - .map_err(|e| anyhow!("Could not read the run's pid: {}", e))?; - let pid = pid.trim().to_string(); #[cfg(windows)] { - windows::cancel(dir, &pid) + windows::cancel(dir) } #[cfg(not(windows))] { + let pid = std::fs::read_to_string(dir.join("pid")) + .map_err(|e| anyhow!("Could not read the run's pid: {}", e))?; + let pid = pid.trim().to_string(); if !run_alive(dir, &pid) { return Ok(()); } diff --git a/src/jobs/localbox/python.rs b/src/jobs/localbox/python.rs index b8d8b7348..b45877c3c 100644 --- a/src/jobs/localbox/python.rs +++ b/src/jobs/localbox/python.rs @@ -20,7 +20,7 @@ const FORWARD_TO_PYTHON: &str = "#!/bin/sh\nexec python \"$@\"\n"; /// The run.sh line that routes whichever of `python`/`python3` hit the stub to /// a real interpreter, or to a clear error. -pub(super) fn prelude(dir: &Path) -> std::io::Result { +pub(crate) fn prelude(dir: &Path) -> std::io::Result { let Some(path) = crate::local::shell_env::search_path() else { return Ok(String::new()); }; diff --git a/src/jobs/localbox/windows.rs b/src/jobs/localbox/windows.rs index 9ae533901..2433759ce 100644 --- a/src/jobs/localbox/windows.rs +++ b/src/jobs/localbox/windows.rs @@ -30,7 +30,7 @@ fn own(handle: HANDLE) -> io::Result { Ok(unsafe { OwnedHandle::from_raw_handle(handle) }) } -pub(super) fn spawn(command: &mut Command, dir: &Path) -> Result { +pub(crate) fn spawn(command: &mut Command, dir: &Path) -> Result { let name = format!("Local\\orx-job-{}", uuid::Uuid::new_v4()); let wide: Vec = name.encode_utf16().chain(Some(0)).collect(); let attributes = SECURITY_ATTRIBUTES { @@ -99,14 +99,15 @@ pub(super) fn open_job(dir: &Path) -> io::Result { own(unsafe { OpenJobObjectW(JOB_OBJECT_TERMINATE | JOB_OBJECT_QUERY, 0, wide.as_ptr()) }) } -pub(super) fn cancel(dir: &Path, pid: &str) -> Result<()> { - if super::exit_code_state(dir).is_some() { - return Ok(()); +pub(super) fn cancel(dir: &Path) -> Result<()> { + if !dir.join("windows_job").try_exists()? { + let pid = std::fs::read_to_string(dir.join("pid"))?; + return super::terminate_tree(pid.trim()); } let job = match open_job(dir) { Ok(job) => job, Err(error) if error.raw_os_error() == Some(ERROR_FILE_NOT_FOUND as i32) => { - return super::terminate_tree(pid); + return Ok(()); } Err(error) => return Err(error.into()), }; @@ -115,21 +116,7 @@ pub(super) fn cancel(dir: &Path, pid: &str) -> Result<()> { return Err(io::Error::last_os_error().into()); } for _ in 0..50 { - let mut info = JOBOBJECT_BASIC_ACCOUNTING_INFORMATION::default(); - // SAFETY: info is writable and its size matches the requested information class. - if unsafe { - QueryInformationJobObject( - job.as_raw_handle(), - JobObjectBasicAccountingInformation, - std::ptr::from_mut(&mut info).cast(), - std::mem::size_of_val(&info) as u32, - std::ptr::null_mut(), - ) - } == 0 - { - return Err(io::Error::last_os_error().into()); - } - if info.ActiveProcesses == 0 { + if !active(&job)? { if super::exit_code_state(dir).is_none() { std::fs::write(dir.join("exit_code"), "1\n")?; } @@ -139,3 +126,65 @@ pub(super) fn cancel(dir: &Path, pid: &str) -> Result<()> { } Err(anyhow!("Could not terminate all local run processes")) } + +pub(super) fn job_is_running(dir: &Path) -> io::Result { + let job = match open_job(dir) { + Ok(job) => job, + Err(error) if error.raw_os_error() == Some(ERROR_FILE_NOT_FOUND as i32) => { + return Ok(false) + } + Err(error) => return Err(error), + }; + active(&job) +} + +fn active(job: &OwnedHandle) -> io::Result { + let mut info = JOBOBJECT_BASIC_ACCOUNTING_INFORMATION::default(); + if unsafe { + QueryInformationJobObject( + job.as_raw_handle(), + JobObjectBasicAccountingInformation, + std::ptr::from_mut(&mut info).cast(), + std::mem::size_of_val(&info) as u32, + std::ptr::null_mut(), + ) + } == 0 + { + return Err(io::Error::last_os_error()); + } + Ok(info.ActiveProcesses != 0) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn cancellation_checks_the_job_even_after_the_exit_code() { + let dir = crate::local::git::TemporaryDirectory::new("orx-job-exited").unwrap(); + let mut command = crate::process::command("cmd"); + command.args(["/C", "ping -n 30 127.0.0.1 >nul"]); + let mut child = spawn(&mut command, dir.path()).unwrap(); + std::fs::write(dir.path().join("exit_code"), "0\n").unwrap(); + assert!(job_is_running(dir.path()).unwrap()); + super::super::cancel_job(dir.path()).unwrap(); + child.wait().unwrap(); + assert!(!job_is_running(dir.path()).unwrap()); + assert_eq!( + std::fs::read_to_string(dir.path().join("exit_code")).unwrap(), + "0\n" + ); + } + + #[test] + fn a_gone_named_job_is_empty() { + let dir = crate::local::git::TemporaryDirectory::new("orx-job-gone").unwrap(); + std::fs::write( + dir.path().join("windows_job"), + format!("Local\\orx-job-{}", uuid::Uuid::new_v4()), + ) + .unwrap(); + assert!(!job_is_running(dir.path()).unwrap()); + super::super::cancel_job(dir.path()).unwrap(); + } +} diff --git a/src/jobs/modal.rs b/src/jobs/modal.rs index 135b14f11..6369aa87a 100644 --- a/src/jobs/modal.rs +++ b/src/jobs/modal.rs @@ -89,6 +89,7 @@ def status(sid): out = {"stage": "COMPLETED"} else: out = {"stage": "ERROR", "message": "exited with code %d" % code} + out["exitCode"] = code print(json.dumps(out)) def logs(sid): @@ -310,6 +311,7 @@ pub fn default_image(gpu: bool) -> String { } } +#[derive(serde::Serialize, serde::Deserialize)] pub struct ModalJobSpec { /// `bash -c` payload (the shared snapshot-and-run script). pub script: String, @@ -318,6 +320,7 @@ pub struct ModalJobSpec { pub cpu: Option, pub memory: Option, /// Passed to the sandbox as an ephemeral Secret (tokens, synced env). + #[serde(default)] pub env: HashMap, pub timeout_seconds: u64, /// Modal app name to group sandboxes under. @@ -367,6 +370,7 @@ pub async fn run_job(spec: &ModalJobSpec) -> Result { pub struct JobState { pub stage: String, pub message: Option, + pub exit_code: Option, } pub async fn inspect_job(sandbox_id: &str) -> Result { @@ -380,6 +384,10 @@ pub async fn inspect_job(sandbox_id: &str) -> Result { .unwrap_or("RUNNING") .to_string(), message: v.get("message").and_then(Value::as_str).map(str::to_string), + exit_code: v + .get("exitCode") + .and_then(Value::as_i64) + .and_then(|code| code.try_into().ok()), }) } @@ -397,7 +405,7 @@ pub async fn cancel_job(sandbox_id: &str) -> Result<()> { pub async fn stream_logs( sandbox_id: &str, skip: u64, - idle: Duration, + idle: Option, sink: &mut (dyn FnMut(&str) + Send), ) -> Result { use tokio::io::{AsyncBufReadExt as _, BufReader}; @@ -421,7 +429,11 @@ pub async fn stream_logs( let mut lines = BufReader::new(stdout).lines(); let mut seen = 0u64; loop { - match tokio::time::timeout(idle, lines.next_line()).await { + let next = match idle { + Some(idle) => tokio::time::timeout(idle, lines.next_line()).await, + None => Ok(lines.next_line().await), + }; + match next { Err(_) => break, // idle — let the caller re-check state Ok(Err(e)) => { return Err(anyhow!( @@ -610,6 +622,36 @@ mod credential_tests { use super::*; use std::io::Write as _; + #[tokio::test] + async fn status_keeps_the_sandbox_exit_code() { + let Ok(python) = + crate::jobs::managed_env::base_python(MODAL_ENV.min_python, MODAL_ENV.label).await + else { + return; + }; + let dir = std::env::temp_dir().join(format!("orx-modal-{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&dir).unwrap(); + for (code, stage) in [("None", "RUNNING"), ("0", "COMPLETED"), ("7", "ERROR")] { + std::fs::write(dir.join("modal.py"), format!( + "class Sandbox:\n @staticmethod\n def from_id(sid): return Sandbox()\n def poll(self): return {code}\n" + )).unwrap(); + let output = crate::process::command(python) + .args(["-B", "-c", LAUNCHER, "status", "sandbox"]) + .env("PYTHONPATH", &dir) + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let state: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(state["stage"], stage); + assert_eq!(state["exitCode"].as_i64(), code.parse::().ok()); + } + std::fs::remove_dir_all(dir).unwrap(); + } + #[test] fn selects_active_or_explicit_profile_and_rejects_ambiguity() { let config: toml::Table = diff --git a/src/jobs/openresearch.rs b/src/jobs/openresearch.rs index a1179a46a..6a8d2030b 100644 --- a/src/jobs/openresearch.rs +++ b/src/jobs/openresearch.rs @@ -103,7 +103,7 @@ fn retained_failure_reason( }) } -fn is_not_found_error(message: &str) -> bool { +pub(crate) fn is_not_found_error(message: &str) -> bool { message.contains("(404 ") } diff --git a/src/jobs/ray.rs b/src/jobs/ray.rs index 452461b57..a2e4ac07a 100644 --- a/src/jobs/ray.rs +++ b/src/jobs/ray.rs @@ -92,7 +92,7 @@ pub fn resolve_address_with_source() -> (String, AddressSource) { // --- flavor → resources ----------------------------------------------------- -#[derive(Debug, Clone)] +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct RayResources { pub cpus: f64, pub gpus: f64, @@ -215,6 +215,11 @@ async fn check(res: reqwest::Response, what: &str) -> Result if status.is_success() { return Ok(res); } + if matches!(status.as_u16(), 401 | 403) { + res.error_for_status_ref().map_err(|error| { + anyhow!(error).context(format!("Ray Jobs {what} rejected access (HTTP {status})")) + })?; + } let body = res.text().await.unwrap_or_default(); Err(anyhow!( "Ray Jobs {} failed ({}): {}", @@ -240,10 +245,12 @@ pub async fn preflight(address: &str) -> Result> { .map(|s| s.to_string())) } +#[derive(serde::Serialize, serde::Deserialize)] pub struct JobSubmission { pub entrypoint: String, pub submission_id: String, pub resources: RayResources, + #[serde(default)] pub env: HashMap, pub metadata: HashMap, pub working_dir: Option, @@ -254,14 +261,20 @@ pub struct JobInfo { /// Shared stage vocabulary (`SCHEDULING` / `RUNNING` / `COMPLETED` / …). pub stage: String, pub message: Option, + pub exit_code: Option, } #[derive(Debug, Deserialize)] struct RawJobStatus { + #[serde(default)] + start_time: Option, + #[serde(default)] + end_time: Option, #[serde(default)] status: Option, #[serde(default)] message: Option, + driver_exit_code: Option, } fn map_ray_status(raw: &str) -> String { @@ -337,6 +350,13 @@ pub async fn stage_working_dir( } pub async fn inspect_job(address: &str, submission_id: &str) -> Result { + Ok(inspect_job_with_times(address, submission_id).await?.0) +} + +pub(crate) async fn inspect_job_with_times( + address: &str, + submission_id: &str, +) -> Result<(JobInfo, Option, Option)> { let res = http() .get(format!("{address}/api/jobs/{submission_id}")) .send() @@ -346,17 +366,27 @@ pub async fn inspect_job(address: &str, submission_id: &str) -> Result // restarted) — a distinct GONE stage for the supervisor to debounce, not // a transport error to retry forever. if res.status() == reqwest::StatusCode::NOT_FOUND { - return Ok(JobInfo { - stage: "GONE".to_string(), - message: None, - }); + return Ok(( + JobInfo { + stage: "GONE".to_string(), + message: None, + exit_code: None, + }, + None, + None, + )); } let raw: RawJobStatus = check(res, "job inspect").await?.json().await?; let status = raw.status.unwrap_or_else(|| "PENDING".into()); - Ok(JobInfo { - stage: map_ray_status(&status), - message: raw.message, - }) + Ok(( + JobInfo { + stage: map_ray_status(&status), + message: raw.message, + exit_code: raw.driver_exit_code, + }, + raw.start_time, + raw.end_time, + )) } pub async fn stop_job(address: &str, submission_id: &str) -> Result<()> { @@ -395,10 +425,6 @@ pub async fn fetch_logs(address: &str, submission_id: &str) -> Result { } } -pub fn job_url(address: &str, submission_id: &str) -> String { - format!("{address}/#/jobs/{submission_id}") -} - #[cfg(test)] mod tests { use super::*; diff --git a/src/jobs/rental.rs b/src/jobs/rental.rs index 7df2df764..10f32354f 100644 --- a/src/jobs/rental.rs +++ b/src/jobs/rental.rs @@ -161,12 +161,16 @@ fn remote_bash_command(script: &str) -> String { fn remote_supervisor_command(binary: &str, directory: &str) -> String { use super::ssh::sh_quote; - // An asynchronous `cd && nohup` list keeps the SSH output pipes open. - format!( - "cd {} || exit; nohup {} rental-supervise {} supervisor.log 2>&1 &", - sh_quote(directory), + let launch = sh_quote(&format!( + "nohup {} rental-supervise {} supervisor.log 2>&1 &", sh_quote(binary), sh_quote(&format!("{directory}/rental.json")) + )); + // The foreground launcher establishes a session before Exec cleans up its original group. + format!( + "cd {} || exit; if command -v setsid >/dev/null 2>&1; then setsid /bin/sh -c {launch}; \ + else python3 -c 'import os,sys; os.setsid(); os.execl(\"/bin/sh\", \"sh\", \"-c\", sys.argv[1])' {launch}; fi; exit $?", + sh_quote(directory), ) } @@ -245,32 +249,66 @@ pub async fn launch( mod tests { use super::*; #[cfg(unix)] - #[tokio::test] - async fn remote_launch_returns_without_waiting_for_the_supervisor() { + #[test] + fn remote_launch_survives_exec_cleanup_without_waiting_for_the_supervisor() { + use std::os::unix::fs::PermissionsExt; + let temp = crate::local::git::TemporaryDirectory::new("orx-rental-detach").unwrap(); + let bin = temp.path().join("bin"); + std::fs::create_dir(&bin).unwrap(); + let python = crate::local::shell_env::find("python3").unwrap(); + std::os::unix::fs::symlink(python, bin.join("python3")).unwrap(); + std::os::unix::fs::symlink("/usr/bin/nohup", bin.join("nohup")).unwrap(); + let setsid = bin.join("setsid"); std::fs::write( - temp.path().join("rental-supervise"), - "touch started; sleep 2\n", - ) - .unwrap(); - let command = remote_supervisor_command("/bin/sh", temp.path().to_str().unwrap()); - let output = tokio::time::timeout( - Duration::from_secs(1), - crate::process::tokio_command("/bin/sh") - .args(["-c", &command]) - .output(), - ) - .await - .unwrap() - .unwrap(); - assert!(output.status.success()); - tokio::time::timeout(Duration::from_secs(1), async { - while !temp.path().join("started").exists() { - tokio::time::sleep(Duration::from_millis(10)).await; + &setsid, + "#!/bin/sh\nexec python3 -c 'import os,sys; os.setsid(); os.execv(sys.argv[1],sys.argv[1:])' \"$@\"\n", + ).unwrap(); + std::fs::set_permissions(&setsid, std::fs::Permissions::from_mode(0o700)).unwrap(); + + for utility in [true, false] { + if !utility { + std::fs::remove_file(&setsid).unwrap(); } - }) - .await - .unwrap(); + let dir = temp.path().join(if utility { + "with setsid" + } else { + "without setsid" + }); + std::fs::create_dir(&dir).unwrap(); + std::fs::write( + dir.join("rental-supervise"), + "read -r value < \"$1\"; /bin/sleep 0.2; printf '%s' \"$value\" > survived\n", + ) + .unwrap(); + std::fs::write(dir.join("rental.json"), "detached\n").unwrap(); + + let command = remote_supervisor_command("/bin/sh", dir.to_str().unwrap()); + let result = orx_host::exec::run( + crate::process::command("/bin/sh") + .args(["-c", &command]) + .env("PATH", &bin), + &[], + Duration::from_secs(2), + None, + ) + .unwrap(); + assert_eq!(result.code, Some(0), "{result:?}"); + assert!(!result.timed_out, "{result:?}"); + + let deadline = std::time::Instant::now() + Duration::from_secs(2); + while std::fs::read_to_string(dir.join("survived")) + .ok() + .as_deref() + != Some("detached") + { + assert!( + std::time::Instant::now() < deadline, + "setsid available: {utility}" + ); + std::thread::sleep(Duration::from_millis(10)); + } + } } #[cfg(unix)] #[test] diff --git a/src/jobs/slurm.rs b/src/jobs/slurm.rs index ff78e251a..0e5986aa0 100644 --- a/src/jobs/slurm.rs +++ b/src/jobs/slurm.rs @@ -1,17 +1,13 @@ -//! Slurm backend — submit an experiment as a batch job on a Slurm cluster. +//! Slurm settings and supervised launches. Engine launches use `engine::adapters::slurm`. //! -//! orx talks to the cluster's **login node** over ssh (reusing the ssh -//! backend's multiplexed transport) and drives the Slurm CLI there: -//! `sbatch --parsable` to submit, `squeue`/`sacct` to poll, `scancel` to -//! cancel. No `slurmrestd`: the REST daemon needs cluster-admin setup that -//! most users don't have, while everyone with a cluster account can ssh to -//! the login node — the same trade SkyPilot makes. +//! orx talks to the cluster's **login node** over ssh and drives the Slurm CLI there: +//! `squeue`/`sacct` to poll, `scancel` to cancel. No `slurmrestd`: the REST daemon needs +//! cluster-admin setup that most users don't have, while everyone with a cluster account can +//! ssh to the login node. //! -//! The remote layout extends the ssh backend's convention. A run owns +//! The 0.2.x layout extends the ssh backend's convention. A run owns //! `/runs//` (root defaults to `~/.orx`) on the cluster's shared filesystem: -//! repo/ the experiment branch, cloned on the login node at submit -//! time (compute nodes often have no internet, so cloning -//! inside the job — the other backends' pattern — would break) +//! repo/ the experiment's committed source snapshot //! job.sbatch the generated batch script (env exports + payload) //! log merged stdout/stderr, captured by Slurm via `--output` //! exit_code written by job.sbatch's closing lines when the payload ends @@ -97,8 +93,6 @@ pub fn save_settings(settings: &SlurmSettings) -> Result<()> { Ok(()) } -// --- job spec & script generation -------------------------------------------- - pub struct SlurmJobSpec { /// ssh config host alias of the cluster's login node. pub host: String, @@ -106,8 +100,6 @@ pub struct SlurmJobSpec { pub run_id: String, /// Configured storage root; `None` is `~/.orx`. pub remote_root: Option, - /// Runs on the login node in the run dir at submit time, with `env` - /// exported — the clone step. Piped to `bash -s`, never written to disk. pub setup_script: String, /// The experiment's run command; the body of the batch job (runs in /// `repo/` on the compute node). @@ -129,74 +121,6 @@ pub struct SlurmJobSpec { pub mem: Option, } -/// Validate a Slurm memory request: a positive integer with an optional -/// `K`/`M`/`G`/`T` suffix ("64G", "65536", "4000M"). Bare numbers are -/// megabytes, as Slurm itself documents. Strict on purpose — the value is -/// interpolated straight into a `#SBATCH` directive, so anything that is not -/// this shape (a newline, a shell metacharacter, a second directive) is -/// rejected here rather than reaching the cluster. -pub fn parse_mem(mem: &str) -> Result { - let m = mem.trim(); - let (digits, suffix) = match m.char_indices().find(|(_, c)| !c.is_ascii_digit()) { - Some((i, _)) => m.split_at(i), - None => (m, ""), - }; - let ok_suffix = matches!(suffix, "" | "K" | "M" | "G" | "T"); - if digits.is_empty() || digits.trim_start_matches('0').is_empty() || !ok_suffix { - return Err(anyhow!( - "Unreadable memory request {:?}. Use a positive size in Slurm's own syntax: \ - 64G, 4000M, or a bare number for megabytes.", - mem - )); - } - Ok(format!("{digits}{suffix}")) -} - -pub fn resolve_time_limit(explicit: Option<&str>, saved: Option<&str>) -> Result> { - explicit - .or(saved) - .map(super::huggingface::parse_timeout) - .transpose() -} - -/// Map a `--flavor` string onto a `--gres` request. A flavor names GPUs — -/// CPU-only runs just omit it (unlike HF/Modal there is no machine shape to -/// pick). Cores and memory are asked for separately, with `--cpus`/`--mem`; -/// omitting those leaves the partition defaults. -/// "gpu" -> gpu:1 -/// "gpu:…" -> passed through verbatim (already a GRES spec) -/// "h100:2" -> gpu:h100:2 -/// "h100" -> gpu:h100 -pub fn resolve_gres(flavor: &str) -> Option { - let f = flavor.trim(); - if f.is_empty() { - return None; - } - if f == "gpu" { - return Some("gpu:1".to_string()); - } - if f.starts_with("gpu:") { - return Some(f.to_string()); - } - Some(format!("gpu:{f}")) -} - -/// Seconds → Slurm's `--time` syntax (`D-HH:MM:SS` / `HH:MM:SS`). -fn slurm_time(secs: u64) -> String { - let (days, rem) = (secs / 86_400, secs % 86_400); - let (h, m, s) = (rem / 3600, (rem % 3600) / 60, rem % 60); - if days > 0 { - format!("{days}-{h:02}:{m:02}:{s:02}") - } else { - format!("{h:02}:{m:02}:{s:02}") - } -} - -/// Render job.sbatch. Slurm captures the whole script's stdout/stderr to -/// `log` (relative paths resolve against the submit-time cwd, the run dir, -/// which sbatch also makes the job's working directory). The payload runs in -/// a SUBSHELL so an `exit`/`set -e` inside it still reaches the -/// `echo $? > exit_code` line — same contract as the ssh backend's run.sh. fn render_sbatch(spec: &SlurmJobSpec) -> String { let mut directives = vec![ format!( @@ -234,13 +158,7 @@ fn render_sbatch(spec: &SlurmJobSpec) -> String { if let Some(m) = spec.mem.as_deref().filter(|m| !m.trim().is_empty()) { directives.push(format!("#SBATCH --mem={m}")); } - // The script exits with the payload's code so Slurm's own COMPLETED/FAILED - // verdict mirrors the payload — inspect leans on that when the exit_code - // file is NFS-lagged behind the compute node's write. - // Default the payload's Python to unbuffered so its prints stream live - // instead of block-buffering behind Slurm's --output redirect. Only the - // sbatch payload runs the job — the login-node setup script (below) is a - // git clone, so it keeps the raw env (see jobs::default_python_env). + // Slurm's verdict must match the payload while its exit_code is NFS-lagged. format!( "#!/usr/bin/env bash\n{directives}\n{exports}\n{tensorboard}\n(\ncd repo || exit 97\n{command}\n)\ncode=$?\necho \"$code\" > exit_code\nexit \"$code\"\n", directives = directives.join("\n"), @@ -260,7 +178,6 @@ fn render_exports(env: &HashMap) -> String { .join("\n") } -/// `sbatch --parsable` prints `` or `;`. fn parse_job_id(out: &str) -> Result { let id = out.trim().split(';').next().unwrap_or("").trim(); if id.is_empty() || !id.chars().all(|c| c.is_ascii_digit()) { @@ -269,22 +186,10 @@ fn parse_job_id(out: &str) -> Result { Ok(id.to_string()) } -// --- lifecycle ---------------------------------------------------------------- - -/// The remote run dir for a run (shared convention with the ssh backend), -/// derived from the root recorded in the descriptor at submit. -pub fn run_dir(root: Option<&str>, run_id: &str) -> String { - super::ssh::remote_run_dir(root, run_id) -} - -/// Submit the job: create the run dir, clone on the login node, write -/// job.sbatch, `sbatch --parsable`. Returns the Slurm job id — the reattach -/// handle (together with the host). pub async fn run_job(spec: &SlurmJobSpec) -> Result { let dir = shell_path(&run_dir(spec.remote_root.as_deref(), &spec.run_id)); - // Login-node setup (clone). Env + script travel via stdin so tokens never - // land on an argv or in a file. + // Tokens travel over stdin rather than argv. let setup = format!( "{exports}\ncd {dir} || exit 97\n{script}\n", exports = render_exports(&spec.env), @@ -315,6 +220,75 @@ pub async fn run_job(spec: &SlurmJobSpec) -> Result { parse_job_id(&out) } +/// Validate a Slurm memory request: a positive integer with an optional +/// `K`/`M`/`G`/`T` suffix ("64G", "65536", "4000M"). Bare numbers are +/// megabytes, as Slurm itself documents. Strict on purpose — the value is +/// interpolated straight into a `#SBATCH` directive, so anything that is not +/// this shape (a newline, a shell metacharacter, a second directive) is +/// rejected here rather than reaching the cluster. +pub fn parse_mem(mem: &str) -> Result { + let m = mem.trim(); + let (digits, suffix) = match m.char_indices().find(|(_, c)| !c.is_ascii_digit()) { + Some((i, _)) => m.split_at(i), + None => (m, ""), + }; + let ok_suffix = matches!(suffix, "" | "K" | "M" | "G" | "T"); + if digits.is_empty() || digits.trim_start_matches('0').is_empty() || !ok_suffix { + return Err(anyhow!( + "Unreadable memory request {:?}. Use a positive size in Slurm's own syntax: \ + 64G, 4000M, or a bare number for megabytes.", + mem + )); + } + Ok(format!("{digits}{suffix}")) +} + +pub fn resolve_time_limit(explicit: Option<&str>, saved: Option<&str>) -> Result> { + explicit + .or(saved) + .map(super::huggingface::parse_timeout) + .transpose() +} + +/// Map a `--flavor` string onto a `--gres` request. A flavor names GPUs — +/// CPU-only runs just omit it (unlike HF/Modal there is no machine shape to +/// pick). Cores and memory are asked for separately, with `--cpus`/`--mem`; +/// omitting those leaves the partition defaults. +/// "gpu" -> gpu:1 +/// "gpu:…" -> passed through verbatim (already a GRES spec) +/// "h100:2" -> gpu:h100:2 +/// "h100" -> gpu:h100 +pub fn resolve_gres(flavor: &str) -> Option { + let f = flavor.trim(); + if f.is_empty() { + return None; + } + if f == "gpu" { + return Some("gpu:1".to_string()); + } + if f.starts_with("gpu:") { + return Some(f.to_string()); + } + Some(format!("gpu:{f}")) +} + +/// Seconds → Slurm's `--time` syntax (`D-HH:MM:SS` / `HH:MM:SS`). +pub(crate) fn slurm_time(secs: u64) -> String { + let (days, rem) = (secs / 86_400, secs % 86_400); + let (h, m, s) = (rem / 3600, (rem % 3600) / 60, rem % 60); + if days > 0 { + format!("{days}-{h:02}:{m:02}:{s:02}") + } else { + format!("{h:02}:{m:02}:{s:02}") + } +} + +/// The remote run dir for a run (shared convention with the ssh backend), +/// derived from the root recorded in the descriptor at submit. +pub fn run_dir(root: Option<&str>, run_id: &str) -> String { + super::ssh::remote_run_dir(root, run_id) +} + /// Job state in the shared stage vocabulary (see `jobs::stage_to_run_status`). #[derive(Debug, Clone)] pub struct JobState { @@ -449,13 +423,13 @@ pub struct SlurmPreflight { pub error: Option, } -pub async fn preflight(host: &str) -> SlurmPreflight { +pub async fn preflight(target: &SshTarget) -> SlurmPreflight { let cmd = "if command -v sbatch >/dev/null 2>&1 && command -v squeue >/dev/null 2>&1 \ && command -v scancel >/dev/null 2>&1; then echo SLURM_OK; fi; \ if command -v bash >/dev/null 2>&1 && command -v tar >/dev/null 2>&1; \ then echo TOOLS_OK; fi; \ sinfo -h -o %P 2>/dev/null || true"; - match ssh_run(&SshTarget::alias(host), cmd, None).await { + match ssh_run(target, cmd, None).await { Ok(out) => { let mut slurm_found = false; let mut tools_found = false; @@ -513,14 +487,12 @@ pub async fn diagnostics(host: &str, job_id: &str) -> Result #[cfg(test)] mod tests { - use super::*; - fn spec() -> SlurmJobSpec { SlurmJobSpec { host: "cluster".into(), run_id: "0123456789abcdef".into(), remote_root: None, - setup_script: "git clone x repo".into(), + setup_script: "test -d repo".into(), command: "python train.py".into(), env: HashMap::new(), gres: None, @@ -600,46 +572,6 @@ mod tests { assert!(!script.contains("--mem")); } - #[test] - fn mem_parses_slurm_sizes_and_rejects_the_rest() { - assert_eq!(parse_mem("64G").unwrap(), "64G"); - assert_eq!(parse_mem(" 4000M ").unwrap(), "4000M"); - assert_eq!(parse_mem("65536").unwrap(), "65536"); - for bad in [ - "", - "0", - "G", - "64g", - "64GB", - "64 G", - "-1", - "64G\n#SBATCH --account=someone-else", - ] { - assert!(parse_mem(bad).is_err(), "{bad:?} should be rejected"); - } - } - - #[test] - fn slurm_time_formats() { - assert_eq!(slurm_time(90), "00:01:30"); - assert_eq!(slurm_time(4 * 3600), "04:00:00"); - assert_eq!(slurm_time(86_400 + 3661), "1-01:01:01"); - } - - #[test] - fn gres_from_flavor() { - assert_eq!(resolve_gres(""), None); - assert_eq!(resolve_gres("gpu").as_deref(), Some("gpu:1")); - assert_eq!(resolve_gres("gpu:a100:4").as_deref(), Some("gpu:a100:4")); - assert_eq!(resolve_gres("h100:2").as_deref(), Some("gpu:h100:2")); - assert_eq!(resolve_gres("h100").as_deref(), Some("gpu:h100")); - } - - /// Live E2E against a real cluster — opt-in, never runs in CI: - /// ORX_SLURM_TEST_HOST= cargo test jobs::slurm -- --ignored - /// Covers submit → SCHEDULING/RUNNING → COMPLETED with logs, plus - /// scancel → the job leaving the queue (CANCELED, or GONE where - /// accounting is disabled — monitoring remains unknown). #[tokio::test] #[ignore = "needs a live slurm cluster; set ORX_SLURM_TEST_HOST"] async fn e2e_lifecycle_against_live_cluster() { @@ -728,6 +660,43 @@ mod tests { assert!(parse_job_id("").is_err()); } + use super::*; + + #[test] + fn mem_parses_slurm_sizes_and_rejects_the_rest() { + assert_eq!(parse_mem("64G").unwrap(), "64G"); + assert_eq!(parse_mem(" 4000M ").unwrap(), "4000M"); + assert_eq!(parse_mem("65536").unwrap(), "65536"); + for bad in [ + "", + "0", + "G", + "64g", + "64GB", + "64 G", + "-1", + "64G\n#SBATCH --account=someone-else", + ] { + assert!(parse_mem(bad).is_err(), "{bad:?} should be rejected"); + } + } + + #[test] + fn slurm_time_formats() { + assert_eq!(slurm_time(90), "00:01:30"); + assert_eq!(slurm_time(4 * 3600), "04:00:00"); + assert_eq!(slurm_time(86_400 + 3661), "1-01:01:01"); + } + + #[test] + fn gres_from_flavor() { + assert_eq!(resolve_gres(""), None); + assert_eq!(resolve_gres("gpu").as_deref(), Some("gpu:1")); + assert_eq!(resolve_gres("gpu:a100:4").as_deref(), Some("gpu:a100:4")); + assert_eq!(resolve_gres("h100:2").as_deref(), Some("gpu:h100:2")); + assert_eq!(resolve_gres("h100").as_deref(), Some("gpu:h100")); + } + #[test] fn inspect_token_mapping() { assert_eq!(map_inspect_token("EXIT 0").stage, "COMPLETED"); diff --git a/src/jobs/ssh.rs b/src/jobs/ssh.rs index dc82f8402..7951a40c6 100644 --- a/src/jobs/ssh.rs +++ b/src/jobs/ssh.rs @@ -20,7 +20,7 @@ mod container; mod prepared; pub(crate) mod service; #[cfg(unix)] -mod sharing; +pub(crate) mod sharing; pub use container::{ resolve as resolve_container, validate_reference as validate_container_reference, ContainerRun, }; @@ -100,6 +100,30 @@ pub struct ResolvedLaunch { pub remote_root: Option, } +pub async fn resolve_launch(args: &crate::ExpRunArgs) -> Result { + let settings = crate::config::ssh_settings()?; + let (host, options) = resolve_options(args, &settings)?; + let target = SshTarget::alias(&host); + let host_check = preflight(&target).await; + if !host_check.reachable || !host_check.tools_found { + return Err(anyhow!( + "{}", + host_check + .error + .unwrap_or_else(|| "SSH host needs bash and tar.".into()) + )); + } + let container = match options.container { + Some(reference) => Some(container::resolve(&target, &reference).await?), + None => None, + }; + Ok(ResolvedLaunch { + target, + container, + remote_root: options.remote_root, + }) +} + pub fn validate_host_options(options: &crate::config::SshHostSettings) -> Result<()> { if let Some(reference) = &options.container { validate_container_reference(reference)?; @@ -186,36 +210,15 @@ pub fn resolve_options( Ok((host, options)) } -pub async fn resolve_launch(args: &crate::ExpRunArgs) -> Result { - let settings = crate::config::ssh_settings()?; - let (host, options) = resolve_options(args, &settings)?; - let target = SshTarget::alias(&host); - let host_check = preflight(&target).await; - if !host_check.reachable || !host_check.tools_found { - return Err(anyhow!( - "{}", - host_check - .error - .unwrap_or_else(|| "SSH host needs bash and tar.".into()) - )); - } - let container = match options.container { - Some(reference) => Some(container::resolve(&target, &reference).await?), - None => None, - }; - Ok(ResolvedLaunch { - target, - container, - remote_root: options.remote_root, - }) -} - /// An ssh endpoint. The classic ssh backend connects by `~/.ssh/config` alias /// (`SshTarget::alias`); backends that learn an endpoint at runtime (an /// OpenResearch box on a provider-assigned host:port) pass an explicit /// `user@host` plus the options no config file knows about. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SshTarget { + #[serde(skip)] + pub(crate) transport: + Option>, /// What goes after `--`: an alias, or `user@host`. pub dest: String, #[serde(default)] @@ -260,6 +263,7 @@ impl SshTarget { auth_agent: crate::local::shell_env::var("SSH_AUTH_SOCK") .map(|value| value.to_string_lossy().into_owned()), run_id: None, + transport: None, extra_opts: Vec::new(), } } @@ -294,6 +298,7 @@ impl SshTarget { auth_agent: crate::local::shell_env::var("SSH_AUTH_SOCK") .map(|value| value.to_string_lossy().into_owned()), run_id: None, + transport: None, } } } @@ -440,11 +445,8 @@ pub(crate) struct InteractiveConnection { _lock: std::fs::File, } -/// Arguments for the short interactive login opened by Settings. `true` ends -/// the visible session after authentication while ControlPersist keeps its -/// master available to the batch-mode calls below — on Windows there is no -/// master, so this only proves the host reachable and primes nothing. -pub(crate) async fn interactive_args( +/// Retires unusable Unix masters and holds their lock through the interactive login. +pub(crate) async fn prepare_interactive_connection( target: &SshTarget, persist: Option, remote_command: Option, @@ -469,23 +471,7 @@ pub(crate) async fn interactive_args( #[cfg(not(unix))] let options = ssh_opts(target, false); #[cfg(unix)] - let lock = { - let file = std::fs::OpenOptions::new() - .create(true) - .truncate(false) - .write(true) - .open(path.with_extension("lock"))?; - loop { - match file.try_lock() { - Ok(()) => break, - Err(std::fs::TryLockError::WouldBlock) => { - tokio::time::sleep(Duration::from_millis(50)).await; - } - Err(std::fs::TryLockError::Error(error)) => return Err(error.into()), - } - } - file - }; + let lock = lock_master(&path).await?; #[cfg(unix)] if control_master(target, &path, &options, "check").await? { if !master_accepts_sessions(target, &path, &options).await? @@ -517,6 +503,25 @@ pub(crate) async fn interactive_args( }) } +#[cfg(unix)] +async fn lock_master(path: &std::path::Path) -> Result { + let file = std::fs::OpenOptions::new() + .create(true) + .truncate(false) + .write(true) + .open(path.with_extension("lock"))?; + loop { + match file.try_lock() { + Ok(()) => break, + Err(std::fs::TryLockError::WouldBlock) => { + tokio::time::sleep(Duration::from_millis(50)).await; + } + Err(std::fs::TryLockError::Error(error)) => return Err(error.into()), + } + } + Ok(file) +} + #[cfg(unix)] async fn control_master( target: &SshTarget, @@ -595,7 +600,7 @@ pub(crate) fn prepare_sharing_env(cmd: &mut tokio::process::Command) { pub(crate) async fn setup_connection_sharing(target: &SshTarget) -> Option { #[cfg(unix)] - if target.extra_opts.is_empty() { + if target.extra_opts.is_empty() && target.transport.is_none() { return sharing::setup(target).await.err().map(|error| { format!("SSH login succeeded, but connection sharing is unavailable: {error}") }); @@ -614,6 +619,11 @@ pub(crate) async fn ssh_run( remote_cmd: &str, stdin: Option<&str>, ) -> Result { + if let Some(transport) = &target.transport { + return transport + .execute(remote_cmd, stdin.map(str::as_bytes).unwrap_or_default()) + .await; + } service::execute(target, remote_cmd, stdin.map(str::as_bytes)).await } @@ -622,6 +632,11 @@ pub(crate) async fn ssh_status( command: &str, input: Option<&str>, ) -> Result { + if let Some(transport) = &target.transport { + return transport + .execute(command, input.map(str::as_bytes).unwrap_or_default()) + .await; + } service::execute_lane(target, command, input.map(str::as_bytes), "status").await } @@ -630,6 +645,11 @@ pub(crate) async fn ssh_control( command: &str, input: Option<&str>, ) -> Result { + if let Some(transport) = &target.transport { + return transport + .execute(command, input.map(str::as_bytes).unwrap_or_default()) + .await; + } service::execute_lane(target, command, input.map(str::as_bytes), "control").await } @@ -704,6 +724,10 @@ async fn ssh_run_file( remote_cmd: &str, source: &std::path::Path, ) -> Result { + if let Some(transport) = &target.transport { + return transport.upload(remote_cmd, source).await; + } + service::upload(target, remote_cmd, source).await } @@ -1332,23 +1356,29 @@ mod tests { prepare_control_dir().unwrap(); let path = resolved_control_path(&target).await.unwrap(); drop(UnixListener::bind(&path).unwrap()); - interactive_args(&target, None, None).await.unwrap(); + prepare_interactive_connection(&target, None, None) + .await + .unwrap(); assert!(std::fs::symlink_metadata(&path).is_err()); symlink(path.with_extension("missing"), &path).unwrap(); - let args = interactive_args(&target, Some(120), None).await.unwrap(); + let args = prepare_interactive_connection(&target, Some(120), None) + .await + .unwrap(); assert!(std::fs::symlink_metadata(&path).is_err()); assert_eq!(args.args[..2], ["-o", "ControlPersist=120"]); let socket = UnixListener::bind(&path).unwrap(); assert!(tokio::time::timeout( Duration::from_millis(100), - interactive_args(&target, None, None) + prepare_interactive_connection(&target, None, None) ) .await .is_err()); assert!(path.exists()); drop(socket); drop(args); - assert!(interactive_args(&target, None, None).await.is_ok()); + assert!(prepare_interactive_connection(&target, None, None) + .await + .is_ok()); let opts = ssh_opts(&target, true); for option in [ "ServerAliveInterval=30", @@ -1454,6 +1484,17 @@ mod tests { assert!(state.trim().is_empty() || state.trim().starts_with('Z')); } + /// Replaces a forked child with `sleep`. Sleeping in place would hold every descriptor the + /// test process had open, so other tests' pipes, sockets and locks would not close. + #[cfg(unix)] + fn exec_sleep() -> ! { + let argv = [c"sleep".as_ptr(), c"60".as_ptr(), std::ptr::null()]; + unsafe { + libc::execv(c"/bin/sleep".as_ptr(), argv.as_ptr()); + libc::_exit(127) + } + } + #[cfg(unix)] #[test] fn host_probe_waits_for_live_group_members() { @@ -1463,10 +1504,7 @@ mod tests { unsafe { libc::setsid() }; let member = unsafe { libc::fork() }; if member == 0 { - unsafe { - libc::sleep(30); - libc::_exit(0) - }; + exec_sleep(); } unsafe { libc::_exit(0) }; } @@ -1540,10 +1578,11 @@ mod tests { libc::close(ready[0]); libc::setsid(); if libc::fork() == 0 { + // An ignored signal stays ignored across exec. libc::signal(libc::SIGTERM, libc::SIG_IGN); // Tell the test TERM is ignored before sleeping. libc::write(ready[1], b"r".as_ptr().cast(), 1); - libc::sleep(60); + exec_sleep(); } libc::_exit(0); } @@ -1557,9 +1596,8 @@ mod tests { unsafe { libc::close(ready[0]); libc::setsid(); - libc::sleep(60); - libc::_exit(0) - }; + } + exec_sleep(); } // Wait for the member to confirm it ignores TERM and for the leader to // exit before cancelling: a group liveness check can pass on the leader @@ -1700,6 +1738,7 @@ mod tests { auth_agent: crate::local::shell_env::var("SSH_AUTH_SOCK") .map(|value| value.to_string_lossy().into_owned()), run_id: None, + transport: None, extra_opts: vec!["-p".into(), port.into()], }; assert_ne!(control_path(&mk("22022")), control_path(&mk("22023"))); diff --git a/src/jobs/ssh/cleanup.rs b/src/jobs/ssh/cleanup.rs index bbaec8fb2..86aff762d 100644 --- a/src/jobs/ssh/cleanup.rs +++ b/src/jobs/ssh/cleanup.rs @@ -7,6 +7,7 @@ use super::{ remote_run_dir, remote_source_dir, sh_quote, shell_path, ssh_run, validate_remote_root, SshTarget, HOST_PROCESS_HELPERS, }; +use crate::engine::handle::Handle; use crate::error::{anyhow, Result}; use crate::jobs::BackendDescriptor; @@ -14,12 +15,20 @@ use crate::jobs::BackendDescriptor; pub(crate) const SOURCE_IDLE_MINUTES: i64 = 60; const HOST_TIMEOUT: Duration = Duration::from_secs(120); +/// A storage root whose source cache a pass sweeps, and whether it is an engine root. +pub(crate) type SourceCache = (Option, bool); + /// A run's remote dir, checked against the layout orx writes before anything removes it. #[derive(Debug, Clone, PartialEq, Eq)] pub struct RemoteRun { pub(crate) run_id: String, pub(crate) host: String, + pub(crate) slurm: bool, root: Option, + /// Engine runs live under `/runs` beside `orx-host`'s `/sources`. + engine: bool, + /// An engine Slurm run's job, whose end vouches for a wrapper on another node. + slurm_job: Option, dir: String, /// Docker id and in-container run dir for container runs. container: Option<(String, String)>, @@ -30,30 +39,62 @@ pub struct RemoteRun { impl RemoteRun { /// `Ok(None)` when orx owns no remote dir for the run; `deleted` also removes TensorBoard logs. - pub fn from_descriptor( - run_id: &str, - descriptor: &BackendDescriptor, - deleted: bool, - ) -> Result> { - // A submission that failed before choosing a host left nothing remote. - let Some(host) = descriptor.namespace.clone().filter(|host| !host.is_empty()) else { - return Ok(None); - }; - if !matches!(descriptor.kind.as_str(), "ssh_job" | "slurm_job") { - return Ok(None); - } + /// An engine run's container comes from its launch intent as `sshContainer`. + pub fn from_backend(run_id: &str, backend_json: &str, deleted: bool) -> Result> { + let descriptor = BackendDescriptor::parse(backend_json)?; if uuid::Uuid::parse_str(run_id).is_err() { return Err(anyhow!("Unexpected run id {run_id}")); } - let root = descriptor.remote_root.clone(); - if let Some(root) = &root { - validate_remote_root(root)?; - } - let dir = remote_run_dir(root.as_deref(), run_id); - // SSH records its dir; a different one was not created by this layout. - if descriptor.kind == "ssh_job" && descriptor.job_id.as_deref().is_some_and(|d| d != dir) { - return Err(anyhow!("Run {run_id} has an unexpected remote dir")); - } + let mut slurm_job = None; + let (host, slurm, root, dir, engine) = if descriptor.kind == "engine" { + let value: serde_json::Value = serde_json::from_str(backend_json)?; + let handle = value + .get("handle") + .map(|handle| serde_json::from_value(handle.clone())) + .transpose()?; + let (host, root, slurm) = match handle { + Some(Handle::Ssh { host, root }) => (host, root, false), + Some(Handle::Slurm { host, root, job }) => { + if let Some(job) = &job { + if job.is_empty() || !job.bytes().all(|b| b.is_ascii_digit() || b == b'_') { + return Err(anyhow!("Run {run_id} has an unexpected Slurm job {job}")); + } + } + slurm_job = job; + (host, root, true) + } + _ => return Ok(None), + }; + let root = match root.strip_prefix("~/") { + Some(relative) => relative.to_owned(), + None => { + validate_remote_root(&root)?; + root + } + }; + let dir = format!("{root}/runs/{run_id}"); + (host, slurm, Some(root), dir, true) + } else { + // A submission that failed before choosing a host left nothing remote. + let Some(host) = descriptor.namespace.clone().filter(|host| !host.is_empty()) else { + return Ok(None); + }; + if !matches!(descriptor.kind.as_str(), "ssh_job" | "slurm_job") { + return Ok(None); + } + let root = descriptor.remote_root.clone(); + if let Some(root) = &root { + validate_remote_root(root)?; + } + let dir = remote_run_dir(root.as_deref(), run_id); + // SSH records its dir; a different one was not created by this layout. + if descriptor.kind == "ssh_job" + && descriptor.job_id.as_deref().is_some_and(|d| d != dir) + { + return Err(anyhow!("Run {run_id} has an unexpected remote dir")); + } + (host, descriptor.kind == "slurm_job", root, dir, false) + }; let container = match &descriptor.ssh_container { Some(container) if container.run_dir.starts_with('/') @@ -67,15 +108,18 @@ impl RemoteRun { Ok(Some(Self { run_id: run_id.into(), host, + slurm, root, + engine, + slurm_job, dir, container, deleted, })) } - pub(crate) fn root(&self) -> Option<&str> { - self.root.as_deref() + pub(crate) fn cache(&self) -> SourceCache { + (self.root.clone(), self.engine) } pub(crate) fn deleted(&self) -> bool { @@ -91,11 +135,12 @@ pub enum Outcome { Failed(String), } -/// One script per host: remove each run dir whose process group is gone, then cached tars -/// under `roots` that no active run references and nothing has touched recently. +/// One script per host: remove each run dir whose process group (an engine run's wrapper) is +/// gone, then cached sources under `roots` that no active run references and nothing has +/// touched recently. Engine sources are `orx-host` blobs no run dir still links. fn host_script( runs: &[RemoteRun], - roots: &BTreeSet>, + roots: &BTreeSet, keep_digests: &BTreeSet, ) -> String { let mut script = format!("{HOST_PROCESS_HELPERS}\n"); @@ -120,9 +165,27 @@ fn host_script( } else { "rm -rf -- \"$d\"" }; + // `v` is `busy`, or why the run cannot be shown to have ended. + let liveness = if run.engine { + match &run.slurm_job { + Some(job) => format!( + "p=; v=; q=$(squeue -h -j {job} -o %T 2>&1); s=$?; \ + if [ $s -eq 0 ] && [ -n \"$q\" ]; then v=busy; \ + elif [ $s -ne 0 ] && ! printf '%s' \"$q\" | grep -q 'Invalid job id'; then \ + v=\"cannot confirm Slurm job {job} ended: $(printf '%s' \"$q\" | head -n 1)\"; fi" + ), + None => "p=; v=; if [ -z \"$ORX_HOST_BINARY\" ]; then v='host binary unavailable'; \ + elif ! v=$(\"$ORX_HOST_BINARY\" check-run \"$d\" 2>&1); then v=${v:-'host liveness check failed'}; \ + elif [ \"$v\" = idle ]; then v=; \ + elif [ \"$v\" != busy ]; then v='invalid host liveness response'; fi".into(), + } + } else { + "v=; p=$(cat \"$d/pid\" 2>/dev/null)".into() + }; script.push_str(&format!( - "d={dir}; p=$(cat \"$d/pid\" 2>/dev/null); case \"$p\" in ''|*[!0-9]*) p=;; esac; \ - if [ -n \"$p\" ] && host_group_alive \"$p\"; then echo 'BUSY {id}'; \ + "d={dir}; {liveness}; case \"$p\" in ''|*[!0-9]*) p=;; esac; \ + if [ \"$v\" = busy ] || {{ [ -n \"$p\" ] && host_group_alive \"$p\"; }}; then echo 'BUSY {id}'; \ + elif [ -n \"$v\" ]; then printf 'FAILED {id} %s\\n' \"$v\"; \ else cf=; if {container_failed}; then cf=1; fi; \ if ! err=$({{ {remove}; }} 2>&1); then printf 'FAILED {id} %s\\n' \"$(printf '%s' \"$err\" | head -n 1)\"; \ elif [ -n \"$cf\" ]; then printf 'FAILED {id} container: %s\\n' \"$(printf '%s' \"$cerr\" | head -n 1)\"; \ @@ -136,7 +199,18 @@ fn host_script( .map(String::as_str) .collect::>() .join(" "); - for root in roots { + for (root, engine) in roots { + if *engine { + let sources = format!("{}/sources", root.as_deref().unwrap_or_default()); + script.push_str(&format!( + "s={sources}; if [ -d \"$s\" ]; then \ + find \"$s\" -maxdepth 1 -type f -links 1 -mmin +{SOURCE_IDLE_MINUTES} | while IFS= read -r f; do \ + n=${{f##*/}}; case \"$n\" in *[!0-9a-f]*) continue;; esac; [ ${{#n}} -eq 64 ] || continue; \ + case ' {keep} ' in *\" $n \"*) continue;; esac; rm -f -- \"$f\"; done; fi\n", + sources = shell_path(&sources), + )); + continue; + } // Only names orx writes (`.tar` and its upload temps): a root may hold the user's own tars. script.push_str(&format!( "s={source}; if [ -d \"$s\" ]; then \ @@ -178,21 +252,19 @@ fn parse_outcomes(runs: &[RemoteRun], output: &str) -> Vec { .collect() } -/// Removes `runs` (all on `host`) and that host's unreferenced cached tars under `roots`. +/// Removes `runs` (all on `target`) and that host's unreferenced cached sources under `roots`. pub async fn clean_host( - host: &str, + target: &SshTarget, runs: &[RemoteRun], - roots: &BTreeSet>, + roots: &BTreeSet, keep_digests: &BTreeSet, ) -> Result> { // Over stdin: a large batch would overrun Windows' command-line limit. let script = host_script(runs, roots, keep_digests); - let output = tokio::time::timeout( - HOST_TIMEOUT, - ssh_run(&SshTarget::alias(host), "bash -s", Some(&script)), - ) - .await - .map_err(|_| anyhow!("Timed out cleaning up runs on {host}"))??; + let host = &target.dest; + let output = tokio::time::timeout(HOST_TIMEOUT, ssh_run(target, "bash -s", Some(&script))) + .await + .map_err(|_| anyhow!("Timed out cleaning up runs on {host}"))??; Ok(parse_outcomes(runs, &output)) } @@ -202,12 +274,8 @@ mod tests { const RUN: &str = "6f1c8f0e-6b5e-4c41-9a0e-6d3f4c1b2a10"; - fn descriptor(json: &str) -> BackendDescriptor { - BackendDescriptor::parse(json).unwrap() - } - fn cleanable(json: &str) -> Result> { - RemoteRun::from_descriptor(RUN, &descriptor(json), false) + RemoteRun::from_backend(RUN, json, false) } #[test] @@ -235,7 +303,7 @@ mod tests { ] { assert!(cleanable(&json).is_err(), "{json}"); } - assert!(RemoteRun::from_descriptor("../x", &descriptor(&ssh), false).is_err()); + assert!(RemoteRun::from_backend("../x", &ssh, false).is_err()); let unsubmitted = format!(r#"{{"kind":"ssh_job","jobId":".orx/runs/{RUN}"}}"#); assert!(cleanable(&unsubmitted).unwrap().is_none()); for kind in ["openresearch_job", "k8s_job", "local_job"] { @@ -245,6 +313,32 @@ mod tests { .is_none() ); } + + let engine = |handle: &str| format!(r#"{{"kind":"engine","handle":{handle}}}"#); + let home = cleanable(&engine( + r#"{"type":"Ssh","host":"lab","root":"~/.orx/engine"}"#, + )) + .unwrap() + .unwrap(); + assert_eq!(home.dir, format!(".orx/engine/runs/{RUN}")); + assert_eq!(home.cache(), (Some(".orx/engine".into()), true)); + let slurm = cleanable(&engine( + r#"{"type":"Slurm","host":"login","root":"/scratch/orx/engine","job":"7"}"#, + )) + .unwrap() + .unwrap(); + assert!(slurm.slurm); + assert_eq!(slurm.slurm_job.as_deref(), Some("7")); + assert_eq!(slurm.dir, format!("/scratch/orx/engine/runs/{RUN}")); + assert!(cleanable(&engine(r#"{"type":"Ssh","host":"lab","root":"/a b"}"#)).is_err()); + assert!(cleanable(&engine( + r#"{"type":"Slurm","host":"login","root":"/scratch/orx/engine","job":"7;rm"}"# + )) + .is_err()); + assert!(cleanable(&engine(r#"{"type":"Local","dir":"/x"}"#)) + .unwrap() + .is_none()); + assert!(cleanable(r#"{"kind":"engine"}"#).unwrap().is_none()); } fn outcomes_by_id(runs: &[RemoteRun], output: &str) -> BTreeMap { @@ -258,7 +352,10 @@ mod tests { RemoteRun { run_id: id.into(), host: "lab".into(), + slurm: false, root: root.map(Into::into), + engine: false, + slurm_job: None, dir: remote_run_dir(root, id), container: None, deleted, @@ -318,7 +415,7 @@ mod tests { "-c", &host_script( &batch, - &BTreeSet::from([None]), + &BTreeSet::from([(None, false)]), &BTreeSet::from([kept.clone()]), ), ]) @@ -353,6 +450,184 @@ mod tests { assert_eq!(left, expected); } + /// An engine run is busy while its wrapper lives on this node or its Slurm job is queued, + /// and stays when neither can be confirmed; a blob goes once no run dir links it and it + /// has sat idle. + #[cfg(unix)] + #[test] + fn engine_dirs_wait_for_their_wrapper_or_slurm_job_and_unlinked_blobs_are_swept() { + use std::os::unix::process::CommandExt as _; + let home = crate::local::git::TemporaryDirectory::new("orx-cleanup-engine").unwrap(); + let root = home.path().join(".orx/engine"); + let sources = root.join("sources"); + std::fs::create_dir_all(&sources).unwrap(); + let mut wrapper = crate::process::command("sleep") + .arg("30") + .process_group(0) + .spawn() + .unwrap(); + let node = orx_host::platform::node().unwrap(); + let (linked, unlinked, fresh, kept) = ( + "a".repeat(64), + "b".repeat(64), + "c".repeat(64), + "d".repeat(64), + ); + for name in [&linked, &unlinked, &fresh, &kept] { + std::fs::write(sources.join(name), "x").unwrap(); + if name != &fresh { + assert!(crate::process::command("touch") + .args(["-t", "202001010000"]) + .arg(sources.join(name)) + .status() + .unwrap() + .success()); + } + } + // Slurm job 41 is still running, 42 has left the queue, and 43 cannot be asked about. + let bin = home.path().join("bin"); + std::fs::create_dir_all(&bin).unwrap(); + let squeue = bin.join("squeue"); + std::fs::write( + &squeue, + "#!/bin/sh\ncase \"$3\" in 41) echo RUNNING;; 42) echo 'slurm_load_jobs error: Invalid job id specified' >&2; exit 1;; *) echo 'Unable to contact slurm controller' >&2; exit 1;; esac\n", + ) + .unwrap(); + { + use std::os::unix::fs::PermissionsExt as _; + std::fs::set_permissions(&squeue, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + for (id, pid, node) in [ + ("busy", wrapper.id(), node.as_str()), + ("done", 999_999, node.as_str()), + ("elsewhere", wrapper.id(), "compute-7"), + ("queued", wrapper.id(), "compute-7"), + ("finished", wrapper.id(), "compute-7"), + ("unknown", wrapper.id(), "compute-7"), + ] { + let dir = root.join("runs").join(id); + std::fs::create_dir_all(dir.join("repo")).unwrap(); + let mut identity = orx_host::platform::identity(wrapper.id()).unwrap(); + identity.node = node.into(); + identity.pid = pid; + if id == "done" { + identity.boot_id.push_str("-rebooted"); + } + orx_host::publish(&dir.join("wrapper.json"), &identity).unwrap(); + } + std::fs::hard_link(sources.join(&linked), root.join("runs/busy/source.tar")).unwrap(); + let engine_run = |id: &str| RemoteRun { + engine: true, + root: Some(".orx/engine".into()), + dir: format!(".orx/engine/runs/{id}"), + ..run(id, None, true) + }; + let slurm_run = |id: &str, job: &str| RemoteRun { + slurm: true, + slurm_job: Some(job.into()), + ..engine_run(id) + }; + let batch = [ + engine_run("busy"), + engine_run("done"), + engine_run("elsewhere"), + slurm_run("queued", "41"), + slurm_run("finished", "42"), + slurm_run("unknown", "43"), + ]; + let out = crate::process::command("bash") + .args([ + "-c", + &host_script( + &batch, + &BTreeSet::from([(Some(".orx/engine".into()), true)]), + &BTreeSet::from([kept.clone()]), + ), + ]) + .env("HOME", home.path()) + .env( + "ORX_HOST_BINARY", + orx_test_support::host_binaries().join(format!( + "orx-host-{}-{}", + if cfg!(target_os = "macos") { + "darwin" + } else { + "linux" + }, + std::env::consts::ARCH + )), + ) + .env( + "PATH", + format!("{}:{}", bin.display(), std::env::var("PATH").unwrap()), + ) + .output() + .unwrap(); + let _ = wrapper.kill(); + let _ = wrapper.wait(); + let outcomes = outcomes_by_id(&batch, &String::from_utf8(out.stdout).unwrap()); + assert_eq!(outcomes["busy"], Outcome::Busy); + assert_eq!(outcomes["done"], Outcome::Removed); + assert_eq!( + outcomes["elsewhere"], + Outcome::Failed("orx-host: wrapper belongs to another node".into()) + ); + assert_eq!(outcomes["queued"], Outcome::Busy); + assert_eq!(outcomes["finished"], Outcome::Removed); + assert_eq!( + outcomes["unknown"], + Outcome::Failed( + "cannot confirm Slurm job 43 ended: Unable to contact slurm controller".into() + ) + ); + for (id, kept) in [("elsewhere", true), ("queued", true), ("finished", false)] { + assert_eq!(root.join("runs").join(id).exists(), kept, "{id}"); + } + let mut left: Vec<_> = std::fs::read_dir(&sources) + .unwrap() + .map(|entry| entry.unwrap().file_name().into_string().unwrap()) + .collect(); + left.sort(); + assert_eq!(left, [linked, fresh, kept]); + } + + #[cfg(unix)] + #[test] + fn engine_retention_keeps_directories_when_the_host_check_fails() { + let home = crate::local::git::TemporaryDirectory::new("orx-cleanup-proof").unwrap(); + let dir = home.path().join("engine/runs/broken"); + std::fs::create_dir_all(dir.join("repo")).unwrap(); + std::fs::write(dir.join("wrapper.json"), "{").unwrap(); + let batch = [RemoteRun { + engine: true, + dir: dir.to_string_lossy().into_owned(), + ..run("broken", None, true) + }]; + let native = orx_test_support::host_binaries().join(format!( + "orx-host-{}-{}", + if cfg!(target_os = "macos") { + "darwin" + } else { + "linux" + }, + std::env::consts::ARCH + )); + for binary in [std::path::Path::new("/usr/bin/false"), &native] { + let output = crate::process::command("bash") + .args([ + "-c", + &host_script(&batch, &BTreeSet::new(), &BTreeSet::new()), + ]) + .env("ORX_HOST_BINARY", binary) + .output() + .unwrap(); + assert!( + matches!(&parse_outcomes(&batch, &String::from_utf8(output.stdout).unwrap())[0], Outcome::Failed(detail) if !detail.is_empty()) + ); + assert!(dir.join("repo").is_dir()); + } + } + #[cfg(unix)] #[test] fn container_runs_stay_queued_until_docker_reports_the_container_gone() { @@ -412,7 +687,7 @@ mod tests { rooted.container = Some(("abc".into(), format!("/root/.orx/runs/{RUN}"))); let script = host_script( &[rooted], - &BTreeSet::from([Some("/scratch/orx".to_string())]), + &BTreeSet::from([(Some("/scratch/orx".to_string()), false)]), &BTreeSet::new(), ); assert!(script.contains(&format!("d='/scratch/orx/runs/{RUN}';"))); diff --git a/src/jobs/ssh/container.rs b/src/jobs/ssh/container.rs index 56e20248b..25b3f223d 100644 --- a/src/jobs/ssh/container.rs +++ b/src/jobs/ssh/container.rs @@ -125,6 +125,50 @@ impl ContainerRun { ) } + /// The engine's run.sh for a run in this container: checks the container generation, + /// copies the inner script and the host's staged source in, then runs it there. + pub(crate) fn engine_run_sh( + &self, + exports: &str, + script: &str, + source: Option<&str>, + ) -> String { + let dir = sh_quote(&self.run_dir); + let id = sh_quote(&self.id); + let check = sh_quote("{{.State.StartedAt}} {{.State.Status}}"); + let expected = sh_quote(&format!("{} running", self.started_at)); + let inner = sh_quote(&inner_script(self, exports, script)); + let write = sh_quote(&format!("umask 077; mkdir -p {dir} && cat > {dir}/run.sh")); + let mut run_sh = format!( + "set -e\nactual=$(docker container inspect --format {check} -- {id})\n[ \"$actual\" = {expected} ] || {{ echo 'Container generation or readiness changed before launch' >&2; exit 97; }}\nprintf '%s' {inner} | docker exec -i {id} bash -c {write}\n" + ); + if let Some(source) = source { + let extract = sh_quote(&format!( + "umask 077; cd {dir} && rm -rf repo.part repo && mkdir repo.part && tar -xf - -C repo.part && mv repo.part repo" + )); + run_sh.push_str(&format!( + "docker exec -i {id} bash -c {extract} < {}\n", + sh_quote(source) + )); + } + run_sh.push_str(&format!( + "exec docker exec {id} setsid --wait bash {dir}/run.sh String { + let id = sh_quote(&self.id); + let check = sh_quote("{{.State.StartedAt}} {{.State.Status}}"); + let running = sh_quote(&format!("{} running", self.started_at)); + let paused = sh_quote(&format!("{} paused", self.started_at)); + let stop = self.exec(&cancel_script(&self.run_dir)); + format!( + "set -e\nfound=$(docker container ls --all --no-trunc --quiet --filter id={id})\n[ -n \"$found\" ] || exit 0\nactual=$(docker container inspect --format {check} -- {id})\ncase \"$actual\" in {running}|{paused}) {stop} ;; *) exit 0 ;; esac\n" + ) + } + pub async fn require_running(&self, target: &SshTarget) -> Result<()> { if let Some(reason) = unavailable(target, self).await? { return Err(anyhow!("{reason}")); @@ -325,8 +369,18 @@ pub(super) async fn cancel(target: &SshTarget, container: &ContainerRun) -> Resu } return Ok(()); } - let directory = sh_quote(&container.run_dir); - let script = format!( + super::ssh_control( + target, + &container.exec(&cancel_script(&container.run_dir)), + None, + ) + .await?; + Ok(()) +} + +fn cancel_script(run_dir: &str) -> String { + let directory = sh_quote(run_dir); + format!( r#"{PROCESS_HELPERS} cd {directory} || exit 1 umask 077 @@ -345,9 +399,7 @@ for ((i=0; i<10; i++)); do group_alive || exit 0; sleep 0.1; done echo 'Experiment process group is still alive' >&2 exit 1 "# - ); - super::ssh_control(target, &container.exec(&script), None).await?; - Ok(()) + ) } #[cfg(test)] diff --git a/src/jobs/ssh/container/tests.rs b/src/jobs/ssh/container/tests.rs index ac774c943..e3b393299 100644 --- a/src/jobs/ssh/container/tests.rs +++ b/src/jobs/ssh/container/tests.rs @@ -108,7 +108,9 @@ async fn ssh_container_lifecycle() { "-i".into(), std::env::var("ORX_SSH_TEST_KEY").expect("fixture key"), ]); - let connection = ssh::interactive_args(&target, None, None).await.unwrap(); + let connection = ssh::prepare_interactive_connection(&target, None, None) + .await + .unwrap(); assert!(crate::process::tokio_command("ssh") .args(&connection.args) .status() @@ -618,3 +620,84 @@ async fn supervisor_restart(target: &SshTarget, reference: &str, port: u16) { .unwrap() .success()); } + +#[cfg(unix)] +#[test] +fn engine_run_sh_runs_the_payload_inside_the_container_with_its_source() { + use std::os::unix::fs::PermissionsExt; + let temp = crate::local::git::TemporaryDirectory::new("orx-engine-container").unwrap(); + let host = temp.path().join("host-run"); + let staged = temp.path().join("staged"); + let bin = temp.path().join("bin"); + for dir in [&host, &staged, &bin] { + std::fs::create_dir_all(dir).unwrap(); + } + std::fs::write(staged.join("source.txt"), "snapshot\n").unwrap(); + assert!(crate::process::command("tar") + .arg("-cf") + .arg(host.join("source.tar")) + .arg("-C") + .arg(&staged) + .arg("source.txt") + .status() + .unwrap() + .success()); + // `docker exec` runs its command here; the container is this machine. + std::fs::write( + bin.join("docker"), + r#"#!/bin/bash +echo "$*" >> "$CALLS" +case "$1" in + container) echo '2026-10-30T00:00:00Z running';; + exec) + shift + [ "$1" = -i ] && shift + shift + [ "$1" = setsid ] && shift 2 + exec "$@";; +esac +"#, + ) + .unwrap(); + std::fs::set_permissions(bin.join("docker"), std::fs::Permissions::from_mode(0o755)).unwrap(); + let container = ContainerRun { + reference: "research".into(), + id: "cid".into(), + started_at: "2026-10-30T00:00:00Z".into(), + run_dir: temp + .path() + .join("container/.orx/runs") + .to_string_lossy() + .into_owned(), + } + .for_run("run"); + let run_sh = container.engine_run_sh( + "export ORX_TEST_SECRET='quote'\"'\"' and $literal'", + &crate::compute::staged_script( + "cat source.txt > ../out; echo \"$ORX_TEST_SECRET\" >> ../out; exit 3", + ), + Some("source.tar"), + ); + std::fs::write(host.join("run.sh"), run_sh).unwrap(); + let status = crate::process::command("bash") + .arg("run.sh") + .current_dir(&host) + .env( + "PATH", + format!("{}:{}", bin.display(), std::env::var("PATH").unwrap()), + ) + .env("CALLS", temp.path().join("calls")) + .status() + .unwrap(); + assert_eq!(status.code(), Some(3)); + assert_eq!( + std::fs::read_to_string(std::path::Path::new(&container.run_dir).join("out")).unwrap(), + "snapshot\nquote' and $literal\n" + ); + let calls = std::fs::read_to_string(temp.path().join("calls")).unwrap(); + assert!(calls.starts_with("container inspect"), "{calls}"); + assert!(calls.contains("exec cid setsid --wait bash"), "{calls}"); + assert!(container + .engine_cancel_sh() + .contains("docker exec -i 'cid' bash -c")); +} diff --git a/src/jobs/ssh/prepared.rs b/src/jobs/ssh/prepared.rs index f7548e87a..364a6ade8 100644 --- a/src/jobs/ssh/prepared.rs +++ b/src/jobs/ssh/prepared.rs @@ -265,8 +265,14 @@ pub(super) async fn prepare(target: &SshTarget, refresh: bool) -> Result Result { Ok(empty) } -#[cfg(test)] -async fn resolve(dest: &str, config: Option<&std::path::Path>) -> Result { +pub(super) async fn resolve(dest: &str, config: Option<&std::path::Path>) -> Result { resolve_with(dest, config, query).await } -#[cfg(test)] async fn resolve_with( dest: &str, config: Option<&std::path::Path>, diff --git a/src/jobs/ssh/service/logs.rs b/src/jobs/ssh/service/logs.rs index 98ac2ac40..8effaa294 100644 --- a/src/jobs/ssh/service/logs.rs +++ b/src/jobs/ssh/service/logs.rs @@ -24,7 +24,7 @@ struct Paths { impl Paths { fn new(run: &str) -> Self { Self { - base: crate::store::log_path(run), + base: crate::store::log_path(&crate::store::data_dir(), run), } } fn cursor(&self) -> PathBuf { @@ -200,6 +200,23 @@ pub(crate) fn read(run: &str, offset: u64, limit: u64, expected: Option<&str>) - read_at(&Paths::new(run), offset, limit, expected) } +pub(crate) fn read_from( + data_dir: &Path, + run: &str, + offset: u64, + limit: u64, + expected: Option<&str>, +) -> Result { + read_at( + &Paths { + base: crate::store::log_path(data_dir, run), + }, + offset, + limit, + expected, + ) +} + fn read_at(paths: &Paths, offset: u64, limit: u64, expected: Option<&str>) -> Result { let lock = paths.lock()?; let _guard = lock.read()?; @@ -239,16 +256,26 @@ fn read_at(paths: &Paths, offset: u64, limit: u64, expected: Option<&str>) -> Re }) } -pub(crate) fn open_current(run: &str) -> Result<(std::fs::File, PathBuf, u64)> { - let paths = Paths::new(run); +pub(crate) fn open_current(base: PathBuf) -> Result<(std::fs::File, PathBuf, u64)> { + let paths = Paths { base }; let lock = paths.lock()?; let _guard = lock.read()?; - let (path, size) = match load(&paths.cursor())? { - Some(cursor) => (paths.version(&cursor.generation)?, cursor.bytes), - None => { - let path = paths.base.clone(); - let size = std::fs::metadata(&path)?.len(); - (path, size) + let engine_cursor: Option = + match std::fs::read(paths.base.with_extension("engine-cursor.json")) { + Ok(bytes) => Some(serde_json::from_slice(&bytes)?), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => None, + Err(error) => return Err(error.into()), + }; + let (path, size) = if let Some(cursor) = engine_cursor { + (paths.base.clone(), cursor.offset) + } else { + match load(&paths.cursor())? { + Some(cursor) => (paths.version(&cursor.generation)?, cursor.bytes), + None => { + let path = paths.base.clone(); + let size = std::fs::metadata(&path)?.len(); + (path, size) + } } }; Ok((std::fs::File::open(&path)?, path, size)) diff --git a/src/jobs/ssh/service/mod.rs b/src/jobs/ssh/service/mod.rs index 97c57ce2e..fa5cbadbc 100644 --- a/src/jobs/ssh/service/mod.rs +++ b/src/jobs/ssh/service/mod.rs @@ -263,26 +263,24 @@ async fn ensure() -> Result { )) } +pub(crate) async fn reset_existing_backoff(target: &SshTarget) -> Result<()> { + if !state::root().join("state.sqlite3").try_exists()? { + return Ok(()); + } + let resolved = state::resolve(target).await?; + state::database()?.execute( + "UPDATE connections SET failures = 0, next_at = 0, last_error = NULL WHERE id = ?1", + [resolved.key], + )?; + Ok(()) +} + pub(crate) async fn request(target: &SshTarget, operation: Value) -> Result { let endpoint = ensure().await?; // A lost response may follow a successful mutation: never replay it here. exchange(&endpoint, Some(target.clone()), operation).await } -pub(crate) async fn healthy(target: &SshTarget) -> bool { - let Ok(endpoint) = endpoint() else { - return false; - }; - exchange(&endpoint, Some(target.clone()), json!({"op":"status"})) - .await - .is_ok_and(|value| value["connected"] == true) -} - -pub(crate) async fn attach(target: &SshTarget) -> Result<()> { - request(target, json!({"op":"attach"})).await?; - Ok(()) -} - pub(crate) async fn execute( target: &SshTarget, command: &str, diff --git a/src/jobs/ssh/sharing.rs b/src/jobs/ssh/sharing.rs index 0bc0ed522..55bd04b60 100644 --- a/src/jobs/ssh/sharing.rs +++ b/src/jobs/ssh/sharing.rs @@ -2,6 +2,7 @@ use super::prepared::{probe_args, Publication}; use super::ROUTE_FIELDS; use sha2::{Digest, Sha256}; use std::collections::BTreeMap; +use std::os::unix::fs::FileTypeExt; use std::path::Path; use std::process::Stdio; @@ -87,7 +88,12 @@ fn predicate(default_dir: &Path, entries: &BTreeMap) -> Str contents } -fn install(ssh_dir: &Path, default_dir: &Path, publication: Option) -> Result<()> { +fn update( + ssh_dir: &Path, + default_dir: &Path, + include: bool, + change: impl FnOnce(&mut BTreeMap) -> Result<()>, +) -> Result<()> { use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt}; let mut builder = std::fs::DirBuilder::new(); @@ -134,20 +140,10 @@ fn install(ssh_dir: &Path, default_dir: &Path, publication: Option) Err(error) if error.kind() == std::io::ErrorKind::NotFound => BTreeMap::new(), Err(error) => return Err(error.into()), }; - if let Some(publication) = publication { - entries.insert( - format!("{}:{}", publication.host, publication.native_id), - publication, - ); - } + change(&mut entries)?; let contents = fragment(default_dir, &entries); let predicate = predicate(default_dir, &entries); let registry_contents = serde_json::to_vec(&entries)?; - let current = match std::fs::read(&user_config) { - Ok(bytes) => bytes, - Err(error) if error.kind() == std::io::ErrorKind::NotFound => Vec::new(), - Err(error) => return Err(error.into()), - }; for (path, contents) in [ (&managed_predicate, predicate.as_bytes()), (&managed_config, contents.as_bytes()), @@ -157,6 +153,34 @@ fn install(ssh_dir: &Path, default_dir: &Path, publication: Option) crate::local::git::atomic_write_with_mode(path, contents, Some(0o600))?; } } + if !include { + return Ok(()); + } + let current = match std::fs::read(&user_config) { + Ok(bytes) => bytes, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Vec::new(), + Err(error) => return Err(error.into()), + }; + if current.split(|&byte| byte == b'\n').any(|line| { + let mut fields = line + .split(|byte| byte.is_ascii_whitespace() || *byte == b'=') + .filter(|field| !field.is_empty()); + fields + .next() + .is_some_and(|key| key.eq_ignore_ascii_case(b"include")) + && fields + .take_while(|field| !field.starts_with(b"#")) + .any(|path| { + matches!( + path, + b"openresearch_config" + | b"\"openresearch_config\"" + | b"'openresearch_config'" + ) + }) + }) { + return Ok(()); + } if std::fs::symlink_metadata(&user_config).is_ok_and(|metadata| metadata.is_symlink()) { return Err(anyhow!( "{} is a symlink; leave it intact and append `Host *` followed by `{}` to your SSH config manually", @@ -164,37 +188,13 @@ fn install(ssh_dir: &Path, default_dir: &Path, publication: Option) INCLUDE.trim() )); } - let mut updated = current.clone(); - while let Some(start) = updated - .windows(FOOTER.len()) - .position(|bytes| bytes == FOOTER.as_bytes()) - { - let end = start + FOOTER.len(); - let from = if end == updated.len() { - start - } else { - end - INCLUDE.len() - }; - updated.drain(from..end); - } - while let Some(start) = updated - .windows(INCLUDE.len()) - .enumerate() - .find(|(start, bytes)| { - (*start == 0 || updated[*start - 1] == b'\n') && *bytes == INCLUDE.as_bytes() - }) - .map(|(start, _)| start) - { - updated.drain(start..start + INCLUDE.len()); - } + let mut updated = current; updated.extend_from_slice(FOOTER.as_bytes()); - if updated != current { - crate::local::git::atomic_write_with_mode(&user_config, &updated, Some(0o600))?; - } + crate::local::git::atomic_write_with_mode(&user_config, &updated, Some(0o600))?; Ok(()) } -pub(super) async fn setup(target: &SshTarget) -> Result<()> { +async fn require_sharing() -> Result<()> { let version = crate::process::tokio_command("ssh") .arg("-V") .stdin(Stdio::null()) @@ -206,12 +206,134 @@ pub(super) async fn setup(target: &SshTarget) -> Result<()> { "automatic sharing requires OpenSSH 8.4 or newer; your SSH config was not changed" )); } + Ok(()) +} + +pub(crate) fn retire_legacy(home: &Path) -> Result<()> { + let ssh_dir = home.join(".ssh"); + if !ssh_dir.join("openresearch_connections.json").exists() { + return Ok(()); + } + let default_dir = control_dir_for(&home.join(".config/openresearch")); + update(&ssh_dir, &default_dir, false, |entries| { + entries.retain(|key, _| { + key.strip_prefix("engine:").is_none_or(|path| { + let path = Path::new(path); + !path.is_absolute() || path.exists() + }) + }); + Ok(()) + }) +} + +pub(crate) async fn publish_engine( + home: &Path, + alias: &str, + config: Option<&Path>, + path: &Path, + route: &str, +) -> Result<()> { + require_sharing().await?; + let connection = super::prepared::resolve(alias, config).await?; + let actual = connection.publication.queries[0] + .output + .lines() + .filter(|line| !line.starts_with("controlpath ")) + .collect::>(); + let pinned = route + .lines() + .filter(|line| !line.starts_with("canonicalizehostname ")) + .collect::>(); + if actual != pinned { + return Err(anyhow!( + "SSH route changed while publishing connection sharing" + )); + } + let _master_lock = super::lock_master(&connection.path).await?; + let publication = connection.publication; + let path = path.to_path_buf(); + super::prepare_control_dir()?; + let home = home.to_path_buf(); + let default_dir = control_dir_for(&home.join(".config/openresearch")); + tokio::task::spawn_blocking(move || { + update(&home.join(".ssh"), &default_dir, true, |entries| { + let link = control_dir().join(&publication.socket_name); + if link + .symlink_metadata() + .is_ok_and(|metadata| metadata.is_symlink()) + && !link.exists() + { + std::fs::remove_file(&link)?; + } + match std::os::unix::fs::symlink(&path, &link) { + Ok(()) => {} + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => { + if !std::fs::metadata(&link)?.file_type().is_socket() { + return Err(anyhow!( + "SSH sharing path {} is not a socket", + link.display() + )); + } + } + Err(error) => return Err(error.into()), + } + entries.insert(format!("engine:{}", path.display()), publication); + Ok(()) + }) + }) + .await??; + Ok(()) +} + +pub(crate) async fn withdraw_engine(home: &Path, path: &Path) -> Result<()> { + let key = format!("engine:{}", path.display()); + let path = path.to_path_buf(); + let home = home.to_path_buf(); + let default_dir = control_dir_for(&home.join(".config/openresearch")); + tokio::task::spawn_blocking(move || { + let ssh_dir = home.join(".ssh"); + if !ssh_dir.join("openresearch_connections.json").exists() { + return Ok(()); + } + update(&ssh_dir, &default_dir, false, |entries| { + let Some(publication) = entries.remove(&key) else { + return Ok(()); + }; + let link = control_dir().join(&publication.socket_name); + if std::fs::read_link(&link).ok().as_ref() == Some(&path) { + std::fs::remove_file(&link)?; + if let Some(other) = entries.iter().find_map(|(key, entry)| { + let path = Path::new(key.strip_prefix("engine:")?); + (entry.socket_name == publication.socket_name + && std::fs::metadata(path) + .is_ok_and(|metadata| metadata.file_type().is_socket())) + .then_some(path) + }) { + std::os::unix::fs::symlink(other, &link)?; + } + } + Ok(()) + }) + }) + .await? +} + +pub(super) async fn setup(target: &SshTarget) -> Result<()> { + require_sharing().await?; let home = dirs::home_dir().ok_or_else(|| anyhow!("could not locate your home directory"))?; let ssh_dir = home.join(".ssh"); let default_dir = control_dir_for(&home.join(".config/openresearch")); let publication = super::prepared::prepare(target, false).await?.publication; - tokio::task::spawn_blocking(move || install(&ssh_dir, &default_dir, Some(publication))) - .await??; + tokio::task::spawn_blocking(move || { + update(&ssh_dir, &default_dir, true, |entries| { + entries.insert( + format!("{}:{}", publication.host, publication.native_id), + publication, + ); + Ok(()) + }) + }) + .await??; let mut command = crate::process::tokio_command("ssh"); command @@ -246,6 +368,73 @@ mod tests { use super::*; use std::path::PathBuf; + #[tokio::test] + async fn shared_master_withdrawal_keeps_other_stores_and_legacy_sockets() { + use std::os::unix::net::UnixListener; + let home = crate::local::git::TemporaryDirectory::new("orx-sharing-withdraw").unwrap(); + if std::env::var("ORX_TEST_SHARED_MASTER").as_deref() != Ok("1") { + let output = crate::process::command(std::env::current_exe().unwrap()) + .env("ORX_TEST_SHARED_MASTER", "1") + .env("XDG_CONFIG_HOME", home.path().join("config")) + .args([ + "--exact", + concat!( + module_path!(), + "::shared_master_withdrawal_keeps_other_stores_and_legacy_sockets" + ), + "--nocapture", + ]) + .output() + .unwrap(); + assert!( + output.status.success(), + "{}\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + return; + } + super::super::prepare_control_dir().unwrap(); + let sockets = Path::new("/tmp").join(format!("orx-sharing-{}", uuid::Uuid::new_v4())); + std::fs::create_dir(&sockets).unwrap(); + let first = sockets.join("first"); + let second = sockets.join("second"); + let _first = UnixListener::bind(&first).unwrap(); + let _second = UnixListener::bind(&second).unwrap(); + let publication = Publication { + host: "lab".into(), + native_id: "a".repeat(40), + socket_name: "same-route-and-agent".into(), + queries: Vec::new(), + }; + let link = control_dir().join(&publication.socket_name); + std::os::unix::fs::symlink(&first, &link).unwrap(); + update(&home.path().join(".ssh"), &control_dir(), true, |entries| { + entries.insert(format!("engine:{}", first.display()), publication.clone()); + entries.insert(format!("engine:{}", second.display()), publication.clone()); + Ok(()) + }) + .unwrap(); + withdraw_engine(home.path(), &first).await.unwrap(); + assert_eq!(std::fs::read_link(&link).unwrap(), second); + withdraw_engine(home.path(), &second).await.unwrap(); + assert!(link.symlink_metadata().is_err()); + let _legacy = UnixListener::bind(&link).unwrap(); + update(&home.path().join(".ssh"), &control_dir(), true, |entries| { + entries.insert(format!("engine:{}", first.display()), publication.clone()); + Ok(()) + }) + .unwrap(); + withdraw_engine(home.path(), &first).await.unwrap(); + assert!(std::fs::symlink_metadata(&link) + .unwrap() + .file_type() + .is_socket()); + std::fs::remove_file(link).unwrap(); + std::fs::remove_dir(control_dir()).unwrap(); + std::fs::remove_dir_all(sockets).unwrap(); + } + #[test] fn native_config_shares_only_matching_live_sockets_and_preserves_user_settings() { use std::os::unix::net::UnixListener; @@ -383,6 +572,73 @@ mod tests { std::fs::remove_dir_all(&dev).unwrap(); } + #[test] + fn engine_and_legacy_publications_share_the_lock_and_registry() { + use std::os::unix::net::UnixListener; + let temp = crate::local::git::TemporaryDirectory::new("orx-sharing-coexist").unwrap(); + let ssh_dir = temp.path().join(".ssh"); + let default_dir = temp.path().join("sockets"); + let socket = Path::new("/tmp").join(format!("orx-sharing-{}", uuid::Uuid::new_v4())); + let listener = UnixListener::bind(&socket).unwrap(); + let publication = Publication { + host: "lab".into(), + native_id: "a".repeat(40), + socket_name: "0123456789abcdef".into(), + queries: Vec::new(), + }; + let key = format!("engine:{}", socket.display()); + update(&ssh_dir, &default_dir, true, |entries| { + entries.insert(key.clone(), publication.clone()); + Ok(()) + }) + .unwrap(); + let user = std::fs::read(ssh_dir.join("config")).unwrap(); + let file = std::fs::OpenOptions::new() + .read(true) + .write(true) + .open(ssh_dir.join(".orx-config.lock")) + .unwrap(); + let mut lock = fd_lock::RwLock::new(file); + let guard = lock.try_write().unwrap(); + let (attempting, attempted) = std::sync::mpsc::channel(); + let writer = std::thread::spawn({ + let ssh_dir = ssh_dir.clone(); + let default_dir = default_dir.clone(); + move || { + attempting.send(()).unwrap(); + update(&ssh_dir, &default_dir, true, |entries| { + entries.insert( + format!("{}:{}", publication.host, publication.native_id), + publication, + ); + Ok(()) + }) + .unwrap(); + } + }); + attempted.recv().unwrap(); + std::thread::sleep(std::time::Duration::from_millis(50)); + assert!(!writer.is_finished()); + drop(guard); + writer.join().unwrap(); + let read = || { + serde_json::from_slice::>( + &std::fs::read(ssh_dir.join("openresearch_connections.json")).unwrap(), + ) + .unwrap() + }; + assert_eq!(read().len(), 2); + retire_legacy(temp.path()).unwrap(); + assert_eq!(read().len(), 2); + assert_eq!(std::fs::read(ssh_dir.join("config")).unwrap(), user); + drop(listener); + std::fs::remove_file(socket).unwrap(); + retire_legacy(temp.path()).unwrap(); + assert_eq!(read().len(), 1); + assert!(!read().contains_key(&key)); + assert_eq!(std::fs::read(ssh_dir.join("config")).unwrap(), user); + } + #[test] fn version_requires_supported_openssh() { for version in ["OpenSSH_8.4p1, LibreSSL", "OpenSSH_9.9p2", "OpenSSH_10.3p1"] { @@ -407,37 +663,34 @@ mod tests { let user_config = ssh_dir.join("config"); let original = b"# user's config\r\nHost lab\r\n User me"; std::fs::write(&user_config, original).unwrap(); - install(&ssh_dir, Path::new("/tmp/default"), None).unwrap(); + update(&ssh_dir, Path::new("/tmp/default"), true, |_| Ok(())).unwrap(); let once = std::fs::read(&user_config).unwrap(); assert_eq!(&once[..original.len()], original); - install(&ssh_dir, Path::new("/tmp/default"), None).unwrap(); + update(&ssh_dir, Path::new("/tmp/default"), true, |_| Ok(())).unwrap(); assert_eq!(std::fs::read(&user_config).unwrap(), once); let later = b"Match final\n ControlPath none\n"; - std::fs::write(&user_config, [once.as_slice(), later].concat()).unwrap(); - install(&ssh_dir, Path::new("/tmp/default"), None).unwrap(); - let moved = std::fs::read(&user_config).unwrap(); - assert_eq!( - moved, - [original.as_slice(), b"\nHost *\n", later, FOOTER.as_bytes()].concat() - ); - install(&ssh_dir, Path::new("/tmp/default"), None).unwrap(); - assert_eq!(std::fs::read(&user_config).unwrap(), moved); - std::fs::write( - &user_config, - [b"# legacy\n", INCLUDE.as_bytes(), moved.as_slice()].concat(), - ) - .unwrap(); - install(&ssh_dir, Path::new("/tmp/default"), None).unwrap(); - assert_eq!( - std::fs::read(&user_config).unwrap(), - [b"# legacy\n", moved.as_slice()].concat() - ); + for contents in [ + [once.as_slice(), later].concat(), + [b"# legacy\n", INCLUDE.as_bytes(), once.as_slice()].concat(), + b"Host *\r\n include openresearch_config\r\nHost office\r\n Port 2222\r\n".to_vec(), + b"Host *\nInclude\t \"openresearch_config\" # sharing\nHost office\n".to_vec(), + b"Host *\nInclude=openresearch_config".to_vec(), + ] { + use std::os::unix::fs::MetadataExt; + std::fs::write(&user_config, &contents).unwrap(); + let before = std::fs::metadata(&user_config).unwrap(); + update(&ssh_dir, Path::new("/tmp/default"), true, |_| Ok(())).unwrap(); + let after = std::fs::metadata(&user_config).unwrap(); + assert_eq!(std::fs::read(&user_config).unwrap(), contents); + assert_eq!(after.modified().unwrap(), before.modified().unwrap()); + assert_eq!((after.ino(), after.mode()), (before.ino(), before.mode())); + } std::fs::write( &user_config, [b"Host office", FOOTER.as_bytes(), b" Port 2222\n"].concat(), ) .unwrap(); - install(&ssh_dir, Path::new("/tmp/default"), None).unwrap(); + update(&ssh_dir, Path::new("/tmp/default"), true, |_| Ok(())).unwrap(); let resolved = crate::process::command("ssh") .args(["-G", "-F"]) .arg(&user_config) @@ -450,11 +703,82 @@ mod tests { let real = temp.path().join("real"); std::fs::write(&real, original).unwrap(); symlink(&real, &user_config).unwrap(); - assert!(install(&ssh_dir, Path::new("/tmp/default"), None).is_err()); + assert!(update(&ssh_dir, Path::new("/tmp/default"), true, |_| Ok(())).is_err()); assert_eq!(std::fs::read(&real).unwrap(), original); assert_eq!( std::fs::read(ssh_dir.join("openresearch_config")).unwrap(), fragment(Path::new("/tmp/default"), &BTreeMap::new()).as_bytes() ); } + #[test] + fn another_stores_live_legacy_publication_is_preserved() { + use crate::engine::clock::TestClock; + use crate::engine::Engine; + use crate::store::{Store, StoredRun}; + use std::fs::{self, OpenOptions}; + use std::os::unix::net::UnixListener; + use std::sync::Arc; + let home = crate::local::git::TemporaryDirectory::new("orx-sharing-stores").unwrap(); + let ssh_dir = home.path().join(".ssh"); + fs::create_dir(&ssh_dir).unwrap(); + fs::write(ssh_dir.join("config"), FOOTER).unwrap(); + let engine = Engine::new( + Store::open_at(home.path().join("data")).unwrap(), + Arc::new(TestClock::new()), + ); + let other = Store::open_at(home.path().join("other-data")).unwrap(); + let run = StoredRun { + id: "other-legacy".into(), + experiment_id: "exp".into(), + project_id: "proj".into(), + status: "running".into(), + backend_json: r#"{"kind":"ssh_job","jobId":"/other/run"}"#.into(), + command: "train".into(), + created_at: 1, + updated_at: 1, + ended_at: None, + exit_code: None, + commit_sha: None, + result_markdown: None, + cancel_requested: false, + cancel_reason: None, + chat_session_id: None, + }; + other.upsert_run(&run).unwrap(); + let [path, _] = other.supervisor_lock_paths(&run.id).unwrap(); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + let file = OpenOptions::new() + .write(true) + .create(true) + .truncate(false) + .open(path) + .unwrap(); + let mut lock = fd_lock::RwLock::new(file); + let _guard = lock.try_write().unwrap(); + let sockets = control_dir_for(&home.path().join(".config/openresearch")); + fs::create_dir(&sockets).unwrap(); + let socket = sockets.join("other-route"); + let _listener = UnixListener::bind(&socket).unwrap(); + let registry = serde_json::json!({ + "engine:other-route": { + "host": "engine", + "native_id": "other-route", + "socket_name": "%C", + "queries": [] + } + }); + let path = ssh_dir.join("openresearch_connections.json"); + fs::write(&path, serde_json::to_vec(®istry).unwrap()).unwrap(); + assert!(engine.retire_ssh_config(home.path()).unwrap()); + assert!(socket.exists()); + assert_eq!( + serde_json::from_slice::(&fs::read(path).unwrap()).unwrap(), + registry + ); + assert_eq!(fs::read(ssh_dir.join("config")).unwrap(), FOOTER.as_bytes()); + assert!(engine.retire_ssh_config(home.path()).unwrap()); + drop(other); + fs::remove_file(socket).unwrap(); + fs::remove_dir(sockets).unwrap(); + } } diff --git a/src/jobs/vercel.rs b/src/jobs/vercel.rs index 9f160f84a..81609bf3d 100644 --- a/src/jobs/vercel.rs +++ b/src/jobs/vercel.rs @@ -65,6 +65,7 @@ def _emit_exit(code): out = {"stage": "COMPLETED"} else: out = {"stage": "ERROR", "message": "exited with code %d" % code} + out["exitCode"] = code print(json.dumps(out)) def submit(): @@ -141,6 +142,9 @@ def status(name, pid): if state == "pending": print(json.dumps({"stage": "SCHEDULING"})) return + if state != "running" and tags.get("orx_cancelled"): + print(json.dumps({"stage": "CANCELED"})) + return if state != "running": # Only a running sandbox is queried for its process: process calls on a # stopped sandbox would boot a fresh session. @@ -210,6 +214,9 @@ def cancel(name): sandbox, _ = _sdk() box = sandbox.get_sandbox(name=name) if _status(box) in ("pending", "running"): + tags = dict(box.tags or {}) + tags["orx_cancelled"] = "1" + box.update(tags=tags) box.stop() def finish(name): @@ -919,6 +926,7 @@ pub fn sandbox_name(run_id: &str) -> String { name.trim_end_matches('-').to_string() } +#[derive(serde::Serialize, serde::Deserialize)] pub struct VercelJobSpec { pub name: String, /// `bash -c` payload (the shared snapshot-and-run script). @@ -992,6 +1000,7 @@ pub fn session_limit(timeout_seconds: u64, session_cap: u64) -> u64 { pub struct JobState { pub stage: String, pub message: Option, + pub exit_code: Option, } pub async fn inspect_job(sandbox_name: &str, process_id: &str) -> Result { @@ -1005,6 +1014,10 @@ pub async fn inspect_job(sandbox_name: &str, process_id: &str) -> Result "answer", News::Question { .. } => "question", - News::Run(_) | News::Unmonitored(_) => "run", }) .collect() }; diff --git a/src/local/chat/mod.rs b/src/local/chat/mod.rs index 5f4920f65..3b1a77089 100644 --- a/src/local/chat/mod.rs +++ b/src/local/chat/mod.rs @@ -882,9 +882,9 @@ pub enum OrxKind { Answer, /// A subscribed chat asks a question. Question, - /// A run the chat asked to be woken for ended. + /// A legacy run-result message retained for stored transcripts. Run, - /// orx lost sight of runs the chat waits on. + /// A legacy monitoring notice retained for stored transcripts. Monitoring, } @@ -8767,10 +8767,236 @@ fn materialize_unfinished_turns( // --- run watcher ---------------------------------------------------------------- -/// Resume explicitly subscribed agent sessions after a run finishes or a chat -/// they subscribe to has news. Busy and draining sessions keep their durable -/// wake-up until idle. -pub async fn watch_runs( +#[derive(Debug)] +struct PermanentRunNoticeError(String); + +impl std::fmt::Display for PermanentRunNoticeError { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str(&self.0) + } +} + +impl std::error::Error for PermanentRunNoticeError {} + +async fn send_run_notice_batch( + chat: &Arc, + session_id: &str, + notices: &[crate::store::RunNotice], + mut guard: TurnGuard, +) -> Result { + let store = Store::open()?; + let existing = store.get_chat_turn_by_client_id(session_id, ¬ices[0].client_turn_id)?; + if let Some(turn) = existing.as_ref().filter(|turn| { + turn.state == "failed" && matches!(turn.delivery_state.as_str(), "not_sent" | "rejected") + }) { + store.record_run_notice_failure( + session_id, + ¬ices[0].client_turn_id, + turn.error_message + .as_deref() + .unwrap_or("Notice was not accepted"), + false, + now_ms(), + )?; + guard.release().await; + let result = chat + .recover_turn(session_id, &turn.id, "retry", RecoveryOverrides::default()) + .await?; + return Ok(TurnSubmission::Existing(result.turn_id)); + } + if existing.is_none() { + let session = store + .get_chat_session(session_id)? + .ok_or_else(|| PermanentRunNoticeError("Chat was deleted".into()))?; + let harness: Box = + if session.harness.starts_with("acp:") { + let state = match store.acp_session_state(session_id)? { + Some(state) => Some(state), + None if session.native_session_id.is_some() + || !crate::local::acp::registered_definitions() + .iter() + .any(|definition| definition.id == session.harness) => + { + None + } + None => store.ensure_acp_session_state(session_id)?, + } + .filter(|state| state.launch.id == session.harness) + .ok_or_else(|| { + PermanentRunNoticeError("Chat harness is no longer configured".into()) + })?; + Box::new(crate::local::harness::acp::Acp(state.launch)) + } else { + crate::local::harness::chat_harness(&session.harness).ok_or_else(|| { + PermanentRunNoticeError("Chat harness is no longer configured".into()) + })? + }; + let info = harness + .detect_snapshot() + .await + .ok_or_else(|| anyhow!("Could not determine chat harness availability"))?; + if !info.installed { + return Err( + PermanentRunNoticeError("Chat harness is no longer installed".into()).into(), + ); + } + } + let result = chat + .send_message_showing(session_id, run_notice_request(notices, guard)) + .await; + if result.is_err() && store.get_chat_session(session_id)?.is_none() { + return Err(PermanentRunNoticeError("Chat was deleted".into()).into()); + } + result +} + +/// Frozen bodies keep the admission hash stable across later run and chat changes. +fn run_notice_request(notices: &[crate::store::RunNotice], guard: TurnGuard) -> SendTurnRequest { + let text = notices + .iter() + .map(|notice| notice.body.as_str()) + .collect::>() + .join("\n\n"); + + SendTurnRequest { + messages: vec![AnnotatedText { + text, + annotations: Vec::new(), + }], + prepared_input: None, + replace_settings: false, + transcript: TranscriptDisplay { + text: Some(String::new()), + annotations: None, + orx: Vec::new(), + record_user_message: false, + }, + overrides: TurnOverrides::default(), + images: TurnAttachments::Uploaded(Vec::new()), + admission: TurnAdmission::Preclaimed(guard), + client_turn_id: Some(notices[0].client_turn_id.clone()), + request_hash: None, + } +} + +async fn process_run_notices( + chat: &Arc, + store: Store, + data_dir_move_in_progress: &std::sync::atomic::AtomicBool, +) -> Result<()> { + if data_dir_move_in_progress.load(std::sync::atomic::Ordering::SeqCst) { + return Ok(()); + } + store.expire_run_notice_batches(now_ms())?; + for session_id in store.pending_run_notice_sessions()? { + if data_dir_move_in_progress.load(std::sync::atomic::Ordering::SeqCst) { + return Ok(()); + } + let Some(mut guard) = TurnGuard::claim_idle(chat, &session_id).await else { + continue; + }; + if data_dir_move_in_progress.load(std::sync::atomic::Ordering::SeqCst) { + guard.release().await; + return Ok(()); + } + let notices = store.run_notice_batch(&session_id)?; + if notices.is_empty() { + guard.release().await; + continue; + } + match send_run_notice_batch(chat, &session_id, ¬ices, guard).await { + Ok(TurnSubmission::Started(_) | TurnSubmission::Existing(_)) => { + if let Some(turn) = + store.get_chat_turn_by_client_id(&session_id, ¬ices[0].client_turn_id)? + { + if turn.delivery_state == "accepted" { + store.mark_run_notice_batch_delivered( + &session_id, + ¬ices[0].client_turn_id, + now_ms(), + )?; + } else if turn.state == "failed" && turn.delivery_state == "unknown" { + store.record_run_notice_failure( + &session_id, + ¬ices[0].client_turn_id, + turn.error_message + .as_deref() + .unwrap_or("Notice delivery could not be confirmed"), + true, + now_ms(), + )?; + } + } + } + Ok(_) => {} + Err(err) => { + let permanent = is_client_turn_conflict(&err) + || err.downcast_ref::().is_some(); + if store.record_run_notice_failure( + &session_id, + ¬ices[0].client_turn_id, + &err.to_string(), + permanent, + now_ms(), + )? == Some(1) + { + eprintln!( + "orx up: run notices: batch {}: {err}", + notices[0].client_turn_id + ); + } + } + } + } + Ok(()) +} + +pub async fn watch_run_notices( + chat: Arc, + mut runs: broadcast::Receiver, + data_dir_move_in_progress: Arc, + data_dir_gate: Arc>, +) { + let mut chats = chat.subscribe(); + let mut busy: HashSet = chat.busy_sessions().await.into_iter().collect(); + let mut sweep = tokio::time::interval(Duration::from_secs(60)); + loop { + tokio::select! { + event = runs.recv() => match event { + Ok(crate::engine::bus::RunEvent::Notices { .. }) + | Err(broadcast::error::RecvError::Lagged(_)) => {}, + Err(broadcast::error::RecvError::Closed) => return, + _ => continue, + }, + event = chats.recv() => match event { + Ok(("chat.busy", data)) => { + let Some(session_id) = data["sessionId"].as_str() else { continue }; + if data["busy"] == true { + busy.insert(session_id.to_string()); + continue; + } + if !busy.remove(session_id) { + continue; + } + }, + Err(broadcast::error::RecvError::Lagged(_)) => {}, + _ => continue, + }, + _ = sweep.tick() => {}, + } + if data_dir_move_in_progress.load(std::sync::atomic::Ordering::SeqCst) { + continue; + } + let _data_dir_guard = data_dir_gate.lock().await; + let Ok(store) = Store::open() else { continue }; + if let Err(err) = process_run_notices(&chat, store, &data_dir_move_in_progress).await { + eprintln!("orx up: run notices: {err}"); + } + } +} + +/// Renews chat-turn leases every 3 s and interrupts turns whose lease was lost. +pub async fn keep_turn_leases( chat: Arc, data_dir_move_in_progress: Arc, data_dir_gate: Arc>, @@ -8796,6 +9022,8 @@ pub async fn watch_runs( } } +// --- spawned agents ------------------------------------------------------------- + /// The PATH a child gets: this orx first, so an agent shelling out to `orx` /// reaches the running one. fn child_path() -> Option { @@ -10862,27 +11090,757 @@ mod run_wakeup_tests { (Store::open_at(dir.clone()).unwrap(), dir) } - #[test] - fn wakeup_messages_are_exact_and_exclude_cancellation() { - assert_eq!( - news::run_wakeup_text(&run("done")).as_deref(), - Some( - "[orx] Run `run_x` finished with status **done**. You can compare this result \ -with other project runs using `orx runs p1` and inspect the file located by `orx logs run_x`." + fn notice_host() -> Arc { + Arc::new(ChatHost::new( + Arc::new(crate::local::opencode::AgentHost::new(None)), + Arc::new(crate::local::codex::CodexHost::new()), + Arc::new(crate::local::claude::ClaudeHost::new()), + )) + } + + fn notice_harness(store: &Store) { + let launch = crate::local::acp::Definition { + id: "acp:00000000-0000-4000-8000-000000000001".into(), + name: "Outbox fixture".into(), + executable: std::env::current_exe() + .unwrap() + .to_string_lossy() + .into_owned(), + arguments: vec!["--list".into()], + }; + let tx = store.begin().unwrap(); + tx.execute("UPDATE chat_sessions SET harness = ?1", [&launch.id]) + .unwrap(); + tx.execute( + "INSERT OR IGNORE INTO acp_sessions (session_id, launch_json, configuration_json) + SELECT id, ?1, '[]' FROM chat_sessions", + [serde_json::to_string(&launch).unwrap()], + ) + .unwrap(); + tx.commit().unwrap(); + } + + #[tokio::test(flavor = "current_thread")] + async fn outbox_crash_retry_freezes_batches_and_coalesces_only_when_idle() { + const CHILD: &str = "ORX_TEST_CHAT_OUTBOX"; + if std::env::var_os(CHILD).is_none() { + let dir = std::env::temp_dir().join(format!("orx-outbox-{}", uuid::Uuid::new_v4())); + for phase in ["send", "restart"] { + let output = crate::process::command(std::env::current_exe().unwrap()) + .args([ + "--exact", + "local::chat::run_wakeup_tests::outbox_crash_retry_freezes_batches_and_coalesces_only_when_idle", + "--nocapture", + ]) + .env(CHILD, phase) + .env("ORX_DATA_DIR", &dir) + .env("ORX_NO_TELEMETRY", "1") + .output() + .unwrap(); + assert_eq!( + output.status.code(), + Some(if phase == "send" { 73 } else { 0 }), + "{}\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + } + let _ = std::fs::remove_dir_all(dir); + return; + } + let store = Store::open().unwrap(); + let moving = std::sync::atomic::AtomicBool::new(false); + let insert = |dedupe: &str, body: &str| { + store + .insert_run_notice("run_x", "owner", "terminal", dedupe, body, 1) + .unwrap(); + }; + let count_turns = || { + let tx = store.begin().unwrap(); + tx.query_row("SELECT COUNT(*) FROM chat_turns", [], |row| { + row.get::<_, i64>(0) + }) + .unwrap() + }; + + if std::env::var(CHILD).unwrap() == "send" { + store + .create_local_project(&crate::local::model::LocalProject { + id: "p1".into(), + name: "outbox".into(), + slug: "outbox".into(), + github_owner: String::new(), + github_repo: String::new(), + github_sync_enabled: false, + baseline_branch: "main".into(), + repo_path: std::env::var("ORX_DATA_DIR").unwrap(), + run_command: None, + paper_id: None, + created_at: 1, + updated_at: 1, + }) + .unwrap(); + session(&store, "owner"); + notice_harness(&store); + store.upsert_run(&run("done")).unwrap(); + let host = notice_host(); + host.turns + .lock() + .await + .insert("owner".into(), TurnState::Draining); + insert("one", "first completion"); + process_run_notices(&host, Store::open().unwrap(), &moving) + .await + .unwrap(); + insert("two", "second completion"); + process_run_notices(&host, Store::open().unwrap(), &moving) + .await + .unwrap(); + assert_eq!(count_turns(), 0); + let tx = store.begin().unwrap(); + let assigned: i64 = tx + .query_row( + "SELECT COUNT(*) FROM run_notices WHERE client_turn_id IS NOT NULL", + [], + |row| row.get(0), + ) + .unwrap(); + assert_eq!(assigned, 0); + tx.commit().unwrap(); + host.turns.lock().await.remove("owner"); + + let frozen = store.run_notice_batch("owner").unwrap(); + assert_eq!(frozen.len(), 2); + let guard = TurnGuard::claim_idle(&host, "owner").await.unwrap(); + let submitted = host + .send_message_showing("owner", run_notice_request(&frozen, guard)) + .await + .unwrap(); + assert!(matches!(submitted, TurnSubmission::Started(_))); + let first = store + .get_chat_turn_by_client_id("owner", &frozen[0].client_turn_id) + .unwrap() + .unwrap(); + assert!(first.user_message_id.is_none()); + assert!(first + .prepared_input + .contains("first completion\n\nsecond completion")); + assert_eq!(count_turns(), 1); + + std::process::exit(73); + } + let frozen = store.run_notice_batch("owner").unwrap(); + assert_eq!(frozen.len(), 2); + let first = store + .get_chat_turn_by_client_id("owner", &frozen[0].client_turn_id) + .unwrap() + .unwrap(); + let tx = store.begin().unwrap(); + tx.execute("DELETE FROM chat_turn_leases", []).unwrap(); + tx.commit().unwrap(); + store + .fail_chat_turn( + &first.id, + "not_sent", + "setup", + "harness unavailable", + Some("retry"), ) + .unwrap(); + insert("three", "later arrival"); + let restarted = notice_host(); + process_run_notices(&restarted, Store::open().unwrap(), &moving) + .await + .unwrap(); + assert_eq!(count_turns(), 1); + let retried = store + .get_chat_turn_by_client_id("owner", &frozen[0].client_turn_id) + .unwrap() + .unwrap(); + assert_eq!(retried.id, first.id); + assert_eq!(retried.client_turn_id, first.client_turn_id); + assert_eq!(retried.prepared_input, first.prepared_input); + let (failures, due): (i64, i64) = store + .begin() + .unwrap() + .query_row( + "SELECT delivery_failures, next_delivery_at FROM run_notices WHERE id = ?1", + [frozen[0].id], + |row| Ok((row.get(0)?, row.get(1)?)), + ) + .unwrap(); + assert_eq!(failures, 1); + assert!(due > now_ms()); + + assert_eq!( + store + .run_notice_batch_at("owner", now_ms() + 16 * 60 * 1000) + .unwrap(), + frozen ); + restarted.interrupt("owner").await.unwrap(); + let tx = store.begin().unwrap(); + tx.execute("UPDATE chat_turns SET state = 'failed', delivery_state = 'rejected', recovery_action = 'retry' WHERE id = ?1", [&first.id]).unwrap(); + tx.execute("DELETE FROM chat_turn_leases", []).unwrap(); + tx.execute("UPDATE run_notices SET next_delivery_at = 0", []) + .unwrap(); + tx.commit().unwrap(); + let restarted = notice_host(); + process_run_notices(&restarted, Store::open().unwrap(), &moving) + .await + .unwrap(); + assert_eq!(count_turns(), 1); assert_eq!( - news::run_wakeup_text(&run("failed")).as_deref(), - Some( - "[orx] Run `run_x` finished with status **failed**. You can compare this result \ -with other project runs using `orx runs p1` and inspect the file located by `orx logs run_x`." + store + .run_notice_batch_at("owner", now_ms() + 16 * 60 * 1000) + .unwrap(), + frozen + ); + restarted.interrupt("owner").await.unwrap(); + let tx = store.begin().unwrap(); + tx.execute( + "UPDATE chat_turns SET state = 'failed', delivery_state = 'unknown', error_message = 'Delivery could not be confirmed' WHERE id = ?1", + [&first.id], + ) + .unwrap(); + tx.execute("DELETE FROM chat_turn_leases", []).unwrap(); + tx.execute("UPDATE run_notices SET next_delivery_at = 0", []) + .unwrap(); + tx.commit().unwrap(); + let restarted = notice_host(); + process_run_notices(&restarted, Store::open().unwrap(), &moving) + .await + .unwrap(); + let retired: (Option, Option) = store + .begin() + .unwrap() + .query_row( + "SELECT delivered_at, retired_at FROM run_notices WHERE id = ?1", + [frozen[0].id], + |row| Ok((row.get(0)?, row.get(1)?)), ) + .unwrap(); + assert!(retired.0.is_none()); + assert!(retired.1.is_some()); + assert_eq!( + store.run_notice_error("run_x").unwrap().as_deref(), + Some("Delivery could not be confirmed") + ); + let next = store.run_notice_batch("owner").unwrap(); + assert_eq!(next.len(), 1); + assert_eq!(next[0].body, "later arrival"); + assert_ne!(next[0].client_turn_id, first.client_turn_id); + assert_eq!(count_turns(), 1); + moving.store(true, std::sync::atomic::Ordering::SeqCst); + process_run_notices(&restarted, Store::open().unwrap(), &moving) + .await + .unwrap(); + assert_eq!(count_turns(), 1); + store.delete_chat_session("owner").unwrap(); + assert!(store.run_notice_batch("owner").unwrap().is_empty()); + } + + async fn settle_run_notices( + chat: &Arc, + moving: &std::sync::atomic::AtomicBool, + ) -> Result<()> { + process_run_notices(chat, Store::open()?, moving).await?; + if !chat.busy_sessions().await.is_empty() { + tokio::time::timeout(Duration::from_secs(15), async { + while !chat.busy_sessions().await.is_empty() { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + process_run_notices(chat, Store::open()?, moving).await?; + } + Ok(()) + } + + #[tokio::test(flavor = "current_thread")] + async fn outbox_wakes_on_idle_and_bus_and_retires_or_retries_delivery_failures() { + const CHILD: &str = "ORX_TEST_OUTBOX_EVENTS"; + if std::env::var_os(CHILD).is_none() { + let dir = + std::env::temp_dir().join(format!("orx-outbox-events-{}", uuid::Uuid::new_v4())); + let output = crate::process::command(std::env::current_exe().unwrap()) + .args(["--exact", "local::chat::run_wakeup_tests::outbox_wakes_on_idle_and_bus_and_retires_or_retries_delivery_failures", "--nocapture"]) + .env(CHILD, "1").env("ORX_DATA_DIR", &dir).env("ORX_NO_TELEMETRY", "1") + .output().unwrap(); + assert!( + output.status.success(), + "{}\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!( + String::from_utf8_lossy(&output.stderr) + .matches("orx up: run notices: batch ") + .count(), + 4 + ); + let _ = std::fs::remove_dir_all(dir); + return; + } + let store = Store::open().unwrap(); + let repo = crate::store::data_dir().join("repo"); + std::fs::create_dir_all(&repo).unwrap(); + crate::local::git::initialize_own_repository(&repo).unwrap(); + store + .create_local_project(&crate::local::model::LocalProject { + id: "p1".into(), + name: "outbox".into(), + slug: "outbox".into(), + github_owner: String::new(), + github_repo: String::new(), + github_sync_enabled: false, + baseline_branch: "main".into(), + repo_path: repo.to_string_lossy().into_owned(), + run_command: None, + paper_id: None, + created_at: 1, + updated_at: 1, + }) + .unwrap(); + store.upsert_run(&run("done")).unwrap(); + let restarted = notice_host(); + let moving = std::sync::atomic::AtomicBool::new(false); + let count_turns = || { + store + .begin() + .unwrap() + .query_row("SELECT COUNT(*) FROM chat_turns", [], |row| { + row.get::<_, i64>(0) + }) + .unwrap() + }; + session(&store, "other"); + store + .insert_run_notice("run_x", "other", "terminal", "deleted", "drop me", 1) + .unwrap(); + let tx = store.begin().unwrap(); + tx.execute("DELETE FROM runs WHERE id = 'run_x'", []) + .unwrap(); + tx.commit().unwrap(); + assert!(store.run_notice_batch("other").unwrap().is_empty()); + settle_run_notices(&restarted, &moving).await.unwrap(); + + store.upsert_run(&run("done")).unwrap(); + notice_harness(&store); + let mut launch = store.acp_session_state("other").unwrap().unwrap().launch; + launch.executable = if cfg!(windows) { "python" } else { "python3" }.into(); + launch.arguments = vec![ + "-u".into(), + "-c".into(), + r#" +import json, os, sys +for line in sys.stdin: + request = json.loads(line) + method = request['method'] + if 'id' not in request: + continue + if method == 'initialize': + result = {'protocolVersion':1, 'agentCapabilities':{'loadSession':True}} + elif method == 'session/new': + result = {'sessionId':'outbox'} + elif method == 'session/load': + result = {} + elif method == 'session/prompt': + with open(os.environ['ORX_DATA_DIR'] + '/accepted-prompts', 'a') as log: + log.write('accepted\n') + result = {'stopReason':'end_turn'} + else: + result = {} + print(json.dumps({'jsonrpc':'2.0','id':request['id'],'result':result}), flush=True) +"# + .into(), + ]; + let tx = store.begin().unwrap(); + tx.execute( + "UPDATE acp_sessions SET launch_json = ?1 WHERE session_id = 'other'", + [serde_json::to_string(&launch).unwrap()], + ) + .unwrap(); + tx.commit().unwrap(); + restarted + .turns + .lock() + .await + .insert("other".into(), TurnState::Draining); + let bus = crate::engine::bus::Bus::new(); + let watcher = tokio::spawn(watch_run_notices( + restarted.clone(), + bus.subscribe(), + Arc::new(moving), + Arc::new(Mutex::new(())), + )); + tokio::task::yield_now().await; + let baseline = count_turns(); + store + .insert_run_notice("run_x", "other", "terminal", "idle-one", "idle first", 1) + .unwrap(); + bus.publish(crate::engine::bus::RunEvent::Notices { + chats: vec!["other".into()], + }); + tokio::task::yield_now().await; + assert_eq!(count_turns(), baseline); + store + .insert_run_notice("run_x", "other", "terminal", "idle-two", "idle second", 1) + .unwrap(); + restarted.turns.lock().await.remove("other"); + restarted.emit("chat.busy", json!({ "sessionId": "other", "busy": false })); + tokio::time::timeout(Duration::from_secs(15), async { + while count_turns() == baseline + || !store.pending_run_notice_sessions().unwrap().is_empty() + || !restarted.busy_sessions().await.is_empty() + { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + assert_eq!(count_turns(), baseline + 1); + assert!(store.run_notice_batch("other").unwrap().is_empty()); + restarted.interrupt("other").await.unwrap(); + store + .insert_run_notice("run_x", "other", "notify", "bus", "bus result", 1) + .unwrap(); + bus.publish(crate::engine::bus::RunEvent::Notices { + chats: vec!["other".into()], + }); + tokio::time::timeout(Duration::from_secs(15), async { + while count_turns() == baseline + 1 + || !store.pending_run_notice_sessions().unwrap().is_empty() + || !restarted.busy_sessions().await.is_empty() + { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + assert_eq!(count_turns(), baseline + 2); + assert_eq!( + std::fs::read_to_string(crate::store::data_dir().join("accepted-prompts")) + .unwrap() + .lines() + .count(), + 2 ); - assert!(news::run_wakeup_text(&run("cancelled")).is_none()); + assert!(store.run_notice_batch("other").unwrap().is_empty()); + restarted.interrupt("other").await.unwrap(); + watcher.abort(); + let _ = watcher.await; + + let (old_id, old_client): (i64, String) = store + .begin() + .unwrap() + .query_row( + "SELECT id, client_turn_id FROM run_notices ORDER BY id LIMIT 1", + [], + |row| Ok((row.get(0)?, row.get(1)?)), + ) + .unwrap(); + assert!(store + .get_chat_turn_by_client_id("other", &old_client) + .unwrap() + .is_some()); + let tx = store.begin().unwrap(); + tx.execute("DELETE FROM runs WHERE id = 'run_x'", []) + .unwrap(); + tx.commit().unwrap(); + store.upsert_run(&run("done")).unwrap(); + store + .insert_run_notice("run_x", "other", "terminal", "reused", "new run result", 1) + .unwrap(); + let reused = store.run_notice_batch("other").unwrap(); + assert_eq!(reused[0].id, old_id); + assert_ne!(reused[0].client_turn_id, old_client); + let before = count_turns(); + let moving = std::sync::atomic::AtomicBool::new(false); + settle_run_notices(&restarted, &moving).await.unwrap(); + assert_eq!(count_turns(), before + 1); + assert!(store.run_notice_batch("other").unwrap().is_empty()); + let delivered = store + .get_chat_turn_by_client_id("other", &reused[0].client_turn_id) + .unwrap() + .unwrap(); + assert!(delivered.prepared_input.contains("new run result")); + restarted.interrupt("other").await.unwrap(); + + store + .insert_run_notice("run_x", "other", "notify", "conflict", "blocked", 1) + .unwrap(); + let blocked = store.run_notice_batch("other").unwrap(); + let mut conflict = delivered; + conflict.id = "conflicting-turn".into(); + conflict.assistant_message_id = "conflicting-message".into(); + conflict.client_turn_id = blocked[0].client_turn_id.clone(); + conflict.request_hash = "different payload".into(); + assert!(matches!( + store.admit_chat_turn(None, &conflict).unwrap(), + ChatTurnAdmission::Inserted + )); + store + .insert_run_notice("run_x", "other", "notify", "after-conflict", "unblocked", 2) + .unwrap(); + settle_run_notices(&restarted, &moving).await.unwrap(); + tokio::task::yield_now().await; + let retirement: (i64, String, i64) = store.begin().unwrap().query_row( + "SELECT delivery_failures, delivery_error, retired_at FROM run_notices WHERE client_turn_id = ?1", + [&blocked[0].client_turn_id], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)), + ).unwrap(); + assert_eq!(retirement.0, 1); + assert!(retirement.1.contains("clientTurnId was already used")); + assert!(retirement.2 > 0); + let later = store.run_notice_batch("other").unwrap(); + assert_eq!(later.len(), 1); + assert_eq!(later[0].body, "unblocked"); + settle_run_notices(&restarted, &moving).await.unwrap(); + assert!(store.pending_run_notice_sessions().unwrap().is_empty()); + assert!(store + .get_chat_turn_by_client_id("other", &later[0].client_turn_id) + .unwrap() + .is_some()); + restarted.interrupt("other").await.unwrap(); + + let tx = store.begin().unwrap(); + tx.execute( + "UPDATE chat_sessions SET harness = 'removed-harness' WHERE id = 'other'", + [], + ) + .unwrap(); + tx.commit().unwrap(); + store + .insert_run_notice( + "run_x", + "other", + "notify", + "removed-harness", + "not delivered", + 3, + ) + .unwrap(); + let removed = store.run_notice_batch("other").unwrap(); + settle_run_notices(&restarted, &moving).await.unwrap(); + tokio::task::yield_now().await; + let reason: String = store + .begin() + .unwrap() + .query_row( + "SELECT delivery_error FROM run_notices WHERE id = ?1 AND retired_at IS NOT NULL", + [removed[0].id], + |row| row.get(0), + ) + .unwrap(); + assert_eq!(reason, "Chat harness is no longer configured"); + notice_harness(&store); + let saved = store.acp_session_state("other").unwrap().unwrap(); + let mut absent = saved.launch.clone(); + absent.executable = crate::store::data_dir() + .join("missing-harness") + .to_string_lossy() + .into_owned(); + let tx = store.begin().unwrap(); + tx.execute( + "UPDATE acp_sessions SET launch_json = ?1 WHERE session_id = 'other'", + [serde_json::to_string(&absent).unwrap()], + ) + .unwrap(); + tx.commit().unwrap(); + store + .insert_run_notice( + "run_x", + "other", + "notify", + "uninstalled", + "missing binary", + 3, + ) + .unwrap(); + let uninstalled = store.run_notice_batch("other").unwrap(); + settle_run_notices(&restarted, &moving).await.unwrap(); + tokio::task::yield_now().await; + let reason: String = store + .begin() + .unwrap() + .query_row( + "SELECT delivery_error FROM run_notices WHERE id = ?1 AND retired_at IS NOT NULL", + [uninstalled[0].id], + |row| row.get(0), + ) + .unwrap(); + assert_eq!(reason, "Chat harness is no longer installed"); + let tx = store.begin().unwrap(); + tx.execute( + "UPDATE acp_sessions SET launch_json = ?1 WHERE session_id = 'other'", + [serde_json::to_string(&saved.launch).unwrap()], + ) + .unwrap(); + tx.commit().unwrap(); + + store + .insert_run_notice( + "run_x", + "other", + "notify", + "temporary", + "retry this result", + 4, + ) + .unwrap(); + let retry = store.run_notice_batch("other").unwrap(); + let tx = store.begin().unwrap(); + tx.execute( + "UPDATE chat_sessions SET project_id = 'temporarily-unavailable' WHERE id = 'other'", + [], + ) + .unwrap(); + tx.commit().unwrap(); + settle_run_notices(&restarted, &moving).await.unwrap(); + tokio::task::yield_now().await; + assert!(store.run_notice_batch("other").unwrap().is_empty()); + let tx = store.begin().unwrap(); + tx.execute( + "UPDATE chat_sessions SET project_id = 'p1' WHERE id = 'other'", + [], + ) + .unwrap(); + tx.commit().unwrap(); + store + .insert_run_notice( + "run_x", + "other", + "notify", + "overtake", + "deliver during backoff", + 5, + ) + .unwrap(); + let overtaking = store.run_notice_batch("other").unwrap(); + assert_eq!(overtaking.len(), 1); + assert_eq!(overtaking[0].body, "deliver during backoff"); + let before = count_turns(); + settle_run_notices(&restarted, &moving).await.unwrap(); + assert_eq!(count_turns(), before + 1); + restarted.interrupt("other").await.unwrap(); + let tx = store.begin().unwrap(); + tx.execute( + "UPDATE run_notices SET next_delivery_at = ?1 WHERE client_turn_id = ?2", + rusqlite::params![now_ms() - 1, retry[0].client_turn_id], + ) + .unwrap(); + tx.commit().unwrap(); + let host = notice_host(); + settle_run_notices(&host, &moving).await.unwrap(); + assert_eq!(count_turns(), before + 2); + host.interrupt("other").await.unwrap(); + settle_run_notices(&host, &moving).await.unwrap(); + assert_eq!(count_turns(), before + 2); + assert!(store + .get_chat_turn_by_client_id("other", &retry[0].client_turn_id) + .unwrap() + .is_some()); + assert!(store.pending_run_notice_sessions().unwrap().is_empty()); assert_eq!( - news::run_wakeup_text(&run("lost")).as_deref(), - Some("[orx] Run `run_x` ended with **Outcome unavailable**. Its final outcome could not be collected. Inspect any partial logs using `orx logs run_x`; do not assume success or failure.") + std::fs::read_to_string(crate::store::data_dir().join("accepted-prompts")) + .unwrap() + .lines() + .count(), + 6 ); + for kind in ["engine", "ssh_job"] { + let delegate = format!("delegate-{kind}"); + let answer = format!("delegate answer exactly once for {kind}"); + let result = format!("run result exactly once for {kind}"); + session(&store, &delegate); + store + .record_chat_delegate(&delegate, "other", false) + .unwrap(); + store.subscribe_chat("other", &delegate, None).unwrap(); + let mut run = run("done"); + run.id = format!("run-{kind}"); + run.backend_json = json!({"kind":kind}).to_string(); + store.upsert_run(&run).unwrap(); + let turn = crate::store::StoredChatTurn { + id: format!("turn-{kind}"), + session_id: delegate.clone(), + user_message_id: None, + assistant_message_id: format!("answer-{kind}"), + client_turn_id: format!("client-{kind}"), + request_hash: "task".into(), + prepared_input: "task".into(), + settings_json: "{}".into(), + state: "preparing".into(), + delivery_state: "not_sent".into(), + attempt_count: 0, + next_retry_at: None, + error_kind: None, + error_message: None, + recovery_action: None, + recovered_by_turn_id: None, + created_at: now_ms(), + updated_at: now_ms(), + }; + store.admit_chat_turn(None, &turn).unwrap(); + store + .upsert_chat_message(&StoredChatMessage { + id: turn.assistant_message_id.clone(), + session_id: delegate, + role: "assistant".into(), + parts_json: serde_json::to_string(&[WirePart::text("answer", &answer)]) + .unwrap(), + created_at: now_ms(), + completed_at: Some(now_ms()), + parent_id: None, + base_native_session_id: None, + result_native_session_id: None, + }) + .unwrap(); + store.complete_chat_turn(&turn.id).unwrap(); + let tx = store.begin().unwrap(); + tx.execute( + "INSERT INTO chat_run_wakeups (run_id, chat_session_id, requested_at, state) VALUES (?1, 'other', 1, 'pending')", + [&run.id], + ).unwrap(); + tx.commit().unwrap(); + store + .insert_run_notice(&run.id, "other", "terminal", "terminal", &result, now_ms()) + .unwrap(); + assert_eq!(news::chat_news(&store, Some("other")).unwrap().len(), 1); + assert_eq!(store.pending_run_notice_sessions().unwrap(), ["other"]); + let before = count_turns(); + for _ in 0..3 { + news::deliver_news(&host, Store::open().unwrap(), None) + .await + .unwrap(); + settle_run_notices(&host, &moving).await.unwrap(); + } + assert_eq!(count_turns(), before + 2); + assert!(news::chat_news(&store, Some("other")).unwrap().is_empty()); + assert!(store.pending_run_notice_sessions().unwrap().is_empty()); + let tx = store.begin().unwrap(); + let mut statement = tx.prepare("SELECT prepared_input, user_message_id FROM chat_turns WHERE session_id = 'other'").unwrap(); + let turns = statement + .query_map([], |row| { + Ok((row.get::<_, String>(0)?, row.get::<_, Option>(1)?)) + }) + .unwrap() + .collect::, _>>() + .unwrap(); + let results: Vec<_> = turns + .iter() + .filter(|(input, _)| input.contains(&result)) + .collect(); + let answers: Vec<_> = turns + .iter() + .filter(|(input, _)| input.contains(&answer)) + .collect(); + assert_eq!(results.len(), 1); + assert!(results[0].1.is_none()); + assert_eq!(answers.len(), 1); + assert!(answers[0].1.is_some()); + } } #[test] @@ -10921,37 +11879,6 @@ with other project runs using `orx runs p1` and inspect the file located by `orx ); } - #[test] - fn each_run_that_ended_is_its_own_message() { - let (store, dir) = temp_store("batched"); - let mut second = run("failed"); - second.id = "run_y".into(); - let news: Vec = [run("done"), second] - .into_iter() - .map(|run| { - news::News::Run(Box::new(crate::store::RunWakeup { - run, - chat_session_id: "owner".into(), - state: "pending".into(), - monitoring_alerted: false, - })) - }) - .collect(); - let messages = news::messages(&store, &news).unwrap(); - assert_eq!(messages.len(), 2); - assert!(messages[0] - .0 - .starts_with("[orx] Run `run_x` finished with status **done**")); - assert!(messages[1] - .0 - .starts_with("[orx] Run `run_y` finished with status **failed**")); - let status = |i: usize| messages[i].1.source.status.as_deref(); - assert_eq!((status(0), status(1)), (Some("done"), Some("failed"))); - assert_eq!(messages[1].1.source.from.as_deref(), Some("run_y")); - drop(store); - let _ = std::fs::remove_dir_all(dir); - } - #[test] fn delivery_certainty_never_replays_accepted_or_unknown_turns() { assert_eq!(DeliveryState::NotSent.recovery_action(), "retry"); @@ -11044,165 +11971,6 @@ with other project runs using `orx runs p1` and inspect the file located by `orx message.dispatch_error = None; assert!(reset_exhausted_queued_message(&message).is_none()); } - - #[tokio::test] - async fn terminal_run_without_subscription_starts_no_turn() { - let (store, dir) = temp_store("unsubscribed"); - session(&store, "owner"); - store.upsert_run(&run("done")).unwrap(); - let host = Arc::new(ChatHost::new( - Arc::new(crate::local::opencode::AgentHost::new(None)), - Arc::new(crate::local::codex::CodexHost::new()), - Arc::new(crate::local::claude::ClaudeHost::new()), - )); - - drop(store); - news::deliver_news(&host, Store::open_at(dir.clone()).unwrap(), None) - .await - .unwrap(); - - assert!(!host.is_busy("owner").await); - let _ = std::fs::remove_dir_all(dir); - } - - #[tokio::test] - async fn data_directory_move_keeps_wakeup_pending() { - let (store, dir) = temp_store("moving"); - session(&store, "owner"); - store.upsert_run(&run("done")).unwrap(); - store.register_run_wakeup("run_x", "owner").unwrap(); - let host = Arc::new(ChatHost::new( - Arc::new(crate::local::opencode::AgentHost::new(None)), - Arc::new(crate::local::codex::CodexHost::new()), - Arc::new(crate::local::claude::ClaudeHost::new()), - )); - let moving = std::sync::atomic::AtomicBool::new(true); - - drop(store); - news::deliver_news(&host, Store::open_at(dir.clone()).unwrap(), Some(&moving)) - .await - .unwrap(); - - let store = Store::open_at(dir.clone()).unwrap(); - assert_eq!(store.list_ready_run_wakeups().unwrap().len(), 1); - assert!(!host.is_busy("owner").await); - drop(store); - let _ = std::fs::remove_dir_all(dir); - } - - #[tokio::test] - async fn draining_user_messages_keep_wakeup_pending() { - let (store, dir) = temp_store("draining"); - session(&store, "owner"); - store.upsert_run(&run("done")).unwrap(); - store.register_run_wakeup("run_x", "owner").unwrap(); - let host = Arc::new(ChatHost::new( - Arc::new(crate::local::opencode::AgentHost::new(None)), - Arc::new(crate::local::codex::CodexHost::new()), - Arc::new(crate::local::claude::ClaudeHost::new()), - )); - host.turns - .lock() - .await - .insert("owner".into(), TurnState::Draining); - - drop(store); - news::deliver_news(&host, Store::open_at(dir.clone()).unwrap(), None) - .await - .unwrap(); - - let store = Store::open_at(dir.clone()).unwrap(); - assert_eq!(store.list_ready_run_wakeups().unwrap().len(), 1); - drop(store); - let _ = std::fs::remove_dir_all(dir); - } - - fn unmonitored_run() -> StoredRun { - StoredRun { - backend_json: - r#"{"kind":"slurm_job","monitoringError":"Monitoring unavailable: ssh failed."}"# - .into(), - ..run("starting") - } - } - - #[test] - fn monitoring_message_names_runs_without_remote_text() { - let first = StoredRun { - backend_json: r#"{"kind":"slurm_job","monitoringError":"REMOTE_SENTINEL"}"#.into(), - ..run("starting") - }; - let mut second = run("running"); - second.id = "run_y".into(); - let text = news::run_monitoring_text(&[first, second]); - assert!(!text.contains("REMOTE_SENTINEL")); - assert_eq!( - text, - "[orx] orx can no longer monitor these live runs:\n\ -- run `run_x` of experiment `exp_1` (still **starting**)\n\ -- run `run_y` of experiment `exp_1` (still **running**)\n\ -Run `orx exp status ` for the reason and tell the user so they can fix it. orx wakes you \ -once it can see a run finish; until then each run keeps its current status." - ); - } - - #[tokio::test] - async fn busy_session_leaves_monitoring_alert_unclaimed() { - let (store, dir) = temp_store("alert-busy"); - session(&store, "owner"); - store.upsert_run(&unmonitored_run()).unwrap(); - store.register_run_wakeup("run_x", "owner").unwrap(); - let host = Arc::new(ChatHost::new( - Arc::new(crate::local::opencode::AgentHost::new(None)), - Arc::new(crate::local::codex::CodexHost::new()), - Arc::new(crate::local::claude::ClaudeHost::new()), - )); - host.turns - .lock() - .await - .insert("owner".into(), TurnState::Draining); - - drop(store); - news::deliver_news(&host, Store::open_at(dir.clone()).unwrap(), None) - .await - .unwrap(); - - let store = Store::open_at(dir.clone()).unwrap(); - assert!(!store.list_active_run_wakeups().unwrap()[0].monitoring_alerted); - assert!(matches!( - host.turns.lock().await.get("owner"), - Some(TurnState::Draining) - )); - drop(store); - let _ = std::fs::remove_dir_all(dir); - } - - #[tokio::test] - async fn restored_monitoring_rearms_the_alert() { - let (store, dir) = temp_store("alert-restored"); - session(&store, "owner"); - store.upsert_run(&run("running")).unwrap(); - store.register_run_wakeup("run_x", "owner").unwrap(); - store - .set_run_wakeup_monitoring_alerted("run_x", "owner", true) - .unwrap(); - let host = Arc::new(ChatHost::new( - Arc::new(crate::local::opencode::AgentHost::new(None)), - Arc::new(crate::local::codex::CodexHost::new()), - Arc::new(crate::local::claude::ClaudeHost::new()), - )); - - drop(store); - news::deliver_news(&host, Store::open_at(dir.clone()).unwrap(), None) - .await - .unwrap(); - - let store = Store::open_at(dir.clone()).unwrap(); - assert!(!store.list_active_run_wakeups().unwrap()[0].monitoring_alerted); - assert!(!host.is_busy("owner").await); - drop(store); - let _ = std::fs::remove_dir_all(dir); - } } #[cfg(test)] diff --git a/src/local/chat/news.rs b/src/local/chat/news.rs index 0b8960ecf..51f4855b0 100644 --- a/src/local/chat/news.rs +++ b/src/local/chat/news.rs @@ -1,6 +1,5 @@ //! What a chat has not been told yet: a finished turn or a question from a -//! chat it subscribes to, and the end of a run it asked to be woken for. Each -//! idle chat's next turn starts with all of its news at once, unless the agent +//! chat it subscribes to. Each idle chat's next turn starts with all of its news at once, unless the agent //! collected chat news first with `wait`. use std::collections::BTreeMap; @@ -15,8 +14,8 @@ use super::{ stored_to_wire, ChatHost, OrxDisplay, OrxKind, OrxSource, TurnGuard, TurnSubmission, ORX_MESSAGE_PREFIX, }; -use crate::error::{bail, Result}; -use crate::store::{ReadyChatSubscription, RunWakeup, Store, StoredRun, ToldEvent}; +use crate::error::Result; +use crate::store::{ReadyChatSubscription, Store, ToldEvent}; /// How much of a message the user wrote in a subscribed chat its news quotes. const USER_PREVIEW_CHARS: usize = 300; @@ -28,10 +27,6 @@ pub enum News { target: String, prompt: Box, }, - /// A run the chat asked to be woken for ended. - Run(Box), - /// orx lost sight of a run the chat waits on; told once per outage. - Unmonitored(Box), } impl News { @@ -39,16 +34,14 @@ impl News { match self { News::Answer(ready) => &ready.subscriber_session_id, News::Question { subscriber, .. } => subscriber, - News::Run(wakeup) | News::Unmonitored(wakeup) => &wakeup.chat_session_id, } } - /// The chat or run the news is about. + /// The chat the news is about. pub fn target(&self) -> &str { match self { News::Answer(ready) => &ready.target_session_id, News::Question { target, .. } => target, - News::Run(wakeup) | News::Unmonitored(wakeup) => &wakeup.run.id, } } @@ -66,10 +59,6 @@ impl News { self.target(), ToldEvent::Prompt(&prompt.id), ), - News::Run(wakeup) => store.claim_run_wakeup(&wakeup.run.id, &wakeup.chat_session_id), - News::Unmonitored(wakeup) => Ok(store - .set_run_wakeup_monitoring_alerted(&wakeup.run.id, &wakeup.chat_session_id, true)? - .then(String::new)), } } @@ -87,26 +76,6 @@ impl News { let told = told.then_some(event); store.settle_chat_subscription(self.subscriber(), self.target(), token, told)?; } - News::Run(wakeup) if told => { - if !store.mark_run_wakeup_delivered( - &wakeup.run.id, - &wakeup.chat_session_id, - token, - )? { - bail!("run wake-up claim expired before delivery was recorded"); - } - } - News::Run(wakeup) => { - store.release_run_wakeup(&wakeup.run.id, &wakeup.chat_session_id, token)? - } - News::Unmonitored(_) if told => {} - News::Unmonitored(wakeup) => { - store.set_run_wakeup_monitoring_alerted( - &wakeup.run.id, - &wakeup.chat_session_id, - false, - )?; - } } Ok(()) } @@ -186,40 +155,13 @@ fn echoes_its_subscriber(store: &Store, ready: &ReadyChatSubscription) -> Result })) } -/// Runs that ended, and runs orx can no longer see, for the chats waiting on -/// them. A run that is seen again re-arms its outage alert. -fn run_news(store: &Store) -> Result> { - store.prune_run_wakeups()?; - let mut news: Vec = store - .list_ready_run_wakeups()? - .into_iter() - .filter(|wakeup| wakeup.state == "pending" && run_wakeup_text(&wakeup.run).is_some()) - .map(|wakeup| News::Run(Box::new(wakeup))) - .collect(); - for wakeup in store.list_active_run_wakeups()? { - let unmonitored = crate::jobs::BackendDescriptor::parse(&wakeup.run.backend_json) - .is_ok_and(|descriptor| descriptor.monitoring_error.is_some()); - if unmonitored && !wakeup.monitoring_alerted { - news.push(News::Unmonitored(Box::new(wakeup))); - } else if !unmonitored && wakeup.monitoring_alerted { - store.set_run_wakeup_monitoring_alerted( - &wakeup.run.id, - &wakeup.chat_session_id, - false, - )?; - } - } - Ok(news) -} - /// What a chat is told about its news, each piece as its agent reads it and -/// as the transcript shows it, with one for every run orx lost sight of. +/// as the transcript shows it. pub fn messages<'a>( store: &Store, news: impl IntoIterator, ) -> Result> { let mut messages = Vec::new(); - let mut unmonitored = Vec::new(); for item in news { let model = || -> Result { Ok(store @@ -236,30 +178,8 @@ pub fn messages<'a>( }, )), News::Answer(ready) => messages.push(answer_text(store, ready, &model()?)?), - News::Run(wakeup) => messages.extend(run_wakeup_text(&wakeup.run).map(|text| { - let shown = text.trim_start_matches(ORX_MESSAGE_PREFIX).to_string(); - let run = &wakeup.run; - let source = source(OrxKind::Run, Some(&run.id), Some(&run.status)); - ( - text, - OrxDisplay { - text: shown, - source, - }, - ) - })), - News::Unmonitored(wakeup) => unmonitored.push(wakeup.run.clone()), } } - if !unmonitored.is_empty() { - messages.push(( - run_monitoring_text(&unmonitored), - OrxDisplay { - text: monitoring_lines(&unmonitored), - source: source(OrxKind::Monitoring, None, None), - }, - )); - } Ok(messages) } @@ -350,46 +270,6 @@ fn answer_text( Ok((text.trim_end().to_string(), shown)) } -pub(super) fn run_wakeup_text(run: &StoredRun) -> Option { - if run.status == "lost" { - return Some(format!( - "{ORX_MESSAGE_PREFIX}Run `{}` ended with **Outcome unavailable**. Its final outcome could not be \ - collected. Inspect any partial logs using `orx logs {}`; do not assume success or failure.", - run.id, run.id - )); - } - matches!(run.status.as_str(), "done" | "failed").then(|| { - format!( - "{ORX_MESSAGE_PREFIX}Run `{}` finished with status **{}**. You can compare this result with other \ - project runs using `orx runs {}` and inspect the file located by `orx logs {}`.", - run.id, run.status, run.project_id, run.id - ) - }) -} - -// Only local identifiers here: the error text includes remote ssh stderr, so the agent reads it -// as command output instead of inside an orx message. -pub(super) fn run_monitoring_text(runs: &[StoredRun]) -> String { - let lines = monitoring_lines(runs); - format!( - "{ORX_MESSAGE_PREFIX}orx can no longer monitor these live runs:\n{lines}\nRun `orx exp status ` \ - for the reason and tell the user so they can fix it. orx wakes you once it can see a run \ - finish; until then each run keeps its current status." - ) -} - -fn monitoring_lines(runs: &[StoredRun]) -> String { - runs.iter() - .map(|run| { - format!( - "- run `{}` of experiment `{}` (still **{}**)", - run.id, run.experiment_id, run.status - ) - }) - .collect::>() - .join("\n") -} - /// Record `target`'s latest turn as told to `subscriber`, as when it stops /// the target itself: the stop is no news to it. pub fn mark_told(store: &Store, subscriber: &str, target: &str) -> Result<()> { @@ -416,10 +296,7 @@ pub(super) async fn deliver_news( return Ok(()); } let mut by_chat: BTreeMap> = BTreeMap::new(); - for item in run_news(&store)? - .into_iter() - .chain(chat_news(&store, None)?) - { + for item in chat_news(&store, None)? { // A turn's end races the host's own bookkeeping; tell it once quiet. if matches!(item, News::Answer(_)) && chat.is_busy(item.target()).await { continue; diff --git a/src/local/experiments.rs b/src/local/experiments.rs index e4c70beb2..e11254068 100644 --- a/src/local/experiments.rs +++ b/src/local/experiments.rs @@ -667,6 +667,16 @@ mod tests { }) .unwrap(); + store + .set_run_contact( + &run_id, + &crate::store::Contact::NeedsAuth { + since: 1, + cause: "host gone".into(), + }, + ) + .unwrap(); + assert!(delete_experiment(&store, "root") .err() .unwrap() diff --git a/src/local/hf.rs b/src/local/hf.rs index c913de4a1..7ad39b8c1 100644 --- a/src/local/hf.rs +++ b/src/local/hf.rs @@ -1,6 +1,4 @@ -//! Local HF Jobs launch — mirrors `commands/exp.rs::launch_hf` with the api -//! calls deleted: the run row comes from and goes to the local store only. -//! The detached `orx supervise` it spawns detects local runs itself. +//! Hugging Face Jobs launch intents. The engine adds the job's tokens as secrets at launch. use std::collections::HashMap; @@ -9,33 +7,51 @@ use crate::compute::SourceSnapshot; use crate::error::{anyhow, Result}; use crate::jobs::{huggingface as hf, BackendDescriptor}; use crate::local::trackio; -use crate::store::{now_ms, Store, StoredRun}; +use crate::store::{now_ms, LaunchSpec, Store, StoredRun}; -/// CLI wrapper around `submit_local_hf`: submit, then print the summary. -pub async fn launch_local_hf(args: &crate::ExpRunArgs) -> Result<()> { - let run = submit_local_hf(args).await?; - let backend = crate::jobs::BackendDescriptor::parse(&run.backend_json)?; - println!("\u{2713} Hugging Face job submitted."); - println!(" run {}", run.id); - println!( - " job {}/{} ({})", - backend.namespace.as_deref().unwrap_or(""), - backend.job_id.as_deref().unwrap_or(""), - backend.flavor.as_deref().unwrap_or("") - ); - println!(" watch {}", backend.url.as_deref().unwrap_or("")); - println!( - "{}", - crate::invocation::follow_up(&run.experiment_id, &run.id) - ); - Ok(()) -} - -/// Submit the local experiment's run as a Hugging Face Job and detach a -/// supervisor. `args.exp_id` must exist in `local_experiments`; requires -/// `--backend hf` and `--flavor`. Shared by the CLI and the `orx up` API. -pub async fn submit_local_hf(args: &crate::ExpRunArgs) -> Result { - crate::compute::submit(args).await +/// Requires `--flavor`; the namespace is the token's account. +pub async fn launch_spec( + args: &crate::ExpRunArgs, + _source: &SourceSnapshot, + run_id: &str, + command: &str, +) -> Result { + let flavor = args.flavor.clone().ok_or_else(|| { + anyhow!( + "--backend hf requires --flavor: t4-small, a10g-small/large, l4x1, \ + l40sx1, a100-large, h200, … (cpu-basic/cpu-upgrade for CPU). \ + Priced per minute on your Hugging Face account." + ) + })?; + // HF's own 30m default is a footgun. + let timeout_seconds = match &args.timeout { + Some(t) => hf::parse_timeout(t)?, + None => 4 * 3600, + }; + let namespace = hf::whoami(&hf::resolve_token()?).await?; + let image = args + .image + .clone() + .unwrap_or_else(|| default_hf_image(&flavor)); + let labels = super::run_labels(&args.exp_id, run_id)?; + let submission = hf::JobSubmission { + command: vec![ + "bash".to_string(), + "-c".to_string(), + crate::compute::snapshot_script("/orx-source/source.tar", command), + ], + docker_image: image, + flavor, + environment: HashMap::new(), + secrets: HashMap::new(), + timeout_seconds, + labels, + }; + Ok(LaunchSpec { + kind: "hf_job".into(), + target: Some(namespace), + options: serde_json::to_value(submission)?, + }) } pub async fn submit_local_hf_with_source( @@ -115,6 +131,7 @@ pub async fn submit_local_hf_with_source( }, &source.path, &source.digest, + None, ) .await?; @@ -128,7 +145,7 @@ pub async fn submit_local_hf_with_source( job_id: Some(job.id.clone()), flavor: Some(flavor.clone()), image: Some(image), - url: Some(hf::job_url(&namespace, &job.id)), + url: Some(format!("{}/jobs/{namespace}/{}", hf::endpoint(), job.id)), context: None, manifest: None, resources: None, diff --git a/src/local/k8s.rs b/src/local/k8s.rs index 5cf715a9e..32b4ad11d 100644 --- a/src/local/k8s.rs +++ b/src/local/k8s.rs @@ -1,7 +1,5 @@ -//! Local Kubernetes launch — the k8s twin of `local/hf.rs`: the run row comes -//! from and goes to the local store only, and the detached `orx supervise` -//! watches the Job via kubectl. Cluster/namespace come from the settings file -//! (`orx up` Settings → Compute, or `~/.config/openresearch/k8s.json`). +//! Kubernetes launch intents. Cluster/namespace come from the settings file (`orx up` +//! Settings → Compute, or `~/.config/openresearch/k8s.json`). //! //! There are no flavors: the run's shape is a **manifest committed on the //! experiment branch** (default `.orx/k8s.yaml`, or `--manifest `), @@ -16,40 +14,84 @@ use crate::compute::SourceSnapshot; use crate::error::{anyhow, Result}; use crate::jobs::{huggingface as hf, kubernetes as k8s, BackendDescriptor}; use crate::local::git; -use crate::store::{now_ms, Store, StoredRun}; +use crate::store::{now_ms, LaunchSpec, Store, StoredRun}; /// Manifest path on the experiment branch when `--manifest` is omitted. const DEFAULT_MANIFEST: &str = ".orx/k8s.yaml"; -/// CLI wrapper around `submit_local_k8s`: submit, then print the summary. -pub async fn launch_local_k8s(args: &crate::ExpRunArgs) -> Result<()> { - let run = submit_local_k8s(args).await?; - let backend = BackendDescriptor::parse(&run.backend_json)?; - println!("\u{2713} Kubernetes resources created."); - println!( - " job {}/{}", - backend.namespace.as_deref().unwrap_or(""), - backend.job_id.as_deref().unwrap_or("") - ); - println!( - " manifest {}", - backend.manifest.as_deref().unwrap_or(DEFAULT_MANIFEST) - ); - if let Some(resources) = backend.resources.as_deref().filter(|r| r.len() > 1) { - println!(" created {}", resources.join(", ")); +pub async fn launch_spec( + args: &crate::ExpRunArgs, + source: &SourceSnapshot, + run_id: &str, + command: &str, +) -> Result { + if args.flavor.is_some() { + return Err(anyhow!( + "--backend k8s has no flavors — the manifest on the experiment branch \ + (default {DEFAULT_MANIFEST}, or --manifest ) declares the resources." + )); } - println!(" run {}", run.id); - println!( - "{} (the log follows the primary Job's leader pod).", - crate::invocation::follow_up(&run.experiment_id, &run.id).trim_end_matches('.') - ); - Ok(()) -} - -/// Submit the local experiment's run from its committed manifest and detach a -/// supervisor. -pub async fn submit_local_k8s(args: &crate::ExpRunArgs) -> Result { - crate::compute::submit(args).await + if args.image.is_some() { + return Err(anyhow!( + "--image doesn't apply to --backend k8s — set the image in the manifest." + )); + } + let settings = k8s::load_settings()?.unwrap_or_default(); + let manifest_path = args + .manifest + .clone() + .unwrap_or_else(|| DEFAULT_MANIFEST.to_string()); + // Same default as the HF path — no-timeout jobs are a footgun. The + // manifest's own activeDeadlineSeconds wins when set. + let timeout_seconds = match &args.timeout { + Some(t) => hf::parse_timeout(t)?, + None => 4 * 3600, + }; + let store = Store::open()?; + let experiment = store + .get_local_experiment(&args.exp_id)? + .ok_or_else(|| anyhow!("Local experiment {} not found.", args.exp_id))?; + let project = store + .get_local_project(&experiment.project_id)? + .ok_or_else(|| anyhow!("Local project {} not found.", experiment.project_id))?; + let manifest = { + let repo_path = project.repo_path.clone(); + let revision = source.revision.clone(); + let path = manifest_path.clone(); + tokio::task::spawn_blocking(move || -> Result { + git::file_at(std::path::Path::new(&repo_path), &revision, &path).map_err(|_| { + anyhow!( + "No manifest at '{path}' in committed revision {revision} — write one \ + and commit it before running. Pass --manifest if it lives elsewhere." + ) + }) + }) + .await + .map_err(|e| anyhow!("git task failed: {e}"))?? + }; + // DNS-safe, run-unique token for {{ORX_RUN}} in resource names. + let run_token = run_id + .chars() + .filter(|c| c.is_ascii_hexdigit()) + .take(10) + .collect::(); + let spec = k8s::ManifestSpec { + manifest, + script: crate::compute::gated_script("/tmp/orx-source/source.tar", command), + run_token, + env: HashMap::new(), + timeout_seconds, + labels: super::run_labels(&args.exp_id, run_id)?, + pod_env: Vec::new(), + source_archive: source.path.clone(), + }; + let mut options = serde_json::to_value(spec)?; + options["context"] = serde_json::json!(settings.context); + Ok(LaunchSpec { + kind: "k8s_job".into(), + target: Some(settings.namespace), + options, + }) } pub async fn submit_local_k8s_with_source( @@ -147,6 +189,7 @@ pub async fn submit_local_k8s_with_source( pod_env: crate::config::run_context_env(&run_id), source_archive: source.path.clone(), }, + None, ) .await?; diff --git a/src/local/localrun.rs b/src/local/localrun.rs index aa47c295b..e03578889 100644 --- a/src/local/localrun.rs +++ b/src/local/localrun.rs @@ -1,8 +1,6 @@ -//! Local launch — the on-this-machine twin of `local/ssh.rs`: run the -//! experiment as a detached process on the machine running orx. Same snapshot -//! contract as every backend — the run extracts the recorded revision into -//! its own run dir, never the agent's worktree. The run row lives in the -//! local store only; a detached `orx supervise` watches the process. +//! Launch intents for runs on this machine: `local`, and `tinker` (a local controller using +//! remote Tinker model compute). Each run extracts the recorded revision into its own run +//! dir, never the agent's worktree. use std::collections::HashMap; @@ -10,25 +8,23 @@ use crate::commands::exp::spawn_detached_supervise; use crate::compute::SourceSnapshot; use crate::error::{anyhow, Result}; use crate::jobs::{localbox, BackendDescriptor}; -use crate::store::{now_ms, Store, StoredRun}; +use crate::store::{now_ms, LaunchSpec, Store, StoredRun}; -/// Submit a local controller and print its run directory. -pub async fn launch_local_run(args: &crate::ExpRunArgs) -> Result<()> { - let run = crate::compute::submit(args).await?; - let backend = BackendDescriptor::parse(&run.backend_json)?; - let label = if backend.kind == "tinker_job" { - "Tinker" - } else { - "Local" - }; - println!("\u{2713} {label} run started."); - println!(" dir {}", backend.job_id.as_deref().unwrap_or("")); - println!(" run {}", run.id); - println!( - "{}", - crate::invocation::follow_up(&run.experiment_id, &run.id) - ); - Ok(()) +pub fn launch_spec(args: &crate::ExpRunArgs, kind: &str) -> Result { + let backend = kind.trim_end_matches("_job"); + if args.flavor.is_some() { + return Err(anyhow!("--backend {backend} does not take --flavor.")); + } + if args.image.is_some() { + return Err(anyhow!( + "--image doesn't apply to --backend {backend} — the controller uses this machine's own environment." + )); + } + Ok(LaunchSpec { + kind: kind.into(), + target: None, + options: serde_json::json!({}), + }) } pub async fn submit_local_run_with_source( diff --git a/src/local/mod.rs b/src/local/mod.rs index c46a53769..cb2a2bda9 100644 --- a/src/local/mod.rs +++ b/src/local/mod.rs @@ -145,6 +145,21 @@ pub(crate) fn assert_agent_guidance_is_ui_agnostic(label: &str, guidance: &str) } } +/// The `or_run` / `or_experiment` / `or_project` labels provider jobs carry. +pub fn run_labels( + experiment_id: &str, + run_id: &str, +) -> Result> { + let experiment = crate::store::Store::open()? + .get_local_experiment(experiment_id)? + .ok_or_else(|| anyhow!("Local experiment {experiment_id} not found."))?; + Ok(std::collections::HashMap::from([ + ("or_run".to_string(), run_id.to_string()), + ("or_experiment".to_string(), experiment.id), + ("or_project".to_string(), experiment.project_id), + ])) +} + /// Fill a local-mode launch's backend/flavor from the persisted default /// (Settings → Compute) when the caller didn't pass them. Explicit args always /// win; see `resolve_compute_default` for the exact precedence. diff --git a/src/local/modal.rs b/src/local/modal.rs index 8cf590520..01a7928eb 100644 --- a/src/local/modal.rs +++ b/src/local/modal.rs @@ -1,8 +1,6 @@ -//! Local Modal launch — the Modal twin of `local/hf.rs` and `local/k8s.rs`: the -//! run row comes from and goes to the local store only, and the detached -//! `orx supervise` watches the sandbox via the Modal Python launcher. Auth is -//! Modal's own (MODAL_TOKEN_ID/SECRET or `~/.modal.toml`); the sandbox runs on -//! the user's Modal account and scales to zero when the run ends. +//! Modal Sandbox launch intents. Auth is Modal's own (MODAL_TOKEN_ID/SECRET or +//! `~/.modal.toml`); the sandbox runs on the user's Modal account and scales to zero when the +//! run ends. use std::collections::HashMap; @@ -10,35 +8,53 @@ use crate::commands::exp::spawn_detached_supervise; use crate::compute::SourceSnapshot; use crate::error::{anyhow, Result}; use crate::jobs::{huggingface as hf, modal, BackendDescriptor}; -use crate::store::{now_ms, Store, StoredRun}; +use crate::store::{now_ms, LaunchSpec, Store, StoredRun}; /// Modal app all orx sandboxes are grouped under (visible in the Modal dashboard). const MODAL_APP: &str = "openresearch"; -/// CLI wrapper around `submit_local_modal`: submit, then print the summary. -pub async fn launch_local_modal(args: &crate::ExpRunArgs) -> Result<()> { - let run = submit_local_modal(args).await?; - let backend = BackendDescriptor::parse(&run.backend_json)?; - println!("\u{2713} Modal sandbox submitted."); - println!( - " sandbox {} ({})", - backend.job_id.as_deref().unwrap_or(""), - backend.flavor.as_deref().unwrap_or("") - ); - println!(" run {}", run.id); - println!( - "{}", - crate::invocation::follow_up(&run.experiment_id, &run.id) - ); - Ok(()) -} - -/// Submit the local experiment's run as a Modal Sandbox and detach a -/// supervisor. Requires `--backend modal` and `--flavor ` where the name -/// is a Modal GPU (t4, l4, a10g, a100, a100-80gb, l40s, h100, h200, …) or -/// `cpu` / `cpu-large` for CPU-only. -pub async fn submit_local_modal(args: &crate::ExpRunArgs) -> Result { - crate::compute::submit(args).await +/// Requires `--flavor `: a Modal GPU (t4, l4, a10g, a100, a100-80gb, l40s, h100, h200, +/// …) or `cpu` / `cpu-large` for CPU-only. +pub fn launch_spec( + args: &crate::ExpRunArgs, + source: &SourceSnapshot, + run_id: &str, + command: &str, +) -> Result { + let flavor = args.flavor.clone().ok_or_else(|| { + anyhow!( + "--backend modal requires --flavor: a Modal GPU (t4, l4, a10g, a100, \ + a100-80gb, l40s, h100, h200, or e.g. h100:2 for a count) — or cpu / cpu-large \ + for CPU-only. Priced per second on your Modal account." + ) + })?; + let resources = modal::resolve_flavor(&flavor); + // Same default as the HF/k8s paths — no-timeout jobs are a footgun. + let timeout_seconds = match &args.timeout { + Some(t) => hf::parse_timeout(t)?, + None => 4 * 3600, + }; + let image = args + .image + .clone() + .unwrap_or_else(|| modal::default_image(resources.gpu.is_some())); + let spec = modal::ModalJobSpec { + script: crate::compute::gated_script("/tmp/orx-source.tar", command), + image, + gpu: resources.gpu, + cpu: resources.cpu, + memory: resources.memory, + env: HashMap::new(), + timeout_seconds, + app: MODAL_APP.to_string(), + tags: super::run_labels(&args.exp_id, run_id)?, + source_archive: Some(source.path.clone()), + }; + Ok(LaunchSpec { + kind: "modal_job".into(), + target: None, + options: serde_json::to_value(spec)?, + }) } pub async fn submit_local_modal_with_source( diff --git a/src/local/opencode.rs b/src/local/opencode.rs index af36c7408..c135493c3 100644 --- a/src/local/opencode.rs +++ b/src/local/opencode.rs @@ -1554,11 +1554,14 @@ mod tests { } #[test] - fn compute_skill_explains_opt_in_run_wakeups() { + fn compute_skill_explains_automatic_result_messages() { let md = sample_playbook(); let compute = agent_skills::find("orx-compute", SkillSet::Local).unwrap(); assert!(compute.content.contains("`orx exp wake `")); - assert!(compute.content.contains("Wake-up is opt-in")); + assert!(compute + .content + .contains("The launching chat is\nsubscribed automatically")); + assert!(!compute.content.contains("Wake-up is opt-in")); assert!(!md.contains("`orx exp wake `")); assert!(!md.contains("OpenResearch injects an `[orx]` message")); } diff --git a/src/local/opencode_db.rs b/src/local/opencode_db.rs index d973c63ba..53f67bc06 100644 --- a/src/local/opencode_db.rs +++ b/src/local/opencode_db.rs @@ -779,6 +779,19 @@ fn referenced_sessions(database: &Path) -> Result> { mod tests { use super::*; + /// A lease just dropped lingers in any child a parallel test forked meanwhile, until that + /// child execs. + fn reacquire(path: &Path, major: u64) -> DatabaseLease { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + loop { + match DatabaseLease::acquire(path, major) { + Ok(lease) => return lease, + Err(error) => assert!(std::time::Instant::now() < deadline, "{error}"), + } + std::thread::sleep(std::time::Duration::from_millis(1)); + } + } + const V1: &str = "CREATE TABLE session (id TEXT PRIMARY KEY, directory TEXT); CREATE TABLE message (id TEXT, session_id TEXT, data TEXT); CREATE TABLE part (id TEXT, message_id TEXT, session_id TEXT, data TEXT); @@ -949,7 +962,7 @@ mod tests { assert!(delete_sessions(std::slice::from_ref(&path), &ids, &BTreeSet::new()).is_err()); connection.execute_batch(V2).unwrap(); assert!(delete_sessions(std::slice::from_ref(&path), &ids, &BTreeSet::new()).is_err()); - let lease = DatabaseLease::acquire(&path, 2).unwrap(); + let lease = reacquire(&path, 2); lease.prepare_with_sessions(ids).unwrap(); assert!(table_has_session(&connection, "session", "history").unwrap()); } @@ -1005,7 +1018,7 @@ mod tests { assert!(has_session(&path, "history").unwrap()); drop(lease); - let mut resumed = DatabaseLease::acquire(&path, 2).unwrap(); + let mut resumed = reacquire(&path, 2); assert_eq!( resumed.prepare_with_sessions(expected).unwrap(), Some(backup.clone()) @@ -1075,9 +1088,7 @@ mod tests { std::fs::remove_file(&backup).unwrap(); } drop(lease); - assert!(!DatabaseLease::acquire(&path, 2) - .unwrap() - .requires_migration()); + assert!(!reacquire(&path, 2).requires_migration()); for suffix in ["", "-wal", "-shm"] { assert!(!sidecar(&backup, suffix).exists()); } @@ -1180,7 +1191,7 @@ mod tests { let busy = DatabaseLease::acquire(&path, 2).err().unwrap(); assert!(busy.downcast_ref::().is_some()); drop((first, second)); - assert!(DatabaseLease::acquire(&path, 2).is_ok()); + reacquire(&path, 2); } #[test] @@ -1202,7 +1213,7 @@ mod tests { .unwrap(); let moved = fixture.0.path().join("moved"); std::fs::rename(&old, &moved).unwrap(); - let lease = DatabaseLease::acquire(&moved.join("opencode.db"), 2).unwrap(); + let lease = reacquire(&moved.join("opencode.db"), 2); let old_backup = crate::paths::canonicalize(&moved) .unwrap() .join(backup.file_name().unwrap()); diff --git a/src/local/openresearch.rs b/src/local/openresearch.rs index 9691f3436..7a73b1b6d 100644 --- a/src/local/openresearch.rs +++ b/src/local/openresearch.rs @@ -1,49 +1,131 @@ -//! Local OpenResearch launch — provision an ephemeral org-billed box for this -//! one run. Unlike `local/ssh.rs`, submit does NOT launch the payload: the box -//! takes minutes to provision and has no SSH endpoint yet, so submit records -//! the run as `starting` and the detached supervisor does the rest (wait for -//! online, launch over ssh, and collect directly; remote supervision releases the box). +//! OpenResearch launch intents: an ephemeral org-billed box for one run. The engine +//! provisions it at launch; the legacy loop waits for it, runs the payload over SSH, collects +//! the log, and releases the box. use crate::client::{create_sandbox, list_orgs, CreateSandboxBody}; use crate::commands::exp::spawn_detached_supervise; use crate::compute::SourceSnapshot; -use crate::error::{anyhow, require_credentials, Result}; +use crate::error::{anyhow, Result}; use crate::jobs::{openresearch, BackendDescriptor}; use crate::local::ssh_identity; -use crate::store::{now_ms, Store, StoredRun}; +use crate::store::{now_ms, LaunchSpec, Store, StoredRun}; -/// CLI wrapper around `submit_local_openresearch`: submit, then print the -/// summary (price is best-effort — it needs one extra API read). -pub async fn launch_local_openresearch(args: &crate::ExpRunArgs) -> Result<()> { - let run = submit_local_openresearch(args).await?; - let backend = BackendDescriptor::parse(&run.backend_json)?; - let sandbox_id = backend.job_id.as_deref().unwrap_or(""); - println!("\u{2713} OpenResearch box requested."); - println!(" flavor {}", backend.flavor.as_deref().unwrap_or("")); - println!(" box {}", sandbox_id); - if let Ok(Some(creds)) = crate::config::load_credentials().await { - if let Ok(envelope) = crate::client::get_sandbox(&creds, sandbox_id).await { - if let Some(price) = envelope.sandbox.price_per_hour { - println!( - " price ${price:.2}/hr (includes up to 60 seconds of final collection)" - ); +/// Requires `--flavor ` (`h100_sxm[:count]` or `cpu5c|cpu5g|cpu5m[:vcpus]`) and +/// `orx login`. The box is provisioned by the engine at launch. +pub async fn launch_spec(args: &crate::ExpRunArgs) -> Result { + if args.host.is_some() { + return Err(anyhow!( + "--host doesn't apply to --backend openresearch — the box is provisioned \ + for you (use --backend ssh to run on your own machine)." + )); + } + if args.manifest.is_some() { + return Err(anyhow!("--manifest is k8s-only.")); + } + if args.image.is_some() { + return Err(anyhow!( + "--image doesn't apply to --backend openresearch — provider base images are fixed \ + by OpenResearch; install project dependencies from the project's lockfile in the \ + run command." + )); + } + let flavor = args.flavor.clone().ok_or_else(|| { + anyhow!( + "--backend openresearch requires --flavor: a GPU id like h100_sxm[:count] \ + or a CPU flavor like cpu5c[:vcpus]. See `orx compute` for the catalog." + ) + })?; + // Parsed now so a typo fails before any billing starts. + openresearch::parse_flavor(&flavor, args.disk.unwrap_or(100), args.provider.clone())?; + let timeout_seconds = match &args.timeout { + Some(t) => crate::jobs::huggingface::parse_timeout(t)?, + None => 4 * 3600, + }; + + let creds = crate::config::load_credentials() + .await? + .ok_or_else(|| anyhow!("OpenResearch requires `orx login`."))?; + + // Which org pays for the box. + let org_id = match &args.org { + Some(org) => org.clone(), + None => { + let orgs = list_orgs(&creds).await?.orgs; + match orgs.len() { + 0 => { + return Err(anyhow!( + "You belong to no organization — create an OpenResearch organization first." + )) + } + 1 => orgs[0].id.clone(), + _ => { + let rows = orgs + .iter() + .map(|o| format!(" {} {}", o.id, o.name)) + .collect::>() + .join("\n"); + return Err(anyhow!( + "You belong to several orgs — pass --org :\n{rows}" + )); + } } } + }; + + // Boxes authorize org members' *registered* SSH keys, and orx authenticates + // with whatever this machine's ssh offers — so a key registered from another + // computer leaves the box online but unreachable. + match ssh_identity::check(&creds).await { + ssh_identity::KeyStatus::Matched => {} + ssh_identity::KeyStatus::Unknown { reason } => { + eprintln!("warning: could not check your registered SSH keys: {reason}"); + } + // No keys at all is the api's own answer, so blocking is safe. + ssh_identity::KeyStatus::NoneRegistered { local } => { + return Err(anyhow!( + "{}\n\n{}", + ssh_identity::diagnosis(&[]), + ssh_identity::remediation(&[], &local) + )); + } + // We only enumerate the agent and ~/.ssh/*.pub, so ssh can still succeed + // via an IdentityFile elsewhere or a key whose .pub isn't on disk. Warn + // loudly rather than block a launch that would have worked. + ssh_identity::KeyStatus::NoLocalMatch { registered, local } => { + eprintln!( + "warning: {}\n\n{}", + ssh_identity::diagnosis(®istered), + ssh_identity::remediation(®istered, &local) + ); + } } - println!(" run {}", run.id); - println!(" The box is provisioning; the supervisor launches the run once it's online."); - println!( - "{}", - crate::invocation::follow_up(&run.experiment_id, &run.id) - ); - Ok(()) + + Ok(LaunchSpec { + kind: "openresearch_job".into(), + target: Some(org_id), + options: serde_json::json!({ + "flavor": flavor, + "disk_gb": args.disk.unwrap_or(100), + "provider": args.provider, + "timeout_seconds": timeout_seconds, + }), + }) } -/// Provision a fresh box for the local experiment's run and detach a -/// supervisor. Requires `--backend openresearch` and `--flavor ` -/// (`h100_sxm[:count]` or `cpu5c|cpu5g|cpu5m[:vcpus]`), plus `orx login`. -pub async fn submit_local_openresearch(args: &crate::ExpRunArgs) -> Result { - crate::compute::submit(args).await +/// Reword a 402 from `POST /sandboxes` (org has no available compute balance) +/// into the top-up action, surfacing the checkout URL the API attaches. +pub(crate) fn billing_friendly(err: crate::error::Error) -> crate::error::Error { + let text = err.to_string(); + if !text.contains("(402 ") { + return err; + } + let url = text + .split("checkoutUrl\":\"") + .nth(1) + .and_then(|rest| rest.split('"').next()) + .map(|u| format!(" Top up at {u}")) + .unwrap_or_default(); + anyhow!("Your org has no available compute balance, so no box was provisioned.{url}") } pub async fn submit_local_openresearch_with_source( @@ -82,7 +164,9 @@ pub async fn submit_local_openresearch_with_source( None => 4 * 3600, }; - let creds = require_credentials().await; + let creds = crate::config::load_credentials() + .await? + .ok_or_else(|| anyhow!("OpenResearch requires `orx login`."))?; // Which org pays for the box. let org_id = match &args.org { @@ -251,19 +335,3 @@ pub async fn submit_local_openresearch_with_source( } Ok(run) } - -/// Reword a 402 from `POST /sandboxes` (org has no available compute balance) -/// into the top-up action, surfacing the checkout URL the API attaches. -fn billing_friendly(err: crate::error::Error) -> crate::error::Error { - let text = err.to_string(); - if !text.contains("(402 ") { - return err; - } - let url = text - .split("checkoutUrl\":\"") - .nth(1) - .and_then(|rest| rest.split('"').next()) - .map(|u| format!(" Top up at {u}")) - .unwrap_or_default(); - anyhow!("Your org has no available compute balance, so no box was provisioned.{url}") -} diff --git a/src/local/ray.rs b/src/local/ray.rs index 49e7134e1..f08f2286d 100644 --- a/src/local/ray.rs +++ b/src/local/ray.rs @@ -1,5 +1,4 @@ -//! Local Ray Jobs launch — submit via the Ray Jobs / Dashboard API, then -//! detach `orx supervise` to poll status and mirror logs. +//! Ray Jobs launch intents, submitted through the Ray Jobs / Dashboard API. use std::collections::HashMap; @@ -8,30 +7,56 @@ use crate::compute::SourceSnapshot; use crate::error::{anyhow, Result}; use crate::jobs::ssh::sh_quote; use crate::jobs::{huggingface, ray, BackendDescriptor}; -use crate::store::{now_ms, Store, StoredRun}; +use crate::store::{now_ms, LaunchSpec, Store, StoredRun}; -/// CLI wrapper: submit, then print the summary. -pub async fn launch_local_ray(args: &crate::ExpRunArgs) -> Result<()> { - let run = submit_local_ray(args).await?; - let backend = BackendDescriptor::parse(&run.backend_json)?; - println!("\u{2713} Ray job submitted."); - println!(" run {}", run.id); - println!( - " job {} ({})", - backend.job_id.as_deref().unwrap_or(""), - backend.flavor.as_deref().unwrap_or("default") - ); - println!(" watch {}", backend.url.as_deref().unwrap_or("")); - println!( - "{}", - crate::invocation::follow_up(&run.experiment_id, &run.id) - ); - Ok(()) -} - -/// Submit the local experiment's run as a Ray Job and detach a supervisor. -pub async fn submit_local_ray(args: &crate::ExpRunArgs) -> Result { - crate::compute::submit(args).await +/// Uploads the working_dir package now; it is content-addressed, so a relaunch reuses it. +pub async fn launch_spec( + args: &crate::ExpRunArgs, + source: &SourceSnapshot, + run_id: &str, + command: &str, +) -> Result { + if args.image.is_some() { + return Err(anyhow!( + "--image doesn't apply to --backend ray — the job runs in the cluster's \ + runtime environment, not a per-job container." + )); + } + if args.host.is_some() { + return Err(anyhow!( + "--host only applies with --backend ssh/slurm. Save the Ray Jobs URL in \ + OpenResearch or set ASTROAI_RAY_JOBS_ADDRESS / RAY_DASHBOARD_URL." + )); + } + if args.manifest.is_some() { + return Err(anyhow!("--manifest only applies with --backend k8s.")); + } + if args.timeout.is_some() { + return Err(anyhow!( + "--timeout isn't supported on --backend ray — Ray Jobs have no time limit; \ + the job runs until the command exits. Bound the run in the command itself." + )); + } + let resources = ray::parse_flavor(args.flavor.as_deref())?; + let address = ray::resolve_address(None); + let (package_digest, package_path) = source + .ray_package + .as_ref() + .ok_or_else(|| anyhow!("Ray source package was not created."))?; + let working_dir = ray::stage_working_dir(&address, package_digest, package_path).await?; + let submission = ray::JobSubmission { + entrypoint: format!("bash -c {}", sh_quote(command)), + submission_id: run_id.to_string(), + resources, + env: HashMap::new(), + metadata: super::run_labels(&args.exp_id, run_id)?, + working_dir: Some(working_dir), + }; + Ok(LaunchSpec { + kind: "ray_job".into(), + target: Some(address), + options: serde_json::to_value(submission)?, + }) } pub async fn submit_local_ray_with_source( @@ -120,7 +145,7 @@ pub async fn submit_local_ray_with_source( ) .await?; - let watch = ray::job_url(&address, &submission_id); + let watch = format!("{address}/#/jobs/{submission_id}"); let mut descriptor = BackendDescriptor { ssh_container: None, diff --git a/src/local/remote_cleanup.rs b/src/local/remote_cleanup.rs index f3882eed8..f7dfaf977 100644 --- a/src/local/remote_cleanup.rs +++ b/src/local/remote_cleanup.rs @@ -1,9 +1,10 @@ //! Background removal of queued remote run dirs; the remote half lives in `jobs::ssh::cleanup`. use std::collections::{BTreeMap, BTreeSet}; +use std::sync::atomic::AtomicBool; use crate::error::Result; -use crate::jobs::ssh::cleanup::{self, Outcome, RemoteRun}; +use crate::jobs::ssh::cleanup::{self, Outcome, RemoteRun, SourceCache}; use crate::jobs::BackendDescriptor; use crate::store::Store; @@ -16,14 +17,12 @@ pub type Failures = Vec<(String, String)>; pub struct HostBatch { host: String, runs: Vec, - /// Storage roots whose source cache this pass sweeps. - roots: BTreeSet>, - keep_digests: BTreeSet, + roots: BTreeSet, } pub struct HostResult { host: String, - roots: BTreeSet>, + roots: BTreeSet, /// (run id, deleted flag the pass acted on, outcome). runs: Vec<(String, bool, Outcome)>, } @@ -36,27 +35,21 @@ pub fn plan(store: &Store) -> Result<(Vec, Failures)> { let slurm_keeps = crate::jobs::slurm::load_settings()? .unwrap_or_default() .keep_remote_runs; - let mut hosts: BTreeMap, BTreeSet>)> = BTreeMap::new(); + let mut hosts: BTreeMap, BTreeSet)> = BTreeMap::new(); let mut rejected = Vec::new(); for entry in store.due_remote_cleanups(BATCH)? { - let parsed = BackendDescriptor::parse(&entry.backend_json).and_then(|descriptor| { - let keeps = match descriptor.kind.as_str() { - "slurm_job" => slurm_keeps, - _ => descriptor - .namespace - .as_deref() - .and_then(|host| ssh.hosts.get(host)) - .is_some_and(|saved| saved.keep_remote_runs), - }; - Ok( - RemoteRun::from_descriptor(&entry.run_id, &descriptor, entry.deleted)? - .map(|run| (run, keeps)), - ) - }); + let parsed = RemoteRun::from_backend(&entry.run_id, &entry.backend_json, entry.deleted); + let keeps = |run: &RemoteRun| match run.slurm { + true => slurm_keeps, + false => ssh + .hosts + .get(&run.host) + .is_some_and(|saved| saved.keep_remote_runs), + }; match parsed { - Ok(Some((run, keeps))) if entry.deleted || !keeps => { + Ok(Some(run)) if entry.deleted || !keeps(&run) => { let (runs, roots) = hosts.entry(run.host.clone()).or_default(); - roots.insert(run.root().map(Into::into)); + roots.insert(run.cache()); runs.push(run); } Ok(_) => store.finish_remote_cleanup(&entry.run_id, entry.deleted)?, @@ -67,32 +60,34 @@ pub fn plan(store: &Store) -> Result<(Vec, Failures)> { } } for (host, root) in store.due_source_sweeps()? { - hosts.entry(host).or_default().1.insert(root); + hosts.entry(host).or_default().1.insert((root, false)); } let batches = hosts .into_iter() - .map(|(host, (runs, roots))| { - Ok(HostBatch { - keep_digests: active_source_digests(store, &host)?, - host, - runs, - roots, - }) - }) - .collect::>()?; + .map(|(host, (runs, roots))| HostBatch { host, runs, roots }) + .collect(); Ok((batches, rejected)) } /// Source digests that unfinished SSH/Slurm runs on `host` may still stage. fn active_source_digests(store: &Store, host: &str) -> Result> { let mut digests = BTreeSet::new(); - for run in store.list_active_runs()? { + for run in store.list_engine_runs()? { let Ok(descriptor) = BackendDescriptor::parse(&run.backend_json) else { continue; }; - if matches!(descriptor.kind.as_str(), "ssh_job" | "slurm_job") - && descriptor.namespace.as_deref() == Some(host) - { + let target = match crate::engine::is_engine_row(&run) { + true => store + .engine_run_state(&run.id)? + .and_then(|state| state.launch) + .filter(|launch| matches!(launch.kind.as_str(), "ssh_job" | "slurm_job")) + .and_then(|launch| launch.target), + false => descriptor + .namespace + .clone() + .filter(|_| matches!(descriptor.kind.as_str(), "ssh_job" | "slurm_job")), + }; + if target.as_deref() == Some(host) { digests.extend(descriptor.source_digest.filter(|digest| { digest.len() == 64 && digest.bytes().all(|c| c.is_ascii_hexdigit()) })); @@ -101,16 +96,51 @@ fn active_source_digests(store: &Store, host: &str) -> Result> Ok(digests) } -pub async fn clean(batches: Vec) -> Vec { +/// Over the engine's connection to each host when `orx up` runs one. +pub async fn clean( + batches: Vec, + moving: &AtomicBool, + gate: &tokio::sync::Mutex<()>, +) -> Vec { let mut results = Vec::new(); - for batch in batches { - let outcomes = - match cleanup::clean_host(&batch.host, &batch.runs, &batch.roots, &batch.keep_digests) - .await - { - Ok(outcomes) => outcomes, - Err(error) => vec![Outcome::Failed(format!("{error:#}")); batch.runs.len()], - }; + for mut batch in batches { + let had_runs = !batch.runs.is_empty(); + let candidates = std::mem::take(&mut batch.runs); + let host = batch.host.clone(); + let eligible = crate::commands::up::with_gated_store(moving, gate, move |store| { + let mut runs = Vec::new(); + for run in candidates { + if store.remote_cleanup_eligible(&run.run_id, run.deleted())? { + runs.push(run); + } + } + Ok((runs, active_source_digests(store, &host)?)) + }) + .await; + let (runs, keep_digests) = match eligible { + Some(Ok(eligible)) => eligible, + None => break, + Some(Err(error)) => { + eprintln!("orx up: remote cleanup eligibility: {error:#}"); + continue; + } + }; + if had_runs && runs.is_empty() { + continue; + } + batch.runs = runs; + let slurm = batch.runs.iter().any(|run| run.slurm); + let (outcomes, roots) = match crate::commands::up::api_v2::host_target(&batch.host, slurm) { + Ok(target) => ( + cleanup::clean_host(&target, &batch.runs, &batch.roots, &keep_digests).await, + batch.roots, + ), + Err(error) => (Err(error), BTreeSet::new()), + }; + let outcomes = match outcomes { + Ok(outcomes) => outcomes, + Err(error) => vec![Outcome::Failed(format!("{error:#}")); batch.runs.len()], + }; let runs = batch .runs .iter() @@ -119,7 +149,7 @@ pub async fn clean(batches: Vec) -> Vec { .collect(); results.push(HostResult { host: batch.host, - roots: batch.roots, + roots, runs, }); } @@ -130,7 +160,8 @@ pub async fn clean(batches: Vec) -> Vec { pub fn record(store: &Store, results: Vec) -> Result { let mut failures = Vec::new(); for result in results { - for root in &result.roots { + // Engine sources are swept by the next pass that cleans a run on their host. + for (root, _) in result.roots.iter().filter(|(_, engine)| !engine) { // Run passes can leave tars too fresh to remove; a sweep-only pass is best effort. if result.runs.is_empty() { store.finish_source_sweep(&result.host, root.as_deref())?; @@ -155,3 +186,90 @@ pub fn record(store: &Store, results: Vec) -> Result { } Ok(failures) } + +#[cfg(test)] +mod tests { + use super::*; + use crate::store::{Contact, StoredRun}; + + #[tokio::test] + async fn queued_retention_rechecks_the_kill_before_contacting_the_host() { + let dir = std::env::temp_dir().join(format!("orx-retention-{}", uuid::Uuid::new_v4())); + const CHILD: &str = "ORX_TEST_RETENTION_GATE"; + if std::env::var_os(CHILD).is_none() { + let output = crate::process::command(std::env::current_exe().unwrap()) + .args(["--exact", "local::remote_cleanup::tests::queued_retention_rechecks_the_kill_before_contacting_the_host", "--nocapture"]) + .env(CHILD, "1") + .env("ORX_DATA_DIR", &dir) + .output().unwrap(); + assert!( + output.status.success(), + "{}\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + let _ = std::fs::remove_dir_all(dir); + return; + } + let dir = crate::store::data_dir(); + let store = Store::open_at(dir.clone()).unwrap(); + let backend = + r#"{"kind":"engine","handle":{"type":"Ssh","host":"never-connect","root":"/orx"}}"#; + let first = uuid::Uuid::from_u128(1).to_string(); + for n in 0..5 { + let id = uuid::Uuid::from_u128(n as u128 + 1).to_string(); + store + .upsert_run(&StoredRun { + id: id.clone(), + experiment_id: "exp".into(), + project_id: "project".into(), + status: "lost".into(), + backend_json: backend.into(), + command: "true".into(), + created_at: n, + updated_at: n, + ended_at: Some(n), + exit_code: None, + commit_sha: None, + result_markdown: None, + cancel_requested: false, + cancel_reason: None, + chat_session_id: None, + }) + .unwrap(); + store.queue_finished_remote_cleanup(&id).unwrap(); + } + assert!(store.remote_cleanup_eligible(&first, false).unwrap()); + let run = RemoteRun::from_backend(&first, backend, false) + .unwrap() + .unwrap(); + let batch = HostBatch { + host: run.host.clone(), + roots: BTreeSet::from([run.cache()]), + runs: vec![run.clone()], + }; + store + .set_run_contact( + &first, + &Contact::Unreconciled { + since: 1, + detail: "pending stop".into(), + }, + ) + .unwrap(); + let moving = AtomicBool::new(true); + let gate = tokio::sync::Mutex::new(()); + assert!(clean(vec![batch], &moving, &gate).await.is_empty()); + moving.store(false, std::sync::atomic::Ordering::SeqCst); + let batch = HostBatch { + host: run.host.clone(), + roots: BTreeSet::from([run.cache()]), + runs: vec![run], + }; + assert!(clean(vec![batch], &moving, &gate).await.is_empty()); + store.set_run_contact(&first, &Contact::Live).unwrap(); + assert!(store.remote_cleanup_eligible(&first, false).unwrap()); + drop(store); + std::fs::remove_dir_all(dir).unwrap(); + } +} diff --git a/src/local/skills.rs b/src/local/skills.rs index 38f85bf5a..b639e4db4 100644 --- a/src/local/skills.rs +++ b/src/local/skills.rs @@ -62,8 +62,9 @@ that fits the available compute. Create experiment nodes for meaningful variants make each change on its printed local branch, and commit it. Use the configured default compute target, or the explicit backend and flavor/host the user chose; source snapshots do not require GitHub. Keep the inherited run command fixed. -Wait with `orx exp wait --project `, inspect `orx runs`, and -locate every terminal run's log with `orx logs `, then inspect the file. +Launch ready runs, then end your turn. Results and attention messages arrive +in this chat. When one arrives, reconcile every newly terminal run with +`orx runs ` and inspect the file located by `orx logs `. Record the paper number, observed number, scale or substitutions, sample size, scoring method, runtime, and an honest assessment in `orx exp desc`. Repair a diff --git a/src/local/slurm.rs b/src/local/slurm.rs index 80467abf3..105e3bcd0 100644 --- a/src/local/slurm.rs +++ b/src/local/slurm.rs @@ -1,36 +1,13 @@ -//! Local Slurm launch — the scheduler-backed twin of `local/ssh.rs`: submit -//! the experiment as a batch job on a Slurm cluster reached via its login -//! node. `--host` names an `~/.ssh/config` alias (defaultable in the slurm -//! settings); `--flavor` asks for GPUs as a GRES spec, `--cpus`/`--mem` for -//! cores and host memory. The run row lives in the local store only; a -//! detached `orx supervise` watches the job. +//! Slurm launch intents: a batch job on a Slurm cluster reached via its login node. +//! `--host` names an `~/.ssh/config` alias (defaultable in the slurm settings); `--flavor` +//! asks for GPUs as a GRES spec, `--cpus`/`--mem` for cores and host memory. use crate::commands::exp::spawn_detached_supervise; use crate::compute::SourceSnapshot; use crate::error::{anyhow, Result}; use crate::jobs::{huggingface, slurm, BackendDescriptor}; -use crate::store::{now_ms, Store, StoredRun}; - -/// CLI wrapper around `submit_local_slurm`: submit, then print the summary. -pub async fn launch_local_slurm(args: &crate::ExpRunArgs) -> Result<()> { - let run = submit_local_slurm(args).await?; - let backend = BackendDescriptor::parse(&run.backend_json)?; - println!("\u{2713} Slurm job submitted."); - println!( - " host {} (job {})", - backend.namespace.as_deref().unwrap_or(""), - backend.job_id.as_deref().unwrap_or("") - ); - if let Some(resources) = requested_resources(&backend) { - println!(" {resources}"); - } - println!(" run {}", run.id); - println!( - "{}", - crate::invocation::follow_up(&run.experiment_id, &run.id) - ); - Ok(()) -} +use crate::store::{now_ms, LaunchSpec, Store, StoredRun}; +use std::collections::BTreeMap; /// The launch-summary line for a Slurm job that asked for cores or memory. pub fn requested_resources(backend: &BackendDescriptor) -> Option { @@ -55,11 +32,169 @@ pub fn status_resources(backend: &BackendDescriptor) -> String { } } -/// Submit the local experiment's run as a Slurm batch job and detach a -/// supervisor. Requires `--backend slurm`; the login node comes from -/// `--host ` or the slurm settings default. -pub async fn submit_local_slurm(args: &crate::ExpRunArgs) -> Result { - crate::compute::submit(args).await +pub fn launch_spec(args: &crate::ExpRunArgs, command: &str) -> Result { + if args.image.is_some() { + return Err(anyhow!( + "--image doesn't apply to --backend slurm — the job runs in your cluster \ + environment (modules/conda), not a container." + )); + } + if args.manifest.is_some() { + return Err(anyhow!("--manifest only applies with --backend k8s.")); + } + // A muscle-memory `--flavor cpu` (HF/Modal habit) would become the + // nonsense GRES `gpu:cpu` and die with an opaque sbatch error. + if let Some(f) = &args.flavor { + if f.trim().to_ascii_lowercase().starts_with("cpu") { + return Err(anyhow!( + "--flavor names GPUs on --backend slurm (e.g. h100:2). For a CPU-only \ + run omit --flavor and ask for cores with --cpus (e.g. --cpus 8)." + )); + } + } + + let settings = slurm::load_settings()?.unwrap_or_default(); + if let Some(root) = &settings.remote_root { + crate::jobs::ssh::validate_remote_root(root)?; + } + let host = args + .host + .clone() + .or_else(|| settings.host.clone()) + .ok_or_else(|| { + anyhow!( + "--backend slurm needs a login node: pass --host (an ~/.ssh/config \ + alias) or use a configured default Slurm host." + ) + })?; + + let launch = crate::engine::adapters::ssh::LaunchOptions { + run_sh: Some(format!( + "{} {}", + crate::compute::TENSORBOARD_LOGDIR_EXPORT, + crate::compute::staged_script(command) + )), + root: Some(crate::engine::runtime::engine_root( + settings.remote_root.as_deref(), + )), + ..Default::default() + }; + let mut options = serde_json::to_value(launch)?; + options["timeout_seconds"] = serde_json::to_value(slurm::resolve_time_limit( + args.timeout.as_deref(), + settings.time_limit.as_deref(), + )?)?; + options["directives"] = serde_json::to_value(directives(args, settings)?)?; + Ok(LaunchSpec { + kind: "slurm_job".into(), + target: Some(host), + options, + }) +} + +/// `#SBATCH` options: flags beat the saved defaults, and neither leaves the cluster's own. +fn directives( + args: &crate::ExpRunArgs, + settings: slurm::SlurmSettings, +) -> Result> { + let time_limit_secs = + slurm::resolve_time_limit(args.timeout.as_deref(), settings.time_limit.as_deref())?; + // Worth asking for explicitly on a GPU run: a partition that hands out one core and + // `DefMemPerCPU` with it will starve a dataloader feeding an H100. + let cpus_per_task = args.cpus.or(settings.cpus_per_task).filter(|c| *c > 0); + let mem = match args.mem.as_deref().or(settings.mem.as_deref()) { + Some(m) => Some(slurm::parse_mem(m)?), + None => None, + }; + // Some clusters' job-submit plugins refuse a job that names no task count. + let mut directives = BTreeMap::from([("ntasks".to_string(), "1".to_string())]); + let optional = [ + ("time", time_limit_secs.map(slurm::slurm_time)), + ("partition", args.partition.clone().or(settings.partition)), + ("account", settings.account), + ("gres", args.flavor.as_deref().and_then(slurm::resolve_gres)), + ("cpus-per-task", cpus_per_task.map(|c| c.to_string())), + ("mem", mem), + ]; + for (name, value) in optional { + if let Some(value) = value.filter(|value| !value.trim().is_empty()) { + directives.insert(name.to_string(), value); + } + } + Ok(directives) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn flags_beat_saved_defaults_and_blank_values_are_omitted() { + let settings = || slurm::SlurmSettings { + partition: Some("gpu".into()), + account: Some(" ".into()), + time_limit: Some("24h".into()), + cpus_per_task: Some(4), + mem: Some("32G".into()), + ..Default::default() + }; + let mut args = crate::compute::tests::tinker_args(); + let saved = directives(&args, settings()).unwrap(); + assert_eq!( + saved, + BTreeMap::from( + [ + ("ntasks", "1"), + ("time", "1-00:00:00"), + ("partition", "gpu"), + ("cpus-per-task", "4"), + ("mem", "32G"), + ] + .map(|(name, value)| (name.to_string(), value.to_string())) + ) + ); + args.timeout = Some("2h".into()); + args.cpus = Some(8); + args.mem = Some("4000".into()); + args.flavor = Some("h100:2".into()); + let flags = directives(&args, settings()).unwrap(); + assert_eq!(flags["time"], "02:00:00"); + assert_eq!(flags["cpus-per-task"], "8"); + assert_eq!(flags["mem"], "4000"); + assert_eq!(flags["gres"], "gpu:h100:2"); + args.mem = Some("lots".into()); + assert!(directives(&args, settings()).is_err()); + let bare = directives( + &crate::compute::tests::tinker_args(), + slurm::SlurmSettings::default(), + ) + .unwrap(); + assert_eq!(bare.keys().collect::>(), ["ntasks"]); + } +} + +#[cfg(test)] +#[test] +fn per_run_partition_overrides_default_and_preserves_lists() { + let mut args = crate::compute::tests::tinker_args(); + args.partition = Some("gpu,batch".into()); + let settings = slurm::SlurmSettings { + partition: Some("cpu".into()), + ..Default::default() + }; + assert_eq!( + directives(&args, settings).unwrap()["partition"], + "gpu,batch" + ); + args.backend = Some("slurm".into()); + crate::compute::validate_run_args(&args).unwrap(); + for partition in ["", "gpu,,cpu", "gpu\n--account=other", "gpu cpu"] { + args.partition = Some(partition.into()); + assert!(crate::compute::validate_run_args(&args).is_err()); + } + args.partition = Some("gpu".into()); + args.backend = Some("ssh".into()); + assert!(crate::compute::validate_run_args(&args).is_err()); } pub async fn submit_local_slurm_with_source( @@ -155,7 +290,10 @@ pub async fn submit_local_slurm_with_source( command: run_command.clone(), env, gres: args.flavor.as_deref().and_then(slurm::resolve_gres), - partition: settings.partition.clone(), + partition: args + .partition + .clone() + .or_else(|| settings.partition.clone()), account: settings.account.clone(), time_limit_secs, cpus_per_task, diff --git a/src/local/ssh.rs b/src/local/ssh.rs index c603766db..4502cb4d2 100644 --- a/src/local/ssh.rs +++ b/src/local/ssh.rs @@ -1,38 +1,34 @@ -//! Local SSH launch — the SSH twin of `local/k8s.rs`: run the experiment as a -//! detached process on one of your own boxes over ssh. `--host` names an -//! `~/.ssh/config` host alias (there's no hardware scheduler on a plain -//! server). The run row lives in the local store only; a detached -//! `orx supervise` watches the remote process. +//! SSH launch intents: the run executes as a detached process on one of your own boxes. +//! `--host` names an `~/.ssh/config` host alias (there's no hardware scheduler on a plain +//! server). use crate::commands::exp::spawn_detached_supervise; use crate::compute::SourceSnapshot; use crate::error::{anyhow, Result}; use crate::jobs::{ssh, BackendDescriptor}; -use crate::store::{now_ms, Store, StoredRun}; +use crate::store::{now_ms, LaunchSpec, Store, StoredRun}; -/// CLI wrapper around `submit_local_ssh`: submit, then print the summary. -pub async fn launch_local_ssh(args: &crate::ExpRunArgs) -> Result<()> { - let run = submit_local_ssh(args).await?; - let backend = BackendDescriptor::parse(&run.backend_json)?; - println!("\u{2713} SSH run submitted."); - println!( - " host {} ({})", - backend.namespace.as_deref().unwrap_or(""), - backend.job_id.as_deref().unwrap_or("") - ); - println!(" run {}", run.id); - println!( - "{}", - crate::invocation::follow_up(&run.experiment_id, &run.id) - ); - Ok(()) -} - -/// Submit the local experiment's run as a detached process on an ssh host and -/// detach a supervisor. Requires `--backend ssh` and `--host ` where -/// the host is an `~/.ssh/config` alias. -pub async fn submit_local_ssh(args: &crate::ExpRunArgs) -> Result { - crate::compute::submit(args).await +/// The saved container is resolved by the engine over its own connection to the host. +pub fn launch_spec(args: &crate::ExpRunArgs, command: &str) -> Result { + let settings = crate::config::ssh_settings()?; + let (host, options) = crate::jobs::ssh::resolve_options(args, &settings)?; + let launch = crate::engine::adapters::ssh::LaunchOptions { + run_sh: Some(format!( + "{} {}", + crate::compute::TENSORBOARD_LOGDIR_EXPORT, + crate::compute::staged_script(command) + )), + container_reference: options.container, + root: Some(crate::engine::runtime::engine_root( + options.remote_root.as_deref(), + )), + ..Default::default() + }; + Ok(LaunchSpec { + kind: "ssh_job".into(), + target: Some(host), + options: serde_json::to_value(launch)?, + }) } pub async fn submit_local_ssh_with_source( diff --git a/src/local/vercel.rs b/src/local/vercel.rs index 90f6e354d..a61492fb5 100644 --- a/src/local/vercel.rs +++ b/src/local/vercel.rs @@ -1,9 +1,4 @@ -//! Local Vercel Sandbox launch — the Vercel twin of `local/modal.rs`: the run -//! row comes from and goes to the local store only, and the detached -//! `orx supervise` watches the sandbox via the Vercel Python launcher. Auth is -//! Vercel's own (VERCEL_TOKEN + VERCEL_TEAM_ID + VERCEL_PROJECT_ID, or -//! VERCEL_OIDC_TOKEN); the sandbox runs on the user's Vercel project and is -//! stopped and destroyed when the run ends. +//! Vercel Sandbox launch intents. Credentials are added only at launch. use std::collections::HashMap; @@ -11,32 +6,48 @@ use crate::commands::exp::spawn_detached_supervise; use crate::compute::SourceSnapshot; use crate::error::{anyhow, Result}; use crate::jobs::{huggingface as hf, vercel, BackendDescriptor}; -use crate::store::{now_ms, Store, StoredRun}; +use crate::store::{now_ms, LaunchSpec, Store, StoredRun}; -/// Optional region override (Vercel defaults to `iad1` or the project default). -const REGION_ENV: &str = "ORX_VERCEL_REGION"; +pub async fn launch_spec( + args: &crate::ExpRunArgs, + source: &SourceSnapshot, + run_id: &str, + command: &str, +) -> Result { + let vcpus = vercel::resolve_flavor(args.flavor.as_deref())?; + let limits = vercel::launch_limits().await; + let timeout_seconds = match &args.timeout { + Some(t) => hf::parse_timeout(t)?, + None => limits.default_timeout(), + }; + vercel::check_timeout(timeout_seconds, &limits)?; + vercel::check_vcpus(vcpus, &limits)?; -/// CLI wrapper around `submit_local_vercel`: submit, then print the summary. -pub async fn launch_local_vercel(args: &crate::ExpRunArgs) -> Result<()> { - let run = crate::compute::submit(args).await?; - let backend = BackendDescriptor::parse(&run.backend_json)?; - println!("\u{2713} Vercel sandbox submitted."); - println!( - " sandbox {} ({})", - backend.namespace.as_deref().unwrap_or(""), - backend.flavor.as_deref().unwrap_or("cpu") - ); - println!(" run {}", run.id); - println!( - "{}", - crate::invocation::follow_up(&run.experiment_id, &run.id) - ); - Ok(()) + let image = args + .image + .clone() + .unwrap_or_else(|| vercel::DEFAULT_IMAGE.to_string()); + let spec = vercel::VercelJobSpec { + name: vercel::sandbox_name(run_id), + script: crate::compute::gated_script("/tmp/orx-source.tar", command), + image, + vcpus, + env: HashMap::new(), + timeout_seconds, + session_cap: limits.session_cap(), + region: std::env::var("ORX_VERCEL_REGION") + .ok() + .filter(|region| !region.trim().is_empty()), + tags: super::run_labels(&args.exp_id, run_id)?, + source_archive: Some(source.path.clone()), + }; + Ok(LaunchSpec { + kind: "vercel_job".into(), + target: None, + options: serde_json::to_value(spec)?, + }) } -/// Submit the local experiment's run as a Vercel Sandbox and detach a -/// supervisor. `--flavor` is optional: `cpu` (2 vCPUs, the default), -/// `cpu-` or `` vCPUs. pub async fn submit_local_vercel_with_source( args: &crate::ExpRunArgs, source: SourceSnapshot, @@ -94,7 +105,7 @@ pub async fn submit_local_vercel_with_source( env, timeout_seconds, session_cap: limits.session_cap(), - region: std::env::var(REGION_ENV) + region: std::env::var("ORX_VERCEL_REGION") .ok() .filter(|r| !r.trim().is_empty()), tags, diff --git a/src/main.rs b/src/main.rs index 647589655..af9b3c3cb 100644 --- a/src/main.rs +++ b/src/main.rs @@ -18,6 +18,7 @@ mod client; mod commands; mod compute; mod config; +mod engine; mod error; mod folder_picker; mod invocation; @@ -285,6 +286,8 @@ pub struct RunsArgs { #[derive(Args, Debug)] pub struct LogsArgs { pub run_id: String, + #[arg(short, long, hide = true)] + pub follow: bool, } #[derive(Args, Debug)] @@ -496,19 +499,28 @@ pub enum ExpCommand { stdin: bool, }, - /// Launch a locally initialized experiment through an orx-supervised backend. + /// Launch a locally initialized experiment through the run engine. Run(Box), - /// Cancel the in-flight run. - Cancel { exp_id: String }, + /// Cancel in-flight runs in an experiment, or one run with --run. + Cancel { + #[arg(required_unless_present = "run")] + exp_id: Option, + /// Cancel only this run. With an experiment id, the run must belong to it. + #[arg(long)] + run: Option, + }, - /// Resume this agent after the experiment's latest run succeeds or fails. + /// Abandon a run whose outcome cannot be recovered; keep its cancel pending. + Abandon { run: String }, + + /// Send this chat the result of the experiment's latest run when it finishes. Wake { exp_id: String }, /// Wait for a run to finish: one experiment (``) or the next completion in a project (`--project`). Wait { - /// Experiment to watch; its latest run is polled until it reaches a - /// terminal state. Omit and pass `--project` to watch a whole project. + /// Experiment to watch until its latest run reaches a terminal state. + /// Omit and pass `--project` to watch a whole project. exp_id: Option, /// Watch every run in this project and return on the FIRST one to /// complete (reach done/failed/cancelled) — a "slot freed" signal. Call @@ -520,13 +532,13 @@ pub enum ExpCommand { /// Give up and exit non-zero after this many seconds (default 1800). #[arg(long)] timeout: Option, - /// Seconds between polls (default 5). - #[arg(long)] + /// Seconds between retries while the local database is busy (default 5). + #[arg(long, hide = true)] interval: Option, }, } -#[derive(Args, Debug)] +#[derive(Args, Debug, serde::Serialize, serde::Deserialize)] pub struct ExpRunArgs { pub exp_id: String, /// Disk in GB for a `--backend openresearch` instance (default 100). @@ -547,8 +559,8 @@ pub struct ExpRunArgs { /// `orx login`), `tinker` (a local controller using remote Tinker model /// compute), or `local` (a detached process on this machine). k8s, /// ssh, slurm, ray, openresearch, tinker, and local are local - /// experiments only. orx submits the job and a detached supervisor - /// records status and logs locally. Omitted on a local experiment: launches on + /// experiments only. The run engine in the OpenResearch server submits + /// the job and records its status and logs locally. Omitted on a local experiment: launches on /// the configured default compute target, if set. #[arg(long)] pub backend: Option, @@ -618,6 +630,9 @@ pub struct ExpRunArgs { /// raises memory with it. #[arg(long)] pub mem: Option, + /// Slurm partition for this run; overrides the saved default. Accepts comma-separated names. + #[arg(long)] + pub partition: Option, /// Launch even when another run is already in flight for this experiment. #[arg(long)] pub force: bool, @@ -634,6 +649,10 @@ pub struct ExpRunArgs { pub forwarded: bool, #[arg(skip)] pub telemetry_suppressed: bool, + /// The caller's compute settings, which must be the server's. + #[arg(skip)] + #[serde(default)] + pub caller_config_dir: Option, } /// Markers the native agent CLIs export to their shells; nested agents are `unknown`. @@ -718,6 +737,9 @@ pub struct UpArgs { /// Don't open the dashboard in the browser on startup. #[arg(long)] pub no_browser: bool, + /// Keep the engine running without opening a window. + #[arg(long, hide = true)] + pub headless: bool, /// Don't spawn the opencode agent on startup (for tests). #[arg(long)] pub no_agent: bool, @@ -996,11 +1018,17 @@ pub struct PaperArgs { pub full: bool, } -// The default multi-thread runtime is load-bearing for desktop app mode: it -// blocks the main thread in the window's run loop while the dashboard server runs -// on worker threads. A `current_thread` flavor would deadlock. See commands::app. +fn main() { + if let Err(error) = commands::remote_host::prepare_readiness_pipe() { + eprintln!("Could not prepare server readiness: {error}"); + std::process::exit(1); + } + run_cli(); +} + +// Desktop app mode blocks the main thread while the dashboard runs on worker threads. #[tokio::main] -async fn main() { +async fn run_cli() { #[cfg(all(target_os = "macos", debug_assertions))] if std::env::args().nth(1).as_deref() == Some("--dev-desktop") { let port = std::env::args() @@ -1014,6 +1042,12 @@ async fn main() { } return; } + if std::env::var_os("ORX_ENGINE_ASKPASS").is_some() { + if engine::transport::askpass::relay().await.is_err() { + std::process::exit(1); + } + return; + } if std::env::var_os("ORX_SSH_ASKPASS_ENDPOINT").is_some() { if jobs::ssh::service::askpass().await.is_err() { std::process::exit(1); @@ -1405,10 +1439,15 @@ async fn dispatch(command: Command) -> error::Result<()> { Command::Serve(args) => commands::serve::run(args).await, Command::Supervise(args) => commands::supervise::run(args).await, Command::RentalSupervise { config } => jobs::rental::supervise(&config).await, - Command::Up(args) => match args.remote.clone() { - Some(host) => commands::up_remote::run(&host, args).await, - None => commands::up::run(args).await, - }, + Command::Up(mut args) => { + if args.headless { + args.no_browser = true; + } + match args.remote.clone() { + Some(host) => commands::up_remote::run(&host, args).await, + None => commands::up::run(args).await, + } + } Command::Telemetry(args) => commands::telemetry::run(args).await, Command::Feedback(args) => commands::feedback::run(args).await, // Handled before dispatch (fast path, no telemetry/update check). diff --git a/src/plane.rs b/src/plane.rs index 9aea0c3e6..22861b23f 100644 --- a/src/plane.rs +++ b/src/plane.rs @@ -3,10 +3,24 @@ use crate::error::{anyhow, Result}; use crate::store::{Store, StoredRun}; +pub(crate) static LABELS: std::sync::LazyLock> = + std::sync::LazyLock::new(|| { + serde_json::from_str(include_str!("../ui/messages/en.json")) + .expect("English message catalog") + }); + +#[derive(serde::Deserialize)] +#[serde(rename_all = "camelCase")] pub struct Run { pub id: String, pub experiment_id: String, pub status: String, + pub contact: crate::store::Contact, + #[serde(default)] + pub cancelling: bool, + #[serde(default)] + pub cancel_unconfirmed: Option>, + pub host: Option, pub commit_sha: Option, pub duration_secs: i64, pub updated_display: String, @@ -20,6 +34,12 @@ impl From<&StoredRun> for Run { id: run.id.clone(), experiment_id: run.experiment_id.clone(), status: run.status.clone(), + contact: crate::store::Contact::Live, + cancelling: run.cancel_requested + && !crate::engine::Phase::parse(&run.status) + .is_some_and(crate::engine::Phase::is_terminal), + cancel_unconfirmed: None, + host: None, commit_sha: run.commit_sha.clone(), duration_secs: crate::local::run_duration_secs(run), updated_display: crate::local::fmt_ago(run.updated_at), @@ -30,9 +50,80 @@ impl From<&StoredRun> for Run { } impl Run { + pub(crate) fn from_store(store: &Store, stored: &StoredRun) -> Result { + let mut run = Self::from(stored); + if let Some(state) = store.engine_run_state(&stored.id)? { + run.cancelling |= state.cancel_accepted_at.is_some() + && !crate::engine::Phase::parse(&stored.status) + .is_some_and(crate::engine::Phase::is_terminal); + run.contact = state.contact; + run.cancel_unconfirmed = state.cancel_unconfirmed; + } + run.host = crate::commands::up::run_host(store, stored)?; + Ok(run) + } + + pub fn contact_detail(&self) -> Option { + use crate::store::Contact; + let (contact, since, cause) = match &self.contact { + Contact::Live | Contact::Stopping { .. } => return None, + Contact::Unreachable { since, cause } => ("unreachable", since, cause), + Contact::NeedsAuth { since, cause } => ("needs_auth", since, cause), + Contact::Unreconciled { since, detail } => ("unreconciled", since, detail), + }; + Some(format!( + "contact: {contact}, since {}: {cause}", + crate::telemetry::iso8601_utc(*since) + )) + } + + pub fn display_status(&self) -> std::borrow::Cow<'_, str> { + if self.status == "cancelled" { + if let crate::store::Contact::Stopping { count, .. } = self.contact { + let host = self.host.as_deref().unwrap_or("localhost"); + let key = if count == 1 { + "status_stopping_one" + } else { + "status_stopping_other" + }; + return LABELS[key] + .replace("{count}", &count.to_string()) + .replace("{host}", host) + .into(); + } + if self.cancel_unconfirmed.is_some() { + return LABELS["status_cancelled_unconfirmed"].as_str().into(); + } + return LABELS["status_cancelled"].as_str().into(); + } + if self.cancelling { + let pending = self.status == "submitting" + || matches!( + self.contact, + crate::store::Contact::Unreachable { .. } + | crate::store::Contact::NeedsAuth { .. } + ); + let key = if pending { + "status_cancellation_pending" + } else { + "status_cancelling" + }; + return LABELS[key].as_str().into(); + } + self.status.as_str().into() + } + pub fn failure_detail(&self) -> Option { if self.status == "cancelled" { - return self.cancel_reason.as_ref().map(|r| format!("reason: {r}")); + let reason = self + .cancel_reason + .iter() + .chain(self.result_markdown.iter()) + .filter(|text| !text.trim().is_empty()) + .map(String::as_str) + .collect::>() + .join(" "); + return (!reason.is_empty()).then(|| format!("reason: {reason}")); } if self.status != "failed" { return None; @@ -73,6 +164,7 @@ pub struct ProjectEdit { pub run_command: Option, } +#[derive(serde::Deserialize)] pub struct RunListing { pub runs: Vec, pub titles: std::collections::HashMap, @@ -147,6 +239,39 @@ mod tests { } } + #[test] + fn contact_details_decode_the_v2_shape() { + for (contact, reason) in [ + ( + serde_json::json!({"type":"unreachable", "since":1000, "cause":"offline"}), + "offline", + ), + ( + serde_json::json!({"type":"needs_auth", "since":1000, "cause":"key rejected"}), + "key rejected", + ), + ( + serde_json::json!({"type":"unreconciled", "since":1000, "detail":"receipt unreadable"}), + "receipt unreadable", + ), + (serde_json::json!({"type":"live"}), ""), + ] { + let mut view = serde_json::to_value(stored_run("running", None)).unwrap(); + view["durationSecs"] = 1.into(); + view["updatedDisplay"] = "now".into(); + view["contact"] = contact.clone(); + let run: Run = serde_json::from_value(view).unwrap(); + if reason.is_empty() { + assert_eq!(run.contact_detail(), None); + } else { + let detail = run.contact_detail().unwrap(); + assert!(detail.contains(contact["type"].as_str().unwrap())); + assert!(detail.contains("1970-01-01T00:00:01")); + assert!(detail.contains(reason)); + } + } + } + #[test] fn stored_run_maps_to_cli_run() { let run = Run::from(&stored_run("done", None)); @@ -235,3 +360,63 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } } + +#[cfg(test)] +mod cancel_tests { + use super::*; + + #[test] + fn cli_labels_decode_the_v2_cancel_fields_without_replacing_the_phase() { + let mut value = serde_json::json!({ + "id": "run", "experimentId": "exp", "status": "running", "commitSha": null, + "durationSecs": 1, "updatedDisplay": "now", "resultMarkdown": null, "cancelReason": null, + "contact": {"type":"live"}, "cancelling": true, "host": "gpu-box", + }); + let run: Run = serde_json::from_value(value.clone()).unwrap(); + assert_eq!(run.status, "running"); + assert_eq!(run.display_status(), "Cancelling…"); + for contact in [ + serde_json::json!({"type":"unreachable", "since":1, "cause":"offline"}), + serde_json::json!({"type":"needs_auth", "since":1, "cause":"connect"}), + ] { + value["contact"] = contact; + let run: Run = serde_json::from_value(value.clone()).unwrap(); + assert_eq!(run.display_status(), "Cancellation pending"); + } + value["status"] = serde_json::json!("cancelled"); + value["cancelling"] = serde_json::json!(false); + value["contact"] = serde_json::json!({"type":"stopping", "since":1, "count":2}); + let run: Run = serde_json::from_value(value.clone()).unwrap(); + assert_eq!(run.status, "cancelled"); + assert_eq!( + run.display_status(), + "Not fully stopped · 2 processes still running on gpu-box" + ); + value["contact"] = serde_json::json!({"type":"stopping", "since":1, "count":1}); + let run: Run = serde_json::from_value(value.clone()).unwrap(); + assert_eq!( + run.display_status(), + "Not fully stopped · 1 process still running on gpu-box" + ); + assert_eq!(run.contact_detail(), None); + value["contact"] = serde_json::json!({"type":"live"}); + assert_eq!( + serde_json::from_value::(value.clone()) + .unwrap() + .display_status(), + "Cancelled" + ); + value["cancelUnconfirmed"] = serde_json::json!([789]); + value["resultMarkdown"] = "The host couldn't inspect process 789.".into(); + let run: Run = serde_json::from_value(value.clone()).unwrap(); + assert_eq!(run.display_status(), "Cancelled · couldn't confirm"); + assert!(run.failure_detail().unwrap().contains("process 789")); + value["resultMarkdown"] = "Edited".into(); + assert_eq!( + serde_json::from_value::(value) + .unwrap() + .display_status(), + "Cancelled · couldn't confirm" + ); + } +} diff --git a/src/plane/local_plane.rs b/src/plane/local_plane.rs index e37bcc69e..041b4145d 100644 --- a/src/plane/local_plane.rs +++ b/src/plane/local_plane.rs @@ -1,6 +1,5 @@ //! Local implementations of project, experiment, run, and log commands. -use std::collections::HashMap; use std::time::{Duration, Instant}; use super::{CreateExperimentSpec, DescInput, ProjectEdit, Run, RunListing}; @@ -43,17 +42,15 @@ impl LocalPlane { } pub async fn list_runs(&self) -> Result { - let store = &self.store; - let project_id = &self.id; - let titles: HashMap = store - .list_experiments_by_project(project_id)? - .into_iter() - .map(|e| (e.id.clone(), e.display_name().to_string())) - .collect(); - - let runs = store.list_runs_by_project(project_id)?; - let runs: Vec = runs.iter().map(Run::from).collect(); - Ok(RunListing { runs, titles }) + let value = ApiClient::discover() + .await? + .json( + reqwest::Method::GET, + &format!("runs?project={}", urlencoding::encode(&self.id)), + None, + ) + .await?; + Ok(serde_json::from_value(value)?) } pub async fn view_project(&self, all: bool) -> Result<()> { @@ -166,7 +163,8 @@ impl LocalPlane { match store.latest_run_for_experiment(&exp.id)? { Some(r) => { - let run = Run::from(&r); + let state = store.engine_run_state(&r.id)?; + let run = Run::from_store(store, &r)?; let commit = run .commit_sha .as_deref() @@ -175,12 +173,19 @@ impl LocalPlane { println!( " last run: {} ({}, commit {}, ran {}, updated {})", run.id, - run.status, + run.display_status(), commit, crate::output::format_duration(run.duration_secs), run.updated_display ); - if let Ok(backend) = crate::jobs::BackendDescriptor::parse(&r.backend_json) { + if let Some(detail) = run.contact_detail() { + println!(" {detail}"); + } + let launch = state.and_then(|state| state.launch); + let backend = crate::store::public_backend(&r.backend_json, launch.as_ref()) + .map(|backend| backend.to_string()) + .unwrap_or_default(); + if let Ok(backend) = crate::jobs::BackendDescriptor::parse(&backend) { if backend.kind == "slurm_job" { println!( " requested time limit: {}", @@ -223,6 +228,14 @@ impl LocalPlane { } // A forced relaunch can leave an older run live; monitoring alerts send agents here. for older in store.list_runs_by_experiment(&exp.id)?.iter().skip(1) { + let run = Run::from_store(store, older)?; + if matches!(run.contact, crate::store::Contact::Stopping { .. }) + || run.cancel_unconfirmed.is_some() + { + println!(" run {}: {}", run.id, run.display_status()); + } else if let Some(detail) = run.contact_detail() { + println!(" run {}: {detail}", run.id); + } if !matches!(older.status.as_str(), "starting" | "running") { continue; } @@ -258,86 +271,26 @@ impl LocalPlane { } pub async fn launch(&self, mut args: ExpRunArgs) -> Result<()> { - // Fill backend/flavor from the persisted default - // BEFORE the flag validations below, so e.g. `--host box1` with a default - // of `ssh` is a valid launch, and before `backend_label` is captured, so - // telemetry records the resolved backend. + // Resolved before validation so e.g. `--host box1` with a default of `ssh` is valid, + // and before telemetry records the backend. crate::local::apply_compute_default(&mut args.backend, &mut args.flavor); - if args.backend.is_none() { - args.backend = Some("local".to_string()); - } + let backend = args.backend.get_or_insert_with(|| "local".into()).clone(); crate::compute::validate_run_args(&args)?; - if let Some(backend) = args.backend.as_deref() { - warn_unreachable_trackio(backend); + warn_unreachable_trackio(&backend); + let experiment = self.experiment()?; + if let Some(warning) = self + .store + .get_local_project(&experiment.project_id)? + .and_then(|project| { + crate::local::experiments::legacy_root_warning(&project, experiment) + }) + { + eprintln!("{warning}"); } - args.agent_origin = crate::agent_origin(); - // Coarse backend label for analytics; the backend name is already an - // enum, never user data. Recorded before the (borrowing) dispatch below. - let backend_label = args.backend.clone(); - let result = match crate::local::chat::trusted_up_port()? { - Some(port) => { - let summary = crate::commands::up::submit_run_via_up(port, &args).await?; - let backend = args.backend.as_deref().unwrap_or("local"); - println!("\u{2713} {backend} run submitted by orx up."); - if let Some(job_id) = summary.job_id { - let label = if backend == "local" { "dir" } else { "job" }; - println!(" {label} {job_id}"); - } - if let Some(resources) = summary.slurm_resources { - println!(" {resources}"); - } - println!(" run {}", summary.run_id); - println!( - "{}", - crate::invocation::follow_up(&summary.experiment_id, &summary.run_id) - ); - Ok(()) - } - None => match args.backend.as_deref() { - Some("hf") => crate::local::hf::launch_local_hf(&args).await, - Some("modal") => crate::local::modal::launch_local_modal(&args).await, - Some("k8s") => crate::local::k8s::launch_local_k8s(&args).await, - Some("ssh") => crate::local::ssh::launch_local_ssh(&args).await, - Some("slurm") => crate::local::slurm::launch_local_slurm(&args).await, - Some("ray") => crate::local::ray::launch_local_ray(&args).await, - Some("vercel") => crate::local::vercel::launch_local_vercel(&args).await, - Some("openresearch") => { - crate::local::openresearch::launch_local_openresearch(&args).await - } - Some("tinker" | "local") => crate::local::localrun::launch_local_run(&args).await, - Some(other) => Err(anyhow!( - "Unknown --backend '{}'. Local experiments support: hf (Hugging Face Jobs), \ - modal (Modal serverless GPUs), k8s (your Kubernetes cluster), ssh (your own box), \ - slurm (your Slurm cluster), ray (a Ray Jobs cluster), \ - vercel (Vercel Sandbox microVMs), \ - openresearch (an ephemeral OpenResearch box), tinker (local controller with remote model compute), \ - local (this machine).", - other - )), - None => Err(anyhow!( - "No --backend given and no default compute target is set. \ - Configure a default compute target in OpenResearch, \ - or pass one per launch: \ - `--backend hf --flavor ` (e.g. --flavor a10g-small), \ - `--backend modal --flavor ` (e.g. --flavor a10g), \ - `--backend k8s` (runs the manifest committed on the branch — \ - default .orx/k8s.yaml, or --manifest ), \ - `--backend ssh --host ` (an ~/.ssh/config alias), \ - `--backend slurm [--host ] [--flavor h100:2]` (your Slurm cluster), \ - `--backend ray [--flavor gpu:1]` (a Ray Jobs cluster), \ - `--backend vercel [--flavor cpu-4]` (a Vercel Sandbox microVM, CPU-only), \ - `--backend openresearch --flavor ` (an ephemeral OpenResearch box, \ - e.g. --flavor h100_sxm or cpu5c; needs `orx login`), \ - `--backend tinker` (a local controller using remote Tinker model compute), \ - or `--backend local` (a detached process on this machine)." - )), - }, - }; + ApiClient::discover().await?.launch(args).await?; // Key event, fired only on a successful launch. Coarse backend only. - // Validation above guarantees a known backend before either dispatch path. - if result.is_ok() && backend_label.as_deref() != Some("openresearch") { - let target = backend_label.as_deref().unwrap_or("unknown"); - crate::telemetry::capture_experiment_started("run", true, Some(target)); + if backend != "openresearch" { + crate::telemetry::capture_experiment_started("run", true, Some(&backend)); // A launch out of the bundled demo is the clearest signal the demo // converted into real work, so it is counted separately. if let Some(label) = self.demo_run_label() { @@ -345,149 +298,32 @@ impl LocalPlane { crate::telemetry::capture_first_action("demo", "run_experiment"); } } - result - } - - pub async fn cancel(&self) -> Result<()> { - let store = &self.store; - let exp = self.experiment()?; - let in_flight: Vec<_> = store - .list_runs_by_experiment(&exp.id)? - .into_iter() - .filter(|r| !crate::local::is_terminal(&r.status)) - .collect(); - if in_flight.is_empty() { - return Err(anyhow!("No run in flight for this experiment.")); - } - let trusted_port = crate::local::chat::trusted_up_port()?; - for r in &in_flight { - match trusted_port { - Some(port) => crate::commands::up::cancel_run_via_up(port, &r.id).await?, - None => crate::commands::exp::request_local_run_cancel( - store, - &r.id, - &crate::commands::exp::exp_cancel_reason( - crate::local::chat::launching_chat_session().as_deref(), - ), - )?, - } - println!("\u{2713} Cancel requested for run {}.", r.id); - } Ok(()) } - pub async fn wait_experiment(&self, interval: Duration, deadline: Instant) -> Result<()> { - let store = &self.store; - let exp_id = &self.id; - let mut last_status: Option = None; - let mut lock_notified = false; - loop { - store.set_busy_timeout(busy_timeout_left(deadline))?; - let run = match store.latest_run_for_experiment(exp_id) { - Ok(run) => run, - Err(error) if is_db_locked(&error) => { - note_db_locked(&mut lock_notified); - sleep_until_or_timeout(interval, deadline).await?; - continue; - } - Err(error) => return Err(error), - }; - match run { - None => { - if last_status.is_none() { - eprintln!("No run yet for this experiment — waiting for one to start…"); - last_status = Some(String::new()); - } - } - Some(r) => { - if last_status.as_deref() != Some(r.status.as_str()) { - eprintln!("{} {}", r.id, r.status); - last_status = Some(r.status.clone()); - } - if crate::local::is_terminal(&r.status) { - let run = Run::from(&r); - println!("{} {}", run.id, run.status); - if let Some(detail) = run.failure_detail() { - eprintln!("{detail}"); - } - return Ok(()); - } - } - } - sleep_until_or_timeout(interval, deadline).await?; - } + pub async fn cancel(&self, run: Option<&str>) -> Result<()> { + ApiClient::discover() + .await? + .cancel(Some(&self.id), run) + .await } - pub async fn wait_project(&self, interval: Duration, deadline: Instant) -> Result<()> { - let store = &self.store; - let project_id = &self.id; - let snapshot: HashMap = retry_on_db_lock( - || { - store.set_busy_timeout(busy_timeout_left(deadline))?; - store.list_runs_by_project(project_id) - }, - interval, - deadline, - ) - .await? - .into_iter() - .map(|r| (r.id, r.status)) - .collect(); - let in_flight = snapshot - .values() - .filter(|s| !crate::local::is_terminal(s)) - .count(); - - if in_flight == 0 { - eprintln!( - "No runs in flight in this project ({} run(s), all terminal).", - snapshot.len() - ); - println!("drained: no runs in flight"); - return Ok(()); - } - - eprintln!( - "Watching {} run(s) in project ({} in flight) — returning on the first completion…", - snapshot.len(), - in_flight - ); - - let mut lock_notified = false; - loop { - sleep_until_or_timeout(interval, deadline).await?; - - store.set_busy_timeout(busy_timeout_left(deadline))?; - let current = match store.list_runs_by_project(project_id) { - Ok(current) => current, - Err(error) if is_db_locked(&error) => { - note_db_locked(&mut lock_notified); - continue; - } - Err(error) => return Err(error), - }; - let mut completed: Vec<(String, Option)> = Vec::new(); - for r in ¤t { - if !crate::local::is_terminal(&r.status) { - continue; - } - let line = match snapshot.get(&r.id) { - Some(prev) if crate::local::is_terminal(prev) => continue, - Some(prev) => format!("{} {} -> {}", r.id, prev, r.status), - None => format!("{} {} (new)", r.id, r.status), - }; - completed.push((line, Run::from(r).failure_detail())); - } - if !completed.is_empty() { - for (line, detail) in &completed { - println!("{line}"); - if let Some(detail) = detail { - eprintln!("{detail}"); - } - } - return Ok(()); - } - } + /// One SSE request held until the condition; nothing polls. + pub async fn wait(&self, deadline: Instant) -> Result<()> { + let filter = crate::commands::up::api_v2::Filter { + experiment: self + .experiment + .as_ref() + .map(|experiment| experiment.id.clone()), + project: self.project.as_ref().map(|project| project.id.clone()), + wait: true, + ..Default::default() + }; + tokio::time::timeout(deadline.saturating_duration_since(Instant::now()), async { + ApiClient::discover().await?.wait(filter).await + }) + .await + .map_err(|_| anyhow!("Timed out waiting for a run state change."))? } // --- create-experiment ------------------------------------------------ @@ -577,6 +413,28 @@ impl LocalPlane { } } +fn experiment_wait_progress(run: Option<(&str, &str)>, last_status: &mut Option) { + match run { + Some((id, status)) if last_status.as_deref() != Some(status) => { + eprintln!("{id} {status}"); + *last_status = Some(status.into()); + } + None if last_status.is_none() => { + eprintln!("No run yet for this experiment — waiting for one to start…"); + *last_status = Some(String::new()); + } + _ => {} + } +} + +fn project_wait_progress(total: usize, in_flight: usize) { + if in_flight == 0 { + eprintln!("No runs in flight in this project ({total} run(s), all terminal)."); + } else { + eprintln!("Watching {total} run(s) in project ({in_flight} in flight) — returning on the first completion…"); + } +} + fn warn_unreachable_trackio(backend: &str) { use crate::local::trackio::{self, Target}; if !crate::compute::backend(backend).is_ok_and(|b| b.capabilities().remote) { @@ -656,6 +514,510 @@ async fn sleep_until_or_timeout(interval: Duration, deadline: Instant) -> Result Ok(()) } +#[derive(Clone)] +pub(crate) struct ApiClient { + server: crate::commands::remote_host::ServerDescriptor, + http: reqwest::Client, +} + +impl ApiClient { + pub async fn discover() -> Result { + Self::new(crate::commands::remote_host::discover().await?) + } + + pub(crate) fn new(server: crate::commands::remote_host::ServerDescriptor) -> Result { + Ok(Self { + server, + http: crate::net::loopback_client().build()?, + }) + } + + pub fn request(&self, method: reqwest::Method, path: &str) -> reqwest::RequestBuilder { + self.http + .request( + method, + format!("http://127.0.0.1:{}/api/v2/{path}", self.server.port), + ) + .bearer_auth(&self.server.token) + } + + pub async fn json( + &self, + method: reqwest::Method, + path: &str, + body: Option<&serde_json::Value>, + ) -> Result { + let request = |client: &Self| { + let mut request = client.request(method.clone(), path); + if let Some(body) = body { + request = request.json(body); + } + request + }; + let response = request(self).send().await; + let retry = match &response { + Ok(response) => response.status() == reqwest::StatusCode::SERVICE_UNAVAILABLE, + Err(error) => { + error.is_connect() || method == reqwest::Method::GET && error.is_request() + } + }; + let response = if retry { + drop(response); + request(&Self::discover().await?).send().await? + } else { + response? + }; + if !response.status().is_success() { + return Err(anyhow!("{}", response.text().await?)); + } + Ok(response.json().await?) + } + + pub async fn connect( + &self, + mut body: serde_json::Value, + prompt: crate::engine::transport::Prompt, + ) -> Result { + use axum::response::IntoResponse as _; + use sha2::{Digest as _, Sha256}; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?; + let token = format!("{}{}", uuid::Uuid::new_v4(), uuid::Uuid::new_v4()); + body["prompt"] = serde_json::json!({"port":listener.local_addr()?.port(), "token":token}); + let auth = crate::commands::remote_host::RemoteAuth::new(&token); + let app = axum::Router::new().route( + "/prompt", + axum::routing::post( + move |headers: axum::http::HeaderMap, axum::Json(question): axum::Json| { + let auth = auth.clone(); + let prompt = prompt.clone(); + async move { + let authorized = headers + .get("authorization") + .and_then(|value| value.to_str().ok()) + .and_then(|value| value.strip_prefix("Bearer ")) + .is_some_and(|token| { + auth.matches_callback(&Sha256::digest(token.as_bytes())) + }); + if !authorized { + return axum::http::StatusCode::UNAUTHORIZED.into_response(); + } + match prompt(question).await { + Ok(answer) => axum::Json(answer).into_response(), + Err(error) => (axum::http::StatusCode::BAD_REQUEST, error.to_string()) + .into_response(), + } + } + }, + ), + ); + let mut server = tokio::task::JoinSet::new(); + server.spawn(async move { axum::serve(listener, app).await }); + self.json(reqwest::Method::POST, "compute/connect", Some(&body)) + .await + } + + pub async fn launch(&self, mut args: ExpRunArgs) -> Result<()> { + args.chat_session_id = args.launching_chat_session(); + args.agent_origin = crate::agent_origin(); + args.caller_config_dir = Some(crate::commands::up::absolute_config_dir()); + args.invocation_context = args + .invocation_identity()? + .map(|identity| serde_json::to_string(&identity)) + .transpose()?; + let run: Run = serde_json::from_value( + self.json( + reqwest::Method::POST, + "runs", + Some(&serde_json::to_value(args)?), + ) + .await?, + )?; + if run.status == "failed" { + return Err(anyhow!( + "Compute submission failed for run {}: {}", + run.id, + run.failure_detail() + .unwrap_or_else(|| "no reason recorded".into()) + )); + } + println!("\u{2713} Run {} submitted ({}).", run.id, run.status); + println!( + "{}", + crate::invocation::follow_up(&run.experiment_id, &run.id) + ); + Ok(()) + } + + pub async fn abandon(&self, run: &str) -> Result<()> { + let path = format!("runs/{}", urlencoding::encode(run)); + let response = self.json(reqwest::Method::GET, &path, None).await?; + if response["contact"]["type"] == "unreachable" { + eprint!("{} ", super::LABELS["run_abandon_unreachable"]); + } + eprintln!("{}", super::LABELS["run_abandon_body"]); + self.json(reqwest::Method::POST, &format!("{path}/abandon"), None) + .await?; + println!("Run {run} abandoned; its cancel stays pending until the job is confirmed gone."); + Ok(()) + } + + pub async fn cancel(&self, experiment: Option<&str>, selected: Option<&str>) -> Result<()> { + let path = match (experiment, selected) { + (_, Some(run)) => format!("runs/{}", urlencoding::encode(run)), + (Some(experiment), None) => { + format!("runs?experiment={}", urlencoding::encode(experiment)) + } + (None, None) => return Err(anyhow!("Pass an experiment id or --run .")), + }; + let response = self.json(reqwest::Method::GET, &path, None).await?; + let rows = if selected.is_some() { + if experiment + .is_some_and(|experiment| response["experimentId"].as_str() != Some(experiment)) + { + return Err(anyhow!("Run does not belong to this experiment.")); + } + vec![response] + } else { + response["runs"] + .as_array() + .ok_or_else(|| anyhow!("Server returned no runs"))? + .clone() + }; + let in_flight: Vec<_> = rows + .iter() + .filter(|run| { + !crate::engine::Phase::parse(run["status"].as_str().unwrap_or_default()) + .is_some_and(crate::engine::Phase::is_terminal) + }) + .map(|run| { + run["id"] + .as_str() + .ok_or_else(|| anyhow!("Server returned no run id")) + }) + .collect::>()?; + if in_flight.is_empty() { + return Err(match selected { + Some(id) => anyhow!("Run {id} has already finished."), + None => anyhow!("No run in flight for this experiment."), + }); + } + println!("Cancelling runs:"); + for id in &in_flight { + println!(" {id}"); + } + for id in in_flight { + let request = serde_json::json!({ + "chatSessionId": crate::local::chat::launching_chat_session(), + }); + self.json( + reqwest::Method::POST, + &format!("runs/{}/cancel", urlencoding::encode(id)), + Some(&request), + ) + .await?; + println!("\u{2713} Cancel requested for run {id}."); + } + Ok(()) + } + + pub async fn wait(&self, filter: crate::commands::up::api_v2::Filter) -> Result<()> { + use futures::StreamExt; + let mut client = self.clone(); + let mut original_in_flight: Option> = None; + let mut last_status = None; + loop { + let mut events = client.events(&filter).await?; + while let Some(event) = events.next().await { + let mut value = match event { + Ok(value) => value, + Err(error) + if error.chain().any(|cause| { + cause.is::() || cause.is::() + }) => + { + break + } + Err(error) => return Err(error), + }; + if let Some(rows) = value["snapshot"].as_array() { + let first = original_in_flight.is_none(); + let original = original_in_flight.get_or_insert_with(|| { + rows.iter() + .filter(|run| { + !crate::engine::Phase::parse( + run["status"].as_str().unwrap_or_default(), + ) + .is_some_and(crate::engine::Phase::is_terminal) + }) + .filter_map(|run| run["id"].as_str().map(str::to_owned)) + .collect() + }); + if filter.project.is_some() { + if first { + project_wait_progress(rows.len(), original.len()); + } + if let Some(run) = rows.iter().find(|run| { + run["id"].as_str().is_some_and(|id| original.contains(id)) + && crate::engine::Phase::parse( + run["status"].as_str().unwrap_or_default(), + ) + .is_some_and(crate::engine::Phase::is_terminal) + }) { + value = run.clone(); + } else if first && original.is_empty() { + println!("drained: no runs in flight"); + return Ok(()); + } else { + continue; + } + } else if let Some(run) = rows.first() { + value = run.clone(); + } else { + experiment_wait_progress(None, &mut last_status); + continue; + } + } + if value["drained"] == true { + println!("drained: no runs in flight"); + return Ok(()); + } + let run: Run = serde_json::from_value(value)?; + if crate::engine::Phase::parse(&run.status) + .is_some_and(crate::engine::Phase::is_terminal) + { + println!("{} {}", run.id, run.display_status()); + if let Some(detail) = run.contact_detail() { + eprintln!("{detail}"); + } + if let Some(detail) = run.failure_detail() { + eprintln!("{detail}"); + } + return Ok(()); + } + if filter.project.is_none() { + experiment_wait_progress( + Some((&run.id, &run.display_status())), + &mut last_status, + ); + } + } + drop(events); + client = Self::discover().await?; + } + } + + pub async fn events( + &self, + filter: &crate::commands::up::api_v2::Filter, + ) -> Result>> { + use futures::{StreamExt, TryStreamExt}; + let response = self + .request(reqwest::Method::GET, "events") + .query(filter) + .send() + .await; + let retry = match &response { + Ok(response) => response.status() == reqwest::StatusCode::SERVICE_UNAVAILABLE, + Err(error) => error.is_connect() || error.is_request(), + }; + let response = if retry { + drop(response); + Self::discover() + .await? + .request(reqwest::Method::GET, "events") + .query(filter) + .send() + .await? + } else { + response? + }; + if !response.status().is_success() { + return Err(anyhow!("{}", response.text().await?)); + } + let stream = response.bytes_stream().map_err(std::io::Error::other); + let reader = tokio_util::io::StreamReader::new(stream); + let lines = tokio::io::AsyncBufReadExt::lines(tokio::io::BufReader::new(reader)); + Ok(futures::stream::try_unfold( + (lines, String::new(), String::new()), + |(mut lines, mut data, mut kind)| async move { + while let Some(line) = lines.next_line().await? { + if line.is_empty() { + if data.is_empty() { + kind.clear(); + continue; + } + if kind == "error" { + return Err(anyhow!("{data}")); + } + if !matches!(kind.as_str(), "run" | "snapshot") { + data.clear(); + kind.clear(); + continue; + } + let value: serde_json::Value = serde_json::from_str(&data)?; + return Ok(Some((value, (lines, String::new(), String::new())))); + } + if let Some(value) = line.strip_prefix("data:") { + if !data.is_empty() { + data.push('\n'); + } + data.push_str(value.strip_prefix(' ').unwrap_or(value)); + } else if let Some(value) = line.strip_prefix("event:") { + kind = value.trim().into(); + } + if data.len() > 2 * 1024 * 1024 { + return Err(anyhow!("Server event exceeds 2 MiB")); + } + } + Ok(None) + }, + ) + .boxed()) + } + + pub async fn logs(&self, id: &str, follow: bool) -> Result<()> { + self.logs_to(id, follow, &mut std::io::stdout()).await + } + + pub(crate) async fn logs_to( + &self, + id: &str, + follow: bool, + output: &mut (impl std::io::Write + Send), + ) -> Result<()> { + use futures::StreamExt; + let filter = crate::commands::up::api_v2::Filter { + run: Some(id.into()), + follow: true, + ..Default::default() + }; + let mut client = self.clone(); + let mut events = if follow { + Some(client.events(&filter).await?) + } else { + None + }; + let mut cursor = 0; + let mut identity: Option = None; + let mut finished = !follow; + let mut backoff = Duration::from_millis(250); + 'follow: loop { + let mut reset = false; + loop { + let mut request = client + .request( + reqwest::Method::GET, + &format!("runs/{}/log", urlencoding::encode(id)), + ) + .timeout(Duration::from_secs(35)) + .query(&[ + ("start", cursor), + ("end", cursor + orx_host_proto::MAX_PAGE_LEN), + ]); + if let Some(ident) = &identity { + request = request.query(&[("ident", String::from(ident.clone()))]); + } + let response = match request.send().await { + Ok(response) => response, + Err(error) + if follow + && (error.is_connect() || error.is_request() || error.is_body()) => + { + client = Self::discover().await?; + events = Some(client.events(&filter).await?); + continue 'follow; + } + Err(error) => return Err(error.into()), + }; + if follow && response.status() == reqwest::StatusCode::SERVICE_UNAVAILABLE { + drop(response); + tokio::time::sleep(backoff).await; + backoff = (backoff * 2).min(Duration::from_secs(5)); + continue; + } + if !response.status().is_success() { + return Err(anyhow!("{}", response.text().await?)); + } + let bytes = match response.bytes().await { + Ok(bytes) => bytes, + Err(error) if follow && error.is_body() => { + client = Self::discover().await?; + events = Some(client.events(&filter).await?); + continue 'follow; + } + Err(error) => return Err(error.into()), + }; + backoff = Duration::from_millis(250); + let page: crate::engine::LogPage = serde_json::from_slice(&bytes)?; + match page { + crate::engine::LogPage::Data { + len: _, + ident, + start, + bytes, + eof, + } => { + if start != cursor + || identity.as_ref().is_some_and(|expected| *expected != ident) + { + return Err(anyhow!( + "Server returned an unexpected log generation or offset" + )); + } + identity = Some(ident); + output.write_all(&bytes)?; + cursor += bytes.len() as u64; + if eof || bytes.is_empty() { + break; + } + } + crate::engine::LogPage::Reset { info } => { + if reset { + return Err(anyhow!("Log keeps changing; try again")); + } + reset = true; + if cursor != 0 || identity.is_some() { + writeln!(output, "\n[log replaced; starting new generation]")?; + } + cursor = 0; + identity = info.as_ref().map(|info| info.ident.clone()); + if info.is_none() { + break; + } + } + } + } + output.flush()?; + if finished { + return Ok(()); + } + let event = events + .as_mut() + .expect("following has an event stream") + .next() + .await; + match event { + Some(Ok(event)) => { + finished = + crate::engine::Phase::parse(event["status"].as_str().unwrap_or_default()) + .is_some_and(crate::engine::Phase::is_terminal) + } + Some(Err(error)) + if !error.chain().any(|cause| { + cause.is::() || cause.is::() + }) => + { + return Err(error) + } + _ => { + client = Self::discover().await?; + events = Some(client.events(&filter).await?); + } + } + } + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/src/store.rs b/src/store.rs index 8325f3780..6a32fd876 100644 --- a/src/store.rs +++ b/src/store.rs @@ -33,16 +33,7 @@ pub struct SessionExperiment { /// Its newest live run, else its newest run; `None` until it has been run. /// A forced relaunch can leave an older run live, so the newest run alone /// could hide work still in flight. - pub current_run: Option, -} - -#[derive(Debug, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct SessionExperimentRun { - pub status: String, - pub cancel_requested: bool, - pub created_at: i64, - pub ended_at: Option, + pub current_run: Option, } pub fn data_dir() -> PathBuf { @@ -249,13 +240,13 @@ pub fn human_bytes(n: u64) -> String { format!("{:.1} {}", size, UNITS[unit]) } -pub fn log_path(run_id: &str) -> PathBuf { +pub fn log_path(data_dir: &Path, run_id: &str) -> PathBuf { // Sanitize the id so malformed local data cannot escape the log directory. let safe: String = run_id .chars() .filter(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_') .collect(); - data_dir().join("run-logs").join(format!("{safe}.log")) + data_dir.join("run-logs").join(format!("{safe}.log")) } /// A locally tracked run. `backend_json` stores the backend descriptor used by @@ -279,7 +270,6 @@ pub struct StoredRun { pub result_markdown: Option, /// Cancel intent polled by the detached supervisor. pub cancel_requested: bool, - /// Who asked for the cancel; written only by `Store::request_cancel`, never by `upsert_run`. pub cancel_reason: Option, /// The `orx up` chat session that launched this run, when it was started by /// an agent harness child (which exports `ORX_CHAT_SESSION_ID`). `None` for @@ -288,10 +278,146 @@ pub struct StoredRun { pub chat_session_id: Option, } -pub fn public_backend(value: &str) -> Option { +pub const TERMINAL: &str = "terminal"; +pub const ATTENTION: &str = "attention"; +pub const RECOVERED: &str = "recovered"; +pub const NOTIFY: &str = "notify"; +const TERMINAL_LOG_BYTES: u64 = 4 * 1024; +const TERMINAL_LOG_LINES: usize = 40; + +pub struct SubmittingRun<'a> { + pub id: &'a str, + pub experiment_id: &'a str, + pub project_id: &'a str, + pub metadata: &'a crate::jobs::BackendDescriptor, + pub command: &'a str, + pub created_at: i64, + pub commit_sha: Option<&'a str>, + pub chat_session_id: Option<&'a str>, + pub spec_digest: &'a str, + pub launch: &'a LaunchSpec, +} + +/// Where and how a run launches, durable from its first transaction so recovery after a +/// restart can find the job. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct LaunchSpec { + /// Backend kind, e.g. `ssh_job`. + pub kind: String, + /// Host alias, cluster, namespace or account, as the backend names it. + pub target: Option, + pub options: serde_json::Value, +} + +/// A run row's `(status, updated_at)` as last seen. +pub type SeenRow = (String, i64); + +/// Notify-file bytes already turned into notices, with the file they came from. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct NotifyCursor { + pub ident: orx_host_proto::FileIdent, + pub offset: u64, + /// Bumped whenever the file is replaced or truncated, so offsets never collide across files. + pub generation: u64, +} + +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum Contact { + Live, + Unreachable { since: i64, cause: String }, + NeedsAuth { since: i64, cause: String }, + Unreconciled { since: i64, detail: String }, + Stopping { since: i64, count: usize }, +} + +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct SubmitterIdentity { + pub pid: u32, + pub starttime: u64, +} + +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct SubmissionFence { + pub taken_at: i64, + pub submitter: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct EngineRunState { + pub started_at: Option, + pub contact: Contact, + pub cancel_unconfirmed: Option>, + pub spec_digest: Option, + pub submission_attempt: u32, + pub submission_fence: Option, + pub cancel_accepted_at: Option, + /// Present on every runner-2 row. + pub launch: Option, + pub notify_cursor: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RunNotice { + pub id: i64, + pub run_id: String, + pub chat_session_id: String, + pub kind: String, + pub dedupe: String, + pub body: String, + pub created_at: i64, + pub client_turn_id: String, +} + +/// The descriptor a run shows, without secrets. An engine run reads as the 0.2.x descriptor of +/// what it launched: its OpenResearch box's own, else the fields its launch intent decided. +pub fn public_backend(value: &str, launch: Option<&LaunchSpec>) -> Option { let mut backend = serde_json::from_str::(value).ok()?; - if let Some(fields) = backend.as_object_mut() { - fields.remove("rentalLease"); + let Some(fields) = backend.as_object_mut() else { + return Some(backend); + }; + if fields.get("kind").and_then(serde_json::Value::as_str) == Some("engine") { + let descriptor = fields + .get("handle") + .and_then(|handle| handle.get("descriptor")) + .and_then(serde_json::Value::as_object) + .cloned(); + if let Some(descriptor) = descriptor { + for (field, value) in descriptor { + if field == "kind" || !fields.contains_key(&field) { + fields.insert(field, value); + } + } + } else if let Some(launch) = launch { + let options = &launch.options; + let directives = &options["directives"]; + let cpus = directives["cpus-per-task"] + .as_str() + .and_then(|cpus| cpus.parse::().ok()); + let derived = [ + ("kind", serde_json::json!(launch.kind)), + ("namespace", serde_json::json!(launch.target)), + ("flavor", options["flavor"].clone()), + ("sshContainer", options["container"].clone()), + ("context", options["context"].clone()), + ("timeoutSecs", options["timeout_seconds"].clone()), + ("cpusPerTask", serde_json::json!(cpus)), + ("mem", directives["mem"].clone()), + ]; + for (field, value) in derived { + if !value.is_null() { + fields.insert(field.into(), value); + } + } + } + } + fields.remove("rentalLease"); + if let Some(descriptor) = fields + .get_mut("handle") + .and_then(|handle| handle.get_mut("descriptor")) + .and_then(serde_json::Value::as_object_mut) + { + descriptor.remove("rentalLease"); } Some(backend) } @@ -301,7 +427,7 @@ fn serialize_public_backend( serializer: S, ) -> Result { serializer.serialize_str( - &public_backend(value) + &public_backend(value, None) .map(|value| value.to_string()) .unwrap_or_default(), ) @@ -403,21 +529,6 @@ pub struct ProjectActivitySummary { pub last_activity_at: i64, } -#[derive(Debug, Clone)] -pub struct RunWakeup { - pub run: StoredRun, - pub chat_session_id: String, - pub state: String, - pub monitoring_alerted: bool, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum RunWakeupRegistration { - Scheduled, - AlreadyPending, - AlreadyDelivered, -} - #[derive(Debug, Clone, PartialEq, Eq)] pub struct Delegation { pub depth: u32, @@ -457,6 +568,8 @@ pub struct ReadyChatSubscription { told_turn_id: Option, } +const CHAT_SUBSCRIPTION_CLAIM_TTL_MS: i64 = 60 * 1000; + /// Each subscription with its target's latest turn and whether the target is /// idle after it: done, and with nothing queued unless a stop held the queue. const LATEST_SUBSCRIBED_TURNS: &str = "subscribed AS ( @@ -479,7 +592,6 @@ latest AS ( SELECT *, NOT (idle IS 1 AND told_turn_id IS turn_id) AS pending FROM subscribed )"; -const RUN_WAKEUP_CLAIM_TTL_MS: i64 = 60 * 1000; pub(crate) const CHAT_TURN_LEASE_TTL_MS: i64 = 60 * 1000; fn migrate_chat_spawns(conn: &Connection) -> Result<()> { @@ -583,17 +695,28 @@ const SLIMMED_RUN_PATHS: [&[&str]; 2] = [&["repo", ".venv"], &["repo", ".cache", const SUBMISSION_HANDLE: (&str, &str) = ("submission-handles", ".json"); const SUPERVISOR_LOCK: (&str, &str) = ("run-logs", ".supervisor.lock"); +const CANCEL_LOCK: (&str, &str) = ("run-logs", ".cancel.lock"); +const SHARED_SSH_LOCK: (&str, &str) = ("run-logs", ".supervisor.shared-ssh.lock"); +/// The kept end of an engine run's log too large to keep whole. +const TAIL_LOG: (&str, &str) = ("run-logs", ".tail.log"); /// Per-run files as (data-dir root, name suffix); the supervisor lock goes last so it excludes until the end. -const RUN_ARTIFACTS: [(&str, &str); 11] = [ +const RUN_ARTIFACTS: [(&str, &str); 18] = [ ("local-runs", ""), ("run-logs", ".log"), + ("run-logs", ".spool.log"), + ("run-logs", ".log.part"), + ("run-logs", ".log.part.json"), + TAIL_LOG, + ("run-logs", ".tail.log.part"), + ("run-logs", ".tail.log.part.json"), + ("run-logs", ".ranges.json"), ("run-logs", ".cursor.json"), ("run-logs", ".pending.json"), ("run-logs", ".cursor.lock"), - ("run-logs", ".supervisor.shared-ssh.lock"), + SHARED_SSH_LOCK, ("run-logs", ".supervisor.log"), ("run-logs", ".supervisor.log.1"), - ("run-logs", ".cancel.lock"), + CANCEL_LOCK, SUBMISSION_HANDLE, SUPERVISOR_LOCK, ]; @@ -619,20 +742,36 @@ pub(crate) struct RemoteCleanup { pub deleted: bool, } -/// `(id, status)` of runs of `kinds` past each project's newest [`FULL_RUNS_PER_PROJECT`]. -fn runs_past_newest(kinds: &'static str) -> String { +/// Runs whose job ran in `/local-runs/`, from 0.2.x or the engine. +const LOCAL_RUNS: &str = "CASE WHEN json_valid(backend_json) THEN + json_extract(backend_json, '$.kind') IN ('local_job', 'tinker_job') + OR json_extract(backend_json, '$.handle.type') IN ('Local', 'Tinker') END"; +/// Runs that left a run dir on an SSH or Slurm host, from 0.2.x or the engine. +const REMOTE_RUNS: &str = "CASE WHEN json_valid(backend_json) THEN + json_extract(backend_json, '$.kind') IN ('ssh_job', 'slurm_job') + OR json_extract(backend_json, '$.handle.type') IN ('Ssh', 'Slurm') END"; + +/// `(id, status)` of runs matching `runs` past each project's newest [`FULL_RUNS_PER_PROJECT`]. +fn runs_past_newest(runs: &'static str) -> String { format!( "SELECT id, status FROM ( SELECT id, status, ROW_NUMBER() OVER (PARTITION BY project_id ORDER BY created_at DESC, id DESC) AS position FROM runs - WHERE CASE WHEN json_valid(backend_json) THEN json_extract(backend_json, '$.kind') END - IN ({kinds})) + WHERE {runs}) WHERE position > {FULL_RUNS_PER_PROJECT}" ) } +fn remote_cleanup_eligibility() -> String { + format!("NOT EXISTS (SELECT 1 FROM runs WHERE id = run_id AND + (contact IS NOT NULL OR status IN ('submitting','starting','running'))) + AND NOT EXISTS (SELECT 1 FROM log_collections WHERE run_id = remote_cleanups.run_id AND done = 0) + AND (deleted = 1 OR run_id IN (SELECT id FROM ({})))", runs_past_newest(REMOTE_RUNS)) +} + /// Queues the SSH/Slurm runs whose `column` equals `value`; deletion wins over a pending finish. +/// An engine run's entry carries its container from the launch intent, which a deletion removes. fn queue_remote_cleanups( conn: &Connection, column: &'static str, @@ -642,9 +781,10 @@ fn queue_remote_cleanups( conn.execute( &format!( "INSERT INTO remote_cleanups (run_id, backend_json, deleted, next_attempt_at) - SELECT id, backend_json, ?2, ?3 FROM runs - WHERE {column} = ?1 AND CASE WHEN json_valid(backend_json) - THEN json_extract(backend_json, '$.kind') END IN ('ssh_job', 'slurm_job') + SELECT id, CASE WHEN json_extract(launch_spec, '$.options.container') IS NULL + THEN backend_json ELSE json_set(backend_json, '$.sshContainer', + json(json_extract(launch_spec, '$.options.container'))) END, ?2, ?3 + FROM runs WHERE {column} = ?1 AND {REMOTE_RUNS} ON CONFLICT(run_id) DO UPDATE SET backend_json = excluded.backend_json, deleted = MAX(deleted, excluded.deleted), attempts = 0, next_attempt_at = excluded.next_attempt_at" @@ -668,6 +808,11 @@ fn validate_deleted_runs(runs: &[StoredRun]) -> Result<()> { Ok(()) } +/// Log collection retries after a minute, doubling to an hour, then hourly. +const LOG_COLLECTION_RETRY_MS: i64 = 60 * 1000; +const LOG_COLLECTION_MAX_RETRY_MS: i64 = 60 * 60 * 1000; +/// Failures before retries reach the cap and the collection reads as failed. +const LOG_COLLECTION_FAILED_AFTER: u32 = 7; /// Failed remote cleanups retry after 5 minutes, doubling up to a day. const REMOTE_CLEANUP_RETRY_MS: i64 = 5 * 60 * 1000; const REMOTE_CLEANUP_MAX_RETRY_MS: i64 = 24 * 60 * 60 * 1000; @@ -714,14 +859,6 @@ impl Store { Self::open_at_with_move_lock(dir, move_lock_path, BUSY_TIMEOUT) } - /// Shrink this connection's lock wait (e.g. to a wait loop's remaining - /// deadline). The next call can pass the default back to restore it. - pub(crate) fn set_busy_timeout(&self, timeout: Duration) -> Result<()> { - self.conn - .pragma_update(None, "busy_timeout", timeout.as_millis() as u64)?; - Ok(()) - } - fn open_at_with_move_lock( dir: PathBuf, data_dir_move_lock_path: PathBuf, @@ -737,10 +874,32 @@ impl Store { std::fs::create_dir_all(dir.join("run-logs")) .map_err(|e| anyhow!("Could not create {}: {}", dir.display(), e))?; let conn = Connection::open(dir.join("orx.db"))?; + let has_floor: bool = conn.query_row( + "SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'store_metadata')", + [], + |row| row.get(0), + )?; + if has_floor { + let floor: Option = conn + .query_row( + "SELECT value FROM store_metadata WHERE key = 'min_reader_version'", + [], + |row| row.get(0), + ) + .optional()?; + if let Some(floor) = floor.filter(|floor| *floor > 1) { + return Err(anyhow!("This database requires a newer OpenResearch reader (min_reader_version {}). Update orx before opening it.", floor)); + } + } conn.pragma_update(None, "journal_mode", "WAL")?; conn.pragma_update(None, "busy_timeout", busy_timeout.as_millis() as u64)?; conn.execute_batch( - "CREATE TABLE IF NOT EXISTS runs ( + "CREATE TABLE IF NOT EXISTS store_metadata ( + key TEXT PRIMARY KEY, + value INTEGER NOT NULL + ); + INSERT OR IGNORE INTO store_metadata (key, value) VALUES ('min_reader_version', 1); + CREATE TABLE IF NOT EXISTS runs ( id TEXT PRIMARY KEY, experiment_id TEXT NOT NULL, project_id TEXT NOT NULL, @@ -752,6 +911,46 @@ impl Store { ended_at INTEGER, exit_code INTEGER ); + CREATE TABLE IF NOT EXISTS engine_host_auth ( + alias TEXT PRIMARY KEY, + state_json TEXT NOT NULL + ); + CREATE TABLE IF NOT EXISTS engine_hosts ( + alias TEXT NOT NULL, + root TEXT NOT NULL, + state_json TEXT NOT NULL, + PRIMARY KEY(alias, root) + ); + CREATE TABLE IF NOT EXISTS run_subscriptions ( + run_id TEXT NOT NULL, + chat_session_id TEXT NOT NULL, + created_at INTEGER NOT NULL, + PRIMARY KEY(run_id, chat_session_id) + ); + CREATE TABLE IF NOT EXISTS run_notices ( + id INTEGER PRIMARY KEY, + run_id TEXT NOT NULL, + chat_session_id TEXT NOT NULL, + kind TEXT NOT NULL, + dedupe TEXT NOT NULL, + body TEXT NOT NULL, + created_at INTEGER NOT NULL, + client_turn_id TEXT, + delivered_at INTEGER, + delivery_failures INTEGER NOT NULL DEFAULT 0, + first_failure_at INTEGER, + next_delivery_at INTEGER, + delivery_error TEXT, + retired_at INTEGER, + UNIQUE(run_id, chat_session_id, dedupe) + ); + CREATE INDEX IF NOT EXISTS idx_run_notices_pending + ON run_notices(chat_session_id, client_turn_id, id) WHERE delivered_at IS NULL; + CREATE TABLE IF NOT EXISTS legacy_watches ( + run_id TEXT PRIMARY KEY, + seen_status TEXT, + seen_updated_at INTEGER + ); CREATE TABLE IF NOT EXISTS native_invocation_identities ( harness TEXT NOT NULL, call_id TEXT NOT NULL, @@ -960,6 +1159,14 @@ impl Store { next_attempt_at INTEGER NOT NULL, last_error TEXT ); + CREATE TABLE IF NOT EXISTS log_collections ( + run_id TEXT PRIMARY KEY, + collected INTEGER NOT NULL DEFAULT 0, + done INTEGER NOT NULL DEFAULT 0, + attempts INTEGER NOT NULL DEFAULT 0, + next_attempt_at INTEGER NOT NULL DEFAULT 0, + last_error TEXT + ); CREATE TABLE IF NOT EXISTS remote_source_sweeps ( host TEXT NOT NULL, root TEXT NOT NULL, @@ -1023,6 +1230,7 @@ impl Store { "ALTER TABLE chat_run_wakeups ADD COLUMN claimed_at INTEGER", "ALTER TABLE chat_run_wakeups ADD COLUMN delivered_at INTEGER", "ALTER TABLE chat_run_wakeups ADD COLUMN monitoring_alerted INTEGER NOT NULL DEFAULT 0", + "ALTER TABLE chat_run_wakeups ADD COLUMN engine_migrated INTEGER NOT NULL DEFAULT 0", "ALTER TABLE chat_messages ADD COLUMN parent_id TEXT", "ALTER TABLE chat_messages ADD COLUMN base_native_session_id TEXT", "ALTER TABLE chat_messages ADD COLUMN result_native_session_id TEXT", @@ -1038,14 +1246,34 @@ impl Store { "ALTER TABLE ui_state ADD COLUMN nested_delegation INTEGER NOT NULL DEFAULT 0", "ALTER TABLE chat_messages ADD COLUMN completed_at INTEGER", "ALTER TABLE runs ADD COLUMN cancel_reason TEXT", + "ALTER TABLE runs ADD COLUMN cancel_unconfirmed TEXT", + "ALTER TABLE runs ADD COLUMN contact TEXT", + "ALTER TABLE runs ADD COLUMN spec_digest TEXT", + "ALTER TABLE runs ADD COLUMN submission_attempt INTEGER NOT NULL DEFAULT 1", + "ALTER TABLE runs ADD COLUMN submission_fence TEXT", + "ALTER TABLE runs ADD COLUMN cancel_accepted_at INTEGER", + "ALTER TABLE runs ADD COLUMN launch_spec TEXT", + "ALTER TABLE runs ADD COLUMN notify_cursor TEXT", + "ALTER TABLE runs ADD COLUMN started_at INTEGER", ] { let _ = conn.execute(ddl, []); } + conn.execute_batch( + "CREATE TRIGGER IF NOT EXISTS delete_run_outbox AFTER DELETE ON runs BEGIN + DELETE FROM run_notices WHERE run_id = OLD.id; + DELETE FROM run_subscriptions WHERE run_id = OLD.id; + END; + CREATE TRIGGER IF NOT EXISTS delete_chat_outbox AFTER DELETE ON chat_sessions BEGIN + DELETE FROM run_notices WHERE chat_session_id = OLD.id; + DELETE FROM run_subscriptions WHERE chat_session_id = OLD.id; + END;", + )?; // Covers the periodic native-id scan so it never reads the large parts_json. conn.execute_batch( "CREATE INDEX IF NOT EXISTS idx_chat_messages_native_ids ON chat_messages(base_native_session_id, result_native_session_id, session_id);", )?; + conn.execute_batch("CREATE TRIGGER IF NOT EXISTS delete_log_collection AFTER DELETE ON runs BEGIN DELETE FROM log_collections WHERE run_id = OLD.id; END;")?; conn.execute_batch("CREATE TRIGGER IF NOT EXISTS delete_chat_steer_receipts AFTER DELETE ON chat_sessions BEGIN DELETE FROM chat_steer_receipts WHERE session_id = OLD.id; END;")?; conn.execute_batch("CREATE TRIGGER IF NOT EXISTS delete_chat_invocation_identities AFTER DELETE ON chat_sessions BEGIN DELETE FROM native_invocation_identities WHERE session_id = OLD.id; END;")?; conn.execute_batch("CREATE TRIGGER IF NOT EXISTS delete_acp_session AFTER DELETE ON chat_sessions BEGIN DELETE FROM acp_sessions WHERE session_id = OLD.id; END;")?; @@ -1502,16 +1730,67 @@ impl Store { Ok(rows.collect::, _>>()?) } - /// Count runs in an active state (`starting`/`running`) — SQL-side and - /// unbounded, so a long-running job older than the newest N rows still - /// counts. Used by the data-dir move's in-flight guard. + pub(crate) fn engine_runs_block_idle(&self) -> Result { + let mut statement = self.conn.prepare("SELECT status FROM runs")?; + let rows = statement.query_map([], |row| row.get::<_, String>(0))?; + for status in rows { + let status = status?; + let phase = crate::engine::Phase::parse(&status) + .ok_or_else(|| anyhow!("Unknown run status: {status}"))?; + if !phase.is_terminal() { + return Ok(true); + } + } + Ok(false) + } + + pub(crate) fn engine_idle_blocked(&self) -> Result { + if self.engine_runs_block_idle()? { + return Ok(true); + } + Ok(self.conn.query_row( + "SELECT EXISTS(SELECT 1 FROM run_notices WHERE delivered_at IS NULL AND retired_at IS NULL) + OR EXISTS(SELECT 1 FROM chat_turns WHERE state IN ('preparing','retrying','running'))", + [], |row| row.get(0), + )?) + } + + /// Runs or local processes that prevent moving their working directory. pub fn count_active_runs(&self) -> Result { - let n: i64 = self.conn.query_row( - "SELECT COUNT(*) FROM runs WHERE status IN ('starting', 'running')", - [], - |r| r.get(0), - )?; - Ok(n as usize) + let mut statement = self + .conn + .prepare("SELECT id FROM runs WHERE status IN ('submitting', 'starting', 'running')")?; + let active = statement + .query_map([], |row| row.get::<_, String>(0))? + .collect::, _>>()?; + let mut count = active.len(); + let entries = match std::fs::read_dir(self.data_dir.join("local-runs")) { + Ok(entries) => entries, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(count), + Err(_) => return Ok(count + 1), + }; + for entry in entries { + let entry = match entry { + Ok(entry) => entry, + Err(_) => return Ok(count + 1), + }; + if active.contains(entry.file_name().to_string_lossy().as_ref()) { + continue; + } + if crate::jobs::localbox::orphaned_job_is_running(&entry.path()).unwrap_or(true) { + count += 1; + } + } + Ok(count) + } + + /// Runs the engine may act on: in flight, or terminal with a kill still pending. + pub fn list_engine_runs(&self) -> Result> { + let mut stmt = self.conn.prepare(&format!( + "{SELECT_RUN} WHERE status IN ('submitting', 'starting', 'running') OR contact IS NOT NULL" + ))?; + let rows = stmt.query_map([], row_to_run)?; + Ok(rows.collect::, _>>()?) } pub fn list_active_runs(&self) -> Result> { @@ -1550,121 +1829,37 @@ impl Store { Ok(run) } - pub fn register_run_wakeup( - &self, - run_id: &str, - chat_session_id: &str, - ) -> Result { - let inserted = self.conn.execute( - "INSERT OR IGNORE INTO chat_run_wakeups (run_id, chat_session_id, requested_at) - VALUES (?1, ?2, ?3)", - params![run_id, chat_session_id, now_ms()], - )?; - if inserted == 1 { - return Ok(RunWakeupRegistration::Scheduled); - } - let state: String = self.conn.query_row( - "SELECT state FROM chat_run_wakeups WHERE run_id = ?1 AND chat_session_id = ?2", - params![run_id, chat_session_id], - |row| row.get(0), - )?; - Ok(if state == "delivered" { - RunWakeupRegistration::AlreadyDelivered - } else { - RunWakeupRegistration::AlreadyPending - }) - } - - pub fn remove_run_wakeup(&self, run_id: &str, chat_session_id: &str) -> Result<()> { - self.conn.execute( - "DELETE FROM chat_run_wakeups WHERE run_id = ?1 AND chat_session_id = ?2", - params![run_id, chat_session_id], - )?; - Ok(()) - } - - pub fn prune_run_wakeups(&self) -> Result<()> { - self.clear_stale_data_dir_move_lease()?; - self.conn.execute( - "UPDATE chat_run_wakeups - SET state = 'pending', claim_token = NULL, claimed_at = NULL - WHERE state = 'claimed' AND claimed_at < ?1 - AND NOT EXISTS (SELECT 1 FROM data_dir_move_lease WHERE id = 1)", - params![now_ms() - RUN_WAKEUP_CLAIM_TTL_MS], - )?; - self.conn.execute( - "DELETE FROM chat_run_wakeups - WHERE NOT EXISTS (SELECT 1 FROM data_dir_move_lease WHERE id = 1) - AND ( - NOT EXISTS (SELECT 1 FROM runs WHERE runs.id = chat_run_wakeups.run_id) - OR NOT EXISTS ( - SELECT 1 FROM chat_sessions - WHERE chat_sessions.id = chat_run_wakeups.chat_session_id - ) - OR EXISTS ( - SELECT 1 FROM runs - WHERE runs.id = chat_run_wakeups.run_id - AND runs.status = 'cancelled' - ) - )", - [], - )?; - Ok(()) - } - - pub fn list_ready_run_wakeups(&self) -> Result> { - self.list_run_wakeups( - "w.state IN ('pending', 'claimed') AND r.status IN ('done', 'failed', 'lost') - ORDER BY COALESCE(r.ended_at, r.updated_at), w.requested_at, r.id", - ) - } - - /// Pending wake-ups whose run is still live, for monitoring alerts. - pub fn list_active_run_wakeups(&self) -> Result> { - self.list_run_wakeups( - "w.state = 'pending' AND r.status IN ('starting', 'running') - ORDER BY w.requested_at, r.id", - ) - } - - fn list_run_wakeups(&self, filter: &'static str) -> Result> { + /// The active runs each chat launched or subscribed to. + pub fn chat_active_runs(&self) -> Result> { let mut stmt = self.conn.prepare(&format!( - "SELECT r.id, r.experiment_id, r.project_id, r.status, r.backend_json, r.command, - r.created_at, r.updated_at, r.ended_at, r.exit_code, - r.commit_sha, r.result_markdown, r.cancel_requested, r.chat_session_id, - r.cancel_reason, w.chat_session_id, w.state, w.monitoring_alerted - FROM chat_run_wakeups w - JOIN runs r ON r.id = w.run_id - WHERE {filter}" + "SELECT * FROM ( + SELECT chat_session_id AS chat, r.* FROM ({SELECT_RUN}) r + WHERE chat_session_id IS NOT NULL + UNION SELECT s.chat_session_id AS chat, r.* FROM run_subscriptions s + JOIN ({SELECT_RUN}) r ON r.id = s.run_id + ) WHERE status IN ('submitting', 'starting', 'running') + ORDER BY chat, id" ))?; let rows = stmt.query_map([], |row| { - Ok(RunWakeup { - run: row_to_run(row)?, - chat_session_id: row.get(15)?, - state: row.get(16)?, - monitoring_alerted: row.get(17)?, - }) + let chat: String = row.get(0)?; + let run = row_to_run_at(row, 1)?; + Ok((chat, run)) })?; Ok(rows.collect::, _>>()?) } - /// Flips a pending wake-up's monitoring alert flag; `true` when this call changed it, - /// which makes setting it an atomic claim across `orx up` processes. - pub fn set_run_wakeup_monitoring_alerted( - &self, - run_id: &str, - chat_session_id: &str, - alerted: bool, - ) -> Result { - let changed = self.conn.execute( - "UPDATE chat_run_wakeups SET monitoring_alerted = ?3 - WHERE run_id = ?1 AND chat_session_id = ?2 - AND state = 'pending' AND monitoring_alerted != ?3", - params![run_id, chat_session_id, alerted], + /// A 0.2.x wake-up row, for migration fixtures. + #[cfg(test)] + pub fn register_run_wakeup(&self, run_id: &str, chat_session_id: &str) -> Result<()> { + self.conn.execute( + "INSERT OR IGNORE INTO chat_run_wakeups (run_id, chat_session_id, requested_at) + VALUES (?1, ?2, ?3)", + params![run_id, chat_session_id, now_ms()], )?; - Ok(changed == 1) + Ok(()) } + #[cfg(test)] pub fn claim_run_wakeup(&self, run_id: &str, chat_session_id: &str) -> Result> { let token = uuid::Uuid::new_v4().to_string(); let claimed = self.conn.execute( @@ -1676,38 +1871,6 @@ impl Store { Ok((claimed == 1).then_some(token)) } - pub fn release_run_wakeup( - &self, - run_id: &str, - chat_session_id: &str, - token: &str, - ) -> Result<()> { - self.conn.execute( - "UPDATE chat_run_wakeups - SET state = 'pending', claim_token = NULL, claimed_at = NULL - WHERE run_id = ?1 AND chat_session_id = ?2 - AND state = 'claimed' AND claim_token = ?3", - params![run_id, chat_session_id, token], - )?; - Ok(()) - } - - pub fn mark_run_wakeup_delivered( - &self, - run_id: &str, - chat_session_id: &str, - token: &str, - ) -> Result { - let delivered = self.conn.execute( - "UPDATE chat_run_wakeups - SET state = 'delivered', claim_token = NULL, claimed_at = NULL, delivered_at = ?4 - WHERE run_id = ?1 AND chat_session_id = ?2 - AND state = 'claimed' AND claim_token = ?3", - params![run_id, chat_session_id, token, now_ms()], - )?; - Ok(delivered == 1) - } - /// Record `child` as a delegate of `parent`; recording it again, as a /// retried start does, changes nothing. pub fn record_chat_delegate( @@ -1849,7 +2012,7 @@ impl Store { ) ORDER BY l.updated_at" ))?; - let rows = stmt.query_map([now_ms() - RUN_WAKEUP_CLAIM_TTL_MS], |row| { + let rows = stmt.query_map([now_ms() - CHAT_SUBSCRIPTION_CLAIM_TTL_MS], |row| { Ok(ReadyChatSubscription { subscriber_session_id: row.get(0)?, target_session_id: row.get(1)?, @@ -1927,7 +2090,7 @@ impl Store { id, token, now_ms(), - now_ms() - RUN_WAKEUP_CLAIM_TTL_MS + now_ms() - CHAT_SUBSCRIPTION_CLAIM_TTL_MS ], )?; Ok((claimed == 1).then_some(token)) @@ -2067,7 +2230,8 @@ impl Store { Ok(changed == 1) } - /// Keeps the reason: a live supervisor may already have acted on the request. + /// What a 0.2.x CLI does when its supervisor spawn fails; the reason stays. + #[cfg(test)] pub fn withdraw_cancel(&self, run_id: &str) -> Result<()> { self.conn.execute( "UPDATE runs SET cancel_requested = 0, updated_at = ?2 WHERE id = ?1", @@ -2343,9 +2507,7 @@ impl Store { started: std::time::Instant, pass: &mut OrphanPass, ) -> Result<()> { - let mut statement = self - .conn - .prepare(&runs_past_newest("'local_job', 'tinker_job'"))?; + let mut statement = self.conn.prepare(&runs_past_newest(LOCAL_RUNS))?; let runs = statement .query_map([], |row| { Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)) @@ -2527,7 +2689,12 @@ impl Store { if dir.exists() && crate::jobs::localbox::orphaned_job_is_running(&dir)? { return live("still has running processes"); } - if self.supervisor_is_held(id)? { + let forgetting_kill = deleting && self.conn.query_row( + &format!("SELECT EXISTS(SELECT 1 FROM runs WHERE id = ?1 AND contact IS NOT NULL AND {REMOTE_RUNS})"), + [id], + |row| row.get::<_, bool>(0), + )?; + if !forgetting_kill && self.supervisor_is_held(id)? { return live("still has a supervisor"); } Ok(fate) @@ -2678,6 +2845,108 @@ impl Store { Ok(()) } + /// A terminal run owes final log and notify collection. + pub(crate) fn queue_log_collection(&self, run_id: &str) -> Result<()> { + self.conn.execute( + "INSERT OR IGNORE INTO log_collections (run_id, next_attempt_at) VALUES (?1, ?2)", + params![run_id, now_ms()], + )?; + Ok(()) + } + + pub(crate) fn log_output_collected(&self, run_id: &str) -> Result { + Ok(self + .conn + .query_row( + "SELECT collected FROM log_collections WHERE run_id = ?1", + [run_id], + |row| row.get(0), + ) + .optional()? + .unwrap_or(false)) + } + + pub(crate) fn checkpoint_log_collection(&self, run_id: &str) -> Result<()> { + self.conn.execute( + "UPDATE log_collections SET collected = 1 WHERE run_id = ?1", + [run_id], + )?; + Ok(()) + } + + /// The terminal run's log and notify have both been consumed. + pub(crate) fn finish_log_collection(&self, run_id: &str) -> Result<()> { + self.conn.execute( + "INSERT INTO log_collections (run_id, done) VALUES (?1, 1) + ON CONFLICT(run_id) DO UPDATE SET done = 1, last_error = NULL", + params![run_id], + )?; + Ok(()) + } + + /// The engine owes this finished run its kept log: local copies may stop short of the end. + pub(crate) fn log_collection_pending(&self, run_id: &str) -> Result { + Ok(self.log_collection(run_id)?.is_some()) + } + + /// An unfinished collection: whether retries have reached their cap, and the last error. + pub(crate) fn log_collection(&self, run_id: &str) -> Result)>> { + Ok(self + .conn + .query_row( + "SELECT attempts >= ?2, last_error FROM log_collections + WHERE run_id = ?1 AND done = 0", + params![run_id, LOG_COLLECTION_FAILED_AFTER], + |row| Ok((row.get(0)?, row.get(1)?)), + ) + .optional()?) + } + + pub(crate) fn due_log_collections(&self, limit: usize) -> Result> { + let mut statement = self.conn.prepare( + "SELECT run_id FROM log_collections WHERE done = 0 AND next_attempt_at <= ?1 + ORDER BY next_attempt_at LIMIT ?2", + )?; + let rows = statement.query_map(params![now_ms(), limit as i64], |row| row.get(0))?; + Ok(rows.collect::, _>>()?) + } + + pub(crate) fn pending_log_collections(&self) -> Result> { + let mut statement = self + .conn + .prepare("SELECT run_id FROM log_collections WHERE done = 0")?; + let rows = statement.query_map([], |row| row.get(0))?; + Ok(rows.collect::, _>>()?) + } + + /// Makes one run's unfinished collection, or every one, due now. + pub(crate) fn retry_log_collections_now(&self, run_id: Option<&str>) -> Result<()> { + self.conn.execute( + "UPDATE log_collections SET next_attempt_at = 0 + WHERE done = 0 AND (?1 IS NULL OR run_id = ?1)", + [run_id], + )?; + Ok(()) + } + + /// Schedules the next attempt; true exactly when this failure brings retries to their cap. + pub(crate) fn defer_log_collection(&self, run_id: &str, error: &str) -> Result { + let attempts: u32 = self.conn.query_row( + "UPDATE log_collections SET attempts = attempts + 1, last_error = ?2, + next_attempt_at = ?3 + MIN(?4 * (1 << MIN(attempts, 10)), ?5) + WHERE run_id = ?1 RETURNING attempts", + params![ + run_id, + error, + now_ms(), + LOG_COLLECTION_RETRY_MS, + LOG_COLLECTION_MAX_RETRY_MS + ], + |row| row.get(0), + )?; + Ok(attempts == LOG_COLLECTION_FAILED_AFTER) + } + /// Queues a finished run's remote dir for removal; non-SSH/Slurm runs are ignored. pub(crate) fn queue_finished_remote_cleanup(&self, run_id: &str) -> Result<()> { queue_remote_cleanups(&self.conn, "id", run_id, false) @@ -2687,10 +2956,9 @@ impl Store { pub(crate) fn due_remote_cleanups(&self, limit: usize) -> Result> { let mut statement = self.conn.prepare(&format!( "SELECT run_id, backend_json, deleted FROM remote_cleanups - WHERE next_attempt_at <= ?1 AND (deleted = 1 OR run_id IN - (SELECT id FROM ({}))) + WHERE next_attempt_at <= ?1 AND {} ORDER BY next_attempt_at LIMIT ?2", - runs_past_newest("'ssh_job', 'slurm_job'") + remote_cleanup_eligibility() ))?; let rows = statement.query_map(params![now_ms(), limit as i64], |row| { Ok(RemoteCleanup { @@ -2702,6 +2970,12 @@ impl Store { Ok(rows.collect::, _>>()?) } + pub(crate) fn remote_cleanup_eligible(&self, run_id: &str, deleted: bool) -> Result { + Ok(self.conn.query_row(&format!( + "SELECT EXISTS(SELECT 1 FROM remote_cleanups WHERE run_id = ?1 AND deleted = ?2 AND {})", + remote_cleanup_eligibility()), params![run_id, deleted], |row| row.get(0))?) + } + /// `deleted` is what the pass acted on; a deletion queued meanwhile stays for the next pass. pub(crate) fn finish_remote_cleanup(&self, run_id: &str, deleted: bool) -> Result<()> { self.conn.execute( @@ -2934,47 +3208,48 @@ impl Store { UNION SELECT experiment_id FROM runs WHERE chat_session_id = ?1 UNION SELECT runs.experiment_id FROM chat_run_wakeups w JOIN runs ON runs.id = w.run_id WHERE w.chat_session_id = ?1 + UNION SELECT runs.experiment_id FROM run_subscriptions s + JOIN runs ON runs.id = s.run_id WHERE s.chat_session_id = ?1 ), headline AS ( - SELECT experiment_id AS current_experiment_id, status AS current_status, - cancel_requested AS current_cancel_requested, + SELECT experiment_id AS current_experiment_id, id AS current_run_id, status AS current_status, created_at AS current_created_at, ended_at AS current_ended_at, ROW_NUMBER() OVER ( PARTITION BY experiment_id - ORDER BY status IN ('starting', 'running') DESC, created_at DESC, id DESC + ORDER BY status IN ('submitting', 'starting', 'running') DESC, created_at DESC, id DESC ) AS current_rank FROM runs WHERE experiment_id IN (SELECT related_id FROM related) ) - SELECT {EXPERIMENT_COLS}, project_name, current_status, - current_cancel_requested, current_created_at, current_ended_at + SELECT {EXPERIMENT_COLS}, project_name, current_run_id FROM local_experiments e JOIN related ON related_id = e.id JOIN (SELECT id AS owner_id, name AS project_name FROM local_projects) ON owner_id = e.project_id LEFT JOIN headline ON current_experiment_id = e.id AND current_rank = 1 - ORDER BY COALESCE(current_status IN ('starting', 'running'), 0) DESC, + ORDER BY COALESCE(current_status IN ('submitting', 'starting', 'running'), 0) DESC, e.archived ASC, COALESCE(current_ended_at, current_created_at, e.created_at) DESC, e.id ASC" ))?; let rows = stmt.query_map(params![session_id], |row| { - let current_run = match row.get::<_, Option>(14)? { - Some(status) => Some(SessionExperimentRun { - status, - cancel_requested: row.get(15)?, - created_at: row.get(16)?, - ended_at: row.get(17)?, - }), - None => None, - }; - Ok(SessionExperiment { - experiment: LocalExperiment::from_row(row)?, - project_name: row.get(13)?, - current_run, - }) + Ok(( + LocalExperiment::from_row(row)?, + row.get::<_, String>(13)?, + row.get::<_, Option>(14)?, + )) })?; - Ok(rows.collect::, _>>()?) - } - + let rows = rows.collect::, _>>()?; + rows.into_iter() + .map(|(experiment, project_name, run_id)| { + let current_run = run_id.map(|id| self.get_run(&id)).transpose()?.flatten(); + Ok(SessionExperiment { + experiment, + project_name, + current_run, + }) + }) + .collect() + } + /// Full-row update by id (title / description / run_command / agent_status). /// /// `chat_session_id` is deliberately omitted: session ownership is stamped @@ -4803,206 +5078,2421 @@ fn row_to_chat_session( }) } -const SELECT_RUN: &str = "SELECT id, experiment_id, project_id, status, backend_json, command, - created_at, updated_at, ended_at, exit_code, - commit_sha, result_markdown, cancel_requested, - chat_session_id, cancel_reason FROM runs"; +const RUN_NOTICE_RETRY_WINDOW_MS: i64 = 24 * 60 * 60 * 1000; -const PROJECT_COLS: &str = "id, name, slug, github_owner, github_repo, github_sync_enabled, \ - baseline_branch, repo_path, run_command, paper_id, created_at, updated_at"; +impl Store { + pub(crate) fn engine_host_auth( + &self, + alias: &str, + ) -> Result { + let json: Option = self + .conn + .query_row( + "SELECT state_json FROM engine_host_auth WHERE alias = ?1", + [alias], + |row| row.get(0), + ) + .optional()?; + json.map(|json| serde_json::from_str(&json).map_err(Into::into)) + .transpose() + .map(Option::unwrap_or_default) + } -const EXPERIMENT_COLS: &str = "id, project_id, parent_experiment_id, slug, branch_name, \ - title, description, run_command, agent_status, created_at, \ - updated_at, chat_session_id, archived"; + pub(crate) fn save_engine_host_auth( + &self, + alias: &str, + state: &crate::engine::transport::AuthState, + ) -> Result<()> { + self.conn.execute( + "INSERT INTO engine_host_auth (alias, state_json) VALUES (?1, ?2) ON CONFLICT(alias) DO UPDATE SET state_json = excluded.state_json", + params![alias, serde_json::to_string(state)?], + )?; + Ok(()) + } -fn row_to_run(row: &rusqlite::Row<'_>) -> std::result::Result { - Ok(StoredRun { - id: row.get(0)?, - experiment_id: row.get(1)?, - project_id: row.get(2)?, - status: row.get(3)?, - backend_json: row.get(4)?, - command: row.get(5)?, - created_at: row.get(6)?, - updated_at: row.get(7)?, - ended_at: row.get(8)?, - exit_code: row.get(9)?, - commit_sha: row.get(10)?, - result_markdown: row.get(11)?, - cancel_requested: row.get(12)?, - chat_session_id: row.get(13)?, - cancel_reason: row.get(14)?, - }) -} + pub fn engine_hosts( + &self, + ) -> Result> { + let mut query = self + .conn + .prepare("SELECT alias, root FROM engine_hosts ORDER BY alias, root")?; + let rows = query.query_map([], |row| { + Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)) + })?; + rows.map(|row| { + let (alias, root) = row?; + let state = self.engine_host(&alias, &root)?.unwrap(); + Ok((alias, root, state)) + }) + .collect() + } -pub fn now_ms() -> i64 { - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.as_millis() as i64) - .unwrap_or(0) -} + pub(crate) fn engine_root( + &self, + alias: &str, + root: &str, + ) -> Result> { + let json: Option = self + .conn + .query_row( + "SELECT state_json FROM engine_hosts WHERE alias = ?1 AND root = ?2", + params![alias, root], + |row| row.get(0), + ) + .optional()?; + json.map(|json| serde_json::from_str(&json).map_err(Into::into)) + .transpose() + } -fn log_generation_run_id(name: &str) -> Option<&str> { - let (run, generation) = name.strip_suffix(".log")?.split_once('.')?; - uuid::Uuid::parse_str(generation).ok()?; - Some(run) -} + pub fn engine_host( + &self, + alias: &str, + root: &str, + ) -> Result> { + let Some(mut state) = self.engine_root(alias, root)? else { + return Ok(None); + }; + if let Some((since, cause)) = self.engine_host_auth(alias)?.blocked { + state.status = crate::engine::transport::Status::NeedsAuth; + state.since_ms = since; + state.cause = Some(cause); + state.next_retry_ms = None; + } + Ok(Some(state)) + } -fn artifact_entries(path: &Path) -> Result> { - match std::fs::read_dir(path) { - Ok(entries) => Ok(entries.collect::>>()?), - Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()), - Err(error) => Err(error.into()), + pub fn save_engine_host( + &self, + alias: &str, + root: &str, + state: &crate::engine::transport::HostState, + ) -> Result<()> { + use crate::engine::transport::Status; + let blocked = state.status == Status::NeedsAuth; + let json = serde_json::json!({ + "status": if blocked { &Status::Idle } else { &state.status }, + "since_ms": state.since_ms, "failures": state.failures, + "last_live_ms": state.last_live_ms, + "next_retry_ms": state.next_retry_ms, + "cause": if blocked { None } else { state.cause.as_ref() }, + }); + self.conn.execute( + "INSERT INTO engine_hosts (alias, root, state_json) VALUES (?1, ?2, ?3) ON CONFLICT(alias, root) DO UPDATE SET state_json = excluded.state_json", + params![alias, root, json.to_string()], + )?; + Ok(()) } -} -fn remove_run_artifact(path: &Path) -> Result<()> { - let result = match std::fs::symlink_metadata(path) { - Ok(metadata) if metadata.file_type().is_dir() => std::fs::remove_dir_all(path), - Ok(_) => std::fs::remove_file(path), - Err(error) => Err(error), - }; - match result { - Ok(()) => Ok(()), - Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()), - Err(error) => Err(anyhow!( - "Could not remove run artifact {}: {error}", - path.display() - )), + #[cfg(test)] + pub(crate) fn seed_engine_host( + &self, + alias: &str, + root: &str, + class: Option, + state: &crate::engine::transport::HostState, + ) -> Result<()> { + self.save_engine_host_auth( + alias, + &crate::engine::transport::AuthState { + class, + route: None, + blocked: (state.status == crate::engine::transport::Status::NeedsAuth) + .then(|| (state.since_ms, state.cause.clone().unwrap_or_default())), + }, + )?; + self.save_engine_host(alias, root, state) } -} -/// Resolves `parts` under `root` through real directories only, so symlinks cannot redirect removal. -fn real_path_under<'a>( - root: &Path, - parts: impl IntoIterator, -) -> Result> { - let mut path = root.to_path_buf(); - for part in parts { - path.push(part); - match std::fs::symlink_metadata(&path) { - Ok(metadata) if metadata.file_type().is_dir() => {} - Ok(_) => return Ok(None), - Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), - Err(error) => return Err(error.into()), + pub fn insert_submitting_run(&self, run: SubmittingRun<'_>) -> Result<()> { + let backend_json = crate::engine::handle::backend_json(run.id, None, run.metadata)?; + self.conn.execute( + "INSERT INTO runs (id, experiment_id, project_id, status, backend_json, command, + created_at, updated_at, commit_sha, chat_session_id, spec_digest, + launch_spec) + VALUES (?1, ?2, ?3, 'submitting', ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)", + params![ + run.id, + run.experiment_id, + run.project_id, + backend_json, + run.command, + run.created_at, + run.created_at, + run.commit_sha, + run.chat_session_id, + run.spec_digest, + serde_json::to_string(run.launch)?, + ], + )?; + Ok(()) + } + + pub fn engine_run_state(&self, run_id: &str) -> Result> { + fn json(value: Option) -> Result> { + Ok(value.map(|json| serde_json::from_str(&json)).transpose()?) } + + let row = self + .conn + .query_row( + "SELECT contact, spec_digest, submission_attempt, submission_fence, + cancel_accepted_at, launch_spec, notify_cursor, cancel_unconfirmed, started_at + FROM runs WHERE id = ?1", + [run_id], + |row| { + Ok(( + row.get::<_, Option>(0)?, + row.get::<_, Option>(1)?, + row.get::<_, u32>(2)?, + row.get::<_, Option>(3)?, + row.get::<_, Option>(4)?, + row.get::<_, Option>(5)?, + row.get::<_, Option>(6)?, + row.get::<_, Option>(7)?, + row.get::<_, Option>(8)?, + )) + }, + ) + .optional()?; + let Some(( + contact, + spec_digest, + submission_attempt, + fence, + cancel_accepted_at, + launch, + notify, + cancel_unconfirmed, + started_at, + )) = row + else { + return Ok(None); + }; + Ok(Some(EngineRunState { + started_at, + contact: json(contact)?.unwrap_or(Contact::Live), + cancel_unconfirmed: json(cancel_unconfirmed)?, + spec_digest, + submission_attempt, + submission_fence: json(fence)?, + cancel_accepted_at, + launch: json(launch)?, + notify_cursor: json(notify)?, + })) } - Ok(Some(path)) -} -#[cfg(test)] -mod tests { - use super::*; + pub fn set_notify_cursor(&self, run_id: &str, cursor: &NotifyCursor) -> Result<()> { + self.conn.execute( + "UPDATE runs SET notify_cursor = ?2 WHERE id = ?1", + params![run_id, serde_json::to_string(cursor)?], + )?; + Ok(()) + } - #[cfg(unix)] - #[test] - fn store_protects_existing_data_and_sqlite_sidecars() { - use std::os::unix::fs::PermissionsExt; - let dir = std::env::temp_dir().join(format!("orx-private-store-{}", uuid::Uuid::new_v4())); - std::fs::create_dir_all(&dir).unwrap(); - std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o755)).unwrap(); - let store = Store::open_at(dir.clone()).unwrap(); - assert_eq!( - std::fs::metadata(&dir).unwrap().permissions().mode() & 0o777, - 0o700 - ); - drop(store); - std::fs::remove_dir_all(dir).unwrap(); + /// Runner-1 runs an old supervisor holds, with the row as the engine last saw it. Durable, + /// so a run that finishes while the engine is down still gets its chat result. + pub fn legacy_watches(&self) -> Result)>> { + let mut stmt = self.conn.prepare( + "SELECT run_id, seen_status, seen_updated_at FROM legacy_watches ORDER BY run_id", + )?; + let rows = stmt.query_map([], |row| { + let seen = match (row.get(1)?, row.get(2)?) { + (Some(status), Some(updated_at)) => Some((status, updated_at)), + _ => None, + }; + Ok((row.get(0)?, seen)) + })?; + Ok(rows.collect::, _>>()?) } - fn project_with_run_artifacts(store: &Store, project: &str, run: &str, digest: &str) { - let repo = store.data_dir.join(format!("repo-{project}")); - std::fs::create_dir_all(&repo).unwrap(); - std::fs::write(repo.join("keep"), "repository").unwrap(); - store.conn.execute( - "INSERT INTO local_projects (id, name, slug, github_owner, github_repo, repo_path, created_at, updated_at) - VALUES (?1, ?1, ?1, '', '', ?2, 1, 1)", - params![project, repo.to_string_lossy()], - ).unwrap(); - let descriptor = serde_json::json!({ - "kind": "local_job", "sourceDigest": digest, - "jobId": repo, "sourcePath": repo.join("keep"), - }); - store.conn.execute( - "INSERT INTO runs (id, experiment_id, project_id, status, backend_json, created_at, updated_at) - VALUES (?1, 'experiment', ?2, 'done', ?3, 1, 1)", - params![run, project, descriptor.to_string()], - ).unwrap(); - for path in [ - store - .data_dir - .join("local-runs") - .join(run) - .join("repo/output"), - store.data_dir.join("run-logs").join(format!("{run}.log")), - store - .data_dir - .join("submission-handles") - .join(format!("{run}.json")), - store - .data_dir - .join("source-snapshots") - .join(format!("{digest}.tar")), - store - .data_dir - .join("source-snapshots") - .join(format!("{digest}.hf/payload")), - ] { - std::fs::create_dir_all(path.parent().unwrap()).unwrap(); - std::fs::write(path, "artifact").unwrap(); - } - std::fs::write( - store - .data_dir - .join("submission-handles") - .join(format!("{run}.json")), - descriptor.to_string(), - ) - .unwrap(); + /// `None` starts watching without overwriting what was already seen. + pub fn watch_legacy_run(&self, run_id: &str, seen: Option<(&str, i64)>) -> Result<()> { + self.conn.execute( + "INSERT INTO legacy_watches (run_id, seen_status, seen_updated_at) VALUES (?1, ?2, ?3) + ON CONFLICT(run_id) DO UPDATE SET + seen_status = COALESCE(excluded.seen_status, seen_status), + seen_updated_at = COALESCE(excluded.seen_updated_at, seen_updated_at)", + params![run_id, seen.map(|seen| seen.0), seen.map(|seen| seen.1)], + )?; + Ok(()) } - #[test] - fn orphan_cleanup_reclaims_rowless_local_artifacts_and_preserves_other_runs() { - let dir = - std::env::temp_dir().join(format!("orx-orphan-artifacts-{}", uuid::Uuid::new_v4())); - let store = Store::open_at(dir.clone()).unwrap(); - let orphan = uuid::Uuid::new_v4().to_string(); - let shared_orphan = uuid::Uuid::new_v4().to_string(); - let surviving = uuid::Uuid::new_v4().to_string(); - let abandoned = uuid::Uuid::new_v4().to_string(); - let tinker = uuid::Uuid::new_v4().to_string(); - let unreferenced = "a".repeat(64); - let shared = "b".repeat(64); - project_with_run_artifacts(&store, "old", &orphan, &unreferenced); - project_with_run_artifacts(&store, "old-shared", &shared_orphan, &shared); - project_with_run_artifacts(&store, "surviving", &surviving, &shared); - project_with_run_artifacts(&store, "abandoned", &abandoned, &unreferenced); - project_with_run_artifacts(&store, "tinker", &tinker, &unreferenced); - let tinker_handle = dir - .join("submission-handles") - .join(format!("{tinker}.json")); - let mut descriptor: serde_json::Value = - serde_json::from_str(&std::fs::read_to_string(&tinker_handle).unwrap()).unwrap(); - descriptor["kind"] = serde_json::json!("tinker_job"); - std::fs::write(tinker_handle, descriptor.to_string()).unwrap(); - let abandoned_dir = dir.join("local-runs").join(&abandoned); - std::fs::write(abandoned_dir.join("run.sh"), "echo never started").unwrap(); - store - .conn - .execute("DELETE FROM runs WHERE project_id != 'surviving'", []) - .unwrap(); - for id in [&orphan, &shared_orphan, &tinker] { - std::fs::write(dir.join("local-runs").join(id).join("exit_code"), "0").unwrap(); - } - let zip = dir - .join("source-snapshots") - .join(format!("{}.zip", "c".repeat(64))); - std::fs::write(&zip, "upload-only").unwrap(); - std::fs::write(dir.join("source-snapshots/keep.txt"), "not an archive").unwrap(); - let sidecar_only = uuid::Uuid::new_v4().to_string(); - for name in [ - format!("{orphan}.supervisor.log"), - format!("{orphan}.cancel.lock"), + pub fn unwatch_legacy_run(&self, run_id: &str) -> Result<()> { + self.conn + .execute("DELETE FROM legacy_watches WHERE run_id = ?1", [run_id])?; + Ok(()) + } + + pub fn last_notice_at(&self, run_id: &str, kind: &str) -> Result> { + Ok(self.conn.query_row( + "SELECT MAX(created_at) FROM run_notices WHERE run_id = ?1 AND kind = ?2", + params![run_id, kind], + |row| row.get(0), + )?) + } + + pub fn set_run_contact(&self, run_id: &str, contact: &Contact) -> Result { + let json = match contact { + Contact::Live => None, + _ => Some(serde_json::to_string(contact)?), + }; + Ok(self.conn.execute( + "UPDATE runs SET contact = ?2 WHERE id = ?1", + params![run_id, json], + )? == 1) + } + + pub fn set_submission_fence( + &self, + run_id: &str, + attempt: u32, + fence: &SubmissionFence, + ) -> Result { + Ok(self.conn.execute( + "UPDATE runs SET submission_fence = ?3 + WHERE id = ?1 AND status = 'submitting' AND submission_attempt = ?2 + AND submission_fence IS NULL AND cancel_accepted_at IS NULL", + params![run_id, attempt, serde_json::to_string(fence)?], + )? == 1) + } + + /// Release only when the launch was never sent. + pub fn clear_submission_fence(&self, run_id: &str, attempt: u32) -> Result { + Ok(self.conn.execute( + "UPDATE runs SET submission_fence = NULL + WHERE id = ?1 AND status = 'submitting' AND submission_attempt = ?2", + params![run_id, attempt], + )? == 1) + } + + /// Call only after recovery proves absence and the previous submitter is gone. + pub fn advance_submission_attempt(&self, run_id: &str, attempt: u32) -> Result { + Ok(self.conn.execute( + "UPDATE runs SET submission_attempt = submission_attempt + 1, submission_fence = NULL + WHERE id = ?1 AND status = 'submitting' AND submission_attempt = ?2 + AND submission_attempt < ?3 AND cancel_accepted_at IS NULL", + params![run_id, attempt, u32::MAX], + )? == 1) + } + + pub fn record_run_handle( + &self, + run_id: &str, + attempt: u32, + handle: &crate::engine::handle::Handle, + ) -> Result { + let tx = self + .conn + .is_autocommit() + .then(|| self.begin_immediate()) + .transpose()?; + let run = self + .get_run(run_id)? + .ok_or_else(|| anyhow!("Run {run_id} not found"))?; + let metadata = crate::jobs::BackendDescriptor::parse(&run.backend_json)?; + let json = crate::engine::handle::backend_json(run_id, Some(handle), &metadata)?; + let changed = self.conn.execute( + "UPDATE runs SET backend_json = ?3, + status = CASE WHEN status = 'submitting' THEN 'starting' ELSE status END, + updated_at = ?4 + WHERE id = ?1 AND submission_attempt = ?2 AND submission_fence IS NOT NULL + AND json_extract(backend_json, '$.handle') IS NULL + AND (status = 'submitting' OR + (status IN ('done','failed','cancelled','lost') AND contact IS NOT NULL))", + params![run_id, attempt, json, now_ms()], + )?; + if changed == 1 + && crate::engine::Phase::parse(&run.status) + .is_some_and(crate::engine::Phase::is_terminal) + { + self.queue_log_collection(run_id)?; + } + if let Some(tx) = tx { + tx.commit()?; + } + Ok(changed == 1) + } + + /// For a submitter subprocess of the fenced attempt, recorded before it can act. + pub fn record_submitter( + &self, + run_id: &str, + attempt: u32, + fence: &SubmissionFence, + ) -> Result { + Ok(self.conn.execute( + "UPDATE runs SET submission_fence = ?3 + WHERE id = ?1 AND status = 'submitting' AND submission_attempt = ?2 + AND submission_fence IS NOT NULL", + params![run_id, attempt, serde_json::to_string(fence)?], + )? == 1) + } + + /// Compare-and-set on `status`; the engine decides which moves are legal. + pub fn set_engine_phase( + &self, + run_id: &str, + from: &str, + to: &str, + ended_at: Option, + exit_code: Option, + started_at: Option, + ) -> Result { + let changed = self.conn.execute( + "UPDATE runs SET status = ?3, updated_at = ?4, ended_at = COALESCE(?5, ended_at), + exit_code = COALESCE(?6, exit_code), + started_at = COALESCE(started_at, ?7) + WHERE id = ?1 AND status = ?2", + params![run_id, from, to, now_ms(), ended_at, exit_code, started_at], + )? == 1; + if let Some(status) = RunStatus::parse(to).filter(|status| changed && status.is_terminal()) + { + self.stage_run_terminal(run_id, status)?; + } + Ok(changed) + } + + pub fn supervisor_lock_paths(&self, run_id: &str) -> Result<[PathBuf; 2]> { + Ok([ + self.run_lock_path(SUPERVISOR_LOCK, run_id)?, + self.run_lock_path(SHARED_SSH_LOCK, run_id)?, + ]) + } + + fn run_lock_path(&self, artifact: (&str, &str), run_id: &str) -> Result { + if run_id.is_empty() + || !run_id + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') + { + return Err(anyhow!("Invalid run id: {run_id}")); + } + Ok(self.run_artifact_path(artifact, run_id)) + } + + /// Ends an outage for a chat: withdraws its attention notice if it was never sent, and + /// returns whether one was sent (or is in flight), so a recovery notice is owed. + pub fn settle_outage_notice(&self, run_id: &str, chat: &str) -> Result { + let dedupe = self.outage_dedupe(run_id, chat, ATTENTION)?; + let withdrawn = self.conn.execute( + "DELETE FROM run_notices WHERE run_id = ?1 AND chat_session_id = ?2 AND dedupe = ?3 + AND client_turn_id IS NULL", + params![run_id, chat, dedupe], + )?; + // Retired attention keeps its audit row without reserving the next outage's key. + self.conn.execute( + "UPDATE run_notices SET dedupe = 'retired:' || client_turn_id || ':' || dedupe + WHERE run_id = ?1 AND chat_session_id = ?2 AND dedupe = ?3 AND retired_at IS NOT NULL", + params![run_id, chat, dedupe], + )?; + Ok(withdrawn == 0 + && self.conn.query_row( + "SELECT EXISTS(SELECT 1 FROM run_notices + WHERE run_id = ?1 AND chat_session_id = ?2 AND dedupe = ?3)", + params![run_id, chat, dedupe], + |row| row.get(0), + )?) + } + + /// `None` accepts legacy intent; a reason accepts an API cancel, including during submission. + pub fn accept_run_cancel(&self, run_id: &str, reason: Option<&str>) -> Result> { + let path = self.run_lock_path(CANCEL_LOCK, run_id)?; + let mut lock = open_lifecycle_lock_at(&path)?; + let _guard = lock.write()?; + Ok(self.conn.query_row( + "UPDATE runs SET cancel_accepted_at = COALESCE(cancel_accepted_at, ?2), + updated_at = CASE WHEN cancel_accepted_at IS NULL THEN ?2 + ELSE updated_at END, + cancel_reason = CASE WHEN cancel_requested = 0 AND cancel_accepted_at IS NULL + THEN COALESCE(?3, cancel_reason) + ELSE cancel_reason END + WHERE id = ?1 AND status IN ('submitting', 'starting', 'running') + AND (cancel_requested = 1 OR cancel_accepted_at IS NOT NULL OR ?3 IS NOT NULL) + RETURNING cancel_accepted_at", + params![run_id, now_ms(), reason], + |row| row.get(0), + ).optional()?) + } + + pub fn subscribe_run( + &self, + run_id: &str, + chat_session_id: &str, + created_at: i64, + ) -> Result<()> { + self.conn.execute( + "INSERT INTO run_subscriptions (run_id, chat_session_id, created_at) VALUES (?1, ?2, ?3) + ON CONFLICT(run_id, chat_session_id) DO NOTHING", + params![run_id, chat_session_id, created_at], + )?; + Ok(()) + } + + pub fn run_subscribers(&self, run_id: &str) -> Result> { + let mut stmt = self.conn.prepare( + "SELECT chat_session_id FROM runs WHERE id = ?1 AND chat_session_id IS NOT NULL + UNION SELECT chat_session_id FROM run_subscriptions WHERE run_id = ?1 + ORDER BY chat_session_id", + )?; + let rows = stmt.query_map([run_id], |row| row.get(0))?; + Ok(rows.collect::, _>>()?) + } + + pub fn insert_run_notice( + &self, + run_id: &str, + chat_session_id: &str, + kind: &str, + dedupe: &str, + body: &str, + created_at: i64, + ) -> Result { + Ok(self.conn.execute( + "INSERT INTO run_notices (run_id, chat_session_id, kind, dedupe, body, created_at) + VALUES (?1, ?2, ?3, ?4, ?5, ?6) ON CONFLICT(run_id, chat_session_id, dedupe) DO NOTHING", + params![run_id, chat_session_id, kind, dedupe, body, created_at], + )? == 1) + } + + pub(crate) fn queue_cancel_settled_notice( + &self, + run_id: &str, + chat: &str, + now: i64, + ) -> Result { + let notified: bool = self.conn.query_row( + "SELECT EXISTS(SELECT 1 FROM run_notices WHERE run_id = ?1 AND chat_session_id = ?2 + AND kind = ?3)", + params![run_id, chat, TERMINAL], + |row| row.get(0), + )?; + if !notified { + return Ok(false); + } + let run = self + .get_run(run_id)? + .ok_or_else(|| anyhow!("Run {run_id} not found"))?; + let view = crate::plane::Run::from_store(self, &run)?; + let status = view.display_status(); + let detail = if view.cancel_unconfirmed.is_some() { + run.result_markdown.as_deref().unwrap_or_default() + } else { + "All remaining processes have stopped." + }; + self.insert_run_notice( + run_id, + chat, + ATTENTION, + "cancel-stopped", + &format!("[orx] Run `{run_id}`: {status}. {detail}"), + now, + ) + } + + pub fn pending_run_notice_sessions(&self) -> Result> { + let mut stmt = self.conn.prepare( + "SELECT DISTINCT chat_session_id FROM run_notices + WHERE delivered_at IS NULL AND retired_at IS NULL + AND (next_delivery_at IS NULL OR next_delivery_at <= ?1) ORDER BY chat_session_id", + )?; + let rows = stmt.query_map([now_ms()], |row| row.get(0))?; + Ok(rows.collect::, _>>()?) + } + + pub fn record_run_notice_failure( + &self, + chat: &str, + client_turn_id: &str, + reason: &str, + permanent: bool, + now: i64, + ) -> Result> { + let tx = self.begin_immediate()?; + let prior: Option<(i64, Option)> = tx + .query_row( + "SELECT delivery_failures, first_failure_at FROM run_notices + WHERE chat_session_id = ?1 AND client_turn_id = ?2 + AND delivered_at IS NULL AND retired_at IS NULL LIMIT 1", + params![chat, client_turn_id], + |row| Ok((row.get(0)?, row.get(1)?)), + ) + .optional()?; + let Some((failures, first)) = prior else { + tx.commit()?; + return Ok(None); + }; + let first = first.unwrap_or(now); + let deadline = first.saturating_add(RUN_NOTICE_RETRY_WINDOW_MS); + let retired = (permanent || now >= deadline).then_some(now); + let delay_minutes = match failures { + 0 => 1, + 1 => 5, + 2 => 15, + _ => 60, + }; + let next = retired + .is_none() + .then(|| now.saturating_add(delay_minutes * 60 * 1000).min(deadline)); + let reason = if !permanent && now >= deadline { + format!("Retry window expired after 24 hours: {reason}") + } else { + reason.to_string() + }; + tx.execute( + "UPDATE run_notices SET delivery_failures = ?3, first_failure_at = ?4, + next_delivery_at = ?5, delivery_error = ?6, retired_at = ?7 + WHERE chat_session_id = ?1 AND client_turn_id = ?2 AND delivered_at IS NULL AND retired_at IS NULL", + params![chat, client_turn_id, failures + 1, first, next, reason, retired], + )?; + tx.commit()?; + Ok(Some(failures + 1)) + } + + /// Why the run's latest retired notice batch never reached its chat. + pub(crate) fn run_notice_error(&self, run_id: &str) -> Result> { + Ok(self + .conn + .query_row( + "SELECT delivery_error FROM run_notices WHERE run_id = ?1 AND retired_at IS NOT NULL + ORDER BY retired_at DESC, id DESC LIMIT 1", + [run_id], + |row| row.get(0), + ) + .optional()? + .flatten()) + } + + pub fn expire_run_notice_batches(&self, now: i64) -> Result<()> { + self.conn.execute( + "UPDATE run_notices SET retired_at = ?1, next_delivery_at = NULL, + delivery_error = 'Retry window expired after 24 hours: ' || delivery_error + WHERE delivered_at IS NULL AND retired_at IS NULL + AND first_failure_at <= ?1 - ?2", + params![now, RUN_NOTICE_RETRY_WINDOW_MS], + )?; + Ok(()) + } + + pub fn run_notice_batch(&self, chat_session_id: &str) -> Result> { + self.run_notice_batch_at(chat_session_id, now_ms()) + } + + pub fn run_notice_batch_at(&self, chat_session_id: &str, now: i64) -> Result> { + let tx = self.begin_immediate()?; + self.expire_run_notice_batches(now)?; + let assigned: Option = tx + .query_row( + "SELECT client_turn_id FROM run_notices + WHERE chat_session_id = ?1 AND delivered_at IS NULL AND client_turn_id IS NOT NULL + AND retired_at IS NULL AND (next_delivery_at IS NULL OR next_delivery_at <= ?2) + ORDER BY id LIMIT 1", + params![chat_session_id, now], + |row| row.get(0), + ) + .optional()?; + let client_turn_id = match assigned { + Some(id) => id, + None => { + let id = format!("run-notice:{}", uuid::Uuid::new_v4()); + let assigned = tx.execute( + "UPDATE run_notices SET client_turn_id = ?2 WHERE chat_session_id = ?1 + AND delivered_at IS NULL AND retired_at IS NULL AND client_turn_id IS NULL", + params![chat_session_id, id], + )?; + if assigned == 0 { + tx.commit()?; + return Ok(Vec::new()); + } + id + } + }; + let notices = { + let mut stmt = tx.prepare( + "SELECT id, run_id, chat_session_id, kind, dedupe, body, created_at, client_turn_id + FROM run_notices WHERE chat_session_id = ?1 AND client_turn_id = ?2 AND delivered_at IS NULL ORDER BY id", + )?; + let rows = stmt.query_map(params![chat_session_id, client_turn_id], |row| { + Ok(RunNotice { + id: row.get(0)?, + run_id: row.get(1)?, + chat_session_id: row.get(2)?, + kind: row.get(3)?, + dedupe: row.get(4)?, + body: row.get(5)?, + created_at: row.get(6)?, + client_turn_id: row.get(7)?, + }) + })?; + rows.collect::, _>>()? + }; + tx.commit()?; + Ok(notices) + } + + pub fn mark_run_notice_batch_delivered( + &self, + chat_session_id: &str, + client_turn_id: &str, + delivered_at: i64, + ) -> Result<()> { + self.conn.execute( + "UPDATE run_notices SET delivered_at = ?3, next_delivery_at = NULL WHERE chat_session_id = ?1 + AND client_turn_id = ?2 AND delivered_at IS NULL", + params![chat_session_id, client_turn_id, delivered_at], + )?; + Ok(()) + } + + /// Run under the engine lock after legacy delivery stops and before notice production. + pub fn migrate_run_wakeups(&self) -> Result<()> { + let tx = self.begin_immediate()?; + let wakeups = { + let mut stmt = tx.prepare( + "SELECT run_id, chat_session_id, state, requested_at, delivered_at, monitoring_alerted + FROM chat_run_wakeups WHERE engine_migrated = 0 ORDER BY run_id, chat_session_id", + )?; + let rows = stmt.query_map([], |row| { + Ok(( + row.get::<_, String>(0)?, + row.get::<_, String>(1)?, + row.get::<_, String>(2)?, + row.get::<_, i64>(3)?, + row.get::<_, Option>(4)?, + row.get::<_, bool>(5)?, + )) + })?; + rows.collect::, _>>()? + }; + for (run_id, chat, state, requested_at, delivered_at, alerted) in wakeups { + let Some(run) = self.get_run(&run_id)? else { + continue; + }; + if matches!(state.as_str(), "pending" | "claimed") { + if !is_terminal_status(&run.status) { + self.subscribe_run(&run_id, &chat, requested_at)?; + } else if matches!(run.status.as_str(), "done" | "failed" | "lost") { + let body = self.terminal_notice_body(&run)?; + self.insert_run_notice( + &run_id, + &chat, + TERMINAL, + TERMINAL, + &body, + requested_at, + )?; + } + } else if state == "delivered" { + self.insert_run_notice(&run_id, &chat, TERMINAL, TERMINAL, "", requested_at)?; + tx.execute( + "UPDATE run_notices SET delivered_at = ?4 WHERE run_id = ?1 AND chat_session_id = ?2 AND dedupe = ?3", + params![run_id, chat, TERMINAL, delivered_at.unwrap_or(requested_at)], + )?; + } + if alerted { + let dedupe = self.outage_dedupe(&run_id, &chat, ATTENTION)?; + self.insert_run_notice(&run_id, &chat, ATTENTION, &dedupe, "", requested_at)?; + tx.execute( + "UPDATE run_notices SET delivered_at = ?4 WHERE run_id = ?1 AND chat_session_id = ?2 AND dedupe = ?3", + params![run_id, chat, dedupe, delivered_at.unwrap_or(requested_at)], + )?; + } + tx.execute( + "UPDATE chat_run_wakeups SET engine_migrated = 1 + WHERE run_id = ?1 AND chat_session_id = ?2", + params![run_id, chat], + )?; + } + tx.pragma_update(None, "user_version", 2)?; + tx.commit()?; + Ok(()) + } + + /// Recovery notices advance the outage generation, including outages begun by 0.2.x. + pub fn outage_dedupe(&self, run_id: &str, chat: &str, kind: &str) -> Result { + let generation: i64 = self.conn.query_row( + "SELECT COUNT(*) FROM run_notices WHERE run_id = ?1 AND chat_session_id = ?2 AND kind = ?3", + params![run_id, chat, RECOVERED], |row| row.get(0), + )?; + Ok(format!("{kind}:{generation}")) + } + + pub fn terminal_notice_body(&self, run: &StoredRun) -> Result { + use std::io::{Read, Seek, SeekFrom}; + + let mut bytes = Vec::new(); + let ranges = crate::commands::up::api_v2::kept_ranges(&self.data_dir, &run.id)?; + let tail = self.run_artifact_path(TAIL_LOG, &run.id); + let current = if let Some(range) = ranges.iter().max_by_key(|range| range.offset) { + let file = std::fs::File::open(&range.file)?; + Ok((file, range.file.clone(), range.len)) + } else if tail.exists() { + let file = std::fs::File::open(&tail)?; + let size = file.metadata()?.len(); + Ok((file, tail, size)) + } else { + crate::jobs::ssh::service::logs::open_current( + self.run_artifact_path(("run-logs", ".log"), &run.id), + ) + }; + match current { + Ok((mut file, _, size)) => { + let start = size.saturating_sub(TERMINAL_LOG_BYTES); + file.seek(SeekFrom::Start(start))?; + bytes.resize(usize::try_from(size - start)?, 0); + file.read_exact(&mut bytes)?; + } + Err(error) + if error + .downcast_ref::() + .is_some_and(|error| error.kind() == std::io::ErrorKind::NotFound) => {} + Err(error) => return Err(error), + } + let first_character = bytes + .iter() + .position(|byte| byte & 0xc0 != 0x80) + .unwrap_or(bytes.len()); + let log = String::from_utf8_lossy(&bytes[first_character..]); + let mut start = log + .len() + .saturating_sub(usize::try_from(TERMINAL_LOG_BYTES)?); + while !log.is_char_boundary(start) { + start += 1; + } + let mut lines: Vec<_> = log[start..] + .lines() + .rev() + .take(TERMINAL_LOG_LINES) + .collect(); + lines.reverse(); + let tail = lines.join("\n"); + let code = run + .exit_code + .map(|code| code.to_string()) + .unwrap_or_else(|| "unavailable".into()); + let duration = run + .ended_at + .map(|ended| format!("{} ms", ended.saturating_sub(run.created_at).max(0))) + .unwrap_or_else(|| "unavailable".into()); + let cancel_reason = run + .cancel_reason + .as_deref() + .filter(|_| run.status == "cancelled"); + let reason = match (cancel_reason, run.result_markdown.as_deref()) { + (Some(cancel), Some(result)) => format!("{cancel} {result}"), + (cancel, result) => cancel.or(result).unwrap_or("unavailable").into(), + }; + let view = crate::plane::Run::from_store(self, run)?; + let status = view.display_status(); + Ok(format!( + "[orx] Run `{}` finished with status **{}**.\nExit code: {code}\nDuration: {duration}\nReason: {reason}\n\nRecent log:\n{tail}", + run.id, status, + )) + } +} + +const SELECT_RUN: &str = "SELECT id, experiment_id, project_id, status, backend_json, command, + created_at, updated_at, ended_at, exit_code, + commit_sha, result_markdown, cancel_requested, + chat_session_id, cancel_reason FROM runs"; + +const PROJECT_COLS: &str = "id, name, slug, github_owner, github_repo, github_sync_enabled, \ + baseline_branch, repo_path, run_command, paper_id, created_at, updated_at"; + +const EXPERIMENT_COLS: &str = "id, project_id, parent_experiment_id, slug, branch_name, \ + title, description, run_command, agent_status, created_at, \ + updated_at, chat_session_id, archived"; + +fn row_to_run(row: &rusqlite::Row<'_>) -> std::result::Result { + row_to_run_at(row, 0) +} + +/// A [`SELECT_RUN`] row whose columns start at `first`. +fn row_to_run_at( + row: &rusqlite::Row<'_>, + first: usize, +) -> std::result::Result { + Ok(StoredRun { + id: row.get(first)?, + experiment_id: row.get(first + 1)?, + project_id: row.get(first + 2)?, + status: row.get(first + 3)?, + backend_json: row.get(first + 4)?, + command: row.get(first + 5)?, + created_at: row.get(first + 6)?, + updated_at: row.get(first + 7)?, + ended_at: row.get(first + 8)?, + exit_code: row.get(first + 9)?, + commit_sha: row.get(first + 10)?, + result_markdown: row.get(first + 11)?, + cancel_requested: row.get(first + 12)?, + chat_session_id: row.get(first + 13)?, + cancel_reason: row.get(first + 14)?, + }) +} + +pub fn now_ms() -> i64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_millis() as i64) + .unwrap_or(0) +} + +fn log_generation_run_id(name: &str) -> Option<&str> { + let (run, generation) = name.strip_suffix(".log")?.split_once('.')?; + uuid::Uuid::parse_str(generation).ok()?; + Some(run) +} + +fn artifact_entries(path: &Path) -> Result> { + match std::fs::read_dir(path) { + Ok(entries) => Ok(entries.collect::>>()?), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()), + Err(error) => Err(error.into()), + } +} + +fn remove_run_artifact(path: &Path) -> Result<()> { + let result = match std::fs::symlink_metadata(path) { + Ok(metadata) if metadata.file_type().is_dir() => std::fs::remove_dir_all(path), + Ok(_) => std::fs::remove_file(path), + Err(error) => Err(error), + }; + match result { + Ok(()) => Ok(()), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(error) => Err(anyhow!( + "Could not remove run artifact {}: {error}", + path.display() + )), + } +} + +/// Resolves `parts` under `root` through real directories only, so symlinks cannot redirect removal. +fn real_path_under<'a>( + root: &Path, + parts: impl IntoIterator, +) -> Result> { + let mut path = root.to_path_buf(); + for part in parts { + path.push(part); + match std::fs::symlink_metadata(&path) { + Ok(metadata) if metadata.file_type().is_dir() => {} + Ok(_) => return Ok(None), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(error) => return Err(error.into()), + } + } + Ok(Some(path)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn min_reader_version_refuses_before_migrations_on_every_open() { + let dir = std::env::temp_dir().join(format!("orx-reader-floor-{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&dir).unwrap(); + let conn = Connection::open(dir.join("orx.db")).unwrap(); + conn.execute_batch( + "CREATE TABLE store_metadata (key TEXT PRIMARY KEY, value INTEGER NOT NULL); + INSERT INTO store_metadata VALUES ('min_reader_version', 2);", + ) + .unwrap(); + let error = Store::open_at(dir.clone()).err().unwrap(); + assert!(error.to_string().contains("min_reader_version 2")); + let migrated: bool = conn + .query_row( + "SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE name = 'runs')", + [], + |row| row.get(0), + ) + .unwrap(); + assert!(!migrated); + conn.execute("UPDATE store_metadata SET value = 1", []) + .unwrap(); + drop(Store::open_at(dir.clone()).unwrap()); + conn.execute("UPDATE store_metadata SET value = 2", []) + .unwrap(); + assert!(Store::open_at(dir.clone()).is_err()); + drop(conn); + std::fs::remove_dir_all(dir).unwrap(); + } + + // Pinned from 0.2.22 main: store.rs, commands/{supervise,up}.rs and jobs/ssh/service/mod.rs. + const LEGACY_SELECT_RUN: &str = + "SELECT id, experiment_id, project_id, status, backend_json, command, + created_at, updated_at, ended_at, exit_code, + commit_sha, result_markdown, cancel_requested, + chat_session_id, cancel_reason FROM runs"; + const LEGACY_ACTIVE_RUNS: &str = + "SELECT id, experiment_id, project_id, status, backend_json, command, + created_at, updated_at, ended_at, exit_code, + commit_sha, result_markdown, cancel_requested, + chat_session_id, cancel_reason FROM runs + WHERE status IN ('starting', 'running') ORDER BY created_at DESC"; + const LEGACY_REQUEST_CANCEL: &str = + "UPDATE runs SET cancel_requested = 1, cancel_reason = ?2, updated_at = ?3 + WHERE id = ?1 AND cancel_requested = 0 AND status IN ('starting', 'running')"; + const LEGACY_WITHDRAW_CANCEL: &str = + "UPDATE runs SET cancel_requested = 0, updated_at = ?2 WHERE id = ?1"; + const LEGACY_SUPERVISE_DISPATCH: &[&str] = &[ + "k8s_job", + "modal_job", + "ssh_job", + "slurm_job", + "ray_job", + "openresearch_job", + "local_job", + "tinker_job", + ]; + const LEGACY_SUPERVISE_FALLTHROUGH: &str = "hf_job"; + const LEGACY_SSH_SERVICE_SCAN: fn(&str, bool, bool) -> bool = + |kind, supervisor_running, uses_shared_ssh| { + matches!(kind, "ssh_job" | "slurm_job" | "openresearch_job") + && supervisor_running + && !uses_shared_ssh + }; + const LEGACY_SUPERVISOR_LOCK: (&str, &str) = ("run-logs", ".supervisor.lock"); + const LEGACY_ADOPTION: fn(bool, bool, bool, bool) -> bool = + |submitted, settled, local_experiment, supervisor_running| { + submitted && settled && local_experiment && !supervisor_running + }; + + #[derive(serde::Deserialize)] + #[serde(rename_all = "camelCase")] + struct LegacyDescriptor { + kind: String, + job_id: Option, + source_digest: Option, + source_path: Option, + source_size: Option, + } + + fn legacy_rows(conn: &Connection, sql: &str) -> Vec> { + conn.prepare(sql) + .unwrap() + .query_map([], |row| { + (0..row.as_ref().column_count()) + .map(|i| row.get(i)) + .collect() + }) + .unwrap() + .collect::>() + .unwrap() + } + + fn legacy_active_runs(conn: &Connection) -> Vec<(String, LegacyDescriptor)> { + conn.prepare(LEGACY_ACTIVE_RUNS) + .unwrap() + .query_map([], |row| { + Ok((row.get::<_, String>(0)?, row.get::<_, String>(4)?)) + }) + .unwrap() + .map(|row| { + let (id, json) = row.unwrap(); + (id, serde_json::from_str(&json).unwrap()) + }) + .collect() + } + + fn test_launch() -> LaunchSpec { + LaunchSpec { + kind: "ssh_job".into(), + target: Some("lab".into()), + options: serde_json::json!({}), + } + } + + fn engine_fixture() -> (PathBuf, Store) { + let dir = std::env::temp_dir().join(format!("orx-engine-store-{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&dir).unwrap(); + let conn = Connection::open(dir.join("orx.db")).unwrap(); + conn.execute_batch(include_str!("../tests/fixtures/store-0.2.22.sql")) + .unwrap(); + assert!(conn.prepare("SELECT contact FROM runs").is_err()); + drop(conn); + let store = Store::open_at(dir.clone()).unwrap(); + (dir, store) + } + + #[test] + fn engine_migration_enqueues_every_finished_pending_or_claimed_result_except_cancelled() { + let (dir, store) = engine_fixture(); + for phase in ["done", "failed", "lost", "cancelled"] { + for state in ["pending", "claimed"] { + let id = format!("{phase}_{state}"); + let mut run = run_fixture(&id, phase, Some("owner")); + run.ended_at = Some(101); + run.exit_code = Some(7); + run.result_markdown = Some("payload ended".into()); + store.upsert_run(&run).unwrap(); + store.register_run_wakeup(&id, "foreign").unwrap(); + if state == "claimed" { + store.claim_run_wakeup(&id, "foreign").unwrap().unwrap(); + } + std::fs::write(dir.join(format!("run-logs/{id}.log")), "result line\n").unwrap(); + } + } + store.migrate_run_wakeups().unwrap(); + for phase in ["done", "failed", "lost", "cancelled"] { + for state in ["pending", "claimed"] { + let id = format!("{phase}_{state}"); + assert_eq!( + store + .conn + .query_row( + "SELECT COUNT(*) FROM run_subscriptions WHERE run_id = ?1", + [&id], + |row| row.get::<_, i64>(0) + ) + .unwrap(), + 0 + ); + let notice: Option<(String, String, Option)> = store + .conn + .query_row( + "SELECT body, dedupe, delivered_at FROM run_notices WHERE run_id = ?1", + [&id], + |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)), + ) + .optional() + .unwrap(); + if phase == "cancelled" { + assert!(notice.is_none()); + continue; + } + let (body, dedupe, delivered) = notice.unwrap(); + assert_eq!( + body, + store + .terminal_notice_body(&store.get_run(&id).unwrap().unwrap()) + .unwrap() + ); + assert!(body.contains(&format!("**{phase}**"))); + assert!(body.contains("Exit code: 7\nDuration: 100 ms\nReason: payload ended")); + assert!(body.ends_with("Recent log:\nresult line")); + assert_eq!(dedupe, TERMINAL); + assert!(delivered.is_none()); + } + } + let frozen = store.run_notice_batch("foreign").unwrap(); + assert_eq!(frozen.len(), 7); + store.migrate_run_wakeups().unwrap(); + assert_eq!(store.run_notice_batch("foreign").unwrap(), frozen); + drop(store); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn terminal_notice_of_a_cancelled_run_gives_the_recorded_cancel_reason() { + let (dir, store) = engine_fixture(); + let mut run = run_fixture("cancelled", "cancelled", None); + run.cancel_reason = Some("Cancel requested with `orx exp cancel`.".into()); + let body = store.terminal_notice_body(&run).unwrap(); + assert!(body.contains("\nReason: Cancel requested with `orx exp cancel`.\n")); + run.result_markdown = Some("Killed by signal 15.".into()); + let body = store.terminal_notice_body(&run).unwrap(); + assert!(body + .contains("\nReason: Cancel requested with `orx exp cancel`. Killed by signal 15.\n")); + run.status = "done".into(); + let body = store.terminal_notice_body(&run).unwrap(); + assert!(body.contains("\nReason: Killed by signal 15.\n")); + drop(store); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn engine_terminal_renderer_bounds_log_bytes_and_lines_without_splitting_utf8() { + let (dir, store) = engine_fixture(); + let run = store.get_run("failed").unwrap().unwrap(); + let path = dir.join("run-logs/failed.log"); + let lines: String = (0..100).map(|i| format!("line-{i:03}\n")).collect(); + std::fs::write(&path, &lines).unwrap(); + let body = store.terminal_notice_body(&run).unwrap(); + let tail = body.split("Recent log:\n").nth(1).unwrap(); + assert_eq!(tail.lines().count(), 40); + assert!(tail.starts_with("line-060\n")); + assert!(tail.ends_with("line-099")); + std::fs::write(&path, format!("{}a", "🦀".repeat(1500))).unwrap(); + let body = store.terminal_notice_body(&run).unwrap(); + let tail = body.split("Recent log:\n").nth(1).unwrap(); + assert!(tail.len() <= 4096); + assert!(!tail.contains('\u{fffd}')); + assert!(tail.ends_with('a')); + drop(store); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn engine_wakeup_migration_imports_new_legacy_rows_after_downgrade() { + let (dir, store) = engine_fixture(); + store.migrate_run_wakeups().unwrap(); + let delivered = store.run_notice_batch("foreign").unwrap(); + assert_eq!(delivered.len(), 1); + store + .mark_run_notice_batch_delivered("foreign", &delivered[0].client_turn_id, 600) + .unwrap(); + drop(store); + + let legacy = Connection::open(dir.join("orx.db")).unwrap(); + legacy + .execute_batch( + "INSERT INTO chat_run_wakeups (run_id, chat_session_id, requested_at) + VALUES ('slurm_job', 'foreign', 700), ('lost', 'foreign', 701); + INSERT INTO chat_run_wakeups + (run_id, chat_session_id, requested_at, state, delivered_at) + VALUES ('done', 'foreign', 702, 'delivered', 703);", + ) + .unwrap(); + drop(legacy); + + let store = Store::open_at(dir.clone()).unwrap(); + store.migrate_run_wakeups().unwrap(); + assert!(store + .run_subscribers("slurm_job") + .unwrap() + .iter() + .any(|chat| chat == "foreign")); + let notices = store.run_notice_batch("foreign").unwrap(); + assert_eq!(notices.len(), 1); + assert_eq!(notices[0].run_id, "lost"); + assert_eq!( + store + .conn + .query_row( + "SELECT delivered_at FROM run_notices + WHERE run_id = 'failed' AND chat_session_id = 'foreign'", + [], + |row| row.get::<_, i64>(0), + ) + .unwrap(), + 600 + ); + store.migrate_run_wakeups().unwrap(); + assert_eq!(store.run_notice_batch("foreign").unwrap(), notices); + drop(store); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn terminal_notice_prefers_kept_ranges_to_the_published_legacy_log_generation() { + let (dir, store) = engine_fixture(); + let run = store.get_run("failed").unwrap().unwrap(); + let path = dir.join("run-logs/failed.log"); + std::fs::write(&path, "obsolete generation\n").unwrap(); + let generation = uuid::Uuid::new_v4(); + let published = "UPGRADE_BEGIN\nFINAL_METRIC=0.862\nUPGRADE_END\n"; + std::fs::write( + path.with_extension(format!("{generation}.log")), + format!("{published}unpublished bytes\n"), + ) + .unwrap(); + std::fs::write( + path.with_extension("cursor.json"), + serde_json::to_vec(&serde_json::json!({ + "generation": generation.to_string(), + "identity": "legacy-log", + "boundary": "boundary", + "bytes": published.len(), + })) + .unwrap(), + ) + .unwrap(); + let body = store.terminal_notice_body(&run).unwrap(); + assert_eq!( + body.split_once("Recent log:\n").unwrap().1, + published.trim_end() + ); + let collected = "collected after adoption\nUPGRADE_END\n"; + std::fs::write(&path, format!("{collected}unpublished bytes\n")).unwrap(); + let manifest = path.with_extension("ranges.json"); + std::fs::write( + &manifest, + serde_json::to_vec(&serde_json::json!([{ + "offset": 0, + "len": collected.len(), + "file": &path, + "ident": "1-2", + "eof": true, + }])) + .unwrap(), + ) + .unwrap(); + let body = store.terminal_notice_body(&run).unwrap(); + assert_eq!( + body.split_once("Recent log:\n").unwrap().1, + collected.trim_end() + ); + std::fs::write(&path, "truncated").unwrap(); + assert!(store.terminal_notice_body(&run).is_err()); + std::fs::write(&path, collected).unwrap(); + std::fs::remove_file(manifest).unwrap(); + let engine_cursor = path.with_extension("engine-cursor.json"); + std::fs::write( + &engine_cursor, + serde_json::to_vec(&serde_json::json!({"offset": collected.len()})).unwrap(), + ) + .unwrap(); + let body = store.terminal_notice_body(&run).unwrap(); + assert_eq!( + body.split_once("Recent log:\n").unwrap().1, + collected.trim_end() + ); + std::fs::remove_file(engine_cursor).unwrap(); + std::fs::write(dir.join("run-logs/failed.tail.log"), "retained tail\n").unwrap(); + let body = store.terminal_notice_body(&run).unwrap(); + assert!(body.ends_with("Recent log:\nretained tail")); + drop(store); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn engine_wakeup_migration_rolls_back_on_an_unreadable_completion_log() { + let (dir, store) = engine_fixture(); + let path = dir.join("run-logs/failed.log"); + std::fs::create_dir(&path).unwrap(); + assert!(store.migrate_run_wakeups().is_err()); + for table in ["run_notices", "run_subscriptions"] { + assert_eq!( + store + .conn + .query_row(&format!("SELECT COUNT(*) FROM {table}"), [], |row| row + .get::<_, i64>(0)) + .unwrap(), + 0 + ); + } + assert_eq!( + store + .conn + .query_row( + "SELECT COUNT(*) FROM chat_run_wakeups WHERE engine_migrated != 0", + [], + |row| row.get::<_, i64>(0), + ) + .unwrap(), + 0 + ); + assert_eq!( + store + .conn + .query_row("PRAGMA user_version", [], |row| row.get::<_, i64>(0)) + .unwrap(), + 1 + ); + std::fs::remove_dir(&path).unwrap(); + store.migrate_run_wakeups().unwrap(); + assert_eq!(store.run_notice_batch("foreign").unwrap().len(), 1); + drop(store); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn engine_absent_recovery_advances_and_refences_only_the_current_uncancelled_attempt() { + let (dir, store) = engine_fixture(); + let metadata = crate::jobs::BackendDescriptor::parse(r#"{"kind":"hf_job"}"#).unwrap(); + store + .insert_submitting_run(SubmittingRun { + id: "retry", + experiment_id: "exp_1", + project_id: "proj_1", + metadata: &metadata, + command: "train", + created_at: 1, + commit_sha: None, + chat_session_id: None, + spec_digest: "digest", + launch: &test_launch(), + }) + .unwrap(); + let fence = SubmissionFence { + taken_at: 1, + submitter: Some(SubmitterIdentity { + pid: 4, + starttime: 5, + }), + }; + assert!(store.set_submission_fence("retry", 1, &fence).unwrap()); + assert!(store.advance_submission_attempt("retry", 1).unwrap()); + let state = store.engine_run_state("retry").unwrap().unwrap(); + assert_eq!(state.submission_attempt, 2); + assert!(state.submission_fence.is_none()); + assert!(!store.advance_submission_attempt("retry", 1).unwrap()); + assert!(!store.set_submission_fence("retry", 1, &fence).unwrap()); + assert!(store.set_submission_fence("retry", 2, &fence).unwrap()); + let handle = crate::engine::adapters::api::test_handle( + "hf_job", + Some("lab"), + None, + vec!["job".into()], + ); + assert!(!store.record_run_handle("retry", 1, &handle).unwrap()); + assert!(!store.advance_submission_attempt("ssh_job", 1).unwrap()); + assert!(!store.advance_submission_attempt("done", 1).unwrap()); + store + .conn + .execute( + "UPDATE runs SET submission_attempt = ?1 WHERE id = 'retry'", + [u32::MAX], + ) + .unwrap(); + assert!(!store.advance_submission_attempt("retry", u32::MAX).unwrap()); + store + .conn + .execute( + "UPDATE runs SET submission_attempt = 2 WHERE id = 'retry'", + [], + ) + .unwrap(); + store + .accept_run_cancel("retry", Some("cancel")) + .unwrap() + .unwrap(); + assert!(!store.advance_submission_attempt("retry", 2).unwrap()); + assert_eq!( + store + .engine_run_state("retry") + .unwrap() + .unwrap() + .submission_fence, + Some(fence) + ); + drop(store); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn engine_run_and_chat_deletion_remove_only_their_outbox_rows_transactionally() { + let (dir, store) = engine_fixture(); + for (run, chat) in [("done", "owner"), ("done", "foreign"), ("failed", "owner")] { + store.subscribe_run(run, chat, 1).unwrap(); + store + .insert_run_notice(run, chat, TERMINAL, TERMINAL, "result", 1) + .unwrap(); + } + let tx = store.begin().unwrap(); + tx.execute("DELETE FROM runs WHERE id = 'done'", []) + .unwrap(); + assert_eq!( + store + .conn + .query_row("SELECT COUNT(*) FROM run_notices", [], |row| row + .get::<_, i64>(0)) + .unwrap(), + 1 + ); + tx.rollback().unwrap(); + assert_eq!( + store + .conn + .query_row("SELECT COUNT(*) FROM run_notices", [], |row| row + .get::<_, i64>(0)) + .unwrap(), + 3 + ); + store.delete_chat_session("foreign").unwrap(); + for table in ["run_notices", "run_subscriptions"] { + assert_eq!( + store + .conn + .query_row(&format!("SELECT COUNT(*) FROM {table}"), [], |row| row + .get::<_, i64>(0)) + .unwrap(), + 2 + ); + } + store + .conn + .execute("DELETE FROM runs WHERE id = 'done'", []) + .unwrap(); + for table in ["run_notices", "run_subscriptions"] { + let rows: Vec<(String, String)> = store + .conn + .prepare(&format!("SELECT run_id, chat_session_id FROM {table}")) + .unwrap() + .query_map([], |row| Ok((row.get(0)?, row.get(1)?))) + .unwrap() + .collect::>() + .unwrap(); + assert_eq!(rows, [("failed".into(), "owner".into())]); + } + drop(store); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn engine_schema_preserves_022_runs_and_legacy_readers_and_cleanup() { + let old = Connection::open_in_memory().unwrap(); + old.execute_batch(include_str!("../tests/fixtures/store-0.2.22.sql")) + .unwrap(); + assert!(old.prepare("SELECT started_at FROM runs").is_err()); + let before = legacy_rows(&old, &format!("{LEGACY_SELECT_RUN} ORDER BY id")); + let (dir, store) = engine_fixture(); + let after = legacy_rows(&store.conn, &format!("{LEGACY_SELECT_RUN} ORDER BY id")); + assert_eq!(before, after); + assert_eq!(store.count_active_runs().unwrap(), 9); + assert!(LEGACY_SSH_SERVICE_SCAN("ssh_job", true, false)); + assert!(!LEGACY_SSH_SERVICE_SCAN("ssh_job", true, true)); + let active = legacy_active_runs(&store.conn); + assert_eq!(active.len(), 9); + assert_eq!(active.first().unwrap().0, "openresearch_job"); + for run in store.list_runs(100).unwrap() { + assert_eq!( + store.engine_run_state(&run.id).unwrap().unwrap(), + EngineRunState { + started_at: None, + contact: Contact::Live, + cancel_unconfirmed: None, + spec_digest: None, + submission_attempt: 1, + submission_fence: None, + cancel_accepted_at: None, + launch: None, + notify_cursor: None, + } + ); + } + let snapshots = dir.join("source-snapshots"); + std::fs::create_dir_all(&snapshots).unwrap(); + for (_, descriptor) in active { + assert!( + LEGACY_SUPERVISE_DISPATCH.contains(&descriptor.kind.as_str()) + || descriptor.kind == LEGACY_SUPERVISE_FALLTHROUGH + ); + assert!(descriptor.job_id.is_some()); + let digest = descriptor.source_digest.unwrap(); + for extension in ["tar", "hf", "zip"] { + std::fs::write(snapshots.join(format!("{digest}.{extension}")), "source").unwrap(); + } + } + let orphan = snapshots.join(format!("{}.tar", "f".repeat(64))); + std::fs::write(&orphan, "unreferenced").unwrap(); + store.cleanup_orphaned_run_artifacts().unwrap(); + assert!(!orphan.exists()); + assert_eq!(std::fs::read_dir(&snapshots).unwrap().count(), 27); + assert_eq!( + store + .conn + .execute( + LEGACY_REQUEST_CANCEL, + params!["slurm_job", "old CLI", now_ms()] + ) + .unwrap(), + 1 + ); + store + .conn + .execute(LEGACY_WITHDRAW_CANCEL, params!["slurm_job", now_ms()]) + .unwrap(); + assert!( + !store + .get_run("slurm_job") + .unwrap() + .unwrap() + .cancel_requested + ); + assert_eq!( + store.get_run("slurm_job").unwrap().unwrap().status, + "starting" + ); + assert!(!store.request_cancel("done", "old CLI").unwrap()); + drop(store); + let reopened = Store::open_at(dir.clone()).unwrap(); + assert_eq!(legacy_active_runs(&reopened.conn).len(), 9); + assert_eq!( + reopened + .conn + .query_row("SELECT COUNT(*) FROM run_notices", [], |row| row + .get::<_, i64>(0)) + .unwrap(), + 0 + ); + drop(reopened); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn engine_submitting_is_hidden_and_owned_handles_skip_legacy_adoption() { + use crate::engine::handle::Handle; + let (dir, store) = engine_fixture(); + let mut run = run_fixture("engine_run", "submitting", Some("owner")); + run.backend_json = store.get_run("ssh_job").unwrap().unwrap().backend_json; + store + .insert_submitting_run(SubmittingRun { + id: &run.id, + experiment_id: &run.experiment_id, + project_id: &run.project_id, + metadata: &crate::jobs::BackendDescriptor::parse(&run.backend_json).unwrap(), + command: &run.command, + created_at: run.created_at, + commit_sha: run.commit_sha.as_deref(), + chat_session_id: run.chat_session_id.as_deref(), + spec_digest: "spec-sha", + launch: &test_launch(), + }) + .unwrap(); + assert!(store + .insert_submitting_run(SubmittingRun { + id: &run.id, + experiment_id: &run.experiment_id, + project_id: &run.project_id, + metadata: &crate::jobs::BackendDescriptor::parse(&run.backend_json).unwrap(), + command: &run.command, + created_at: run.created_at, + commit_sha: run.commit_sha.as_deref(), + chat_session_id: run.chat_session_id.as_deref(), + spec_digest: "spec-sha", + launch: &test_launch(), + }) + .is_err()); + assert_eq!(store.count_active_runs().unwrap(), 10); + assert!(!legacy_active_runs(&store.conn) + .iter() + .any(|(id, _)| id == &run.id)); + assert_eq!( + store + .conn + .execute(LEGACY_REQUEST_CANCEL, params![run.id, "old CLI", now_ms()]) + .unwrap(), + 0 + ); + let submitting = store.get_run(&run.id).unwrap().unwrap(); + let descriptor = crate::jobs::BackendDescriptor::parse(&submitting.backend_json).unwrap(); + assert_eq!(descriptor.kind, "engine"); + assert!(descriptor.job_id.is_none()); + let handle = Handle::Ssh { + host: "lab".into(), + root: "/orx".into(), + }; + assert!(!store.record_run_handle(&run.id, 1, &handle).unwrap()); + let fence = SubmissionFence { + taken_at: 1000, + submitter: Some(SubmitterIdentity { + pid: 42, + starttime: 5678, + }), + }; + assert!(!store.set_submission_fence(&run.id, 2, &fence).unwrap()); + assert!(store.set_submission_fence(&run.id, 1, &fence).unwrap()); + assert!(!store.set_submission_fence(&run.id, 1, &fence).unwrap()); + assert!(!store.record_run_handle(&run.id, 2, &handle).unwrap()); + let mut supervisor = + open_lifecycle_lock_at(&dir.join("run-logs/engine_run.supervisor.lock")).unwrap(); + let mut shared = + open_lifecycle_lock_at(&dir.join("run-logs/engine_run.supervisor.shared-ssh.lock")) + .unwrap(); + let supervisor_guard = supervisor.write().unwrap(); + let shared_guard = shared.write().unwrap(); + assert!(store.record_run_handle(&run.id, 1, &handle).unwrap()); + assert!(!store.record_run_handle(&run.id, 1, &handle).unwrap()); + assert!(store.supervisor_is_held(&run.id).unwrap()); + let mut old_shared_probe = + open_lifecycle_lock_at(&dir.join("run-logs/engine_run.supervisor.shared-ssh.lock")) + .unwrap(); + assert!( + matches!(old_shared_probe.try_write(), Err(e) if e.kind() == std::io::ErrorKind::WouldBlock) + ); + let active = legacy_active_runs(&store.conn); + assert_eq!(active.len(), 10); + for (id, descriptor) in &active { + assert!(descriptor.job_id.is_some()); + let mut probe = + open_lifecycle_lock_at(&store.run_artifact_path(LEGACY_SUPERVISOR_LOCK, id)) + .unwrap(); + let held = matches!(probe.try_write(), Err(error) if error.kind() == std::io::ErrorKind::WouldBlock); + if id == &run.id { + assert!(!LEGACY_ADOPTION( + descriptor.job_id.is_some(), + true, + true, + held + )); + assert!(!LEGACY_SUPERVISE_DISPATCH.contains(&descriptor.kind.as_str())); + assert_ne!(descriptor.kind, LEGACY_SUPERVISE_FALLTHROUGH); + assert!(!LEGACY_SSH_SERVICE_SCAN(&descriptor.kind, held, true)); + assert_eq!( + descriptor.source_digest.as_deref(), + Some("0000000000000000000000000000000000000000000000000000000000000000") + ); + assert_eq!(descriptor.source_path.as_deref(), Some("/sources/0.tar")); + assert_eq!(descriptor.source_size, Some(123)); + } + } + let row = store.get_run(&run.id).unwrap().unwrap(); + let descriptor = crate::jobs::BackendDescriptor::parse(&row.backend_json).unwrap(); + assert_eq!(descriptor.job_id.as_deref(), Some("/orx/runs/engine_run")); + assert_eq!( + descriptor.source_digest.as_deref(), + Some("0000000000000000000000000000000000000000000000000000000000000000") + ); + assert_eq!(descriptor.source_path.as_deref(), Some("/sources/0.tar")); + assert_eq!(descriptor.source_size, Some(123)); + let digest = descriptor.source_digest.clone().unwrap(); + let snapshot = dir.join(format!("source-snapshots/{digest}.tar")); + std::fs::create_dir_all(snapshot.parent().unwrap()).unwrap(); + std::fs::write(&snapshot, "keep").unwrap(); + store + .conn + .execute("DELETE FROM runs WHERE id = 'ssh_job'", []) + .unwrap(); + store.cleanup_orphaned_run_artifacts().unwrap(); + assert!(snapshot.exists()); + assert!(serde_json::from_str::(&row.backend_json) + .unwrap() + .get("handle") + .is_some()); + assert!( + serde_json::from_str::(&descriptor.to_json()) + .unwrap() + .get("handle") + .is_none() + ); + assert!(store + .update_status(&run.id, RunStatus::Running, None, None) + .unwrap()); + assert!(legacy_active_runs(&store.conn) + .iter() + .any(|(id, _)| id == &run.id)); + drop(shared_guard); + drop(supervisor_guard); + drop(store); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn engine_contact_and_submission_fence_survive_reopen() { + let (dir, store) = engine_fixture(); + assert!(store.engine_run_state("missing").unwrap().is_none()); + let mut run = run_fixture("engine_contact", "submitting", None); + run.backend_json = r#"{"kind":"hf_job"}"#.into(); + store + .insert_submitting_run(SubmittingRun { + id: &run.id, + experiment_id: &run.experiment_id, + project_id: &run.project_id, + metadata: &crate::jobs::BackendDescriptor::parse(&run.backend_json).unwrap(), + command: &run.command, + created_at: run.created_at, + commit_sha: run.commit_sha.as_deref(), + chat_session_id: run.chat_session_id.as_deref(), + spec_digest: "digest", + launch: &test_launch(), + }) + .unwrap(); + let fence = SubmissionFence { + taken_at: 123, + submitter: Some(SubmitterIdentity { + pid: 1234, + starttime: u64::MAX, + }), + }; + assert!(store.set_submission_fence(&run.id, 1, &fence).unwrap()); + let contacts = [ + Contact::Unreachable { + since: 100, + cause: "transport".into(), + }, + Contact::NeedsAuth { + since: 200, + cause: "key rejected".into(), + }, + Contact::Unreconciled { + since: 300, + detail: "submit unknown".into(), + }, + Contact::Live, + ]; + for contact in contacts { + assert!(store.set_run_contact(&run.id, &contact).unwrap()); + let reopened = Store::open_at(dir.clone()).unwrap(); + let state = reopened.engine_run_state(&run.id).unwrap().unwrap(); + assert_eq!(state.contact, contact); + assert_eq!(state.spec_digest.as_deref(), Some("digest")); + assert_eq!(state.submission_attempt, 1); + assert_eq!(state.submission_fence.as_ref(), Some(&fence)); + assert!(state.cancel_accepted_at.is_none()); + assert_eq!( + reopened.get_run(&run.id).unwrap().unwrap().status, + "submitting" + ); + } + assert!(store + .conn + .query_row( + "SELECT contact IS NULL FROM runs WHERE id = ?1", + [&run.id], + |row| row.get::<_, bool>(0) + ) + .unwrap()); + assert!(!store.set_run_contact("missing", &Contact::Live).unwrap()); + drop(store); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn engine_notice_backoff_survives_restart_and_expires_after_one_day() { + let (dir, store) = engine_fixture(); + for run in ["ssh_job", "slurm_job"] { + store + .insert_run_notice(run, "owner", TERMINAL, TERMINAL, "result", 1) + .unwrap(); + } + let start = 1_000_000; + let frozen = store.run_notice_batch_at("owner", start).unwrap(); + assert_eq!(frozen.len(), 2); + drop(store); + + let deadline = start + RUN_NOTICE_RETRY_WINDOW_MS; + let mut now = start; + let mut failures = 0; + while now < deadline { + let store = Store::open_at(dir.clone()).unwrap(); + assert_eq!(store.run_notice_batch_at("owner", now).unwrap(), frozen); + failures += 1; + assert_eq!( + store + .record_run_notice_failure( + "owner", + &frozen[0].client_turn_id, + "rate limited", + false, + now + ) + .unwrap(), + Some(failures) + ); + let expected_minutes = match failures { + 1 => 1, + 2 => 5, + 3 => 15, + _ => 60, + }; + let due = (now + expected_minutes * 60_000).min(deadline); + let recorded: (i64, i64, Option) = store.conn.query_row( + "SELECT first_failure_at, next_delivery_at, retired_at FROM run_notices WHERE id = ?1", + [frozen[0].id], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)), + ).unwrap(); + assert_eq!(recorded, (start, due, None)); + assert!(store + .run_notice_batch_at("owner", due - 1) + .unwrap() + .is_empty()); + drop(store); + now = due; + } + let store = Store::open_at(dir.clone()).unwrap(); + assert!(store + .run_notice_batch_at("owner", deadline) + .unwrap() + .is_empty()); + let retired: (i64, String) = store + .conn + .query_row( + "SELECT retired_at, delivery_error FROM run_notices WHERE id = ?1", + [frozen[0].id], + |row| Ok((row.get(0)?, row.get(1)?)), + ) + .unwrap(); + assert_eq!( + retired, + ( + deadline, + "Retry window expired after 24 hours: rate limited".into() + ) + ); + assert_eq!( + store + .record_run_notice_failure( + "owner", + &frozen[0].client_turn_id, + "again", + false, + deadline + ) + .unwrap(), + None + ); + assert!(store.pending_run_notice_sessions().unwrap().is_empty()); + drop(store); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn a_retired_notice_batch_does_not_block_idle_and_is_reported_on_its_run() { + let dir = std::env::temp_dir().join(format!("orx-retired-{}", uuid::Uuid::new_v4())); + let store = Store::open_at(dir.clone()).unwrap(); + store + .insert_run_notice("run", "owner", TERMINAL, TERMINAL, "done", 1) + .unwrap(); + assert!(store.engine_idle_blocked().unwrap()); + assert_eq!(store.run_notice_error("run").unwrap(), None); + let batch = store.run_notice_batch_at("owner", 10).unwrap(); + store + .record_run_notice_failure( + "owner", + &batch[0].client_turn_id, + "harness removed", + true, + 20, + ) + .unwrap(); + assert!(!store.engine_idle_blocked().unwrap()); + assert_eq!( + store.run_notice_error("run").unwrap().as_deref(), + Some("harness removed") + ); + drop(store); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn engine_permanent_notice_failure_keeps_reason_and_unblocks_later_batches() { + let (dir, store) = engine_fixture(); + store + .insert_run_notice("ssh_job", "owner", ATTENTION, "attention:0", "outage", 1) + .unwrap(); + let first = store.run_notice_batch_at("owner", 10).unwrap(); + assert_eq!( + store + .record_run_notice_failure( + "owner", + &first[0].client_turn_id, + "harness removed", + true, + 20 + ) + .unwrap(), + Some(1) + ); + store + .insert_run_notice("ssh_job", "owner", NOTIFY, "later", "later", 21) + .unwrap(); + let later = store.run_notice_batch_at("owner", 21).unwrap(); + assert_eq!(later.len(), 1); + assert_eq!(later[0].body, "later"); + store + .mark_run_notice_batch_delivered("owner", &later[0].client_turn_id, 22) + .unwrap(); + assert!(!store.settle_outage_notice("ssh_job", "owner").unwrap()); + let retired: (i64, String) = store + .conn + .query_row( + "SELECT retired_at, delivery_error FROM run_notices WHERE id = ?1", + [first[0].id], + |row| Ok((row.get(0)?, row.get(1)?)), + ) + .unwrap(); + assert_eq!(retired, (20, "harness removed".into())); + assert!(store + .insert_run_notice( + "ssh_job", + "owner", + ATTENTION, + "attention:0", + "new outage", + 23 + ) + .unwrap()); + drop(store); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn engine_notices_dedupe_freeze_and_retry_across_connections() { + let (dir, store) = engine_fixture(); + let second = Store::open_at(dir.clone()).unwrap(); + assert!(store.run_notice_batch("owner").unwrap().is_empty()); + assert_eq!(store.run_subscribers("ssh_job").unwrap(), ["owner"]); + store.subscribe_run("ssh_job", "foreign", 1).unwrap(); + store.subscribe_run("ssh_job", "foreign", 2).unwrap(); + assert_eq!( + store.run_subscribers("ssh_job").unwrap(), + ["foreign", "owner"] + ); + store.subscribe_run("ssh_job", "owner", 3).unwrap(); + assert_eq!( + store.run_subscribers("ssh_job").unwrap(), + ["foreign", "owner"] + ); + assert_eq!( + store + .conn + .query_row( + "SELECT created_at FROM run_subscriptions WHERE chat_session_id = 'foreign'", + [], + |row| row.get::<_, i64>(0) + ) + .unwrap(), + 1 + ); + { + let tx = store.begin().unwrap(); + store + .insert_run_notice("ssh_job", "owner", "terminal", "terminal", "rolled back", 1) + .unwrap(); + tx.rollback().unwrap(); + } + assert!(store.run_notice_batch("owner").unwrap().is_empty()); + assert!(store + .insert_run_notice("ssh_job", "owner", "terminal", "terminal", "finished", 10) + .unwrap()); + assert!(store + .insert_run_notice( + "slurm_job", + "owner", + "terminal", + "terminal", + "also finished", + 11 + ) + .unwrap()); + let frozen = store.run_notice_batch("owner").unwrap(); + assert_eq!(frozen.len(), 2); + uuid::Uuid::parse_str( + frozen[0] + .client_turn_id + .strip_prefix("run-notice:") + .unwrap(), + ) + .unwrap(); + assert!(frozen + .iter() + .all(|row| row.client_turn_id == frozen[0].client_turn_id)); + assert!(!second + .insert_run_notice("ssh_job", "owner", "terminal", "terminal", "changed", 12) + .unwrap()); + assert!(second + .insert_run_notice("ssh_job", "owner", "notify", "notify:1", "new bytes", 13) + .unwrap()); + assert!(second + .insert_run_notice( + "ssh_job", + "foreign", + "terminal", + "terminal", + "foreign result", + 14 + ) + .unwrap()); + assert_eq!(second.run_notice_batch("owner").unwrap(), frozen); + assert_eq!(store.run_notice_batch("owner").unwrap(), frozen); + let foreign = second.run_notice_batch("foreign").unwrap(); + assert_eq!(foreign.len(), 1); + assert_ne!(foreign[0].client_turn_id, frozen[0].client_turn_id); + let turn = frozen[0].client_turn_id.as_str(); + second + .mark_run_notice_batch_delivered("foreign", turn, 15) + .unwrap(); + assert_eq!(store.run_notice_batch("owner").unwrap(), frozen); + second + .mark_run_notice_batch_delivered("owner", turn, 16) + .unwrap(); + store + .mark_run_notice_batch_delivered("owner", turn, 17) + .unwrap(); + assert_eq!( + store + .conn + .query_row( + "SELECT MIN(delivered_at) FROM run_notices WHERE client_turn_id = ?1", + [turn], + |row| row.get::<_, i64>(0) + ) + .unwrap(), + 16 + ); + let next = store.run_notice_batch("owner").unwrap(); + assert_eq!(next.len(), 1); + assert_eq!(next[0].body, "new bytes"); + assert_ne!(next[0].client_turn_id, frozen[0].client_turn_id); + drop(second); + drop(store); + let reopened = Store::open_at(dir.clone()).unwrap(); + assert_eq!(reopened.run_notice_batch("owner").unwrap(), next); + drop(reopened); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn engine_wakeup_migration_never_refires_and_preserves_foreign_chats() { + let (dir, store) = engine_fixture(); + let claimed = store + .claim_run_wakeup("failed", "foreign") + .unwrap() + .unwrap(); + assert!(!claimed.is_empty()); + store.subscribe_run("ssh_job", "foreign", 1).unwrap(); + assert_eq!( + store + .conn + .query_row("SELECT COUNT(*) FROM run_notices", [], |row| row + .get::<_, i64>(0)) + .unwrap(), + 0 + ); + store.migrate_run_wakeups().unwrap(); + let subscriptions: Vec<(String, String)> = store + .conn + .prepare("SELECT run_id, chat_session_id FROM run_subscriptions ORDER BY 1,2") + .unwrap() + .query_map([], |row| Ok((row.get(0)?, row.get(1)?))) + .unwrap() + .collect::>() + .unwrap(); + assert_eq!( + subscriptions, + [ + ("ssh_job".into(), "foreign".into()), + ("ssh_job".into(), "owner".into()) + ] + ); + let delivered: (String, String, i64) = store + .conn + .query_row( + "SELECT kind, dedupe, delivered_at FROM run_notices WHERE run_id = 'done'", + [], + |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)), + ) + .unwrap(); + assert_eq!(delivered, ("terminal".into(), "terminal".into(), 500)); + let alert: (String, String, i64) = store.conn.query_row( + "SELECT kind, chat_session_id, delivered_at FROM run_notices WHERE run_id = 'ssh_job'", [], + |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)), + ).unwrap(); + assert_eq!(alert, ("attention".into(), "foreign".into(), 400)); + assert!(store.run_notice_batch("owner").unwrap().is_empty()); + let completion = store.run_notice_batch("foreign").unwrap(); + assert_eq!(completion.len(), 1); + assert_eq!(completion[0].run_id, "failed"); + assert_eq!( + completion[0].body, + store + .terminal_notice_body(&store.get_run("failed").unwrap().unwrap()) + .unwrap() + ); + assert_eq!(completion[0].dedupe, TERMINAL); + let key = store + .outage_dedupe("ssh_job", "foreign", ATTENTION) + .unwrap(); + assert_eq!(key, "attention:0"); + assert!(!store + .insert_run_notice( + "ssh_job", + "foreign", + ATTENTION, + &key, + "duplicate outage", + 500 + ) + .unwrap()); + let recovered_key = store + .outage_dedupe("ssh_job", "foreign", RECOVERED) + .unwrap(); + store + .insert_run_notice( + "ssh_job", + "foreign", + RECOVERED, + &recovered_key, + "recovered", + 501, + ) + .unwrap(); + let next_key = store + .outage_dedupe("ssh_job", "foreign", ATTENTION) + .unwrap(); + assert_eq!(next_key, "attention:1"); + assert!(store + .insert_run_notice( + "ssh_job", + "foreign", + ATTENTION, + &next_key, + "next outage", + 502 + ) + .unwrap()); + assert!(!store + .insert_run_notice( + "done", + "owner", + "terminal", + "terminal", + "must not re-fire", + 600 + ) + .unwrap()); + let legacy_rows: i64 = store + .conn + .query_row("SELECT COUNT(*) FROM chat_run_wakeups", [], |row| { + row.get(0) + }) + .unwrap(); + assert_eq!(legacy_rows, 4); + store + .conn + .execute( + "DELETE FROM run_subscriptions WHERE chat_session_id = 'foreign'", + [], + ) + .unwrap(); + drop(store); + let reopened = Store::open_at(dir.clone()).unwrap(); + reopened.migrate_run_wakeups().unwrap(); + assert_eq!( + reopened + .conn + .query_row( + "SELECT COUNT(*) FROM run_subscriptions WHERE chat_session_id = 'foreign'", + [], + |row| row.get::<_, i64>(0) + ) + .unwrap(), + 0 + ); + assert_eq!( + reopened + .conn + .query_row("SELECT COUNT(*) FROM run_notices", [], |row| row + .get::<_, i64>(0)) + .unwrap(), + 5 + ); + assert_eq!( + reopened + .conn + .query_row("PRAGMA user_version", [], |row| row.get::<_, i64>(0)) + .unwrap(), + 2 + ); + drop(reopened); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn engine_cancel_acceptance_survives_legacy_withdraw_and_handles_submitting() { + let (dir, store) = engine_fixture(); + let path = dir.join("run-logs/slurm_job.cancel.lock"); + let mut old_lock = open_lifecycle_lock_at(&path).unwrap(); + let old_guard = old_lock.write().unwrap(); + assert!(store.request_cancel("slurm_job", "old CLI").unwrap()); + store.withdraw_cancel("slurm_job").unwrap(); + drop(old_guard); + assert_eq!(store.accept_run_cancel("slurm_job", None).unwrap(), None); + let old_guard = old_lock.write().unwrap(); + assert!(store.request_cancel("slurm_job", "old CLI").unwrap()); + drop(old_guard); + let accepted = store.accept_run_cancel("slurm_job", None).unwrap().unwrap(); + assert!(accepted > 0); + let old_guard = old_lock.write().unwrap(); + store.withdraw_cancel("slurm_job").unwrap(); + drop(old_guard); + assert_eq!( + store.accept_run_cancel("slurm_job", None).unwrap(), + Some(accepted) + ); + let state = store.engine_run_state("slurm_job").unwrap().unwrap(); + assert_eq!(state.cancel_accepted_at, Some(accepted)); + assert!( + !store + .get_run("slurm_job") + .unwrap() + .unwrap() + .cancel_requested + ); + let mut run = run_fixture("engine_cancel", "submitting", None); + run.backend_json = r#"{"kind":"modal_job"}"#.into(); + store + .insert_submitting_run(SubmittingRun { + id: &run.id, + experiment_id: &run.experiment_id, + project_id: &run.project_id, + metadata: &crate::jobs::BackendDescriptor::parse(&run.backend_json).unwrap(), + command: &run.command, + created_at: run.created_at, + commit_sha: run.commit_sha.as_deref(), + chat_session_id: run.chat_session_id.as_deref(), + spec_digest: "digest", + launch: &test_launch(), + }) + .unwrap(); + assert!(!store.request_cancel(&run.id, "old CLI").unwrap()); + assert!(store + .accept_run_cancel(&run.id, Some("API")) + .unwrap() + .is_some()); + let fence = SubmissionFence { + taken_at: 1, + submitter: None, + }; + assert!(!store.set_submission_fence(&run.id, 1, &fence).unwrap()); + store + .accept_run_cancel(&run.id, Some("later API request")) + .unwrap(); + assert_eq!( + store + .get_run(&run.id) + .unwrap() + .unwrap() + .cancel_reason + .as_deref(), + Some("API") + ); + assert_eq!(store.accept_run_cancel("done", Some("API")).unwrap(), None); + assert_eq!(store.accept_run_cancel("missing", None).unwrap(), None); + assert!(store.accept_run_cancel("../escape", None).is_err()); + drop(store); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn engine_cancel_acceptance_waits_for_legacy_writer_to_commit_or_withdraw() { + let (dir, store) = engine_fixture(); + let second = Store::open_at(dir.clone()).unwrap(); + let mut old_lock = + open_lifecycle_lock_at(&dir.join("run-logs/slurm_job.cancel.lock")).unwrap(); + let guard = old_lock.write().unwrap(); + store.request_cancel("slurm_job", "old CLI").unwrap(); + let (started_tx, started_rx) = std::sync::mpsc::channel(); + let (result_tx, result_rx) = std::sync::mpsc::channel(); + let thread = std::thread::spawn(move || { + started_tx.send(()).unwrap(); + result_tx + .send(second.accept_run_cancel("slurm_job", None).unwrap()) + .unwrap(); + }); + started_rx.recv().unwrap(); + assert!(matches!( + result_rx.recv_timeout(Duration::from_millis(100)), + Err(std::sync::mpsc::RecvTimeoutError::Timeout) + )); + store.withdraw_cancel("slurm_job").unwrap(); + drop(guard); + assert_eq!( + result_rx.recv_timeout(Duration::from_secs(5)).unwrap(), + None + ); + thread.join().unwrap(); + assert!(store + .engine_run_state("slurm_job") + .unwrap() + .unwrap() + .cancel_accepted_at + .is_none()); + drop(store); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[cfg(unix)] + #[test] + fn store_protects_existing_data_and_sqlite_sidecars() { + use std::os::unix::fs::PermissionsExt; + let dir = std::env::temp_dir().join(format!("orx-private-store-{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o755)).unwrap(); + let store = Store::open_at(dir.clone()).unwrap(); + assert_eq!( + std::fs::metadata(&dir).unwrap().permissions().mode() & 0o777, + 0o700 + ); + drop(store); + std::fs::remove_dir_all(dir).unwrap(); + } + + fn project_with_run_artifacts(store: &Store, project: &str, run: &str, digest: &str) { + let repo = store.data_dir.join(format!("repo-{project}")); + std::fs::create_dir_all(&repo).unwrap(); + std::fs::write(repo.join("keep"), "repository").unwrap(); + store.conn.execute( + "INSERT INTO local_projects (id, name, slug, github_owner, github_repo, repo_path, created_at, updated_at) + VALUES (?1, ?1, ?1, '', '', ?2, 1, 1)", + params![project, repo.to_string_lossy()], + ).unwrap(); + let descriptor = serde_json::json!({ + "kind": "local_job", "sourceDigest": digest, + "jobId": repo, "sourcePath": repo.join("keep"), + }); + store.conn.execute( + "INSERT INTO runs (id, experiment_id, project_id, status, backend_json, created_at, updated_at) + VALUES (?1, 'experiment', ?2, 'done', ?3, 1, 1)", + params![run, project, descriptor.to_string()], + ).unwrap(); + for path in [ + store + .data_dir + .join("local-runs") + .join(run) + .join("repo/output"), + store.data_dir.join("run-logs").join(format!("{run}.log")), + store + .data_dir + .join("submission-handles") + .join(format!("{run}.json")), + store + .data_dir + .join("source-snapshots") + .join(format!("{digest}.tar")), + store + .data_dir + .join("source-snapshots") + .join(format!("{digest}.hf/payload")), + ] { + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, "artifact").unwrap(); + } + std::fs::write( + store + .data_dir + .join("submission-handles") + .join(format!("{run}.json")), + descriptor.to_string(), + ) + .unwrap(); + } + + #[test] + fn orphan_cleanup_reclaims_rowless_local_artifacts_and_preserves_other_runs() { + let dir = + std::env::temp_dir().join(format!("orx-orphan-artifacts-{}", uuid::Uuid::new_v4())); + let store = Store::open_at(dir.clone()).unwrap(); + let orphan = uuid::Uuid::new_v4().to_string(); + let shared_orphan = uuid::Uuid::new_v4().to_string(); + let surviving = uuid::Uuid::new_v4().to_string(); + let abandoned = uuid::Uuid::new_v4().to_string(); + let tinker = uuid::Uuid::new_v4().to_string(); + let unreferenced = "a".repeat(64); + let shared = "b".repeat(64); + project_with_run_artifacts(&store, "old", &orphan, &unreferenced); + project_with_run_artifacts(&store, "old-shared", &shared_orphan, &shared); + project_with_run_artifacts(&store, "surviving", &surviving, &shared); + project_with_run_artifacts(&store, "abandoned", &abandoned, &unreferenced); + project_with_run_artifacts(&store, "tinker", &tinker, &unreferenced); + let tinker_handle = dir + .join("submission-handles") + .join(format!("{tinker}.json")); + let mut descriptor: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&tinker_handle).unwrap()).unwrap(); + descriptor["kind"] = serde_json::json!("tinker_job"); + std::fs::write(tinker_handle, descriptor.to_string()).unwrap(); + let abandoned_dir = dir.join("local-runs").join(&abandoned); + std::fs::write(abandoned_dir.join("run.sh"), "echo never started").unwrap(); + store + .conn + .execute("DELETE FROM runs WHERE project_id != 'surviving'", []) + .unwrap(); + for id in [&orphan, &shared_orphan, &tinker] { + std::fs::write(dir.join("local-runs").join(id).join("exit_code"), "0").unwrap(); + } + let zip = dir + .join("source-snapshots") + .join(format!("{}.zip", "c".repeat(64))); + std::fs::write(&zip, "upload-only").unwrap(); + std::fs::write(dir.join("source-snapshots/keep.txt"), "not an archive").unwrap(); + let sidecar_only = uuid::Uuid::new_v4().to_string(); + for name in [ + format!("{orphan}.supervisor.log"), + format!("{orphan}.cancel.lock"), format!("{orphan}.supervisor.lock"), format!("{sidecar_only}.supervisor.log"), ] { @@ -5264,9 +7754,34 @@ mod tests { refused(&store); drop(held); drop(supervisor); + store + .conn + .execute( + "UPDATE runs SET backend_json = ?2 WHERE id = ?1", + params![ + run, + r#"{"kind":"engine","handle":{"type":"Ssh","host":"dead","root":"/orx"}}"# + ], + ) + .unwrap(); + store + .set_run_contact( + &run, + &Contact::Unreachable { + since: 1, + cause: "host gone".into(), + }, + ) + .unwrap(); + let mut supervisor = + open_lifecycle_lock_at(&dir.join("run-logs").join(format!("{run}.supervisor.lock"))) + .unwrap(); + let held = supervisor.write().unwrap(); store .delete_local_experiment("experiment", || Ok(())) .unwrap(); + drop(held); + drop(supervisor); // A repeat delete is refused before touching anything. refused(&store); assert!(!dir.join("local-runs").join(&run).exists()); @@ -5331,36 +7846,215 @@ mod tests { for id in ["r1", "r2", "r3", "box", "local"] { store.queue_finished_remote_cleanup(id).unwrap(); } - // The newest three remote runs stay whole; local and other kinds don't count. - assert!(due(&store).is_empty()); - insert("r4", "done", "ssh_job", 5); - store.queue_finished_remote_cleanup("r4").unwrap(); - assert_eq!(due(&store), finished(&["r1"])); - // As locally, an unfinished newer run takes one of the slots. - insert("r5", "running", "slurm_job", 6); - assert_eq!(due(&store), finished(&["r1", "r2"])); + // The newest three remote runs stay whole; local and other kinds don't count. + assert!(due(&store).is_empty()); + insert("r4", "done", "ssh_job", 5); + store.queue_finished_remote_cleanup("r4").unwrap(); + assert_eq!(due(&store), finished(&["r1"])); + // As locally, an unfinished newer run takes one of the slots. + insert("r5", "running", "slurm_job", 6); + assert_eq!(due(&store), finished(&["r1", "r2"])); + store + .defer_remote_cleanup("r1", false, "unreachable") + .unwrap(); + assert_eq!(due(&store), finished(&["r2"])); + store + .conn + .execute("UPDATE runs SET status = 'done'", []) + .unwrap(); + store.delete_local_project("p").unwrap(); + // Deletion marks every SSH/Slurm run, including the newest and one waiting to retry. + assert_eq!( + due(&store), + ["r1", "r2", "r3", "r4", "r5"] + .iter() + .map(|id| (id.to_string(), true)) + .collect::>() + ); + // A pass that started before the deletion queued only finishes what it acted on. + store.finish_remote_cleanup("r2", false).unwrap(); + store.defer_remote_cleanup("r2", false, "stale").unwrap(); + store.finish_remote_cleanup("r1", true).unwrap(); + assert_eq!(due(&store).len(), 4); + drop(store); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn unfinished_log_collection_survives_retries_and_a_collected_log_stays_collected() { + let dir = std::env::temp_dir().join(format!("orx-collection-{}", uuid::Uuid::new_v4())); + let store = Store::open_at(dir.clone()).unwrap(); + assert!(!store.log_collection_pending("legacy").unwrap()); + // Kept before its terminal commit queues it: the queue leaves it kept. + store.finish_log_collection("early").unwrap(); + store.queue_log_collection("early").unwrap(); + assert!(!store.log_collection_pending("early").unwrap()); + + store.queue_log_collection("late").unwrap(); + assert_eq!(store.log_collection("late").unwrap(), Some((false, None))); + assert_eq!(store.due_log_collections(10).unwrap(), ["late"]); + assert!(!store + .defer_log_collection("late", "host in backoff") + .unwrap()); + assert!(store.due_log_collections(10).unwrap().is_empty()); + drop(store); + let store = Store::open_at(dir.clone()).unwrap(); + assert!(store.log_collection_pending("late").unwrap()); + // Retries reach their cap once, then go on hourly; it never stops being owed. + let capped: Vec = (1..LOG_COLLECTION_FAILED_AFTER + 3) + .map(|_| store.defer_log_collection("late", "gone").unwrap()) + .collect(); + assert_eq!(capped.iter().filter(|capped| **capped).count(), 1); + assert_eq!( + store.log_collection("late").unwrap(), + Some((true, Some("gone".into()))) + ); + let next: i64 = store + .conn + .query_row( + "SELECT next_attempt_at FROM log_collections WHERE run_id = 'late'", + [], + |row| row.get(0), + ) + .unwrap(); + assert!(next - now_ms() <= LOG_COLLECTION_MAX_RETRY_MS); + store.retry_log_collections_now(None).unwrap(); + assert_eq!(store.due_log_collections(10).unwrap(), ["late"]); + store.finish_log_collection("late").unwrap(); + assert!(!store.log_collection_pending("late").unwrap()); + drop(store); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn an_engine_slurm_run_reads_as_the_descriptor_exp_status_shows() { + let launch = LaunchSpec { + kind: "slurm_job".into(), + target: Some("login".into()), + options: serde_json::json!({ + "timeout_seconds": 3600, + "directives": {"cpus-per-task": "4", "mem": "32G", "ntasks": "1"}, + }), + }; + let stored = r#"{"kind":"engine","jobId":"7","handle":{"type":"Slurm","host":"login","root":"~/.orx/engine","job":"7"}}"#; + let public = public_backend(stored, Some(&launch)).unwrap(); + let descriptor = crate::jobs::BackendDescriptor::parse(&public.to_string()).unwrap(); + assert_eq!(descriptor.kind, "slurm_job"); + assert_eq!(descriptor.slurm_ref().unwrap(), ("login", "7")); + assert_eq!(descriptor.timeout_secs, Some(3600)); + assert_eq!( + crate::local::slurm::status_resources(&descriptor), + "requested cpus 4 mem 32G" + ); + assert_eq!(public_backend(stored, None).unwrap()["kind"], "engine"); + } + + #[test] + fn engine_runs_queue_their_host_dir_and_container_for_cleanup() { + let dir = std::env::temp_dir().join(format!("orx-engine-cleanup-{}", uuid::Uuid::new_v4())); + let store = Store::open_at(dir.clone()).unwrap(); + let container = serde_json::json!({ + "reference": "dev", "id": "c1", "startedAt": "t", "runDir": "/root/.orx/runs/e1" + }); + for (id, handle, launch, created_at) in [ + ( + "e1", + r#"{"type":"Ssh","host":"lab","root":"~/.orx/engine"}"#, + serde_json::json!({"kind":"ssh_job","target":"lab","options":{"container":container}}), + 1, + ), + ( + "e2", + r#"{"type":"Slurm","host":"login","root":"~/.orx/engine","job":"7"}"#, + serde_json::json!({"kind":"slurm_job","target":"login","options":{}}), + 2, + ), + ( + "e3", + r#"{"type":"Api","provider":"hf_job","account":{"target":"org","context":null},"ids":["j"]}"#, + serde_json::json!({"kind":"hf_job","target":"org","options":{}}), + 3, + ), + ] { + store.conn.execute( + "INSERT INTO runs (id, experiment_id, project_id, status, backend_json, launch_spec, created_at, updated_at) + VALUES (?1, 'experiment', 'p', 'done', ?2, ?3, ?4, ?4)", + params![id, format!(r#"{{"kind":"engine","handle":{handle}}}"#), launch.to_string(), created_at], + ).unwrap(); + store.queue_finished_remote_cleanup(id).unwrap(); + } + store.delete_local_project("p").unwrap(); + let mut due = store.due_remote_cleanups(10).unwrap(); + due.sort_by(|a, b| a.run_id.cmp(&b.run_id)); + assert_eq!( + due.iter() + .map(|entry| entry.run_id.as_str()) + .collect::>(), + ["e1", "e2"] + ); + let queued: serde_json::Value = serde_json::from_str(&due[0].backend_json).unwrap(); + assert_eq!(queued["sshContainer"], container); + assert_eq!(queued["handle"]["host"], "lab"); + drop(store); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn retention_rechecks_tombstones_and_output_debt_until_explicit_deletion() { + let (dir, store) = engine_fixture(); + for n in 0..5 { + let mut run = run_fixture(&format!("retention-{n}"), "done", None); + run.backend_json = + r#"{"kind":"engine","handle":{"type":"Ssh","host":"lab","root":"/orx"}}"#.into(); + run.created_at = n; + run.project_id = "retention".into(); + store.upsert_run(&run).unwrap(); + store.queue_finished_remote_cleanup(&run.id).unwrap(); + } + let run = "retention-0"; + assert!(store.remote_cleanup_eligible(run, false).unwrap()); store - .defer_remote_cleanup("r1", false, "unreachable") + .set_run_contact( + run, + &Contact::Unreconciled { + since: 1, + detail: "kill pending".into(), + }, + ) .unwrap(); - assert_eq!(due(&store), finished(&["r2"])); + assert!(!store.remote_cleanup_eligible(run, false).unwrap()); + assert!(!store + .due_remote_cleanups(100) + .unwrap() + .iter() + .any(|entry| entry.run_id == run)); + store.set_run_contact(run, &Contact::Live).unwrap(); + store.queue_log_collection(run).unwrap(); + assert!(!store.remote_cleanup_eligible(run, false).unwrap()); + store.finish_log_collection(run).unwrap(); + assert!(store.remote_cleanup_eligible(run, false).unwrap()); store .conn - .execute("UPDATE runs SET status = 'done'", []) + .execute( + "UPDATE remote_cleanups SET deleted = 1 WHERE run_id = ?1", + [run], + ) .unwrap(); - store.delete_local_project("p").unwrap(); - // Deletion marks every SSH/Slurm run, including the newest and one waiting to retry. - assert_eq!( - due(&store), - ["r1", "r2", "r3", "r4", "r5"] - .iter() - .map(|id| (id.to_string(), true)) - .collect::>() - ); - // A pass that started before the deletion queued only finishes what it acted on. - store.finish_remote_cleanup("r2", false).unwrap(); - store.defer_remote_cleanup("r2", false, "stale").unwrap(); - store.finish_remote_cleanup("r1", true).unwrap(); - assert_eq!(due(&store).len(), 4); + store + .set_run_contact( + run, + &Contact::NeedsAuth { + since: 1, + cause: "offline".into(), + }, + ) + .unwrap(); + assert!(!store.remote_cleanup_eligible(run, true).unwrap()); + store + .conn + .execute("DELETE FROM runs WHERE id = ?1", [run]) + .unwrap(); + assert!(store.remote_cleanup_eligible(run, true).unwrap()); drop(store); std::fs::remove_dir_all(dir).unwrap(); } @@ -5393,6 +8087,78 @@ mod tests { std::fs::remove_dir_all(dir).unwrap(); } + #[cfg(unix)] + #[test] + fn live_wrapper_runs_survive_slimming_orphan_reclaim_and_block_data_dir_moves() { + let dir = std::env::temp_dir().join(format!("orx-live-wrapper-{}", uuid::Uuid::new_v4())); + let store = Store::open_at(dir.clone()).unwrap(); + let id = uuid::Uuid::new_v4().to_string(); + project_with_run_artifacts(&store, "wrapper", &id, &"d".repeat(64)); + let run_dir = dir.join("local-runs").join(&id); + std::fs::create_dir_all(run_dir.join("repo/.venv")).unwrap(); + let script = "touch ready; sleep 60"; + std::fs::write(run_dir.join("run.sh"), script).unwrap(); + orx_host::publish( + &run_dir.join("launch.json"), + &orx_host_proto::LaunchIntent { + run: id.clone(), + digest: orx_host::sha(script.as_bytes()), + run_sh: script.into(), + env: Default::default(), + source: None, + cancel_sh: None, + }, + ) + .unwrap(); + let binary = orx_test_support::host_binaries().join(format!( + "orx-host-{}-{}", + if cfg!(target_os = "macos") { + "darwin" + } else { + "linux" + }, + std::env::consts::ARCH + )); + let mut wrapper = orx_test_support::Process::spawn( + crate::process::command(binary) + .arg("wrap") + .arg(&run_dir) + .env("ORX_TEST_FAST_STOPS", "1"), + ) + .unwrap(); + let deadline = std::time::Instant::now() + Duration::from_secs(10); + while !run_dir.join("ready").exists() { + assert!(std::time::Instant::now() < deadline); + std::thread::sleep(Duration::from_millis(10)); + } + let identity: orx_host_proto::ProcessIdentity = + orx_host::read_json(&run_dir.join("wrapper.json")).unwrap(); + assert!(!store.slim_run(&id).unwrap()); + assert!(run_dir.join("repo/.venv").is_dir()); + assert_eq!(store.count_active_runs().unwrap(), 1); + std::fs::remove_file(dir.join("submission-handles").join(format!("{id}.json"))).unwrap(); + store + .conn + .execute("DELETE FROM runs WHERE id=?1", [&id]) + .unwrap(); + store.cleanup_orphaned_run_artifacts().unwrap(); + assert!(run_dir.join("repo/.venv").is_dir()); + assert!(run_dir.join("repo/output").is_file()); + assert_eq!(store.count_active_runs().unwrap(), 1); + let mut elsewhere = identity.clone(); + elsewhere.node.push_str("-elsewhere"); + orx_host::publish(&run_dir.join("wrapper.json"), &elsewhere).unwrap(); + assert!(store.slim_run(&id).is_err()); + store.cleanup_orphaned_run_artifacts().unwrap(); + assert!(run_dir.join("repo/.venv").is_dir()); + assert_eq!(store.count_active_runs().unwrap(), 1); + orx_host::publish(&run_dir.join("wrapper.json"), &identity).unwrap(); + orx_host::wrapper::cancel(&run_dir).unwrap(); + wrapper.wait(Duration::from_secs(5)).unwrap(); + drop(store); + std::fs::remove_dir_all(dir).unwrap(); + } + #[test] fn orphan_cleanup_preserves_live_local_runs_and_remote_recovery_handles() { let dir = std::env::temp_dir().join(format!("orx-live-orphan-{}", uuid::Uuid::new_v4())); @@ -7063,7 +9829,16 @@ mod tests { if std::env::var(CHILD_PHASE).unwrap() == "blocked" { assert!(store.lock_native_deletion().is_err()); } else { - let _lock = store.lock_native_deletion().unwrap(); + // A released lock lingers in children the parent's other tests forked, until + // they exec. + let deadline = std::time::Instant::now() + Duration::from_secs(10); + let _lock = loop { + match store.lock_native_deletion() { + Ok(lock) => break lock, + Err(error) => assert!(std::time::Instant::now() < deadline, "{error}"), + } + std::thread::sleep(Duration::from_millis(1)); + }; let (deleting, retained) = store .native_sessions_for_deletion(&["second".into()], &["opencode", "claude-code"]) .unwrap(); @@ -7968,25 +10743,6 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } - #[test] - fn lost_run_wakes_its_waiting_chat() { - let dir = std::env::temp_dir().join(format!("orx-lost-wake-{}", uuid::Uuid::new_v4())); - let store = Store::open_at(dir.clone()).unwrap(); - store - .create_chat_session(&chat_session_fixture("chat_A")) - .unwrap(); - store - .upsert_run(&run_fixture("run_lost", "lost", Some("chat_A"))) - .unwrap(); - store.register_run_wakeup("run_lost", "chat_A").unwrap(); - store.prune_run_wakeups().unwrap(); - let ready = store.list_ready_run_wakeups().unwrap(); - assert_eq!(ready.len(), 1); - assert_eq!(ready[0].run.id, "run_lost"); - drop(store); - std::fs::remove_dir_all(dir).unwrap(); - } - #[test] fn news_of_a_turn_names_the_answers_it_overtook() { let dir = std::env::temp_dir().join(format!("orx-store-untold-{}", uuid::Uuid::new_v4())); @@ -8248,238 +11004,6 @@ mod tests { let _ = std::fs::remove_dir_all(dir); } - #[test] - fn run_wakeups_are_idempotent_ready_only_at_success_or_failure_and_pruned() { - let dir = std::env::temp_dir().join(format!("orx-store-wake-{}", uuid::Uuid::new_v4())); - let store = Store::open_at(dir.clone()).unwrap(); - store - .create_chat_session(&chat_session_fixture("chat_A")) - .unwrap(); - for (id, status) in [ - ("run_active", "running"), - ("run_done", "done"), - ("run_failed", "failed"), - ("run_cancelled", "cancelled"), - ] { - store - .upsert_run(&run_fixture(id, status, Some("chat_A"))) - .unwrap(); - assert_eq!( - store.register_run_wakeup(id, "chat_A").unwrap(), - RunWakeupRegistration::Scheduled - ); - assert_eq!( - store.register_run_wakeup(id, "chat_A").unwrap(), - RunWakeupRegistration::AlreadyPending - ); - } - store.register_run_wakeup("missing_run", "chat_A").unwrap(); - store - .register_run_wakeup("run_done", "missing_chat") - .unwrap(); - - store.prune_run_wakeups().unwrap(); - let ready = store.list_ready_run_wakeups().unwrap(); - assert_eq!( - ready - .iter() - .map(|wakeup| wakeup.run.id.as_str()) - .collect::>(), - ["run_done", "run_failed"] - ); - - assert!(store - .update_status("run_active", RunStatus::Done, Some(2), Some(0)) - .unwrap()); - assert_eq!(store.list_ready_run_wakeups().unwrap().len(), 3); - let token = store - .claim_run_wakeup("run_done", "chat_A") - .unwrap() - .unwrap(); - assert!(store - .claim_run_wakeup("run_done", "chat_A") - .unwrap() - .is_none()); - assert!(store - .list_ready_run_wakeups() - .unwrap() - .iter() - .any(|wakeup| wakeup.run.id == "run_done" && wakeup.state == "claimed")); - store - .release_run_wakeup("run_done", "chat_A", &token) - .unwrap(); - assert!(store - .list_ready_run_wakeups() - .unwrap() - .iter() - .any(|wakeup| wakeup.run.id == "run_done")); - let token = store - .claim_run_wakeup("run_done", "chat_A") - .unwrap() - .unwrap(); - assert!(store - .mark_run_wakeup_delivered("run_done", "chat_A", &token) - .unwrap()); - assert_eq!( - store.register_run_wakeup("run_done", "chat_A").unwrap(), - RunWakeupRegistration::AlreadyDelivered - ); - assert!(store - .list_ready_run_wakeups() - .unwrap() - .iter() - .all(|wakeup| wakeup.run.id != "run_done")); - - drop(store); - let _ = std::fs::remove_dir_all(dir); - } - - #[test] - fn monitoring_alert_claims_once_and_keeps_the_terminal_wakeup() { - let dir = std::env::temp_dir().join(format!("orx-store-alert-{}", uuid::Uuid::new_v4())); - let first = Store::open_at(dir.clone()).unwrap(); - first - .create_chat_session(&chat_session_fixture("chat_A")) - .unwrap(); - for (id, status) in [("run_live", "starting"), ("run_done", "done")] { - first - .upsert_run(&run_fixture(id, status, Some("chat_A"))) - .unwrap(); - first.register_run_wakeup(id, "chat_A").unwrap(); - } - let second = Store::open_at(dir.clone()).unwrap(); - - let active = first.list_active_run_wakeups().unwrap(); - assert_eq!(active.len(), 1); - assert_eq!(active[0].run.id, "run_live"); - assert!(!active[0].monitoring_alerted); - assert!(first - .set_run_wakeup_monitoring_alerted("run_live", "chat_A", true) - .unwrap()); - assert!(!second - .set_run_wakeup_monitoring_alerted("run_live", "chat_A", true) - .unwrap()); - assert!(second.list_active_run_wakeups().unwrap()[0].monitoring_alerted); - - assert!(second - .set_run_wakeup_monitoring_alerted("run_live", "chat_A", false) - .unwrap()); - assert!(!first - .set_run_wakeup_monitoring_alerted("run_live", "chat_A", false) - .unwrap()); - - first - .set_run_wakeup_monitoring_alerted("run_live", "chat_A", true) - .unwrap(); - assert!(first - .update_status("run_live", RunStatus::Done, Some(2), Some(0)) - .unwrap()); - assert!(first.list_active_run_wakeups().unwrap().is_empty()); - assert!(first - .list_ready_run_wakeups() - .unwrap() - .iter() - .any(|wakeup| wakeup.run.id == "run_live" && wakeup.state == "pending")); - first - .claim_run_wakeup("run_live", "chat_A") - .unwrap() - .unwrap(); - assert!(!first - .set_run_wakeup_monitoring_alerted("run_live", "chat_A", false) - .unwrap()); - - drop(second); - drop(first); - let _ = std::fs::remove_dir_all(dir); - } - - #[test] - fn run_wakeup_claim_is_atomic_across_store_connections_and_recoverable() { - let dir = std::env::temp_dir().join(format!("orx-store-claim-{}", uuid::Uuid::new_v4())); - let first = Store::open_at(dir.clone()).unwrap(); - first - .create_chat_session(&chat_session_fixture("chat_A")) - .unwrap(); - first - .upsert_run(&run_fixture("run_done", "done", Some("chat_A"))) - .unwrap(); - first.register_run_wakeup("run_done", "chat_A").unwrap(); - let second = Store::open_at(dir.clone()).unwrap(); - - let stale_token = first - .claim_run_wakeup("run_done", "chat_A") - .unwrap() - .unwrap(); - assert!(second - .claim_run_wakeup("run_done", "chat_A") - .unwrap() - .is_none()); - first - .conn - .execute( - "UPDATE chat_run_wakeups SET claimed_at = 0 WHERE run_id = 'run_done'", - [], - ) - .unwrap(); - second.prune_run_wakeups().unwrap(); - let current_token = second - .claim_run_wakeup("run_done", "chat_A") - .unwrap() - .unwrap(); - first - .release_run_wakeup("run_done", "chat_A", &stale_token) - .unwrap(); - assert!(!first - .mark_run_wakeup_delivered("run_done", "chat_A", &stale_token) - .unwrap()); - assert!( - first - .claim_run_wakeup("run_done", "chat_A") - .unwrap() - .is_none(), - "a stale token releases nothing" - ); - second - .release_run_wakeup("run_done", "chat_A", ¤t_token) - .unwrap(); - assert!(first - .claim_run_wakeup("run_done", "chat_A") - .unwrap() - .is_some()); - - drop(second); - drop(first); - let _ = std::fs::remove_dir_all(dir); - } - - #[test] - fn ready_run_wakeups_are_ordered_by_terminal_time() { - let dir = std::env::temp_dir().join(format!("orx-store-order-{}", uuid::Uuid::new_v4())); - let store = Store::open_at(dir.clone()).unwrap(); - store - .create_chat_session(&chat_session_fixture("chat_A")) - .unwrap(); - for (id, ended_at) in [("run_late", 20), ("run_early", 10)] { - let mut run = run_fixture(id, "done", Some("chat_A")); - run.ended_at = Some(ended_at); - store.upsert_run(&run).unwrap(); - store.register_run_wakeup(id, "chat_A").unwrap(); - } - - assert_eq!( - store - .list_ready_run_wakeups() - .unwrap() - .iter() - .map(|wakeup| wakeup.run.id.as_str()) - .collect::>(), - ["run_early", "run_late"] - ); - - drop(store); - let _ = std::fs::remove_dir_all(dir); - } - #[test] fn chat_turn_lease_is_cross_process_and_token_scoped() { let dir = std::env::temp_dir().join(format!("orx-store-turn-{}", uuid::Uuid::new_v4())); @@ -8858,4 +11382,69 @@ mod tests { assert_eq!(stored.parent_experiment_id, None, "only a move re-parents"); let _ = std::fs::remove_dir_all(&dir); } + #[test] + fn host_roots_never_persist_alias_authorization() { + let dir = std::env::temp_dir().join(format!("orx-alias-store-{}", uuid::Uuid::new_v4())); + let store = Store::open_at(dir.clone()).unwrap(); + use crate::engine::transport::{AuthState, HostClass, HostState, Status}; + let auth = AuthState { + class: Some(HostClass::Key), + route: Some("approved route".into()), + blocked: Some((123, "auth rejected".into())), + }; + store.save_engine_host_auth("lab", &auth).unwrap(); + for root in ["ssh", "slurm"] { + store + .save_engine_host( + "lab", + root, + &HostState { + status: Status::NeedsAuth, + ..HostState::default() + }, + ) + .unwrap(); + } + assert!(store + .engine_hosts() + .unwrap() + .iter() + .all(|(_, _, state)| state.status == Status::NeedsAuth)); + let mut rows = store + .conn + .prepare("SELECT state_json FROM engine_hosts") + .unwrap(); + for json in rows.query_map([], |row| row.get::<_, String>(0)).unwrap() { + let json: serde_json::Value = serde_json::from_str(&json.unwrap()).unwrap(); + assert!(json.get("class").is_none()); + assert!(json.get("route").is_none()); + assert_eq!(json["status"], "Idle"); + assert!(json["cause"].is_null()); + } + drop(rows); + store + .save_engine_host_auth( + "lab", + &AuthState { + blocked: None, + ..auth + }, + ) + .unwrap(); + assert!(store + .engine_hosts() + .unwrap() + .iter() + .all(|(_, _, state)| state.status == Status::Idle && state.cause.is_none())); + drop(store); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn log_path_keeps_the_explicit_directory_and_sanitizes_the_run_id() { + assert_eq!( + log_path(Path::new("/isolated/data"), "../run_A-1/../../x"), + Path::new("/isolated/data/run-logs/run_A-1x.log") + ); + } } diff --git a/src/telemetry.rs b/src/telemetry.rs index e9213a0d2..b07933a80 100644 --- a/src/telemetry.rs +++ b/src/telemetry.rs @@ -107,6 +107,8 @@ fn flush_window() -> Duration { #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub(crate) struct Settings { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub run_engine: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub desktop_zoom_percent: Option, #[serde(default)] @@ -1336,6 +1338,25 @@ mod tests { const OPT_VARS: &[&str] = &["XDG_CONFIG_HOME", "ORX_TELEMETRY_ENV", "ORX_TELEMETRY_HOST"]; + #[test] + fn run_engine_defaults_off_and_preserves_other_settings() { + let _guard = EnvGuard::new(&["XDG_CONFIG_HOME"]); + let dir = std::env::temp_dir().join(format!("orx-engine-setting-{}", uuid::Uuid::new_v4())); + std::env::set_var("XDG_CONFIG_HOME", &dir); + assert_eq!(load_settings().unwrap_or_default().run_engine, None); + set_persisted_disabled(true).unwrap(); + let untouched: serde_json::Value = + serde_json::from_slice(&std::fs::read(settings_path()).unwrap()).unwrap(); + assert!(untouched.get("runEngine").is_none()); + crate::config::set_run_engine_enabled(true).unwrap(); + assert_eq!(load_settings().unwrap().run_engine, Some(true)); + assert_eq!(load_settings().unwrap().telemetry_disabled, Some(true)); + crate::config::set_run_engine_enabled(false).unwrap(); + assert_eq!(load_settings().unwrap().run_engine, Some(false)); + assert_eq!(load_settings().unwrap().telemetry_disabled, Some(true)); + std::fs::remove_dir_all(dir).unwrap(); + } + #[test] fn environment_policy_is_fail_closed_and_downgrade_only() { let _g = EnvGuard::new(OPT_VARS); diff --git a/tests/chaos_properties.rs b/tests/chaos_properties.rs new file mode 100644 index 000000000..6f45f62f6 --- /dev/null +++ b/tests/chaos_properties.rs @@ -0,0 +1,423 @@ +#![cfg(unix)] + +use orx_host_proto::*; +use std::io::{self, Read}; +#[path = "../src/engine/runtime/chaos/rng.rs"] +mod rng; +use rng::Rng; + +struct Fragments<'a> { + bytes: &'a [u8], + width: usize, + interrupted: bool, +} +impl Read for Fragments<'_> { + fn read(&mut self, out: &mut [u8]) -> io::Result { + self.interrupted = !self.interrupted; + if self.interrupted { + return Err(io::ErrorKind::Interrupted.into()); + } + let len = out.len().min(self.width); + self.bytes.read(&mut out[..len]) + } +} + +fn check_frame( + frame: &[u8], + width: usize, + seed: u64, + case: usize, +) { + let expected = if frame.is_empty() { + Ok(None) + } else if frame.len() < 4 { + Err(io::ErrorKind::UnexpectedEof) + } else { + let len = u32::from_be_bytes(frame[..4].try_into().unwrap()) as usize; + if len == 0 || len > MAX_FRAME_LEN { + Err(io::ErrorKind::InvalidData) + } else if frame.len() - 4 < len { + Err(io::ErrorKind::UnexpectedEof) + } else { + serde_json::from_slice::(&frame[4..4 + len]) + .map(Some) + .map_err(|_| io::ErrorKind::InvalidData) + } + }; + let mut fragments = Fragments { + bytes: frame, + width, + interrupted: false, + }; + let actual = read_frame::(&mut fragments).map_err(|e| e.kind()); + assert_eq!(actual, expected, "seed={seed} case={case} bytes={frame:?}"); + if let Ok(Some(parsed)) = actual { + let mut encoded = Vec::new(); + write_frame(&mut encoded, &parsed).unwrap(); + assert_eq!( + read_frame::(&mut encoded.as_slice()).unwrap(), + Some(parsed) + ); + } +} + +fn request(rng: &mut Rng) -> Message { + let run = format!("r-{}", rng.next()); + let body = match rng.next() % 8 { + 0 => Request::Hello { + proto: rng.next() as u32, + }, + 1 => Request::Launch(LaunchIntent { + run, + digest: format!("{:x}", rng.next()), + run_sh: "printf 'λ\\n'".into(), + env: std::collections::BTreeMap::from([("KEY".into(), format!("{}", rng.next()))]), + source: None, + cancel_sh: None, + }), + 2 => Request::ReadLog { + target: LogTarget::Run(run), + file: LogFile::Log, + ident: None, + range: ByteRange { + start: rng.next(), + end: rng.next(), + }, + anchor: Some([rng.next() as u8; 64]), + }, + 3 => Request::Exec { + command: run, + stdin: (0..rng.next() % 128).map(|_| rng.next() as u8).collect(), + timeout_ms: rng.next() as u32, + }, + 4 => Request::PutBlob { + sha: run, + offset: rng.next(), + bytes: vec![rng.next() as u8; rng.next() as usize % 128], + }, + 5 => Request::Cancel { run }, + 6 => Request::Changes { + watch: vec![], + follow_logs: vec![run], + wait_ms: rng.next() as u32, + }, + _ => Request::SlurmSubmit { + intent: LaunchIntent { + run, + digest: format!("{:x}", rng.next()), + run_sh: "true".into(), + env: Default::default(), + source: None, + cancel_sh: None, + }, + directives: "#SBATCH --job-name=r\n".into(), + }, + }; + Message { + id: rng.next(), + body, + } +} + +fn response(rng: &mut Rng) -> Message { + let body = match rng.next() % 8 { + 0 => Response::Hello { + proto: rng.next() as u32, + binary_sha: format!("{}", rng.next()), + boot_id: "boot".into(), + os: "Linux".into(), + arch: "aarch64".into(), + kernel: "test".into(), + }, + 1 => Response::ReadLog { + page: LogPage::Data { + len: None, + ident: FileIdent { + dev: rng.next(), + ino: rng.next(), + }, + start: rng.next(), + bytes: (0..rng.next() % 256).map(|_| rng.next() as u8).collect(), + eof: rng.next() & 1 == 0, + }, + }, + 2 => Response::ReadLog { + page: LogPage::Reset { info: None }, + }, + 3 => Response::Error { + code: ErrorCode::Io, + message: format!("error-{}\nλ", rng.next()), + }, + 4 => Response::Cancel { + outcome: CancelAck::Accepted, + }, + 5 => Response::Launch { + summary: Summary { + started_at: None, + state: RunState::Unreconciled { + detail: "missing receipt".into(), + }, + log_len: Some(rng.next()), + notify_len: rng.next(), + cleanup: None, + }, + }, + 6 => Response::Exec { + result: ExecResult { + code: Some(rng.next() as i32), + signal: None, + timed_out: false, + stdout: vec![rng.next() as u8; 32], + stderr: vec![], + stdout_truncated: false, + stderr_truncated: false, + }, + }, + _ => Response::SlurmQueue { jobs: vec![] }, + }; + Message { + id: rng.next(), + body, + } +} + +#[test] +fn seeded_consecutive_frames_preserve_boundaries() { + let seed = 0x5513827cc8bed129; + let mut rng = Rng(seed); + for case in 0..1000 { + let requests = [request(&mut rng), request(&mut rng)]; + let responses = [response(&mut rng), response(&mut rng)]; + let mut bytes = Vec::new(); + for value in &requests { + write_frame(&mut bytes, value).unwrap(); + } + for value in &responses { + write_frame(&mut bytes, value).unwrap(); + } + let mut reader = Fragments { + bytes: &bytes, + width: 1 + rng.next() as usize % 31, + interrupted: false, + }; + for value in requests { + assert_eq!( + read_frame::>(&mut reader).unwrap(), + Some(value), + "seed={seed} case={case}" + ); + } + for value in responses { + assert_eq!( + read_frame::>(&mut reader).unwrap(), + Some(value), + "seed={seed} case={case}" + ); + } + assert!(read_frame::>(&mut reader) + .unwrap() + .is_none()); + } +} + +#[test] +fn seeded_frame_decoder_matches_length_and_json_oracle() { + let seed = 0xb857ac092a772813; + let mut rng = Rng(seed); + for case in 0..5000 { + let mut frame = Vec::new(); + if rng.next() & 1 == 0 { + write_frame(&mut frame, &request(&mut rng)).unwrap(); + } else { + write_frame(&mut frame, &response(&mut rng)).unwrap(); + } + match rng.next() % 5 { + 0 => { + let len = rng.next() as usize % frame.len(); + frame.truncate(len); + } + 1 => { + let index = rng.next() as usize % frame.len(); + frame[index] ^= (rng.next() as u8) | 1; + } + 2 => { + let length = [0, MAX_FRAME_LEN as u32 + 1, u32::MAX][rng.next() as usize % 3]; + frame[..4].copy_from_slice(&length.to_be_bytes()); + } + 3 => { + for byte in &mut frame[4..] { + *byte = rng.next() as u8; + } + } + _ => {} + } + let width = 1 + rng.next() as usize % 17; + check_frame::>(&frame, width, seed, case); + check_frame::>(&frame, width, seed, case); + } +} + +#[test] +fn seeded_exit_and_wrapper_receipts_survive_roundtrips_and_reject_corruption() { + let seed = 0x29ae8175c385bd08; + let mut rng = Rng(seed); + let directory = + std::env::temp_dir().join(format!("orx-receipt-properties-{}", uuid::Uuid::new_v4())); + std::fs::create_dir(&directory).unwrap(); + struct Cleanup(std::path::PathBuf); + impl Drop for Cleanup { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + let _cleanup = Cleanup(directory.clone()); + for case in 0..1000 { + let identity = ProcessIdentity { + node: format!("node-{}", rng.next()), + boot_id: format!("boot-{}", rng.next()), + pid: rng.next() as u32, + starttime: rng.next(), + }; + let receipt = ExitReceipt { + finished_at: None, + code: if rng.next() & 1 == 0 { + Some(rng.next() as i32) + } else { + None + }, + signal: if rng.next() & 1 == 0 { + Some(rng.next() as i32) + } else { + None + }, + reason: match rng.next() % 3 { + 0 => ExitReason::Exited, + 1 => ExitReason::Cancelled, + _ => ExitReason::SpawnFailed, + }, + processes: (0..rng.next() % 4) + .map(|_| Survivor { + pid: rng.next() as u32, + starttime: rng.next(), + state: "S".into(), + }) + .collect(), + outcome: match rng.next() % 3 { + 0 => CancelOutcome::Verified, + 1 => CancelOutcome::Survivors, + _ => CancelOutcome::Unverifiable { + unreadable: vec![rng.next() as u32], + }, + }, + }; + std::fs::write( + directory.join("wrapper.json"), + serde_json::to_vec(&identity).unwrap(), + ) + .unwrap(); + std::fs::write( + directory.join("exit.json"), + serde_json::to_vec(&receipt).unwrap(), + ) + .unwrap(); + assert_eq!( + orx_host::read_json::(&directory.join("wrapper.json")).unwrap(), + identity, + "seed={seed} case={case}" + ); + assert_eq!( + orx_host::wrapper::receipt(&directory).unwrap(), + Some(receipt.clone()), + "seed={seed} case={case}" + ); + for (name, value) in [ + ("wrapper.json", serde_json::to_value(&identity).unwrap()), + ("exit.json", serde_json::to_value(&receipt).unwrap()), + ] { + // Every required field is independently deleted or given an impossible type. + for key in value.as_object().unwrap().keys() { + for replacement in [None, Some(serde_json::json!({"invalid":true}))] { + let mut corrupted = value.clone(); + if let Some(replacement) = replacement { + corrupted[key] = replacement; + } else { + corrupted.as_object_mut().unwrap().remove(key); + } + let bytes = serde_json::to_vec(&corrupted).unwrap(); + std::fs::write(directory.join(name), &bytes).unwrap(); + if name == "wrapper.json" { + let expected = serde_json::from_slice::(&bytes); + assert_eq!( + orx_host::read_json::(&directory.join(name)).is_ok(), + expected.is_ok(), + "seed={seed} case={case} key={key}" + ); + } else { + let expected = serde_json::from_slice::(&bytes); + assert_eq!( + orx_host::wrapper::receipt(&directory).is_ok(), + expected.is_ok(), + "seed={seed} case={case} key={key}" + ); + } + } + } + let bytes = serde_json::to_vec(&value).unwrap(); + let end = rng.next() as usize % bytes.len(); + std::fs::write(directory.join(name), &bytes[..end]).unwrap(); + if name == "wrapper.json" { + assert!(orx_host::read_json::(&directory.join(name)).is_err()); + } else { + assert!(orx_host::wrapper::receipt(&directory).is_err()); + } + } + } +} + +#[test] +fn seeded_byte_fields_use_base64_and_round_trip_arbitrary_bytes() { + let mut rng = Rng(0x7a3f819ceab20d64); + for _ in 0..512 { + let bytes: Vec<_> = (0..rng.next() % 2048).map(|_| rng.next() as u8).collect(); + for body in [ + Request::Exec { + command: "cat".into(), + stdin: bytes.clone(), + timeout_ms: 1, + }, + Request::PutBlob { + sha: "sha".into(), + offset: 0, + bytes: bytes.clone(), + }, + Request::ReadLog { + target: LogTarget::Run("r".into()), + file: LogFile::Log, + ident: None, + range: ByteRange { start: 0, end: 64 }, + anchor: Some(std::array::from_fn(|_| rng.next() as u8)), + }, + ] { + let value = serde_json::to_value(&body).unwrap(); + for key in ["stdin", "bytes", "anchor"] { + if let Some(value) = value.get(key) { + assert!(value.is_string()); + } + } + assert_eq!(serde_json::from_value::(value).unwrap(), body); + } + let result = ExecResult { + code: Some(0), + signal: None, + timed_out: false, + stdout: bytes.clone(), + stderr: bytes, + stdout_truncated: false, + stderr_truncated: false, + }; + let value = serde_json::to_value(&result).unwrap(); + assert!(value["stdout"].is_string()); + assert!(value["stderr"].is_string()); + assert_eq!(serde_json::from_value::(value).unwrap(), result); + } +} diff --git a/tests/cli.rs b/tests/cli.rs index f2dfbe4ee..e62e012ea 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -3,6 +3,8 @@ #[path = "cli/compute_cli.rs"] mod compute_cli; +#[path = "cli/engine_cli.rs"] +mod engine_cli; #[path = "cli/invocation_gate_cli.rs"] mod invocation_gate_cli; #[path = "cli/logs_cli.rs"] diff --git a/tests/cli/compute_cli.rs b/tests/cli/compute_cli.rs index 58ea41b37..6362a8fbf 100644 --- a/tests/cli/compute_cli.rs +++ b/tests/cli/compute_cli.rs @@ -49,6 +49,8 @@ impl Sandbox { } impl Drop for Sandbox { fn drop(&mut self) { + #[cfg(unix)] + orx_test_support::stop_server(&self.0.join("data")); if let Ok(db) = rusqlite::Connection::open(self.0.join("data/orx.db")) { let _ = db.execute( "UPDATE runs SET status='cancelled' WHERE status IN ('running','starting')", @@ -328,213 +330,6 @@ fn standalone_settings_defaults_and_instruction_conflicts() { ); } -#[cfg(unix)] -#[test] -fn interactive_ssh_retires_rejected_masters_without_unlinking_unknown_connections() { - std::thread::scope(|scope| { - for case in [ - "healthy", - "legacy_other", - "legacy_unresolvable", - "legacy_same", - "rejection", - "exit_zero", - "stop_failure", - "probe_timeout", - "check_timeout", - "stop_timeout", - ] { - scope.spawn(move || interactive_ssh_case(case)); - } - }); -} - -#[cfg(unix)] -fn interactive_ssh_case(case: &str) { - use portable_pty::{native_pty_system, CommandBuilder, PtySize}; - use std::io::Read; - use std::os::unix::fs::PermissionsExt; - - let sandbox = Sandbox::new(); - std::fs::write( - sandbox.0.join(".ssh/config"), - "Host lab\n HostName localhost\n", - ) - .unwrap(); - let bin = sandbox.0.join("bin"); - std::fs::create_dir(&bin).unwrap(); - let ssh = bin.join("ssh"); - std::fs::write(&ssh, r#"#!/bin/sh -if [ "$1" = -G ]; then - for dest do :; done - if [ "$dest" = unresolvable-host ]; then echo "Invalid legacy SSH route" >&2; exit 1; fi - exec /usr/bin/ssh -F /dev/null "$@" -fi -printf '%s\n' "$*" >> "$HOME/calls" -case "$*" in - *'-O check -S '*) - socket=$4 - printf '%s' "$socket" > "$HOME/socket-path" - : > "$socket" - if [ "$CASE" = check_timeout ]; then exec sleep 30; fi - exit 0;; - *'-O stop -S '*) - socket=$4 - case "$CASE" in - stop_failure) exit 1;; - stop_timeout) exec sleep 30;; - esac - rm "$socket" - exit 0;; - *'echo __ORX_SESSION_OK__'*) - case "$*" in - *'-oBatchMode=yes -oControlMaster=no -oControlPersist=no -oProxyCommand=false -oClearAllForwardings=yes -oRemoteCommand=none -T -S '*) ;; - *) echo 'probe allows fallback or user configuration' >&2; exit 99;; - esac - case "$CASE" in - healthy) echo __ORX_SESSION_OK__;; - rejection) echo 'cannot assign requested address' >&2; exit 1;; - exit_zero|stop_failure|stop_timeout) echo 'cannot assign requested address';; - probe_timeout) exec sleep 30;; - esac - exit 0;; - *'-- lab true') echo LOGIN; exit 0;; - *'sys.stdin.buffer.read'*) for cmd do :; done; exec /bin/sh -c "$cmd";; - *'command -v bash'*) exit 0;; - *) exit 1;; -esac -"#).unwrap(); - std::fs::set_permissions(&ssh, std::fs::Permissions::from_mode(0o755)).unwrap(); - - for case in std::iter::once(case).chain((case == "healthy").then_some("backoff")) { - let _ = std::fs::remove_file(sandbox.0.join("calls")); - let command = sandbox.command(); - let mut builder = CommandBuilder::new(command.get_program()); - builder.args(command.get_args()); - for (key, value) in command.get_envs() { - match value { - Some(value) => builder.env(key, value), - None => builder.env_remove(key), - } - } - builder.env("PATH", format!("{}:/usr/bin:/bin", bin.display())); - let data = sandbox - .0 - .join(if case == "backoff" { "healthy" } else { case }); - if case == "backoff" { - let root = std::fs::read_dir(&data) - .unwrap() - .map(|entry| entry.unwrap().path()) - .find(|path| { - path.file_name() - .unwrap() - .to_string_lossy() - .starts_with("ssh-service-") - }) - .unwrap(); - let db = rusqlite::Connection::open(root.join("state.sqlite3")).unwrap(); - db.execute( - "UPDATE connections SET failures=6, next_at=?1", - [i64::try_from( - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap() - .as_millis(), - ) - .unwrap() - + 300_000], - ) - .unwrap(); - } - let legacy = matches!(case, "legacy_other" | "legacy_same" | "legacy_unresolvable"); - let mut legacy_lock = if legacy { - let output = sandbox - .command() - .env("ORX_DATA_DIR", &data) - .args(["projects", "--json"]) - .output() - .unwrap(); - assert!(output.status.success()); - let db = rusqlite::Connection::open(data.join("orx.db")).unwrap(); - let host = match case { - "legacy_same" => "lab", - "legacy_unresolvable" => "unresolvable-host", - _ => "unrelated-host", - }; - let backend = json!({"kind":"ssh_job", "namespace":host, "jobId":".orx/runs/legacy"}); - db.execute("INSERT INTO local_experiments (id, project_id, slug, branch_name, run_command, created_at, updated_at) VALUES ('exp','project','exp','main','true',0,0)", []).unwrap(); - db.execute("INSERT INTO runs (id, experiment_id, project_id, status, backend_json, created_at, updated_at) VALUES ('legacy','exp','project','running',?1,0,0)", [backend.to_string()]).unwrap(); - std::fs::create_dir_all(data.join("run-logs")).unwrap(); - Some(fd_lock::RwLock::new( - std::fs::File::create(data.join("run-logs/legacy.supervisor.lock")).unwrap(), - )) - } else { - None - }; - let _legacy_guard = legacy_lock.as_mut().map(|lock| lock.write().unwrap()); - builder.env("ORX_DATA_DIR", &data); - builder.env( - "CASE", - if case == "backoff" || legacy { - "healthy" - } else { - case - }, - ); - builder.args(["compute", "connect", "ssh", "--host", "lab"]); - let pair = native_pty_system().openpty(PtySize::default()).unwrap(); - let mut child = pair.slave.spawn_command(builder).unwrap(); - drop(pair.slave); - let mut reader = pair.master.try_clone_reader().unwrap(); - let mut output = Vec::new(); - // Linux PTYs report EIO instead of EOF when the slave closes. - if let Err(error) = reader.read_to_end(&mut output) { - assert_eq!(error.raw_os_error(), Some(libc::EIO)); - } - let status = child.wait().unwrap(); - let calls = std::fs::read_to_string(sandbox.0.join("calls")).unwrap(); - let socket = PathBuf::from(std::fs::read_to_string(sandbox.0.join("socket-path")).unwrap()); - let output = String::from_utf8_lossy(&output); - if legacy { - rusqlite::Connection::open(data.join("orx.db")) - .unwrap() - .execute("UPDATE runs SET status='cancelled' WHERE id='legacy'", []) - .unwrap(); - sandbox.stop_service(&data); - } - match case { - "healthy" | "backoff" | "legacy_other" | "legacy_unresolvable" => { - assert!(status.success(), "{output}"); - assert!(!calls.contains("-O stop")); - assert!(socket.exists()); - assert!(output.contains("LOGIN")); - } - "legacy_same" => { - assert!(!status.success(), "{output}"); - assert!(output.contains("older OpenResearch process"), "{output}"); - } - "rejection" | "exit_zero" => { - assert!(status.success(), "{output}"); - assert!(calls.find("-O stop").unwrap() < calls.find("-- lab true").unwrap()); - assert!(!socket.exists()); - assert!(output.contains("LOGIN")); - } - _ => { - assert!(!status.success(), "{case}: {output}"); - assert!(socket.exists(), "{case} removed an unknown/live socket"); - assert!(!output.contains("LOGIN")); - if case != "stop_failure" && case != "stop_timeout" { - assert!(!calls.contains("-O stop")); - } - } - } - sandbox.stop_service(&data); - assert!(!calls.contains("-O exit")); - let _ = std::fs::remove_file(&socket); - let _ = std::fs::remove_file(socket.with_extension("lock")); - } -} - #[cfg(unix)] #[test] fn ssh_config_conflict_and_execution_target_checks() { @@ -950,8 +745,8 @@ esac } }; let child = spawn(); - wait(&|| status() == "running"); - assert!(sandbox.0.join("cancel-calls").exists()); + // The supervisor reports the job running before it delivers the pending cancel. + wait(&|| status() == "running" && sandbox.0.join("cancel-calls").exists()); assert_ne!(metadata()["cancellationAccepted"], true); assert_eq!(status(), "running"); std::fs::write(sandbox.0.join("phase"), "unavailable").unwrap(); diff --git a/tests/cli/engine_cli.rs b/tests/cli/engine_cli.rs new file mode 100644 index 000000000..fc35ed0d8 --- /dev/null +++ b/tests/cli/engine_cli.rs @@ -0,0 +1,1086 @@ +#![cfg(unix)] + +use std::path::{Path, PathBuf}; +use std::process::{Command, Output, Stdio}; +use std::time::{Duration, Instant}; + +use orx_test_support::Sshd; +use sha2::Digest; + +const RUN_FREE: &str = "00000000-0000-4000-8000-0000000000f1"; +const RUN_HELD: &str = "00000000-0000-4000-8000-0000000000a2"; + +struct Sandbox { + root: PathBuf, + server: Sshd, +} + +impl Sandbox { + fn new() -> Self { + let root = std::env::temp_dir().join(format!("orx-engine-cli-{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(root.join(".ssh")).unwrap(); + Self { + root, + server: Sshd::start().unwrap(), + } + } + + fn data(&self) -> PathBuf { + self.root.join("data") + } + + fn command(&self) -> Command { + let mut command = Command::new(env!("CARGO_BIN_EXE_orx")); + command + .env("HOME", &self.root) + .env("XDG_CONFIG_HOME", self.root.join("config")) + .env("ORX_DATA_DIR", self.data()) + .env("ORX_NO_UPDATE_CHECK", "1") + .env("ORX_RUN_ENGINE", "1") + .env("ORX_SSH_CONFIG", self.server.config_path()) + .env("ORX_HOST_BIN_DIR", orx_test_support::host_binaries()) + .env("ORX_CHAT_SESSION_ID", "chat") + .env_remove("ORX_LOCAL_SESSION") + .env_remove("ORX_UP_PORT") + .env_remove("ORX_UP_AUTH_TOKEN") + .env_remove("HF_TOKEN") + .arg("--no-telemetry"); + command + } + + fn connect(&self, engine: &str) { + use portable_pty::{native_pty_system, CommandBuilder, PtySize}; + use std::io::Read; + + std::fs::write( + self.root.join(".ssh/config"), + format!("Include {}\n", self.server.config_path().display()), + ) + .unwrap(); + let command = self.command(); + let mut builder = CommandBuilder::new(command.get_program()); + builder.args(command.get_args()); + for (key, value) in command.get_envs() { + match value { + Some(value) => builder.env(key, value), + None => builder.env_remove(key), + } + } + builder.env("ORX_RUN_ENGINE", engine); + builder.args(["compute", "connect", "ssh", "--host", self.server.alias()]); + let pair = native_pty_system().openpty(PtySize::default()).unwrap(); + let mut child = pair.slave.spawn_command(builder).unwrap(); + drop(pair.slave); + let mut reader = pair.master.try_clone_reader().unwrap(); + let output = std::thread::spawn(move || { + let mut output = String::new(); + let _ = reader.read_to_string(&mut output); + output + }); + if !wait_for(Duration::from_secs(60), || { + child.try_wait().unwrap().is_some() + }) { + child.kill().unwrap(); + } + let status = child.wait().unwrap(); + assert!(status.success(), "{}", output.join().unwrap()); + } + + fn stop_service(&self) -> Output { + Command::new(env!("CARGO_BIN_EXE_orx")) + .env("HOME", &self.root) + .env("XDG_CONFIG_HOME", self.root.join("config")) + .env("ORX_DATA_DIR", self.data()) + .args(["ssh-service", "stop"]) + .output() + .unwrap() + } + + fn run(&self, args: &[&str]) -> Output { + self.command().args(args).output().unwrap() + } + + fn db(&self) -> rusqlite::Connection { + rusqlite::Connection::open(self.data().join("orx.db")).unwrap() + } + + fn status(&self, run: &str) -> String { + self.db() + .query_row("SELECT status FROM runs WHERE id = ?1", [run], |row| { + row.get(0) + }) + .unwrap() + } + + fn terminal_notices(&self, run: &str) -> Vec { + let db = self.db(); + let mut statement = db + .prepare( + "SELECT body FROM run_notices + WHERE run_id = ?1 AND chat_session_id = 'chat' AND kind = 'terminal'", + ) + .unwrap(); + statement + .query_map([run], |row| row.get(0)) + .unwrap() + .collect::>() + .unwrap() + } + + /// Project `project` with experiment `exp`, whose run command is `bash train.sh`. + fn project(&self, train: &str) { + assert!(self.run(&["projects", "--json"]).status.success()); + let repo = self.root.join("repo"); + std::fs::create_dir(&repo).unwrap(); + git(&repo, &["init", "-b", "main"]); + std::fs::write(repo.join("train.sh"), train).unwrap(); + git(&repo, &["add", "train.sh"]); + git(&repo, &["commit", "-m", "train"]); + let db = self.db(); + db.execute( + "INSERT INTO local_projects (id, name, slug, github_owner, github_repo, github_sync_enabled, + baseline_branch, repo_path, created_at, updated_at) + VALUES ('project', 'P', 'p', 'o', 'r', 0, 'main', ?1, 1, 1)", + [repo.to_str().unwrap()], + ) + .unwrap(); + db.execute( + "INSERT INTO local_experiments (id, project_id, slug, branch_name, run_command, agent_status, + created_at, updated_at) + VALUES ('exp', 'project', 'exp', 'main', 'bash train.sh', 'idle', 1, 1)", + [], + ) + .unwrap(); + } + + /// A run row and remote run dir shaped like orx 0.2.x left them. + fn legacy_run(&self, id: &str, exit_code: Option<&str>) { + let dir = self.server.home().join(".orx/runs").join(id); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("log"), "legacy output\n").unwrap(); + if let Some(code) = exit_code { + std::fs::write(dir.join("exit_code"), code).unwrap(); + } + let backend = serde_json::json!({ + "kind": "ssh_job", + "namespace": self.server.alias(), + "jobId": format!(".orx/runs/{id}"), + }); + self.db() + .execute( + "INSERT INTO runs (id, experiment_id, project_id, status, backend_json, command, + created_at, updated_at, chat_session_id) + VALUES (?1, 'exp', 'project', 'running', ?2, 'train', 1, 1, 'chat')", + rusqlite::params![id, backend.to_string()], + ) + .unwrap(); + } + + /// Where the autostarted server keeps its runtime files for this data directory. + fn runtime(&self, extension: &str) -> Option { + let data = std::fs::canonicalize(self.data()).ok()?; + let digest = sha2::Sha256::digest(data.as_os_str().as_encoded_bytes()); + let name: String = digest[..16] + .iter() + .map(|byte| format!("{byte:02x}")) + .collect(); + let uid = unsafe { libc::geteuid() }; + Some(PathBuf::from(format!("/tmp/orx-{uid}/{name}.{extension}"))) + } + + fn descriptor(&self) -> Option { + serde_json::from_slice(&std::fs::read(self.runtime("server.json")?).ok()?).ok() + } + + fn server_log(&self) -> String { + self.runtime("log") + .and_then(|path| std::fs::read_to_string(path).ok()) + .unwrap_or_default() + } +} + +impl Drop for Sandbox { + fn drop(&mut self) { + orx_test_support::stop_server(&self.data()); + let _ = self.stop_service(); + let _ = std::fs::remove_dir_all(&self.root); + } +} + +fn wait_for(timeout: Duration, mut ready: impl FnMut() -> bool) -> bool { + let deadline = Instant::now() + timeout; + while Instant::now() < deadline { + if ready() { + return true; + } + std::thread::sleep(Duration::from_millis(200)); + } + false +} + +fn git(repo: &Path, args: &[&str]) { + let output = Command::new("git") + .current_dir(repo) + .args(["-c", "user.name=Test", "-c", "user.email=test@example.com"]) + .args(args) + .output() + .unwrap(); + assert!(output.status.success(), "{output:?}"); +} + +fn supervise_processes(runs: &[&str]) -> Vec { + let output = Command::new("ps") + .args(["-ax", "-o", "command="]) + .output() + .unwrap(); + String::from_utf8_lossy(&output.stdout) + .lines() + .filter(|line| line.contains(" supervise ") && runs.iter().any(|run| line.contains(run))) + .map(str::to_owned) + .collect() +} + +fn stdout(output: &Output) -> String { + String::from_utf8_lossy(&output.stdout).into_owned() +} + +fn diagnostics(output: &Output) -> String { + format!( + "stdout: {}\nstderr: {}", + stdout(output), + String::from_utf8_lossy(&output.stderr) + ) +} + +/// The engine end to end: `orx exp run` autostarts the server, which launches over SSH through +/// `orx-host`; `orx exp wait` returns from one event stream; the launching chat gets exactly +/// one result. Startup recovers legacy supervisors; a second `orx up` attaches. +#[test] +fn ssh_runs_go_through_the_autostarted_engine() { + let sandbox = Sandbox::new(); + sandbox.project("echo engine-says-hi\necho step 2\n"); + sandbox.legacy_run(RUN_FREE, Some("0\n")); + sandbox.legacy_run(RUN_HELD, None); + let locks = sandbox.data().join("run-logs"); + std::fs::create_dir_all(&locks).unwrap(); + let held = std::fs::File::create(locks.join(format!("{RUN_HELD}.supervisor.lock"))).unwrap(); + held.try_lock().unwrap(); + let shared = + std::fs::File::create(locks.join(format!("{RUN_HELD}.supervisor.shared-ssh.lock"))) + .unwrap(); + shared.try_lock().unwrap(); + + let launched = sandbox.run(&[ + "exp", + "run", + "exp", + "--force", + "--backend", + "ssh", + "--host", + sandbox.server.alias(), + ]); + assert!(launched.status.success(), "{}", diagnostics(&launched)); + let run = stdout(&launched) + .split_whitespace() + .find(|word| word.len() == 36 && word.matches('-').count() == 4) + .unwrap() + .to_owned(); + + let started = Instant::now(); + let waited = sandbox.run(&["exp", "wait", "exp", "--timeout", "120"]); + assert!(waited.status.success(), "{}", diagnostics(&waited)); + assert!( + stdout(&waited).contains(&format!("{run} done")), + "{}", + diagnostics(&waited) + ); + assert!(started.elapsed() < Duration::from_secs(90)); + assert!( + wait_for(Duration::from_secs(10), || sandbox + .terminal_notices(&run) + .len() + == 1), + "{:?}", + sandbox.terminal_notices(&run) + ); + let notices = sandbox.terminal_notices(&run); + assert!(notices[0].contains("engine-says-hi"), "{notices:?}"); + + // With final output kept, the run's remote dir is queued for retention cleanup. + let queued = || -> i64 { + sandbox + .db() + .query_row( + "SELECT COUNT(*) FROM remote_cleanups WHERE run_id = ?1", + [&run], + |row| row.get(0), + ) + .unwrap() + }; + assert!( + wait_for(Duration::from_secs(60), || queued() == 1), + "{}", + sandbox.server_log() + ); + + // The dashboard reads the log the engine kept when the run finished. + let port = sandbox.descriptor().unwrap()["port"].as_u64().unwrap(); + let page = Command::new("curl") + .args([ + "-sf", + &format!("http://127.0.0.1:{port}/api/runs/{run}/log?start=0&end=1048576"), + ]) + .output() + .unwrap(); + assert!(page.status.success(), "{}", diagnostics(&page)); + let page: serde_json::Value = serde_json::from_slice(&page.stdout).unwrap(); + use base64::Engine as _; + let bytes = base64::engine::general_purpose::STANDARD + .decode(page["data"].as_str().unwrap()) + .unwrap(); + assert_eq!(bytes, b"engine-says-hi\nstep 2\n"); + assert_eq!(page["kind"], "data"); + assert_eq!(page["start"], 0); + assert_eq!(page["len"], bytes.len()); + assert_eq!(page["kept"], serde_json::json!([[0, bytes.len()]])); + assert_eq!(page["eof"], true); + // `exp wake` from another chat subscribes it; a finished run's result is queued at once. + sandbox + .db() + .execute( + "INSERT INTO chat_sessions (id, project_id, harness, created_at, updated_at) + VALUES ('other', 'project', 'codex', 1, 1)", + [], + ) + .unwrap(); + for _ in 0..2 { + let woke = sandbox + .command() + .env("ORX_LOCAL_SESSION", "1") + .env("ORX_CHAT_SESSION_ID", "other") + .args(["exp", "wake", "exp"]) + .output() + .unwrap(); + assert!(woke.status.success(), "{}", diagnostics(&woke)); + } + let other: i64 = sandbox + .db() + .query_row( + "SELECT COUNT(*) FROM run_notices WHERE run_id = ?1 AND chat_session_id = 'other'", + [&run], + |row| row.get(0), + ) + .unwrap(); + assert_eq!(other, 1); + + assert!( + wait_for(Duration::from_secs(60), || sandbox.status(RUN_FREE) + == "done"), + "{}\n{}", + sandbox.status(RUN_FREE), + sandbox.server_log() + ); + assert_eq!(sandbox.terminal_notices(RUN_FREE).len(), 1); + let kept = sandbox.data().join(format!("run-logs/{RUN_FREE}.log")); + assert_eq!(std::fs::read_to_string(kept).unwrap(), "legacy output\n"); + assert!(supervise_processes(&[&run, RUN_FREE, RUN_HELD]).is_empty()); + assert_eq!(sandbox.status(RUN_HELD), "running"); + let watched: i64 = sandbox + .db() + .query_row( + "SELECT COUNT(*) FROM legacy_watches WHERE run_id = ?1", + [RUN_HELD], + |row| row.get(0), + ) + .unwrap(); + assert_eq!(watched, 1); + + // The old supervisor finishes its run; the engine only reads it and tells the chat. + sandbox + .db() + .execute( + "UPDATE runs SET status = 'done', exit_code = 0, updated_at = 2, ended_at = 2 + WHERE id = ?1", + [RUN_HELD], + ) + .unwrap(); + assert!(wait_for(Duration::from_secs(20), || { + sandbox.terminal_notices(RUN_HELD).len() == 1 + })); + drop(held); + + let mut second = sandbox + .command() + .args(["up", "--no-browser", "--port", "0"]) + .stdout(Stdio::null()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + assert!( + wait_for(Duration::from_secs(20), || second + .try_wait() + .unwrap() + .is_some()), + "a second orx up started another server" + ); + let attached = second.wait_with_output().unwrap(); + assert!(attached.status.success(), "{}", diagnostics(&attached)); + assert!(String::from_utf8_lossy(&attached.stderr).contains("dashboard on http://127.0.0.1:")); +} + +/// A local run's output reaches `orx logs -f` while it runs, not only once it ends. +#[test] +fn local_logs_stream_while_the_run_is_live() { + use std::io::{BufRead, BufReader}; + let sandbox = Sandbox::new(); + let (proceed, release) = (sandbox.root.join("proceed"), sandbox.root.join("release")); + sandbox.project(&format!( + "echo first\nwhile [ ! -f '{}' ]; do sleep 0.2; done\necho second\n\ + while [ ! -f '{}' ]; do sleep 0.2; done\n", + proceed.display(), + release.display() + )); + let launched = sandbox.run(&["exp", "run", "exp", "--force", "--backend", "local"]); + assert!(launched.status.success(), "{}", diagnostics(&launched)); + let run = stdout(&launched) + .split_whitespace() + .find(|word| word.len() == 36 && word.matches('-').count() == 4) + .unwrap() + .to_owned(); + /// A follower left running would autostart a new server once the sandbox stops its own. + struct Follower(std::process::Child); + impl Drop for Follower { + fn drop(&mut self) { + let _ = self.0.kill(); + let _ = self.0.wait(); + } + } + let mut follow = Follower( + sandbox + .command() + .args(["logs", &run, "-f"]) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .unwrap(), + ); + let (lines, received) = std::sync::mpsc::channel(); + let output = follow.0.stdout.take().unwrap(); + std::thread::spawn(move || { + for line in BufReader::new(output).lines() { + if lines.send(line.unwrap()).is_err() { + break; + } + } + }); + let first = std::iter::from_fn(|| received.recv_timeout(Duration::from_secs(60)).ok()) + .find(|line| line.contains("first")); + assert!(first.is_some(), "{}", sandbox.server_log()); + // Past its last phase change, only log growth can wake the follower. + assert!(wait_for(Duration::from_secs(30), || sandbox.status(&run) + == "running")); + std::fs::write(&proceed, "").unwrap(); + let second = std::iter::from_fn(|| received.recv_timeout(Duration::from_secs(20)).ok()) + .find(|line| line.contains("second")); + assert!(second.is_some(), "{}", sandbox.server_log()); + let status = sandbox.status(&run); + assert!( + matches!(status.as_str(), "starting" | "running"), + "{status}" + ); + std::fs::write(&release, "").unwrap(); + assert!(wait_for(Duration::from_secs(30), || follow + .0 + .try_wait() + .unwrap() + .is_some())); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn cancellation_labels_agree_in_runs_status_and_wait() { + use axum::{routing::get, Json, Router}; + use serde_json::{json, Value}; + use std::sync::{Arc, Mutex}; + + let sandbox = Sandbox::new(); + assert!(sandbox.run(&["projects", "--json"]).status.success()); + let db = sandbox.db(); + db.execute("INSERT INTO local_projects (id,name,slug,github_owner,github_repo,repo_path,created_at,updated_at) VALUES ('project','P','p','','',?1,1,1)", [sandbox.root.to_str().unwrap()]).unwrap(); + db.execute_batch("INSERT INTO local_experiments (id,project_id,slug,branch_name,run_command,agent_status,created_at,updated_at) VALUES ('exp','project','exp','main','sleep 60','idle',1,1); + INSERT INTO runs (id,experiment_id,project_id,status,backend_json,command,created_at,updated_at) VALUES ('run','exp','project','running','{\"kind\":\"local_job\"}','sleep 60',1,1)").unwrap(); + let value = Arc::new(Mutex::new(Value::Null)); + let (rows, events) = (value.clone(), value.clone()); + let app = Router::new() + .route( + "/api/v2/runs", + get(move || { + let run = rows.lock().unwrap().clone(); + async move { Json(json!({"runs":[run], "titles":{}})) } + }), + ) + .route( + "/api/v2/events", + get(move || { + let run = events.lock().unwrap().clone(); + async move { + ( + [("content-type", "text/event-stream")], + format!("event: run\ndata: {run}\n\n"), + ) + } + }), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + for (status, contact, cancelling, unconfirmed, note, label) in [ + ( + "running", + json!({"type":"live"}), + true, + false, + None, + "Cancelling…", + ), + ( + "running", + json!({"type":"unreachable","since":1,"cause":"Offline"}), + true, + false, + None, + "Cancellation pending", + ), + ( + "running", + json!({"type":"needs_auth","since":1,"cause":"Connect"}), + true, + false, + None, + "Cancellation pending", + ), + ( + "submitting", + json!({"type":"live"}), + true, + false, + None, + "Cancellation pending", + ), + ( + "submitting", + json!({"type":"unreconciled","since":1,"detail":"No handle"}), + true, + false, + None, + "Cancellation pending", + ), + ( + "running", + json!({"type":"unreconciled","since":1,"detail":"Stop pending"}), + true, + false, + None, + "Cancelling…", + ), + ( + "cancelled", + json!({"type":"stopping","since":1,"count":2}), + false, + false, + None, + "Not fully stopped · 2 processes still running on localhost", + ), + ( + "cancelled", + json!({"type":"stopping","since":1,"count":1}), + false, + false, + None, + "Not fully stopped · 1 process still running on localhost", + ), + ( + "cancelled", + json!({"type":"live"}), + false, + false, + None, + "Cancelled", + ), + ( + "cancelled", + json!({"type":"live"}), + false, + true, + Some("Container processes couldn't be checked."), + "Cancelled · couldn't confirm", + ), + ( + "cancelled", + json!({"type":"live"}), + false, + false, + Some("Editable result."), + "Cancelled", + ), + ] { + *value.lock().unwrap() = json!({"id":"run", "experimentId":"exp", "status":status, + "contact":contact, "cancelling":cancelling, + "cancelUnconfirmed":if unconfirmed { json!([]) } else { Value::Null }, + "host":null, "commitSha":null, "durationSecs":1, + "updatedDisplay":"now", "cancelReason":null, "resultMarkdown":note}); + let stored_contact = (contact["type"] != "live").then(|| contact.to_string()); + db.execute( + "UPDATE runs SET status=?1,contact=?2,cancel_requested=?3,cancel_unconfirmed=?4,result_markdown=?5 WHERE id='run'", + rusqlite::params![status, stored_contact, cancelling, unconfirmed.then_some("[]"), note], + ).unwrap(); + for args in [ + vec!["runs", "project"], + vec!["exp", "status", "exp"], + vec![ + "exp", + "wait", + "exp", + "--timeout", + if cancelling { "1" } else { "10" }, + ], + ] { + let output = sandbox + .command() + .env("ORX_UP_PORT", port.to_string()) + .env("ORX_UP_AUTH_TOKEN", "test-only") + .args(&args) + .output() + .unwrap(); + assert_eq!( + output.status.success(), + !(cancelling && args[1] == "wait"), + "{args:?}: {}", + diagnostics(&output) + ); + assert_eq!( + format!( + "{}{}", + stdout(&output), + String::from_utf8_lossy(&output.stderr) + ) + .matches(label) + .count(), + 1, + "{args:?}: {}", + diagnostics(&output) + ); + if unconfirmed { + assert!( + diagnostics(&output).contains(note.unwrap()), + "{args:?}: {}", + diagnostics(&output) + ); + } + } + } + server.abort(); +} + +#[test] +fn session_hover_runs_preserve_their_fields_and_expose_cancellation_proof() { + use serde_json::{json, Value}; + + let sandbox = Sandbox::new(); + assert!(sandbox.run(&["projects", "--json"]).status.success()); + let db = sandbox.db(); + db.execute("INSERT INTO local_projects (id,name,slug,github_owner,github_repo,repo_path,created_at,updated_at) VALUES ('project','P','p','','',?1,1,1)", [sandbox.root.to_str().unwrap()]).unwrap(); + db.execute("INSERT INTO chat_sessions (id,project_id,harness,created_at,updated_at) VALUES ('chat','project','codex',1,1)", []).unwrap(); + for (id, status, contact, unconfirmed) in [ + ("pending", "running", None, false), + ("verified", "cancelled", None, false), + ( + "survivors", + "cancelled", + Some(json!({"type":"stopping","since":1,"count":2})), + false, + ), + ("unconfirmed", "cancelled", None, true), + ] { + db.execute("INSERT INTO local_experiments (id,project_id,slug,branch_name,run_command,agent_status,created_at,updated_at,chat_session_id) VALUES (?1,'project',?1,'main','sleep 60','idle',1,1,'chat')", [id]).unwrap(); + db.execute("INSERT INTO runs (id,experiment_id,project_id,status,backend_json,command,created_at,updated_at,cancel_requested,contact,cancel_unconfirmed) VALUES (?1,?1,'project',?2,'{\"kind\":\"engine\"}','sleep 60',100,100,1,?3,?4)", rusqlite::params![id,status,contact.map(|value|value.to_string()),unconfirmed.then_some("[]")]).unwrap(); + } + let started = sandbox.run(&["runs", "project"]); + assert!(started.status.success(), "{}", diagnostics(&started)); + let port = sandbox.descriptor().unwrap()["port"].as_u64().unwrap(); + let response = Command::new("curl") + .args([ + "-sf", + "--noproxy", + "*", + "--max-time", + "10", + &format!("http://127.0.0.1:{port}/api/chat/sessions/chat/experiments"), + ]) + .output() + .unwrap(); + assert!(response.status.success(), "{}", diagnostics(&response)); + let body: Value = serde_json::from_slice(&response.stdout).unwrap(); + let rows = body["experiments"].as_array().unwrap(); + assert_eq!(rows.len(), 4); + for row in rows { + let id = row["experiment"]["id"].as_str().unwrap(); + let run = &row["currentRun"]; + assert_eq!( + run["status"], + if id == "pending" { + "running" + } else { + "cancelled" + } + ); + assert_eq!(run["cancelRequested"], true); + assert_eq!(run["createdAt"], 100); + assert_eq!(run.get("endedAt"), Some(&Value::Null)); + assert_eq!(run["cancelling"], id == "pending"); + assert_eq!(run["cancelUnconfirmed"].is_array(), id == "unconfirmed"); + assert!(run.get("host").is_some()); + if id == "survivors" { + assert_eq!(run["contact"]["type"], "stopping"); + assert_eq!(run["contact"]["count"], 2); + } else if id != "pending" { + assert!(run["contact"].is_null()); + } + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn abandon_warns_that_actual_compute_must_be_shut_down() { + use axum::{routing::get, Json, Router}; + use serde_json::json; + use std::sync::{ + atomic::{AtomicUsize, Ordering}, + Arc, Mutex, + }; + + let sandbox = Sandbox::new(); + let contact = Arc::new(Mutex::new("unreachable")); + let calls = Arc::new(AtomicUsize::new(0)); + let (read_contact, abandoned) = (contact.clone(), calls.clone()); + let app = Router::new() + .route( + "/api/v2/runs/run", + get(move || { + let contact = *read_contact.lock().unwrap(); + async move { Json(json!({"id":"run", "contact":{"type":contact}})) } + }), + ) + .route( + "/api/v2/runs/run/abandon", + axum::routing::post(move || { + abandoned.fetch_add(1, Ordering::SeqCst); + async { Json(json!({"ok":true})) } + }), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + for (index, kind) in ["unreachable", "needs_auth", "unreconciled"] + .into_iter() + .enumerate() + { + *contact.lock().unwrap() = kind; + let output = sandbox + .command() + .env("ORX_UP_PORT", port.to_string()) + .env("ORX_UP_AUTH_TOKEN", "test-only") + .args(["exp", "abandon", "run"]) + .output() + .unwrap(); + assert!(output.status.success(), "{}", diagnostics(&output)); + let warning = String::from_utf8_lossy(&output.stderr); + assert_eq!( + warning.contains("The machine is unreachable."), + kind == "unreachable" + ); + assert!(warning.contains("OpenResearch will stop tracking this run. Double-check that the actual compute is shut down."), "{warning}"); + assert!(stdout(&output).contains("cancel stays pending")); + assert_eq!(calls.load(Ordering::SeqCst), index + 1); + } + server.abort(); +} + +#[test] +fn an_engine_run_finishing_while_up_is_down_keeps_the_receipt_finish_time() { + let sandbox = Sandbox::new(); + let release = sandbox.root.join("release"); + sandbox.project(&format!( + "echo started\nwhile [ ! -f '{}' ]; do sleep 0.05; done\necho finished\n", + release.display(), + )); + let launched = sandbox.run(&["exp", "run", "exp", "--force", "--backend", "local"]); + assert!(launched.status.success(), "{}", diagnostics(&launched)); + let run = stdout(&launched) + .split_whitespace() + .find(|word| word.len() == 36 && word.matches('-').count() == 4) + .unwrap() + .to_owned(); + assert!(wait_for(Duration::from_secs(30), || sandbox.status(&run) + == "running")); + let backend: String = sandbox + .db() + .query_row( + "SELECT backend_json FROM runs WHERE id = ?1", + [&run], + |row| row.get(0), + ) + .unwrap(); + let backend: serde_json::Value = serde_json::from_str(&backend).unwrap(); + let dir = PathBuf::from(backend["handle"]["dir"].as_str().unwrap()); + orx_test_support::stop_server(&sandbox.data()); + std::fs::write(release, "").unwrap(); + assert!(wait_for(Duration::from_secs(15), || dir + .join("exit.json") + .exists())); + let receipt: serde_json::Value = + serde_json::from_slice(&std::fs::read(dir.join("exit.json")).unwrap()).unwrap(); + let finished_at = receipt["finished_at"].as_i64().unwrap(); + assert_eq!(sandbox.status(&run), "running"); + std::thread::sleep(Duration::from_millis(150)); + let resumed = sandbox.run(&["runs", "project"]); + assert!(resumed.status.success(), "{}", diagnostics(&resumed)); + assert!(wait_for(Duration::from_secs(30), || sandbox.status(&run) == "done")); + let (started_at, ended_at): (i64, i64) = sandbox + .db() + .query_row( + "SELECT started_at, ended_at FROM runs WHERE id = ?1", + [&run], + |row| Ok((row.get(0)?, row.get(1)?)), + ) + .unwrap(); + assert_eq!(ended_at, finished_at); + assert!(started_at <= ended_at); +} + +#[test] +fn engine_setting_flips_preserve_in_flight_runs_across_restart() { + use serde_json::{json, Value}; + + let sandbox = Sandbox::new(); + let release = sandbox.root.join("release"); + std::fs::create_dir(&release).unwrap(); + sandbox.project(&format!( + "echo run-$ORX_RUN_ID\nwhile [ ! -f '{}/'$ORX_RUN_ID ]; do sleep 0.2; done\necho finished\n", + release.display(), + )); + let launched = sandbox + .command() + .env_remove("ORX_RUN_ENGINE") + .args(["exp", "run", "exp", "--force", "--backend", "local"]) + .output() + .unwrap(); + assert!(launched.status.success(), "{}", diagnostics(&launched)); + let supervised = stdout(&launched) + .split_whitespace() + .find(|word| word.len() == 36 && word.matches('-').count() == 4) + .unwrap() + .to_owned(); + let backend = |id: &str| -> Value { + let raw: String = sandbox + .db() + .query_row("SELECT backend_json FROM runs WHERE id = ?1", [id], |row| { + row.get(0) + }) + .unwrap(); + serde_json::from_str(&raw).unwrap() + }; + assert_eq!(backend(&supervised)["kind"], "local_job"); + let request = |path: &str, body: Option| -> Value { + let port = sandbox.descriptor().unwrap()["port"].as_u64().unwrap(); + let mut command = Command::new("curl"); + command.args(["-sf", "--noproxy", "*", "--max-time", "60"]); + if let Some(body) = body { + command.args([ + "-H", + "Content-Type: application/json", + "-d", + &body.to_string(), + ]); + } + let output = command + .arg(format!("http://127.0.0.1:{port}{path}")) + .output() + .unwrap(); + assert!( + output.status.success(), + "{}\n{}", + diagnostics(&output), + sandbox.server_log() + ); + serde_json::from_slice(&output.stdout).unwrap() + }; + assert_eq!( + request("/api/settings/run-engine", None), + json!({"enabled": false, "forcedBy": null}) + ); + assert_eq!( + request("/api/settings/run-engine", Some(json!({"enabled":true})))["enabled"], + true + ); + let launched = request( + "/api/runs", + Some(json!({ + "experimentId":"exp", "backend":"local", "force":true, "chatSessionId":"chat", + })), + ); + let engine = launched["run"]["id"].as_str().unwrap(); + assert_eq!(backend(engine)["kind"], "engine"); + assert!(wait_for(Duration::from_secs(30), || sandbox + .status(&supervised) + == "running" + && sandbox.status(engine) == "running")); + assert_eq!( + request("/api/settings/run-engine", Some(json!({"enabled":false})))["enabled"], + false + ); + orx_test_support::stop_server(&sandbox.data()); + let restarted = sandbox + .command() + .env_remove("ORX_RUN_ENGINE") + .args(["runs", "project"]) + .output() + .unwrap(); + assert!(restarted.status.success(), "{}", diagnostics(&restarted)); + assert_eq!(request("/api/settings/run-engine", None)["enabled"], false); + assert_eq!(backend(&supervised)["kind"], "local_job"); + assert_eq!(backend(engine)["kind"], "engine"); + let stopped = sandbox.run(&["exp", "cancel", "--run", engine]); + assert!(stopped.status.success(), "{}", diagnostics(&stopped)); + std::fs::write(release.join(&supervised), "").unwrap(); + assert!( + wait_for(Duration::from_secs(45), || sandbox.status(engine) + == "cancelled" + && sandbox.status(&supervised) == "done"), + "{}", + sandbox.server_log() + ); + assert!( + wait_for(Duration::from_secs(15), || sandbox + .terminal_notices(engine) + .len() + == 1 + && sandbox.terminal_notices(&supervised).len() == 1), + "{}", + sandbox.server_log() + ); + assert_eq!( + request(&format!("/api/runs/{supervised}"), None)["run"]["exitCode"], + 0 + ); + for run in [&supervised, engine] { + let logs = sandbox.run(&["logs", run]); + assert!(logs.status.success(), "{}", diagnostics(&logs)); + assert!( + stdout(&logs).contains(&format!("run-{run}")), + "{}", + stdout(&logs) + ); + } +} + +#[test] +fn environment_off_restores_ssh_supervision_over_the_shared_transport() { + let sandbox = Sandbox::new(); + sandbox.project("echo supervisor-says-hi\nsleep 2\necho finished\n"); + let config = sandbox.root.join("config/openresearch"); + std::fs::create_dir_all(&config).unwrap(); + std::fs::write(config.join("settings.json"), r#"{"runEngine":true}"#).unwrap(); + sandbox.connect("0"); + let launched = sandbox.run(&[ + "exp", + "run", + "exp", + "--backend", + "ssh", + "--host", + sandbox.server.alias(), + ]); + assert!( + launched.status.success(), + "{}\n{}", + diagnostics(&launched), + sandbox.server_log() + ); + let run = stdout(&launched) + .split_whitespace() + .find(|word| word.len() == 36 && word.matches('-').count() == 4) + .unwrap() + .to_owned(); + let backend: String = sandbox + .db() + .query_row("SELECT backend_json FROM runs WHERE id=?1", [&run], |row| { + row.get(0) + }) + .unwrap(); + let backend: serde_json::Value = serde_json::from_str(&backend).unwrap(); + assert_eq!(backend["kind"], "ssh_job"); + let waited = sandbox.run(&["exp", "wait", "exp", "--timeout", "120"]); + assert!( + waited.status.success(), + "{}\n{}", + diagnostics(&waited), + sandbox.server_log() + ); + assert_eq!(sandbox.status(&run), "done"); + let log = sandbox.run(&["logs", &run]); + assert!(log.status.success(), "{}", diagnostics(&log)); + assert!( + stdout(&log).contains("supervisor-says-hi"), + "{}", + diagnostics(&log) + ); + assert!(sandbox + .data() + .join(format!("run-logs/{run}.supervisor.log")) + .exists()); + assert!(wait_for(Duration::from_secs(15), || sandbox + .terminal_notices(&run) + .len() + == 1)); + let service = std::fs::read_dir(sandbox.data()) + .unwrap() + .flatten() + .find(|entry| { + entry + .file_name() + .to_string_lossy() + .starts_with("ssh-service-") + }) + .unwrap(); + let db = rusqlite::Connection::open(service.path().join("state.sqlite3")).unwrap(); + let resolved: String = db + .query_row("SELECT resolved FROM connections LIMIT 1", [], |row| { + row.get(0) + }) + .unwrap(); + let resolved: serde_json::Value = serde_json::from_str(&resolved).unwrap(); + let socket = PathBuf::from(resolved["socket"].as_str().unwrap()); + let stopped = sandbox.stop_service(); + assert!(stopped.status.success(), "{}", diagnostics(&stopped)); + std::fs::remove_file(&socket).unwrap(); + drop(std::os::unix::net::UnixListener::bind(&socket).unwrap()); + sandbox.connect("0"); + assert!( + std::fs::read_link(&socket).is_ok(), + "{}", + sandbox.server_log() + ); + let relaunched = sandbox.run(&[ + "exp", + "run", + "exp", + "--backend", + "ssh", + "--host", + sandbox.server.alias(), + ]); + assert!(relaunched.status.success(), "{}", diagnostics(&relaunched)); + let waited = sandbox.run(&["exp", "wait", "exp", "--timeout", "120"]); + assert!(waited.status.success(), "{}", diagnostics(&waited)); + std::fs::remove_file(socket).unwrap(); +} diff --git a/tests/cli/logs_cli.rs b/tests/cli/logs_cli.rs index a0499ab42..b93daa9ce 100644 --- a/tests/cli/logs_cli.rs +++ b/tests/cli/logs_cli.rs @@ -65,6 +65,8 @@ impl Sandbox { } impl Drop for Sandbox { fn drop(&mut self) { + #[cfg(unix)] + orx_test_support::stop_server(&self.data_dir()); let _ = std::fs::remove_dir_all(&self.0); } } @@ -200,3 +202,55 @@ fn missing_unknown_and_removed_flags() { let flags = sandbox.run(&["logs", run_id, "--full"]); assert!(!flags.status.success()); } + +#[test] +fn large_kept_log_previews_tail_and_identifies_both_ranges_and_missing_middle() { + use std::io::{Seek, SeekFrom, Write}; + + let sandbox = Sandbox::new(); + let run_id = "run-large-kept"; + sandbox.seed_run(run_id); + let head = sandbox.write_log(run_id, b"SETUP_SENTINEL"); + std::fs::OpenOptions::new() + .write(true) + .open(&head) + .unwrap() + .set_len(64 << 20) + .unwrap(); + let tail = head.with_file_name(format!("{run_id}.tail.log")); + let mut file = std::fs::File::create(&tail).unwrap(); + file.set_len(256 << 20).unwrap(); + let result = b"TRAINING_COMPLETE_SENTINEL\n"; + file.seek(SeekFrom::End(-(result.len() as i64))).unwrap(); + file.write_all(result).unwrap(); + let total: u64 = 3 << 30; + let ranges = serde_json::json!([ + {"offset":0,"len":64 << 20,"file":head,"ident":"1-2","eof":false}, + {"offset":total - (256 << 20),"len":256 << 20,"file":tail,"ident":"1-2","eof":true} + ]); + std::fs::write( + head.with_file_name(format!("{run_id}.ranges.json")), + ranges.to_string(), + ) + .unwrap(); + let output = sandbox.run(&["logs", run_id]); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let stdout = lossy_stdout(&output); + for expected in [ + "Original log: 3221225472 bytes.", + "Kept bytes 0..67108864:", + "Kept bytes 2952790016..3221225472:", + head.to_str().unwrap(), + tail.to_str().unwrap(), + "The middle of the log is not on this computer.", + "TRAINING_COMPLETE_SENTINEL", + ] { + assert!(stdout.contains(expected), "missing {expected}"); + } + assert!(!stdout.contains("SETUP_SENTINEL")); + assert!(!stdout.contains("full log file")); +} diff --git a/tests/cli/up_auto_restart.rs b/tests/cli/up_auto_restart.rs index 87c92da25..555c49528 100644 --- a/tests/cli/up_auto_restart.rs +++ b/tests/cli/up_auto_restart.rs @@ -8,6 +8,7 @@ use std::time::{Duration, Instant}; struct Sandbox(PathBuf); impl Drop for Sandbox { fn drop(&mut self) { + orx_test_support::stop_server(&self.0.join("data")); let _ = std::fs::remove_dir_all(&self.0); } } @@ -89,7 +90,9 @@ fn idle_orx_up_relaunches_into_an_installed_update() { } std::fs::write(config.join("update-check-unknown.json"), cache.to_string()).unwrap(); - let relaunched = wait_for(Duration::from_secs(45), || marker.exists()); + // Startup, the 10 s update sample, shutdown and the relaunched process's first instructions + // all wait for CPU, which a loaded machine rations. + let relaunched = wait_for(Duration::from_secs(120), || marker.exists()); let _ = up.kill(); let _ = up.wait(); assert!(serving, "orx up never started serving"); diff --git a/tests/fixtures/engine-ui.md b/tests/fixtures/engine-ui.md new file mode 100644 index 000000000..f0e9a40d4 --- /dev/null +++ b/tests/fixtures/engine-ui.md @@ -0,0 +1,73 @@ +# Live engine dashboard fixture + +From the workspace root: + +```sh +env -u CLAUDE_CONFIG_DIR -u CODEX_HOME sh tests/fixtures/engine-ui.sh +``` + +The command builds this tree's dashboard and native host, then runs the ignored +`ui_fixture` integration test. No installs or database inserts are used. Port +4930 must be free. Open **http://localhost:4930** after `READY` appears. The +project is **Engine live fixture**. In the collaborative browser, allow port +4930 in the browser toolbar if its port guard asks; a local browser can open +localhost directly. All home, config, data, SSH keys, host logs, +and control sockets are isolated under the printed temporary directories. + +| Experiment | Initial behavior | +| --- | --- | +| Steady output | Running payload emits a timestamp and training line each second; contact becomes Unreachable during the initial outage. | +| Large log with host-only middle | Finished log is 1 GiB + 1 MiB. Kept ranges are the first 64 MiB and last 256 MiB. Offset 512 MiB is fetched during setup and cached. Other middle offsets, such as 600 MiB, require the host. | +| Key rejected: NeedsAuth | `lab-login` rejects its configured key; first engine contact opens the authentication breaker. | +| Established run: NeedsAuth | `expired-key` starts a real running job, then its authorized key is revoked and its session reset. The established run becomes NeedsAuth. | +| Interactive Connect | `mfa-box` uses an encrypted key. Connect with passphrase `fixture-passphrase`; its pending payload then starts. | +| Cancel pending during outage | Cancellation is requested after `gpu-box` is blackholed. Restore the host to observe cancellation reconciliation; an unverified cancel may honestly remain Unreconciled. | +| Finished successfully | Exit 0, Done. | +| Finished with failure | Exit 7, Failed. | +| Final log collection pending | Exit 0 after writing 8 MiB. A throttled transfer holds collection pending; the outage interrupts it. Restore the host to complete collection. | + +`gpu-box` begins blackholed after successful large-log collection. The fixture +asserts the project runs endpoint and host endpoint, plus a successful middle +page before the outage and a structured 503 afterwards. `lab-login` and +`mfa-box` remain separate real sshd hosts. The lab-login and mfa-box launches stay Submitting with NeedsAuth contact: +no Launch frame was sent. Their causes carry the cleaned SSH diagnostic. +The expired-key run demonstrates NeedsAuth after a handle has been established. +Unreconciled is not manufactured in this fixture; the response-loss regression +uses a real host crash after publishing the launch intent. +Collection remains pending; the hourly failed threshold is not faked. + +`READY` prints the control FIFO and `ready.json` path. The latter contains run +and experiment IDs, API snapshots, and measured disk use. Send newline-terminated +commands, for example: + +```sh +echo 'restore gpu-box' > /tmp/orx-ui-fixture-/controls +echo 'blackhole gpu-box' > /tmp/orx-ui-fixture-/controls +echo 'restart-sshd gpu-box' > /tmp/orx-ui-fixture-/controls +echo quit > /tmp/orx-ui-fixture-/controls +``` + +Controls also accept `lab-login`, `expired-key` and `mfa-box`. Blackhole resets existing TCP +sessions and discards new traffic. Restore resets sessions again so dropped +protocol bytes cannot poison recovery. Restart preserves host keys, home, port, +and proxy. Run IDs and directories change on each start. + +The large-log run is launched among the newest three remote runs so normal +retention keeps its host-only middle. Launching several newer runs in the same +project can naturally evict it. + +Expect about 1.4 GiB of fixture data: 1,074,790,400 host log bytes, 320 MiB kept +locally, plus the 8 MiB collection log and small runtime/source files. Build +artifacts and `ui/dist` are additional reusable workspace files. Steady logs +grow slowly until stopped. Disk use is measured with `du -sk` before readiness. + +Ctrl-C, SIGTERM, or `quit` stops the app, detached payload process groups, SSH +sessions, sshd listeners and proxies, and removes temporary homes including big +logs. Cleanup runs `pgrep` against each isolated directory and fails if a process +survives. SIGKILL cannot run cleanup. The fixture stays in the foreground and is +ignored by the normal test suite. + +Host GET and `host.updated` SSE objects include `root`; keep per-root details +keyed by `(alias, root)`. Retry acts on every active root for the alias and +returns the worst resulting host object: needs_auth > backoff > connecting > +live > idle. An alias with no root in use returns 404; NeedsAuth requires Connect. diff --git a/tests/fixtures/engine-ui.sh b/tests/fixtures/engine-ui.sh new file mode 100644 index 000000000..55d1245fe --- /dev/null +++ b/tests/fixtures/engine-ui.sh @@ -0,0 +1,18 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/../.." +unset CLAUDE_CONFIG_DIR CODEX_HOME +export CARGO_TARGET_DIR="$PWD/target" +export CARGO_PROFILE_DEV_DEBUG=0 CARGO_PROFILE_TEST_DEBUG=0 +export CARGO_HOME="${CARGO_HOME:-$HOME/.cargo}" RUSTUP_HOME="${RUSTUP_HOME:-$HOME/.rustup}" +export HOME="$CARGO_TARGET_DIR/ui-fixture-build-home" +export XDG_CONFIG_HOME="$HOME/config" XDG_DATA_HOME="$HOME/data" XDG_CACHE_HOME="$HOME/cache" +mkdir -p "$HOME" +(cd ui && pnpm build) +cargo build -p orx-host --profile host +mkdir -p "$CARGO_TARGET_DIR/ui-fixture-host" +case "$(uname -s)" in Darwin) host_os=darwin;; Linux) host_os=linux;; *) exit 1;; esac +case "$(uname -m)" in arm64) host_arch=aarch64;; *) host_arch="$(uname -m)";; esac +cp "$CARGO_TARGET_DIR/host/orx-host" "$CARGO_TARGET_DIR/ui-fixture-host/orx-host-$host_os-$host_arch" +export ORX_FIXTURE_HOST_BIN_DIR="$CARGO_TARGET_DIR/ui-fixture-host" +exec cargo test --test ui_fixture -- --ignored --nocapture diff --git a/tests/fixtures/store-0.2.22.sql b/tests/fixtures/store-0.2.22.sql new file mode 100644 index 000000000..e678b976e --- /dev/null +++ b/tests/fixtures/store-0.2.22.sql @@ -0,0 +1,64 @@ +-- Written by Store::open_at/upsert_run and the wakeup writers from orx 0.2.22. +CREATE TABLE runs ( + id TEXT PRIMARY KEY, + experiment_id TEXT NOT NULL, + project_id TEXT NOT NULL, + status TEXT NOT NULL, + backend_json TEXT NOT NULL, + command TEXT NOT NULL DEFAULT '', + created_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL, + ended_at INTEGER, + exit_code INTEGER + , commit_sha TEXT, result_markdown TEXT, cancel_requested INTEGER NOT NULL DEFAULT 0, chat_session_id TEXT, cancel_reason TEXT); +INSERT INTO runs VALUES ('cancelled','exp_1','proj_1','cancelled','{"kind":"ssh_job","jobId":"finished"}','echo hi',1,1,300,0,NULL,NULL,0,'owner',NULL); +INSERT INTO runs VALUES ('done','exp_1','proj_1','done','{"kind":"ssh_job","jobId":"finished"}','echo hi',1,1,300,0,NULL,NULL,0,'owner',NULL); +INSERT INTO runs VALUES ('failed','exp_1','proj_1','failed','{"kind":"ssh_job","jobId":"finished"}','echo hi',1,1,300,0,NULL,NULL,0,'owner',NULL); +INSERT INTO runs VALUES ('hf_job','exp_1','proj_1','running','{"kind":"hf_job","namespace":"lab","jobId":"handle-4","sourceDigest":"0000000000000000000000000000000000000000000000000000000000000004","sourcePath":"/sources/4.tar","sourceSize":123,"rentalLease":null}','echo hi',104,204,NULL,NULL,NULL,NULL,0,'owner',NULL); +INSERT INTO runs VALUES ('k8s_job','exp_1','proj_1','running','{"kind":"k8s_job","namespace":"lab","jobId":"handle-6","sourceDigest":"0000000000000000000000000000000000000000000000000000000000000006","sourcePath":"/sources/6.tar","sourceSize":123,"rentalLease":null}','echo hi',106,206,NULL,NULL,NULL,NULL,0,'owner',NULL); +INSERT INTO runs VALUES ('local_job','exp_1','proj_1','running','{"kind":"local_job","namespace":"lab","jobId":"handle-2","sourceDigest":"0000000000000000000000000000000000000000000000000000000000000002","sourcePath":"/sources/2.tar","sourceSize":123,"rentalLease":null}','echo hi',102,202,NULL,NULL,NULL,NULL,0,'owner',NULL); +INSERT INTO runs VALUES ('lost','exp_1','proj_1','lost','{"kind":"ssh_job","jobId":"finished"}','echo hi',1,1,300,0,NULL,NULL,0,'owner',NULL); +INSERT INTO runs VALUES ('modal_job','exp_1','proj_1','starting','{"kind":"modal_job","namespace":"lab","jobId":"handle-5","sourceDigest":"0000000000000000000000000000000000000000000000000000000000000005","sourcePath":"/sources/5.tar","sourceSize":123,"rentalLease":null}','echo hi',105,205,NULL,NULL,NULL,NULL,0,'owner',NULL); +INSERT INTO runs VALUES ('openresearch_job','exp_1','proj_1','running','{"kind":"openresearch_job","namespace":"lab","jobId":"handle-8","sourceDigest":"0000000000000000000000000000000000000000000000000000000000000008","sourcePath":"/sources/8.tar","sourceSize":123,"rentalLease":null}','echo hi',108,208,NULL,NULL,NULL,NULL,0,'owner',NULL); +INSERT INTO runs VALUES ('ray_job','exp_1','proj_1','starting','{"kind":"ray_job","namespace":"lab","jobId":"handle-7","sourceDigest":"0000000000000000000000000000000000000000000000000000000000000007","sourcePath":"/sources/7.tar","sourceSize":123,"rentalLease":null}','echo hi',107,207,NULL,NULL,NULL,NULL,0,'owner',NULL); +INSERT INTO runs VALUES ('slurm_job','exp_1','proj_1','starting','{"kind":"slurm_job","namespace":"lab","jobId":"handle-1","sourceDigest":"0000000000000000000000000000000000000000000000000000000000000001","sourcePath":"/sources/1.tar","sourceSize":123,"rentalLease":null}','echo hi',101,201,NULL,NULL,NULL,NULL,0,'owner',NULL); +INSERT INTO runs VALUES ('ssh_job','exp_1','proj_1','running','{"kind":"ssh_job","namespace":"lab","jobId":"handle-0","sourceDigest":"0000000000000000000000000000000000000000000000000000000000000000","sourcePath":"/sources/0.tar","sourceSize":123,"rentalLease":null}','echo hi',100,200,NULL,NULL,NULL,NULL,1,'owner',NULL); +INSERT INTO runs VALUES ('tinker_job','exp_1','proj_1','starting','{"kind":"tinker_job","namespace":"lab","jobId":"handle-3","sourceDigest":"0000000000000000000000000000000000000000000000000000000000000003","sourcePath":"/sources/3.tar","sourceSize":123,"rentalLease":null}','echo hi',103,203,NULL,NULL,NULL,NULL,0,'owner',NULL); +CREATE TABLE chat_sessions ( + id TEXT PRIMARY KEY, + project_id TEXT NOT NULL, + harness TEXT NOT NULL, + native_session_id TEXT, + title TEXT, + title_source TEXT, + model TEXT, + service_tier TEXT, + permission_mode TEXT, + plan_mode INTEGER NOT NULL DEFAULT 0, + plan_reset_pending INTEGER NOT NULL DEFAULT 0, + reasoning_level TEXT, + archived INTEGER NOT NULL DEFAULT 0, + context_usage_json TEXT, + bootstrap_context TEXT, + parent_session_id TEXT, + created_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL + , active_leaf_id TEXT, goal TEXT, autonomy TEXT, side_parent_session_id TEXT, side_parent_leaf_id TEXT); +INSERT INTO chat_sessions VALUES ('foreign','proj_1','claude-code',NULL,NULL,NULL,NULL,NULL,NULL,0,0,NULL,0,NULL,NULL,NULL,1,1,NULL,NULL,NULL,NULL,NULL); +INSERT INTO chat_sessions VALUES ('owner','proj_1','claude-code',NULL,NULL,NULL,NULL,NULL,NULL,0,0,NULL,0,NULL,NULL,NULL,1,1,NULL,NULL,NULL,NULL,NULL); +CREATE TABLE chat_run_wakeups ( + run_id TEXT NOT NULL, + chat_session_id TEXT NOT NULL, + requested_at INTEGER NOT NULL, + state TEXT NOT NULL DEFAULT 'pending', + claim_token TEXT, + claimed_at INTEGER, + delivered_at INTEGER, + monitoring_alerted INTEGER NOT NULL DEFAULT 0, + PRIMARY KEY(run_id, chat_session_id) + ); +INSERT INTO chat_run_wakeups VALUES ('done','owner',400,'delivered',NULL,NULL,500,0); +INSERT INTO chat_run_wakeups VALUES ('failed','foreign',400,'pending',NULL,NULL,NULL,0); +INSERT INTO chat_run_wakeups VALUES ('ssh_job','foreign',400,'pending',NULL,NULL,NULL,1); +INSERT INTO chat_run_wakeups VALUES ('ssh_job','owner',400,'pending',NULL,NULL,NULL,0); +PRAGMA user_version = 1; diff --git a/tests/local_restart.rs b/tests/local_restart.rs new file mode 100644 index 000000000..095d3ee2d --- /dev/null +++ b/tests/local_restart.rs @@ -0,0 +1,178 @@ +// Separate test crate; commands inherit the terminal environment. +#![allow(clippy::disallowed_methods)] +#![cfg(unix)] + +use orx_host::{platform, read_json, wrapper}; +use orx_host_proto::ProcessIdentity; +use orx_test_support::Process; +use serde_json::{json, Value}; +use std::fs; +use std::net::TcpListener; +use std::process::Command; +use std::time::{Duration, Instant}; + +#[tokio::test] +async fn local_cancel_and_observe_survive_an_orx_up_exec_restart() { + let root = std::env::temp_dir().join(format!("orx-local-restart-{}", uuid::Uuid::new_v4())); + let data = root.join("data"); + let config = root.join("config/openresearch"); + fs::create_dir_all(&config).unwrap(); + fs::create_dir_all(root.join(".ssh")).unwrap(); + fs::write(root.join(".ssh/config"), "").unwrap(); + let command = || { + let mut command = Command::new(env!("CARGO_BIN_EXE_orx")); + command + .env_remove("CLAUDE_CONFIG_DIR") + .env_remove("CODEX_HOME") + .env_remove("ORX_LOCAL_SESSION") + .env_remove("ORX_UP_PORT") + .env_remove("ORX_UP_AUTH_TOKEN") + .env_remove("SSH_AUTH_SOCK") + .env("HOME", &root) + .env("PATH", "/usr/bin:/bin:/usr/sbin:/sbin") + .env("XDG_CONFIG_HOME", root.join("config")) + .env("XDG_CACHE_HOME", root.join("cache")) + .env("XDG_DATA_HOME", root.join("xdg-data")) + .env("ORX_DATA_DIR", &data) + .env("ORX_CACHE_DIR", root.join("cache")) + .env("ORX_SSH_CONFIG", root.join(".ssh/config")) + .env("ORX_HOST_BIN_DIR", orx_test_support::host_binaries()) + .env("ORX_NO_UPDATE_CHECK", "1") + .arg("--no-telemetry"); + command + }; + let initialized = command().args(["projects", "--json"]).output().unwrap(); + assert!(initialized.status.success(), "{initialized:?}"); + let db = rusqlite::Connection::open(data.join("orx.db")).unwrap(); + db.busy_timeout(Duration::from_secs(5)).unwrap(); + db.execute("INSERT INTO local_projects (id,name,slug,github_owner,github_repo,repo_path,created_at,updated_at) VALUES ('project','P','p','','',?1,1,1)", [root.to_str().unwrap()]).unwrap(); + db.execute_batch("INSERT INTO local_experiments (id,project_id,slug,branch_name,run_command,agent_status,created_at,updated_at) VALUES ('exp','project','exp','main','sleep 60','idle',1,1)").unwrap(); + let run = uuid::Uuid::new_v4().to_string(); + let script = "echo $$ > payload-pid; touch ready; exec sleep 120"; + let launch = + json!({"kind":"local_job","target":null,"options":{"env":{"ORX_TEST_FAST_STOPS":"1"}}}); + db.execute("INSERT INTO runs (id,experiment_id,project_id,status,backend_json,command,created_at,updated_at,spec_digest,submission_attempt,launch_spec) VALUES (?1,'exp','project','submitting','{\"kind\":\"engine\"}',?2,1,1,?3,1,?4)", rusqlite::params![run, script, orx_host::sha(script.as_bytes()), launch.to_string()]).unwrap(); + let port = TcpListener::bind("127.0.0.1:0") + .unwrap() + .local_addr() + .unwrap() + .port(); + let mut up = command(); + up.args([ + "up", + "--no-browser", + "--no-agent", + "--headless", + "--port", + &port.to_string(), + ]); + let app = Process::spawn(&mut up).unwrap(); + #[allow(clippy::disallowed_methods)] + let client = reqwest::Client::builder() + .no_proxy() + .timeout(Duration::from_secs(5)) + .build() + .unwrap(); + let url = format!("http://127.0.0.1:{port}"); + let dir = data.join("local-runs").join(&run); + let deadline = Instant::now() + Duration::from_secs(45); + while !dir.join("ready").exists() { + assert!(Instant::now() < deadline, "{}", app.stderr().unwrap()); + tokio::time::sleep(Duration::from_millis(50)).await; + } + let identity: ProcessIdentity = read_json(&dir.join("wrapper.json")).unwrap(); + assert_ne!(platform::process(identity.pid).unwrap().ppid, app.pid()); + let payload: u32 = fs::read_to_string(dir.join("payload-pid")) + .unwrap() + .trim() + .parse() + .unwrap(); + let payload = platform::identity(payload).unwrap(); + let deadline = Instant::now() + Duration::from_secs(15); + while db + .query_row("SELECT status FROM runs WHERE id=?1", [&run], |row| { + row.get::<_, String>(0) + }) + .unwrap() + != "running" + { + assert!(Instant::now() < deadline, "{}", app.stderr().unwrap()); + tokio::time::sleep(Duration::from_millis(50)).await; + } + let app_identity = platform::identity(app.pid()).unwrap(); + let before: Value = client + .get(format!("{url}/api/update")) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + fs::write(config.join("update-check-unknown.json"), json!({"checked_at":0,"latest":"0.2.99","installed_version":"0.2.99","installed_tag":"v0.2.99"}).to_string()).unwrap(); + let response = client + .post(format!("{url}/api/update/restart")) + .send() + .await + .unwrap(); + assert!( + response.status().is_success(), + "{}", + response.text().await.unwrap() + ); + let deadline = Instant::now() + Duration::from_secs(45); + loop { + if let Ok(response) = client.get(format!("{url}/api/update")).send().await { + if let Ok(after) = response.json::().await { + if after["instance"] != before["instance"] { + break; + } + } + } + assert!(Instant::now() < deadline, "{}", app.stderr().unwrap()); + tokio::time::sleep(Duration::from_millis(50)).await; + } + assert!(platform::alive(&identity).unwrap()); + assert!(platform::alive(&app_identity).unwrap()); + assert!(app.stderr().unwrap().contains("orx up: restarting")); + let response = client + .post(format!("{url}/api/runs/{run}/cancel")) + .send() + .await + .unwrap(); + assert!( + response.status().is_success(), + "{}", + response.text().await.unwrap() + ); + let deadline = Instant::now() + Duration::from_secs(30); + while !dir.join("exit.json").exists() { + assert!(Instant::now() < deadline, "{}", app.stderr().unwrap()); + tokio::time::sleep(Duration::from_millis(50)).await; + } + let receipt = wrapper::receipt(&dir).unwrap().unwrap(); + assert_eq!(receipt.reason, orx_host_proto::ExitReason::Cancelled); + assert!(receipt.processes.is_empty()); + assert_eq!(receipt.outcome, orx_host_proto::CancelOutcome::Verified); + loop { + let (status, contact): (String, Option) = db + .query_row( + "SELECT status,contact FROM runs WHERE id=?1", + [&run], + |row| Ok((row.get(0)?, row.get(1)?)), + ) + .unwrap(); + if status == "cancelled" && contact.is_none() { + break; + } + assert!( + Instant::now() < deadline, + "{status} {contact:?}: {}", + app.stderr().unwrap() + ); + tokio::time::sleep(Duration::from_millis(50)).await; + } + assert!(!platform::alive(&payload).unwrap()); + drop(app); + drop(db); + fs::remove_dir_all(root).unwrap(); +} diff --git a/tests/packaged_host.rs b/tests/packaged_host.rs new file mode 100644 index 000000000..207434bc9 --- /dev/null +++ b/tests/packaged_host.rs @@ -0,0 +1,96 @@ +// Separate test crate; commands inherit the terminal environment. +#![allow(clippy::disallowed_methods)] +#![cfg(unix)] + +use orx_test_support::{Process, Sshd}; +use sha2::{Digest, Sha256}; +use std::fs; +use std::process::Command; +use std::time::{Duration, Instant}; + +#[test] +#[ignore = "requires an orx built with embedded hosts; release CI supplies ORX_PACKAGED_BINARY"] +fn packaged_orx_bootstraps_host_without_binary_directory() { + let binary = std::env::var_os("ORX_PACKAGED_BINARY") + .expect("set ORX_PACKAGED_BINARY to the orx built with embedded hosts"); + let server = Sshd::start().unwrap(); + let local = server.directory().join("laptop"); + fs::create_dir_all(&local).unwrap(); + let data = local.join("data"); + let command = || { + let mut command = Command::new(&binary); + command + .env("HOME", &local) + .env("XDG_CONFIG_HOME", local.join("config")) + .env("ORX_DATA_DIR", &data) + .env("ORX_SSH_CONFIG", server.config_path()) + .env("ORX_NO_UPDATE_CHECK", "1") + .env_remove("ORX_HOST_BIN_DIR") + .env_remove("ORX_LOCAL_SESSION") + .env_remove("ORX_UP_PORT") + .env_remove("ORX_UP_AUTH_TOKEN") + .arg("--no-telemetry"); + command + }; + let initialized = command().args(["projects", "--json"]).output().unwrap(); + assert!(initialized.status.success(), "{initialized:?}"); + let db = rusqlite::Connection::open(data.join("orx.db")).unwrap(); + db.execute( + "INSERT INTO local_projects (id, name, slug, github_owner, github_repo, github_sync_enabled, + baseline_branch, repo_path, created_at, updated_at) + VALUES ('project', 'P', 'p', 'o', 'r', 0, 'main', ?1, 1, 1)", + [local.to_str().unwrap()], + ) + .unwrap(); + db.execute_batch( + "INSERT INTO local_experiments (id, project_id, slug, branch_name, run_command, agent_status, + created_at, updated_at) + VALUES ('exp', 'project', 'exp', 'main', 'true', 'idle', 1, 1);", + ) + .unwrap(); + let run = uuid::Uuid::new_v4().to_string(); + let remote = server.home().join(".orx/runs").join(&run); + fs::create_dir_all(&remote).unwrap(); + fs::write(remote.join("log"), "packaged host smoke\n").unwrap(); + fs::write(remote.join("exit_code"), "0\n").unwrap(); + let descriptor = serde_json::json!({ + "kind": "ssh_job", "namespace": server.alias(), "jobId": format!(".orx/runs/{run}") + }); + db.execute( + "INSERT INTO runs (id, experiment_id, project_id, status, backend_json, command, created_at, updated_at) + VALUES (?1, 'exp', 'project', 'running', ?2, 'true', 1, 1)", + rusqlite::params![run, descriptor.to_string()], + ) + .unwrap(); + let bin = server.home().join(".orx/engine/bin"); + assert!(!bin.exists()); + let _app = Process::spawn(command().args(["up", "--no-browser", "--port", "0"])).unwrap(); + let deadline = Instant::now() + Duration::from_secs(45); + loop { + let status: String = db + .query_row("SELECT status FROM runs WHERE id = ?1", [&run], |row| { + row.get(0) + }) + .unwrap(); + if status == "done" { + break; + } + assert!( + Instant::now() < deadline, + "packaged host did not observe the remote receipt: {status}" + ); + std::thread::sleep(Duration::from_millis(100)); + } + let uploaded: Vec<_> = fs::read_dir(bin) + .unwrap() + .map(|entry| entry.unwrap().path()) + .collect(); + assert_eq!(uploaded.len(), 1, "{uploaded:?}"); + let bytes = fs::read(&uploaded[0]).unwrap(); + let sha = format!("{:x}", Sha256::digest(&bytes)); + assert_eq!( + uploaded[0].file_name().unwrap().to_str().unwrap(), + format!("orx-host-{sha}") + ); + println!("packaged orx bootstrapped orx-host-{sha} over SSH with ORX_HOST_BIN_DIR unset"); +} diff --git a/tests/sshd.rs b/tests/sshd.rs new file mode 100644 index 000000000..41e3e467e --- /dev/null +++ b/tests/sshd.rs @@ -0,0 +1,570 @@ +// Separate test crate; commands inherit the terminal environment. +#![allow(clippy::disallowed_methods)] +#![cfg(unix)] + +use orx_test_support::{FaultProxy, Faults, Process, Sshd, SshdBuilder}; +use std::fs; +use std::io::{Read, Write}; +use std::net::{Ipv4Addr, SocketAddr, TcpListener, TcpStream}; +use std::num::NonZeroU64; +use std::panic::{catch_unwind, AssertUnwindSafe}; +use std::process::Command; +use std::thread; +use std::time::{Duration, Instant}; + +fn until(timeout: Duration, mut condition: impl FnMut() -> bool) { + let deadline = Instant::now() + timeout; + while !condition() { + assert!( + Instant::now() < deadline, + "condition timed out after {timeout:?}" + ); + thread::sleep(Duration::from_millis(10)); + } +} + +fn master(server: &Sshd) -> Process { + let process = server.spawn(&["-M", "-N"], None).unwrap(); + until(Duration::from_secs(5), || { + server + .spawn(&["-O", "check"], None) + .unwrap() + .wait(Duration::from_secs(1)) + .unwrap() + .status + .success() + }); + process +} + +fn live_session(server: &Sshd, marker: &str, options: &[&str]) -> Process { + let process = server + .spawn( + options, + Some(&format!( + "touch {marker}; while printf .; do sleep 0.1; done" + )), + ) + .unwrap(); + until(Duration::from_secs(5), || { + server.home().join(marker).exists() + }); + process +} + +fn alive(pid: u32) -> bool { + unsafe { libc::kill(pid as i32, 0) == 0 } +} + +fn assert_auth_attempts(server: &Sshd, expected: &[(&str, &str, usize)]) { + let expected = expected + .iter() + .map(|&(method, outcome, count)| ((method.to_owned(), outcome.to_owned()), count)) + .collect(); + let deadline = Instant::now() + Duration::from_secs(1); + loop { + let actual = server.auth_attempts().unwrap(); + if actual == expected { + return; + } + assert!( + Instant::now() < deadline, + "auth attempts: {actual:?}, expected {expected:?}" + ); + thread::sleep(Duration::from_millis(10)); + } +} + +#[test] +fn command_through_generated_alias() { + let server = Sshd::start().unwrap(); + let mut command = Command::new("ssh"); + command + .args(server.ssh_args()) + .arg("printf '%s\\n' \"$USER\"; pwd"); + let output = Process::spawn(&mut command) + .unwrap() + .wait(Duration::from_secs(5)) + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!( + String::from_utf8(output.stdout).unwrap(), + format!("{}\n{}\n", server.user(), server.home().display()) + ); + assert!(server.port() > 0); + assert_eq!(server.alias(), "orx-test"); +} + +#[test] +fn missing_managed_include_is_harmless_to_config_and_connect() { + let server = Sshd::start().unwrap(); + let managed = server.directory().join("openresearch_config"); + fs::write(&managed, "# retired connection sharing\n").unwrap(); + let original = fs::read_to_string(server.config_path()).unwrap(); + fs::write( + server.config_path(), + format!("Include {}\n{original}", managed.display()), + ) + .unwrap(); + fs::remove_file(&managed).unwrap(); + + let mut command = Command::new("ssh"); + command.arg("-G").args(server.ssh_args()); + let output = Process::spawn(&mut command) + .unwrap() + .wait(Duration::from_secs(5)) + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + assert!(String::from_utf8(output.stdout) + .unwrap() + .contains("hostname 127.0.0.1")); + assert!(server.run("true").unwrap().status.success()); +} + +#[test] +fn remote_home_is_isolated_and_real_orx_is_untouched() { + let server = Sshd::start().unwrap(); + let real_orx = server.real_home().join(".orx"); + let before = fs::metadata(&real_orx) + .map(|m| (m.is_dir(), m.len(), m.modified().unwrap())) + .ok(); + let marker = server.directory().file_name().unwrap().to_str().unwrap(); + let real_marker = real_orx.join(marker); + assert!(!real_marker.exists()); + let output = server + .run(&format!( + "printf '%s' \"$HOME\"; mkdir -p \"$HOME/.orx\"; printf isolated >\"$HOME/.orx/{marker}\"" + )) + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!( + String::from_utf8(output.stdout).unwrap(), + server.home().to_str().unwrap() + ); + assert_eq!( + fs::read_to_string(server.home().join(".orx").join(marker)).unwrap(), + "isolated" + ); + assert!(!real_marker.exists()); + assert_eq!( + before, + fs::metadata(&real_orx) + .map(|m| (m.is_dir(), m.len(), m.modified().unwrap())) + .ok() + ); +} + +#[test] +fn black_hole_is_detected_by_client_keepalives() { + let server = Sshd::start().unwrap(); + let mut client = live_session( + &server, + "black-hole-ready", + &[ + "-o", + "ServerAliveInterval=1", + "-o", + "ServerAliveCountMax=2", + "-o", + "LogLevel=INFO", + ], + ); + let start = Instant::now(); + server + .proxy() + .set(Faults { + black_hole: true, + ..Faults::default() + }) + .unwrap(); + let output = client.wait(Duration::from_secs(8)).unwrap(); + assert!(!output.status.success()); + assert!( + String::from_utf8_lossy(&output.stderr).contains("Timeout, server"), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + assert!(start.elapsed() < Duration::from_secs(8)); + server.proxy().set(Faults::default()).unwrap(); + assert!(server.run("true").unwrap().status.success()); +} + +#[test] +fn reset_disconnects_live_clients_and_allows_reconnect() { + let server = Sshd::start().unwrap(); + let mut clients = [ + live_session(&server, "reset-a", &[]), + live_session(&server, "reset-b", &[]), + ]; + server.proxy().reset().unwrap(); + for client in &mut clients { + assert!(!client + .wait(Duration::from_secs(3)) + .unwrap() + .status + .success()); + } + assert!(server.run("true").unwrap().status.success()); +} + +#[test] +fn latency_applies_to_an_established_ssh_connection() { + let server = Sshd::start().unwrap(); + let _master = master(&server); + let baseline = Instant::now(); + assert!(server.run("true").unwrap().status.success()); + let baseline = baseline.elapsed(); + server + .proxy() + .set(Faults { + latency: Duration::from_millis(150), + ..Faults::default() + }) + .unwrap(); + let delayed = Instant::now(); + assert!(server.run("true").unwrap().status.success()); + let delayed = delayed.elapsed(); + assert!( + delayed >= Duration::from_millis(280), + "latency was only {delayed:?}" + ); + assert!( + delayed > baseline + Duration::from_millis(150), + "baseline={baseline:?}, delayed={delayed:?}" + ); + server.proxy().set(Faults::default()).unwrap(); + assert!(server.run("true").unwrap().status.success()); +} + +#[test] +fn max_sessions_is_enforced_over_a_control_master() { + let server = SshdBuilder { + max_sessions: 1, + ..SshdBuilder::default() + } + .start() + .unwrap(); + let _master = master(&server); + let mut first = live_session(&server, "session-ready", &["-o", "ProxyCommand=false"]); + let output = server + .spawn(&["-o", "ProxyCommand=false"], Some("true")) + .unwrap() + .wait(Duration::from_secs(3)) + .unwrap(); + assert!(!output.status.success()); + assert!( + String::from_utf8_lossy(&output.stderr).contains("Session open refused"), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + server.proxy().reset().unwrap(); + assert!(!first.wait(Duration::from_secs(3)).unwrap().status.success()); +} + +#[test] +fn panic_cleans_up_daemon_master_and_directory() { + let mut recorded = None; + let mut kept_master = None; + let result = catch_unwind(AssertUnwindSafe(|| { + let server = Sshd::start().unwrap(); + let process = master(&server); + recorded = Some(( + server.pid(), + process.pid(), + server.directory().to_path_buf(), + )); + // Keep the process guard outside the unwind: only Sshd's socket cleanup can stop it. + kept_master = Some(process); + panic!("intentional harness cleanup test"); + })); + assert!(result.is_err()); + let (sshd_pid, master_pid, directory) = recorded.unwrap(); + assert!(!alive(sshd_pid), "sshd {sshd_pid} survived unwind"); + assert!(!directory.exists(), "temporary directory survived unwind"); + let output = kept_master + .as_mut() + .unwrap() + .wait(Duration::from_secs(3)) + .unwrap(); + assert!( + output.status.code().is_some(), + "master was terminated by a signal" + ); + assert!(!alive(master_pid), "master {master_pid} survived unwind"); +} + +#[test] +fn proxy_pause_bandwidth_and_refusal_are_reversible() { + let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap(); + let proxy = FaultProxy::start(listener.local_addr().unwrap()).unwrap(); + let mut client = TcpStream::connect((Ipv4Addr::LOCALHOST, proxy.port())).unwrap(); + client + .set_read_timeout(Some(Duration::from_millis(200))) + .unwrap(); + listener.set_nonblocking(true).unwrap(); + let deadline = Instant::now() + Duration::from_secs(3); + let (mut remote, _) = loop { + match listener.accept() { + Ok(connection) => break connection, + Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => { + assert!(Instant::now() < deadline, "proxy did not connect to target"); + thread::sleep(Duration::from_millis(10)); + } + Err(error) => panic!("accept proxy connection: {error}"), + } + }; + remote.set_nonblocking(false).unwrap(); + remote + .set_read_timeout(Some(Duration::from_millis(200))) + .unwrap(); + proxy + .set(Faults { + paused: true, + ..Faults::default() + }) + .unwrap(); + client.write_all(b"paused").unwrap(); + remote.write_all(b"return").unwrap(); + let mut bytes = [0; 6]; + assert!(remote.read(&mut bytes).is_err()); + assert!(client.read(&mut bytes).is_err()); + proxy.set(Faults::default()).unwrap(); + remote.read_exact(&mut bytes).unwrap(); + assert_eq!(&bytes, b"paused"); + client.read_exact(&mut bytes).unwrap(); + assert_eq!(&bytes, b"return"); + + proxy + .set(Faults { + bytes_per_second: NonZeroU64::new(4096), + ..Faults::default() + }) + .unwrap(); + remote + .set_read_timeout(Some(Duration::from_secs(3))) + .unwrap(); + let start = Instant::now(); + client.write_all(&[7; 4096]).unwrap(); + let mut payload = [0; 4096]; + remote.read_exact(&mut payload).unwrap(); + assert_eq!(payload, [7; 4096]); + assert!(start.elapsed() >= Duration::from_millis(900)); + + proxy + .set(Faults { + refuse_new: true, + ..Faults::default() + }) + .unwrap(); + let address = SocketAddr::from((Ipv4Addr::LOCALHOST, proxy.port())); + assert!(TcpStream::connect_timeout(&address, Duration::from_millis(200)).is_err()); + client.write_all(b"alive!").unwrap(); + remote.read_exact(&mut bytes).unwrap(); + assert_eq!(&bytes, b"alive!"); + proxy.set(Faults::default()).unwrap(); + assert!(TcpStream::connect_timeout(&address, Duration::from_secs(1)).is_ok()); +} + +#[test] +fn invalid_server_configuration_fails_with_diagnostics() { + let result = SshdBuilder { + max_startups: "invalid".into(), + ..SshdBuilder::default() + } + .start(); + let error = result.err().expect("invalid MaxStartups must fail"); + assert!(error.to_string().contains("MaxStartups"), "{error:#}"); +} + +/// A throughput floor holds only on an idle machine; run with `--ignored`. +#[test] +#[ignore = "benchmark"] +fn pass_through_upload_exceeds_fifty_megabytes_per_second() { + const BYTES: u64 = 256 * 1024 * 1024; + let server = Sshd::start().unwrap(); + let upload = server.directory().join("upload"); + fs::File::create(&upload).unwrap().set_len(BYTES).unwrap(); + let mut command = Command::new("/bin/sh"); + command + .args([ + "-c", + r#"exec ssh -o Compression=no "$@" 'cat > /dev/null' < "$ORX_SSH_UPLOAD""#, + "upload", + ]) + .args(server.ssh_args()) + .env("ORX_SSH_UPLOAD", upload); + let start = Instant::now(); + let output = Process::spawn(&mut command) + .unwrap() + .wait(Duration::from_secs(20)) + .unwrap(); + let elapsed = start.elapsed(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let megabytes_per_second = BYTES as f64 / elapsed.as_secs_f64() / 1_000_000.0; + println!("256 MiB SSH upload: {megabytes_per_second:.1} MB/s in {elapsed:.3?}"); + assert!( + megabytes_per_second > 50.0, + "pass-through was only {megabytes_per_second:.1} MB/s" + ); +} + +#[test] +fn interactive_key_counts_one_batch_probe_and_askpass_unlocks_it() { + let server = SshdBuilder { + extra_client_keys: vec![Some("a 'quoted' passphrase $with `shell` syntax".into())], + identity_files: vec!["client_key_1".into()], + ..SshdBuilder::default() + } + .start() + .unwrap(); + assert!(server.auth_attempts().unwrap().is_empty()); + let output = server.run("true").unwrap(); + assert!(!output.status.success()); + assert_auth_attempts(&server, &[("publickey", "Postponed", 1)]); + let attempts = server.auth_attempts().unwrap(); + thread::sleep(Duration::from_millis(100)); + assert_eq!(server.auth_attempts().unwrap(), attempts); + + let askpass = server + .askpass("a 'quoted' passphrase $with `shell` syntax") + .unwrap(); + let mut command = Command::new("ssh"); + command + .args(["-o", "BatchMode=no"]) + .args(server.ssh_args()) + .arg("true") + .env("SSH_ASKPASS", askpass) + .env("SSH_ASKPASS_REQUIRE", "force") + .env("DISPLAY", "orx-test"); + let output = Process::spawn(&mut command) + .unwrap() + .wait(Duration::from_secs(3)) + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let prompts = fs::read_to_string(server.directory().join("askpass-prompts")).unwrap(); + assert_eq!(prompts.lines().count(), 1, "{prompts}"); + assert!(prompts.contains("client_key_1"), "{prompts}"); + assert_auth_attempts( + &server, + &[("publickey", "Postponed", 2), ("publickey", "Accepted", 1)], + ); +} + +#[test] +fn mfa_requires_two_distinct_keys_and_a_passphrase() { + let server = SshdBuilder { + authentication_methods: "publickey,publickey".into(), + extra_client_keys: vec![Some("second factor".into())], + ..SshdBuilder::default() + } + .start() + .unwrap(); + assert!(!server.run("true").unwrap().status.success()); + assert_auth_attempts( + &server, + &[("publickey", "Postponed", 1), ("publickey", "Partial", 1)], + ); + let mut config = fs::read_to_string(server.config_path()).unwrap(); + config.push_str(&format!( + " IdentityFile {}\n", + server.directory().join("client_key_1").display() + )); + fs::write(server.config_path(), config).unwrap(); + assert!(!server.run("true").unwrap().status.success()); + assert_auth_attempts( + &server, + &[("publickey", "Postponed", 3), ("publickey", "Partial", 2)], + ); + + let askpass = server.askpass("second factor").unwrap(); + let mut command = Command::new("ssh"); + command + .args(["-o", "BatchMode=no"]) + .args(server.ssh_args()) + .arg("true") + .env("SSH_ASKPASS", askpass) + .env("SSH_ASKPASS_REQUIRE", "force") + .env("DISPLAY", "orx-test"); + let output = Process::spawn(&mut command) + .unwrap() + .wait(Duration::from_secs(3)) + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + assert_auth_attempts( + &server, + &[ + ("publickey", "Postponed", 5), + ("publickey", "Partial", 3), + ("publickey", "Accepted", 1), + ], + ); + let prompts = fs::read_to_string(server.directory().join("askpass-prompts")).unwrap(); + assert_eq!(prompts.lines().count(), 1, "{prompts}"); + assert!(prompts.contains("client_key_1"), "{prompts}"); +} + +#[test] +fn clear_restores_pass_through_after_black_hole_and_reset() { + let server = Sshd::start().unwrap(); + let mut session = live_session(&server, "before-black-hole", &[]); + server + .proxy() + .set(Faults { + black_hole: true, + ..Faults::default() + }) + .unwrap(); + server.proxy().reset().unwrap(); + assert!(!session + .wait(Duration::from_secs(3)) + .unwrap() + .status + .success()); + let mut blocked = server.spawn(&[], Some("true")).unwrap(); + thread::sleep(Duration::from_millis(100)); + assert!(blocked.wait(Duration::from_millis(50)).is_err()); + server.proxy().reset().unwrap(); + assert!(!blocked + .wait(Duration::from_secs(3)) + .unwrap() + .status + .success()); + server.proxy().clear().unwrap(); + assert!(server.run("true").unwrap().status.success()); +} + +#[test] +fn rejected_key_is_counted_as_a_failed_publickey_attempt() { + let server = SshdBuilder { + identity_files: vec!["host_key".into()], + ..SshdBuilder::default() + } + .start() + .unwrap(); + assert!(!server.run("true").unwrap().status.success()); + assert_auth_attempts(&server, &[("publickey", "Failed", 1)]); +} diff --git a/tests/support/Cargo.toml b/tests/support/Cargo.toml new file mode 100644 index 000000000..4ba484566 --- /dev/null +++ b/tests/support/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "orx-test-support" +version = "0.0.0" +edition = "2021" +publish = false + +[target.'cfg(unix)'.dependencies] +anyhow = "1" +libc = "0.2" +sha2 = "0.10" +socket2 = "0.6" +tempfile = "3" diff --git a/tests/support/README.md b/tests/support/README.md new file mode 100644 index 000000000..4c4d48aa3 --- /dev/null +++ b/tests/support/README.md @@ -0,0 +1,78 @@ +# Real SSH test support + +`orx-test-support` is a Unix-only path dev-dependency shared by binary unit tests +and integration tests. `cargo test --locked` runs its unit test and the +`tests/sshd.rs` integration suite; no Docker, root, running SSH service, or +pre-existing SSH keys are required. Debian/Ubuntu needs `openssh-server` +(`sudo apt-get install -y openssh-server`); macOS uses `/usr/sbin/sshd`. + +```rust +use orx_test_support::{Faults, SshdBuilder}; + +let server = SshdBuilder { + max_sessions: 1, + ..SshdBuilder::default() +}.start()?; +let output = server.run("mkdir -p ~/.orx; printf '%s' \"$HOME\"")?; +assert!(output.status.success()); +server.proxy().set(Faults { + black_hole: true, + ..Faults::default() +})?; +server.proxy().reset()?; +server.proxy().clear()?; +``` + +Always connect with `server.ssh_args()` (`-F config alias`) or `server.spawn()`. +OpenSSH finds its client configuration through the passwd home, so changing the +local `HOME` alone does not isolate a client. The generated config pins the host +key and client identity, disables agent use, and puts ControlPath in the private +test directory. sshd sets HOME before starting the user's shell; its forced +command also sets HOME and cwd to `server.home()`. Commands use `/bin/sh`. + +`spawn(options, command)` returns a `Process` guard with a PID and bounded +`wait(timeout)`. Keep ControlMasters in the foreground (`-M -N`, without `-f`). +Output is captured in anonymous temporary files so pipe buffers cannot deadlock +commands. Unwinding kills and reaps the owned process group. Server teardown +requests exit on ControlMaster sockets in its directory before killing sshd, +stopping the proxy, and deleting the directory. + +The proxy blocks in `poll` on socket readiness and a control wake socket, with +deadlines only for delayed chunks. Queues bound reads and preserve backpressure. + +`Faults` changes both directions of existing and future connections. `set()` and +`reset()` acknowledge after application. Latency delays received chunks; +bandwidth is per connection and direction, with chunks at most 4096 bytes. +Pause retains bytes and applies backpressure; black-hole reads and discards +bytes while keeping sockets open. Black-hole recovery does not restore discarded +SSH bytes: reset connections before reconnecting. Refusal closes the listener +without affecting established connections; clearing it reopens the same port. + +`SshdBuilder::authentication_methods` defaults to `publickey`. Additional +`extra_client_keys` entries generate authorized `client_key_1`, `client_key_2`, +etc.; `None` leaves a key unencrypted and `Some(passphrase)` encrypts it. +`identity_files` selects paths relative to the harness directory (default: +`client_key`; an empty list offers no identities). Startup waits for the listener +without authenticating. + +`server.askpass(passphrase)` returns a script path for `SSH_ASKPASS`; set +`SSH_ASKPASS_REQUIRE=force`, `DISPLAY=orx-test`, and override `BatchMode=no`. +Each invocation appends its prompt to `server.directory().join("askpass-prompts")`. +Answers are read from a private file, so shell syntax in passphrases is literal. + +`auth_attempts()` snapshots counts keyed by `(method, outcome)` from sshd stderr. +Log delivery is asynchronous; wait for the expected events before comparing +snapshots for a quiet window. `Postponed` counts unsigned public-key probes; `Partial` counts a completed MFA factor, `Accepted` completes +authentication, and `Failed` rejects an attempt. A successful key login normally +logs both a probe and an acceptance; summing those events counts protocol steps, +not login connections. Method discovery (`none`) and key-file lookup messages +are excluded. An encrypted key under BatchMode logs one `Postponed` probe and +no signed attempt. The parser accepts optional log prefixes and submethods. +The auth_log format is checked against upstream +[8.0p1](https://github.com/openssh/openssh-portable/blob/V_8_0_P1/auth.c), +[8.9p1](https://github.com/openssh/openssh-portable/blob/V_8_9_P1/auth.c), and +[9.6p1](https://github.com/openssh/openssh-portable/blob/V_9_6_P1/auth.c). + +`host_binaries()` honors `CARGO_TARGET_DIR` for its nested host build; without it, +it uses `target`. The nested build lives in its `test-hooks` subdirectory. +The opt-in seeded chaos tier and sage release gate are documented in [runner-stress](../../docs/runner-stress.md). diff --git a/tests/support/src/lib.rs b/tests/support/src/lib.rs new file mode 100644 index 000000000..58e396802 --- /dev/null +++ b/tests/support/src/lib.rs @@ -0,0 +1,643 @@ +// Separate test crate; commands inherit the terminal environment. +#![allow(clippy::disallowed_methods)] +#![cfg(unix)] + +mod process; +mod proxy; + +pub use process::Process; +pub use proxy::{FaultProxy, Faults}; + +use anyhow::{bail, Result}; +use std::collections::BTreeMap; +use std::ffi::{CStr, OsString}; +use std::fs; +use std::net::{Ipv4Addr, SocketAddr, TcpListener}; +use std::os::unix::fs::{FileTypeExt, PermissionsExt}; +use std::path::{Path, PathBuf}; +use std::process::{Command, Output}; +use std::thread; +use std::time::{Duration, Instant}; +use tempfile::TempDir; + +pub struct SshdBuilder { + pub authentication_methods: String, + /// Additional authorized keys, named client_key_1, client_key_2, etc. + pub extra_client_keys: Vec>, + pub identity_files: Vec, + pub max_sessions: u32, + pub max_startups: String, + pub login_grace_time: Duration, + pub client_alive_interval: Duration, + pub client_alive_count_max: u32, +} + +impl Default for SshdBuilder { + fn default() -> Self { + Self { + authentication_methods: "publickey".into(), + extra_client_keys: Vec::new(), + identity_files: vec!["client_key".into()], + max_sessions: 10, + max_startups: "10:30:100".into(), + login_grace_time: Duration::from_secs(10), + client_alive_interval: Duration::ZERO, + client_alive_count_max: 3, + } + } +} + +/// `orx-host` built for this machine (with test hooks), in the layout the engine reads from +/// `ORX_HOST_BIN_DIR`. Each build gets its own directory, so a rebuild never changes a binary +/// another test is uploading. +/// Stops the `orx up` that CLI calls autostarted for `data_dir`, and waits for it to exit. +/// An autostarted server outlives the test; one with unresolved runs never idles out. Each +/// signal goes only to the process the descriptor recorded, never to one that reused its pid. +pub fn stop_server(data_dir: &Path) { + let Some(descriptor) = descriptor_path(data_dir).and_then(|path| fs::read_to_string(path).ok()) + else { + return; + }; + let number = |field: &str| { + let rest = descriptor + .split_once(&format!("\"{field}\":"))? + .1 + .trim_start(); + let end = rest + .find(|c: char| !c.is_ascii_digit()) + .unwrap_or(rest.len()); + rest[..end].parse::().ok() + }; + let (Some(pid), Some(starttime)) = (number("pid"), number("starttime")) else { + return; + }; + let Ok(pid) = libc::pid_t::try_from(pid) else { + return; + }; + let recorded = || pid > 1 && start_stamp(pid) == Some(starttime); + let signal = |signal| recorded() && unsafe { libc::kill(pid, signal) } == 0; + let exited = |timeout: Duration| { + let deadline = Instant::now() + timeout; + while Instant::now() < deadline { + if !recorded() { + return true; + } + thread::sleep(Duration::from_millis(50)); + } + false + }; + if signal(libc::SIGTERM) && !exited(Duration::from_secs(10)) && signal(libc::SIGKILL) { + exited(Duration::from_secs(5)); + } +} + +/// Where `orx up` publishes its descriptor for `data_dir`. +fn descriptor_path(data_dir: &Path) -> Option { + use sha2::{Digest, Sha256}; + let data_dir = fs::canonicalize(data_dir).ok()?; + let digest = Sha256::digest(data_dir.as_os_str().as_encoded_bytes()); + let name: String = digest[..16] + .iter() + .map(|byte| format!("{byte:02x}")) + .collect(); + let uid = unsafe { libc::geteuid() }; + Some(PathBuf::from(format!("/tmp/orx-{uid}/{name}.server.json"))) +} + +/// The OS start stamp `orx up` records beside its pid; `None` once the process is gone. +#[cfg(target_os = "linux")] +fn start_stamp(pid: libc::pid_t) -> Option { + let stat = fs::read_to_string(format!("/proc/{pid}/stat")).ok()?; + let fields: Vec<&str> = stat[stat.rfind(')')? + 1..].split_whitespace().collect(); + if fields.first() == Some(&"Z") { + return None; + } + fields.get(19)?.parse().ok() +} + +#[cfg(target_os = "macos")] +fn start_stamp(pid: libc::pid_t) -> Option { + let mut info: libc::proc_bsdinfo = unsafe { std::mem::zeroed() }; + let size = std::mem::size_of::() as libc::c_int; + // SAFETY: `info` is a writable proc_bsdinfo of exactly `size` bytes. + let written = unsafe { + libc::proc_pidinfo( + pid, + libc::PROC_PIDTBSDINFO, + 0, + (&mut info as *mut libc::proc_bsdinfo).cast(), + size, + ) + }; + if written != size || info.pbi_status == libc::SZOMB { + return None; + } + Some(info.pbi_start_tvsec * 1_000_000 + info.pbi_start_tvusec) +} + +pub fn host_binaries() -> PathBuf { + use std::hash::{Hash, Hasher}; + static BINARIES: std::sync::OnceLock = std::sync::OnceLock::new(); + BINARIES + .get_or_init(|| { + let workspace = Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); + let target = std::env::var_os("CARGO_TARGET_DIR") + .map(PathBuf::from) + .unwrap_or_else(|| workspace.join("target")) + .join("test-hooks"); + let output = Command::new(env!("CARGO")) + .env("CARGO_PROFILE_DEV_DEBUG", "0") + .env("CARGO_PROFILE_DEV_STRIP", "symbols") + .env("CARGO_PROFILE_DEV_OPT_LEVEL", "1") + .args([ + "build", + "--locked", + "--features", + "test-hooks", + "-p", + "orx-host", + ]) + .arg("--target-dir") + .arg(&target) + .current_dir(&workspace) + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let binary = target.join("debug/orx-host"); + let mut digest = std::collections::hash_map::DefaultHasher::new(); + fs::read(&binary).unwrap().hash(&mut digest); + let directory = target + .join("native") + .join(format!("{:016x}", digest.finish())); + fs::create_dir_all(&directory).unwrap(); + let os = if cfg!(target_os = "macos") { + "darwin" + } else { + "linux" + }; + let destination = directory.join(format!("orx-host-{os}-{}", std::env::consts::ARCH)); + match fs::hard_link(binary, destination) { + Ok(()) => {} + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {} + Err(error) => panic!("Cannot publish test host binary: {error}"), + } + directory + }) + .clone() +} + +/// An isolated real SSH server reached through a live, controllable fault proxy. +/// Clients must use `ssh_args()` or `spawn()`; changing local HOME does not configure OpenSSH. +pub struct Sshd { + daemon: Process, + proxy: FaultProxy, + user: String, + real_home: PathBuf, + directory: TempDir, +} + +impl SshdBuilder { + pub fn start(self) -> Result { + let sshd = find_sshd()?; + // Short paths also leave room for Unix-domain ControlPath sockets on macOS. + let directory = tempfile::Builder::new() + .prefix("orx-ssh-") + .tempdir_in("/tmp")?; + let root = directory.path(); + let (user, real_home) = account()?; + let home = root.join("home"); + fs::create_dir(&home)?; + let mut keys = vec![ + ("host_key".to_owned(), None), + ("client_key".to_owned(), None), + ]; + keys.extend( + self.extra_client_keys + .iter() + .enumerate() + .map(|(index, passphrase)| { + (format!("client_key_{}", index + 1), passphrase.as_deref()) + }), + ); + let mut authorized_keys = String::new(); + for (name, passphrase) in keys { + let mut command = Command::new("ssh-keygen"); + command + .args(["-q", "-t", "ed25519", "-N", passphrase.unwrap_or(""), "-f"]) + .arg(root.join(&name)); + let output = Process::spawn(&mut command)?.wait(Duration::from_secs(5))?; + if !output.status.success() { + bail!( + "ssh-keygen failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + } + if name != "host_key" { + authorized_keys.push_str(&fs::read_to_string(root.join(format!("{name}.pub")))?); + } + } + fs::write(root.join("authorized_keys"), authorized_keys)?; + let wrapper = root.join("command"); + fs::write( + &wrapper, + format!( + r#"#!/bin/sh +HOME='{}' +export HOME +cd "$HOME" || exit 1 +if [ -n "$SSH_ORIGINAL_COMMAND" ]; then + exec /bin/sh -c "$SSH_ORIGINAL_COMMAND" +else + exec /bin/sh +fi +"#, + home.display() + ), + )?; + fs::set_permissions(&wrapper, fs::Permissions::from_mode(0o700))?; + let config = root.join("sshd_config"); + let deadline = Instant::now() + Duration::from_secs(8); + let mut attempts = 0; + // sshd cannot inherit a bound listener. Retry only its bind race, never configuration errors. + let (daemon, server_port) = 'bind: loop { + attempts += 1; + let reservation = TcpListener::bind((Ipv4Addr::LOCALHOST, 0))?; + let server_port = reservation.local_addr()?.port(); + fs::write( + &config, + format!( + r#"ListenAddress 127.0.0.1 +Port {server_port} +HostKey {root}/host_key +PidFile {root}/sshd.pid +AuthorizedKeysFile {root}/authorized_keys +StrictModes no +UsePAM no +PasswordAuthentication no +KbdInteractiveAuthentication no +AuthenticationMethods {authentication_methods} +PermitRootLogin yes +AllowUsers {user} +PermitUserRC no +AllowAgentForwarding no +AllowTcpForwarding no +X11Forwarding no +PermitTTY no +SetEnv HOME={home} +ForceCommand {root}/command +MaxSessions {sessions} +MaxStartups {startups} +LoginGraceTime {grace} +ClientAliveInterval {alive} +ClientAliveCountMax {count} +LogLevel VERBOSE +"#, + root = root.display(), + home = home.display(), + authentication_methods = self.authentication_methods, + sessions = self.max_sessions, + startups = self.max_startups, + grace = self.login_grace_time.as_secs(), + alive = self.client_alive_interval.as_secs(), + count = self.client_alive_count_max, + ), + )?; + drop(reservation); + let mut command = Command::new(&sshd); + command.args(["-D", "-e", "-f"]).arg(&config); + let process = Process::spawn(&mut command)?; + loop { + let log = process.stderr()?; + if log.contains("Server listening on") { + break 'bind (process, server_port); + } + if log.contains("Address already in use") { + if attempts == 8 { + bail!("sshd could not bind after eight attempts: {log}"); + } + break; + } + if !log.trim().is_empty() || Instant::now() >= deadline { + bail!("sshd did not become ready: {log}"); + } + thread::sleep(Duration::from_millis(10)); + } + }; + let proxy = FaultProxy::start(SocketAddr::from((Ipv4Addr::LOCALHOST, server_port)))?; + let identities = if self.identity_files.is_empty() { + " IdentityFile none\n".to_owned() + } else { + self.identity_files + .iter() + .map(|name| format!(" IdentityFile {}\n", root.join(name).display())) + .collect::() + }; + fs::write( + root.join("ssh_config"), + format!( + r#"Host orx-test + HostName 127.0.0.1 + Port {} + User {user} +{identities} IdentitiesOnly yes + IdentityAgent none + BatchMode yes + StrictHostKeyChecking yes + UserKnownHostsFile {}/known_hosts + GlobalKnownHostsFile /dev/null + ControlMaster no + ControlPath {}/control-%C + ControlPersist no + ConnectTimeout 3 + ConnectionAttempts 1 + LogLevel ERROR +"#, + proxy.port(), + root.display(), + root.display() + ), + )?; + let public_key = fs::read_to_string(root.join("host_key.pub"))?; + fs::write( + root.join("known_hosts"), + format!("[127.0.0.1]:{} {public_key}", proxy.port()), + )?; + Ok(Sshd { + directory, + daemon, + proxy, + user, + real_home, + }) + } +} + +impl Sshd { + pub fn start() -> Result { + SshdBuilder::default().start() + } + /// Restarts the listener with the same keys, port, home and proxy. + pub fn restart(&mut self) -> Result<()> { + unsafe { + libc::kill(self.daemon.pid() as i32, libc::SIGKILL); + } + self.daemon.wait(Duration::from_secs(5))?; + let mut command = Command::new(find_sshd()?); + command + .args(["-D", "-e", "-f"]) + .arg(self.directory.path().join("sshd_config")); + self.daemon = Process::spawn(&mut command)?; + let deadline = Instant::now() + Duration::from_secs(5); + while !self.daemon.stderr()?.contains("Server listening on") { + if Instant::now() >= deadline { + bail!("restarted sshd did not listen: {}", self.daemon.stderr()?); + } + thread::sleep(Duration::from_millis(10)); + } + self.proxy.reset()?; + Ok(()) + } + + pub fn alias(&self) -> &str { + "orx-test" + } + pub fn config_path(&self) -> PathBuf { + self.directory.path().join("ssh_config") + } + pub fn port(&self) -> u16 { + self.proxy.port() + } + pub fn user(&self) -> &str { + &self.user + } + pub fn home(&self) -> PathBuf { + self.directory.path().join("home") + } + pub fn real_home(&self) -> &Path { + &self.real_home + } + pub fn directory(&self) -> &Path { + self.directory.path() + } + pub fn pid(&self) -> u32 { + self.daemon.pid() + } + pub fn proxy(&self) -> &FaultProxy { + &self.proxy + } + + /// Counts sshd auth_log events by (method, outcome); Postponed is an unsigned probe. + /// Excludes method discovery (none); compare snapshots to assert a quiet window. + pub fn auth_attempts(&self) -> Result> { + Ok(parse_auth_attempts(&self.daemon.stderr()?)) + } + + /// Writes askpass and askpass-prompts in the harness directory; returns SSH_ASKPASS. + pub fn askpass(&self, passphrase: &str) -> Result { + let root = self.directory.path(); + let answer = root.join("askpass-answer"); + fs::write(&answer, passphrase)?; + fs::set_permissions(&answer, fs::Permissions::from_mode(0o600))?; + fs::write(root.join("askpass-prompts"), "")?; + let script = root.join("askpass"); + fs::write( + &script, + format!( + r#"#!/bin/sh +printf '%s\n' "$1" >> '{root}/askpass-prompts' +cat '{root}/askpass-answer' +printf '\n' +"#, + root = root.display(), + ), + )?; + fs::set_permissions(&script, fs::Permissions::from_mode(0o700))?; + Ok(script) + } + + pub fn ssh_args(&self) -> [OsString; 3] { + [ + "-F".into(), + self.config_path().into_os_string(), + self.alias().into(), + ] + } + + /// Options precede the host alias. Masters must stay in the foreground (no `-f`). + pub fn spawn(&self, options: &[&str], command: Option<&str>) -> Result { + let mut ssh = Command::new("ssh"); + ssh.arg("-F") + .arg(self.config_path()) + .args(options) + .arg(self.alias()); + if let Some(command) = command { + ssh.arg(command); + } + Process::spawn(&mut ssh) + } + + pub fn run(&self, command: &str) -> Result { + self.spawn(&[], Some(command))? + .wait(Duration::from_secs(10)) + } +} + +impl Drop for Sshd { + fn drop(&mut self) { + // Ask masters to exit before destroying the transport; socket paths are private to this test. + let mut directories = vec![self.directory.path().to_path_buf()]; + while let Some(directory) = directories.pop() { + if let Ok(entries) = fs::read_dir(directory) { + for entry in entries.flatten() { + if let Ok(kind) = entry.file_type() { + if kind.is_dir() { + directories.push(entry.path()); + } + if kind.is_socket() { + let mut ssh = Command::new("ssh"); + ssh.arg("-F") + .arg(self.config_path()) + .arg("-S") + .arg(entry.path()) + .args(["-O", "exit", self.alias()]); + if let Ok(mut process) = Process::spawn(&mut ssh) { + let _ = process.wait(Duration::from_millis(500)); + } + } + } + } + } + } + } +} + +fn parse_auth_attempts(log: &str) -> BTreeMap<(String, String), usize> { + let mut counts = BTreeMap::new(); + for line in log.lines() { + let mut words = line.split_whitespace(); + // Syslog-style prefixes vary across OpenSSH versions; auth_log's body does not. + while let Some(outcome) = words.next() { + if !matches!(outcome, "Accepted" | "Failed" | "Partial" | "Postponed") { + continue; + } + let Some(method) = words.next() else { break }; + if words.next() == Some("for") && method != "none" { + *counts + .entry((method.to_owned(), outcome.to_owned())) + .or_default() += 1; + } + break; + } + } + counts +} + +fn find_sshd() -> Result { + let mut paths = vec![ + PathBuf::from("/usr/sbin/sshd"), + PathBuf::from("/usr/local/sbin/sshd"), + ]; + if let Some(path) = std::env::var_os("PATH") { + paths.extend(std::env::split_paths(&path).map(|directory| directory.join("sshd"))); + } + for path in paths { + if path.is_file() { + return Ok(path); + } + } + bail!("real-sshd tests require OpenSSH sshd. On Debian/Ubuntu install it with `sudo apt-get update && sudo apt-get install -y openssh-server`; on macOS use /usr/sbin/sshd (Remote Login need not be enabled).") +} + +fn account() -> Result<(String, PathBuf)> { + let mut record = unsafe { std::mem::zeroed::() }; + let mut buffer = vec![0; 16384]; + let mut result = std::ptr::null_mut(); + let error = unsafe { + libc::getpwuid_r( + libc::getuid(), + &mut record, + buffer.as_mut_ptr(), + buffer.len(), + &mut result, + ) + }; + if error != 0 || result.is_null() { + bail!("getpwuid_r failed for current user: {error}"); + } + let name = unsafe { CStr::from_ptr(record.pw_name) } + .to_str()? + .to_owned(); + let home = unsafe { CStr::from_ptr(record.pw_dir) }.to_str()?.into(); + Ok((name, home)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn stop_server_signals_only_the_process_its_descriptor_recorded() { + let data = tempfile::tempdir().unwrap(); + let path = descriptor_path(data.path()).unwrap(); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + let mut child = Command::new("sleep").arg("30").spawn().unwrap(); + let pid = child.id() as libc::pid_t; + let stamp = start_stamp(pid).unwrap(); + // A stale descriptor whose pid now names another process. + fs::write( + &path, + format!(r#"{{"pid":{pid},"starttime":{}}}"#, stamp + 1), + ) + .unwrap(); + stop_server(data.path()); + assert!(child.try_wait().unwrap().is_none()); + fs::write(&path, format!(r#"{{"pid":{pid},"starttime":{stamp}}}"#)).unwrap(); + stop_server(data.path()); + fs::remove_file(&path).unwrap(); + use std::os::unix::process::ExitStatusExt; + assert!(child.wait().unwrap().signal().is_some()); + } + + #[test] + fn auth_log_outcomes_ignore_prefixes_and_key_lookup_messages() { + let log = "sshd[10]: Failed none for user from 127.0.0.1 port 42 ssh2\n\ + Accepted key ED25519 SHA256:example found at /tmp/authorized_keys:1\n\ + Postponed publickey for user from 127.0.0.1 port 42 ssh2 [preauth]\n\ + Partial publickey for user from 127.0.0.1 port 42 ssh2: ED25519 SHA256:example\n\ + sshd-auth[11]: Accepted publickey for user from 127.0.0.1 port 42 ssh2: ED25519 SHA256:example\n\ + Oct 29 00:00:00 host sshd[12]: Failed password for invalid user nobody from ::1 port 43 ssh2\n\ + Failed keyboard-interactive/pam for user from ::1 port 44 ssh2\n"; + assert_eq!( + parse_auth_attempts(log), + [ + (("publickey".into(), "Postponed".into()), 1), + (("publickey".into(), "Partial".into()), 1), + (("publickey".into(), "Accepted".into()), 1), + (("password".into(), "Failed".into()), 1), + (("keyboard-interactive/pam".into(), "Failed".into()), 1), + ] + .into() + ); + } + + #[test] + fn builder_knobs_work_in_unit_tests() { + let server = SshdBuilder { + extra_client_keys: vec![None], + identity_files: vec!["client_key_1".into()], + max_sessions: 2, + max_startups: "2:50:4".into(), + login_grace_time: Duration::from_secs(4), + client_alive_interval: Duration::from_secs(1), + client_alive_count_max: 2, + ..SshdBuilder::default() + } + .start() + .unwrap(); + assert!(server.run("true").unwrap().status.success()); + } +} diff --git a/tests/support/src/process.rs b/tests/support/src/process.rs new file mode 100644 index 000000000..adb799cd3 --- /dev/null +++ b/tests/support/src/process.rs @@ -0,0 +1,105 @@ +use anyhow::{bail, Context, Result}; +use std::fs::File; +use std::io::{Read, Seek, SeekFrom}; +use std::os::unix::fs::FileExt; +use std::os::unix::process::CommandExt; +use std::process::{Child, Command, Output, Stdio}; +use std::thread; +use std::time::{Duration, Instant}; + +/// A foreground child in its own process group, killed and reaped on unwind. +pub struct Process { + child: Child, + stdout: File, + stderr: File, + reaped: bool, +} + +impl Process { + pub fn spawn(command: &mut Command) -> Result { + let stdout = tempfile::tempfile()?; + let stderr = tempfile::tempfile()?; + let child = command + .process_group(0) + .stdin(Stdio::null()) + .stdout(stdout.try_clone()?) + .stderr(stderr.try_clone()?) + .spawn() + .with_context(|| format!("spawn {command:?}"))?; + + Ok(Self { + child, + stdout, + stderr, + reaped: false, + }) + } + + pub fn pid(&self) -> u32 { + self.child.id() + } + + pub fn stderr(&self) -> Result { + let mut bytes = vec![0; self.stderr.metadata()?.len() as usize]; + self.stderr.read_exact_at(&mut bytes, 0)?; + Ok(String::from_utf8_lossy(&bytes).into_owned()) + } + + pub fn wait(&mut self, timeout: Duration) -> Result { + let deadline = Instant::now() + timeout; + loop { + let mut info = unsafe { std::mem::zeroed::() }; + let result = unsafe { + libc::waitid( + libc::P_PID, + self.pid() as _, + &mut info, + libc::WEXITED | libc::WNOHANG | libc::WNOWAIT, + ) + }; + if result != 0 { + return Err(std::io::Error::last_os_error().into()); + } + if unsafe { info.si_pid() } != 0 { + self.kill_group(); + let status = self.child.wait()?; + self.reaped = true; + let mut stdout = Vec::new(); + let mut stderr = Vec::new(); + self.stdout.seek(SeekFrom::Start(0))?; + self.stderr.seek(SeekFrom::Start(0))?; + self.stdout.read_to_end(&mut stdout)?; + self.stderr.read_to_end(&mut stderr)?; + return Ok(Output { + status, + stdout, + stderr, + }); + } + if Instant::now() >= deadline { + bail!( + "process {} timed out after {timeout:?}: {}", + self.pid(), + self.stderr()? + ); + } + thread::sleep(Duration::from_millis(10)); + } + } + + fn kill_group(&self) { + // The unreaped child reserves this process-group ID; it cannot name an unrelated group. + unsafe { + libc::kill(-(self.pid() as i32), libc::SIGKILL); + } + } +} + +impl Drop for Process { + fn drop(&mut self) { + if !self.reaped { + self.kill_group(); + let _ = self.child.wait(); + } + } +} diff --git a/tests/support/src/proxy.rs b/tests/support/src/proxy.rs new file mode 100644 index 000000000..1605d9e26 --- /dev/null +++ b/tests/support/src/proxy.rs @@ -0,0 +1,374 @@ +use anyhow::Result; +use socket2::{Domain, Protocol, Socket, Type}; +use std::collections::VecDeque; +use std::io::{self, Read, Write}; +use std::net::{Ipv4Addr, Shutdown, SocketAddr, TcpListener, TcpStream}; +use std::num::NonZeroU64; +use std::os::fd::AsRawFd; +use std::os::unix::net::UnixStream; +use std::sync::mpsc::{self, Receiver, Sender}; +use std::thread::{self, JoinHandle}; +use std::time::{Duration, Instant}; + +const MAX_QUEUED_CHUNKS: usize = 16; + +/// Applied to both directions of every connection, including existing connections. +#[derive(Clone, Copy, Debug, Default)] +pub struct Faults { + /// Delay each received chunk once, without blocking other connections. + pub latency: Duration, + /// Per-direction, per-connection bytes/second; no initial burst allowance. + pub bytes_per_second: Option, + /// Read and discard traffic while leaving TCP connections open. + pub black_hole: bool, + /// Stop reading and writing without discarding buffered traffic. + pub paused: bool, + /// Close the listening socket; established connections remain alive. + pub refuse_new: bool, +} + +enum Control { + Set(Faults, Sender>), + Reset(Sender>), + Stop, +} + +/// One worker owns all sockets; control calls acknowledge after the change takes effect. +pub struct FaultProxy { + port: u16, + control: Sender, + wake: UnixStream, + worker: Option>, +} + +impl FaultProxy { + pub fn start(target: SocketAddr) -> Result { + let listener = listen(0)?; + let port = listener.local_addr()?.port(); + let (control, receiver) = mpsc::channel(); + let (wake, worker_wake) = UnixStream::pair()?; + wake.set_nonblocking(true)?; + worker_wake.set_nonblocking(true)?; + let worker = thread::Builder::new() + .name("sshd-fault-proxy".into()) + .spawn(move || { + serve(listener, target, receiver, worker_wake); + })?; + Ok(Self { + port, + control, + wake, + worker: Some(worker), + }) + } + + pub fn port(&self) -> u16 { + self.port + } + + pub fn set(&self, faults: Faults) -> Result<()> { + self.update(|ack| Control::Set(faults, ack)) + } + + pub fn clear(&self) -> Result<()> { + self.set(Faults::default()) + } + + /// Drops established connections while keeping the configured faults. + pub fn reset(&self) -> Result<()> { + self.update(Control::Reset) + } + + fn update(&self, message: impl FnOnce(Sender>) -> Control) -> Result<()> { + let (sender, receiver) = mpsc::channel(); + self.send(message(sender))?; + receiver.recv_timeout(Duration::from_secs(2))??; + Ok(()) + } + + fn send(&self, message: Control) -> Result<()> { + self.control.send(message)?; + match (&self.wake).write_all(&[1]) { + Ok(()) => Ok(()), + // A full wake socket already guarantees that poll will return. + Err(error) if error.kind() == io::ErrorKind::WouldBlock => Ok(()), + Err(error) => Err(error.into()), + } + } +} + +impl Drop for FaultProxy { + fn drop(&mut self) { + let _ = self.send(Control::Stop); + if let Some(worker) = self.worker.take() { + let _ = worker.join(); + } + } +} + +fn listen(port: u16) -> io::Result { + let socket = Socket::new(Domain::IPV4, Type::STREAM, Some(Protocol::TCP))?; + socket.set_reuse_address(true)?; + socket.set_nonblocking(true)?; + socket.bind(&SocketAddr::from((Ipv4Addr::LOCALHOST, port)).into())?; + socket.listen(128)?; + Ok(socket.into()) +} + +struct Chunk { + ready: Instant, + bytes: Vec, + written: usize, +} + +#[derive(Default)] +struct Direction { + queue: VecDeque, + eof: bool, +} + +impl Direction { + fn pump(&mut self, from: &mut TcpStream, to: &mut TcpStream, faults: Faults) -> io::Result<()> { + if faults.paused { + return Ok(()); + } + if faults.black_hole { + self.queue.clear(); + } + // Bound queued memory and preserve backpressure when the receiver stalls. + for _ in self.queue.len()..MAX_QUEUED_CHUNKS { + if self.eof { + break; + } + let mut bytes = [0; 4096]; + match from.read(&mut bytes) { + Ok(0) => self.eof = true, + Ok(n) if !faults.black_hole => { + let now = Instant::now(); + let previous = self.queue.back().map(|chunk| chunk.ready).unwrap_or(now); + let transfer = faults + .bytes_per_second + .map(|rate| Duration::from_secs_f64(n as f64 / rate.get() as f64)) + .unwrap_or_default(); + self.queue.push_back(Chunk { + ready: (now + faults.latency).max(previous) + transfer, + bytes: bytes[..n].to_vec(), + written: 0, + }); + } + Ok(_) => {} + Err(e) if e.kind() == io::ErrorKind::WouldBlock => break, + Err(e) => return Err(e), + } + } + while let Some(chunk) = self.queue.front_mut() { + if chunk.ready > Instant::now() { + break; + } + match to.write(&chunk.bytes[chunk.written..]) { + Ok(0) => return Err(io::ErrorKind::WriteZero.into()), + Ok(n) => { + chunk.written += n; + if chunk.written == chunk.bytes.len() { + self.queue.pop_front(); + } + } + Err(e) if e.kind() == io::ErrorKind::WouldBlock => break, + Err(e) => return Err(e), + } + } + if self.eof && self.queue.is_empty() { + to.shutdown(Shutdown::Write)?; + } + Ok(()) + } +} + +struct Connection { + client: TcpStream, + server: TcpStream, + upstream: Direction, + downstream: Direction, +} + +impl Connection { + fn reset(&self) { + for stream in [&self.client, &self.server] { + let _ = socket2::SockRef::from(stream).set_linger(Some(Duration::ZERO)); + } + } + + fn pump(&mut self, faults: Faults) -> io::Result { + self.upstream + .pump(&mut self.client, &mut self.server, faults)?; + self.downstream + .pump(&mut self.server, &mut self.client, faults)?; + Ok(!(self.upstream.eof + && self.downstream.eof + && self.upstream.queue.is_empty() + && self.downstream.queue.is_empty())) + } +} + +fn serve( + listener: TcpListener, + target: SocketAddr, + receiver: Receiver, + mut wake: UnixStream, +) { + let port = listener.local_addr().unwrap().port(); + let mut listener = Some(listener); + let mut faults = Faults::default(); + let mut connections: Vec = Vec::new(); + 'worker: loop { + let mut bytes = [0; 256]; + loop { + match wake.read(&mut bytes) { + Ok(0) => break 'worker, + Ok(_) => {} + Err(error) if error.kind() == io::ErrorKind::WouldBlock => break, + Err(error) if error.kind() == io::ErrorKind::Interrupted => continue, + Err(_) => break 'worker, + } + } + while let Ok(message) = receiver.try_recv() { + match message { + Control::Stop => break 'worker, + Control::Set(next, ack) => { + let result = if next.refuse_new { + listener = None; + Ok(()) + } else if listener.is_none() { + listen(port).map(|socket| listener = Some(socket)) + } else { + Ok(()) + }; + if result.is_ok() { + faults = next; + if faults.black_hole { + for connection in &mut connections { + connection.upstream.queue.clear(); + connection.downstream.queue.clear(); + } + } + } + let _ = ack.send(result); + } + Control::Reset(ack) => { + for connection in &connections { + connection.reset(); + } + connections.clear(); + let _ = ack.send(Ok(())); + } + } + } + if let Some(listener) = &listener { + // Bound accepts so a connection flood cannot starve control messages. + for _ in 0..32 { + match listener.accept() { + Ok((client, _)) => { + // The target is loopback; a short deadline bounds teardown even if sshd dies. + let connection = (|| -> Result { + let server = + TcpStream::connect_timeout(&target, Duration::from_millis(50))?; + client.set_nonblocking(true)?; + server.set_nonblocking(true)?; + client.set_nodelay(true)?; + server.set_nodelay(true)?; + Ok(Connection { + client, + server, + upstream: Direction::default(), + downstream: Direction::default(), + }) + })(); + if let Ok(connection) = connection { + connections.push(connection); + } + } + Err(e) if e.kind() == io::ErrorKind::WouldBlock => break, + Err(_) => break, + } + } + } + connections.retain_mut(|connection| connection.pump(faults).unwrap_or(false)); + if wait(&wake, listener.as_ref(), &connections, faults).is_err() { + break; + } + } + for connection in &connections { + connection.reset(); + } +} + +fn wait( + wake: &UnixStream, + listener: Option<&TcpListener>, + connections: &[Connection], + faults: Faults, +) -> io::Result<()> { + let mut sockets = vec![libc::pollfd { + fd: wake.as_raw_fd(), + events: libc::POLLIN, + revents: 0, + }]; + if let Some(listener) = listener { + sockets.push(libc::pollfd { + fd: listener.as_raw_fd(), + events: libc::POLLIN, + revents: 0, + }); + } + let now = Instant::now(); + let mut deadline = None; + if !faults.paused { + for connection in connections { + let client = connection.client.as_raw_fd(); + let server = connection.server.as_raw_fd(); + for (from, to, direction) in [ + (client, server, &connection.upstream), + (server, client, &connection.downstream), + ] { + if !direction.eof && direction.queue.len() < MAX_QUEUED_CHUNKS { + sockets.push(libc::pollfd { + fd: from, + events: libc::POLLIN, + revents: 0, + }); + } + if let Some(chunk) = direction.queue.front() { + if chunk.ready <= now { + sockets.push(libc::pollfd { + fd: to, + events: libc::POLLOUT, + revents: 0, + }); + } else { + deadline = + Some(deadline.map_or(chunk.ready, |previous: Instant| { + previous.min(chunk.ready) + })); + } + } + } + } + } + let timeout = deadline.map_or(-1, |deadline| { + deadline + .saturating_duration_since(Instant::now()) + .as_nanos() + .div_ceil(1_000_000) + .min(i32::MAX as u128) as i32 + }); + // Descriptors stay owned by this worker throughout the poll call. + let result = + unsafe { libc::poll(sockets.as_mut_ptr(), sockets.len() as libc::nfds_t, timeout) }; + if result < 0 { + let error = io::Error::last_os_error(); + if error.kind() != io::ErrorKind::Interrupted { + return Err(error); + } + } + Ok(()) +} diff --git a/tests/ui_fixture.rs b/tests/ui_fixture.rs new file mode 100644 index 000000000..61e16284e --- /dev/null +++ b/tests/ui_fixture.rs @@ -0,0 +1,576 @@ +// Separate test crate; commands inherit the terminal environment. +#![allow(clippy::disallowed_methods)] +#![cfg(unix)] + +use anyhow::{bail, ensure, Context, Result}; +use orx_test_support::{Faults, Process, Sshd, SshdBuilder}; +use serde_json::{json, Value}; +use std::fs::{self, OpenOptions}; +use std::io::Read; +use std::num::NonZeroU64; +use std::os::unix::fs::{OpenOptionsExt, PermissionsExt}; +use std::path::PathBuf; +use std::process::Command; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; + +static STOP: AtomicBool = AtomicBool::new(false); + +extern "C" fn stop(_: libc::c_int) { + STOP.store(true, Ordering::Relaxed); +} + +struct Fixture { + server: Option, + hosts: Vec<(&'static str, Sshd)>, + root: PathBuf, + client: reqwest::Client, + url: String, +} + +impl Fixture { + fn control(&mut self, line: &str) -> Result<()> { + let words: Vec<_> = line.split_whitespace().collect(); + match words.as_slice() { + ["quit"] => { + STOP.store(true, Ordering::Relaxed); + Ok(()) + } + ["blackhole", alias] => self.fault( + alias, + Faults { + black_hole: true, + ..Default::default() + }, + ), + ["restore", alias] => self.fault(alias, Faults::default()), + ["restart-sshd", alias] => self + .hosts + .iter_mut() + .find(|(name, _)| name == alias) + .ok_or_else(|| anyhow::anyhow!("unknown host")) + .and_then(|(_, host)| host.restart()), + _ => Err(anyhow::anyhow!("unknown control: {}", line.trim())), + } + } + + fn command(&self) -> Command { + let mut cmd = Command::new(env!("CARGO_BIN_EXE_orx")); + let root = self.root.as_path(); + cmd.env_remove("CLAUDE_CONFIG_DIR") + .env_remove("CODEX_HOME") + .env_remove("ORX_LOCAL_SESSION") + .env_remove("ORX_UP_AUTH_TOKEN") + .env_remove("ORX_UP_PORT") + .env_remove("SSH_AUTH_SOCK") + .env("HOME", root) + .env("XDG_CONFIG_HOME", root.join("config")) + .env("XDG_DATA_HOME", root.join("xdg-data")) + .env("XDG_CACHE_HOME", root.join("cache")) + .env("ORX_DATA_DIR", root.join("data")) + .env("ORX_SSH_CONFIG", root.join(".ssh/config")) + .env( + "ORX_HOST_BIN_DIR", + std::env::var_os("ORX_FIXTURE_HOST_BIN_DIR").unwrap(), + ) + .env("ORX_NO_UPDATE_CHECK", "1") + .env("GIT_CONFIG_NOSYSTEM", "1") + .env("GIT_AUTHOR_NAME", "UI fixture") + .env("GIT_AUTHOR_EMAIL", "fixture@example.invalid") + .env("GIT_COMMITTER_NAME", "UI fixture") + .env("GIT_COMMITTER_EMAIL", "fixture@example.invalid") + .arg("--no-telemetry"); + cmd + } + + async fn request(&self, path: &str, body: Option) -> Result { + let url = format!("{}{path}", self.url); + let request = match body { + Some(body) => self.client.post(url).json(&body), + None => self.client.get(url), + }; + let response = request.send().await?; + let status = response.status(); + let value: Value = response.json().await?; + ensure!(status.is_success(), "{path}: {status} {value}"); + Ok(value) + } + + async fn wait(&self, path: &str, predicate: impl Fn(&Value) -> bool) -> Result { + let deadline = Instant::now() + Duration::from_secs(180); + let mut last = Value::Null; + while Instant::now() < deadline && !STOP.load(Ordering::Relaxed) { + if let Ok(value) = self.request(path, None).await { + if predicate(&value) { + return Ok(value); + } + last = value; + } + tokio::time::sleep(Duration::from_millis(100)).await; + } + bail!( + "timed out waiting for {path}: {last}; server: {}", + self.server.as_ref().unwrap().stderr()? + ); + } + + async fn run(&self, project: &str, title: &str, command: &str, host: &str) -> Result { + let output = Process::spawn(self.command().args([ + "create-experiment", + project, + "--title", + title, + "--baseline", + "--run-command", + command, + ]))? + .wait(Duration::from_secs(30))?; + ensure!( + output.status.success(), + "create experiment: {}", + String::from_utf8_lossy(&output.stderr) + ); + let experiments = self + .request(&format!("/api/projects/{project}/experiments"), None) + .await?; + let experiment = experiments["experiments"] + .as_array() + .context("experiments array")? + .iter() + .find(|e| e["title"] == title) + .context("created experiment")?; + let run = self.request("/api/runs", Some(json!({"experimentId":experiment["id"],"backend":"ssh","host":host,"force":true}))).await?; + let id = run["run"]["id"] + .as_str() + .or_else(|| run["id"].as_str()) + .context(format!("run id: {run}"))? + .to_owned(); + println!("{title}: run={id}, experiment={}", experiment["id"]); + Ok(id) + } + + fn fault(&self, alias: &str, faults: Faults) -> Result<()> { + let host = &self + .hosts + .iter() + .find(|(name, _)| *name == alias) + .context("unknown host")? + .1; + host.proxy().set(faults)?; + host.proxy().reset() + } +} + +impl Drop for Fixture { + fn drop(&mut self) { + self.server.take(); + for (_, host) in &self.hosts { + let runs = host.home().join(".orx/engine/runs"); + if let Ok(entries) = fs::read_dir(runs) { + for entry in entries.flatten() { + if let Ok(bytes) = fs::read(entry.path().join("wrapper.json")) { + if let Ok(identity) = + serde_json::from_slice::(&bytes) + { + if orx_host::platform::identity(identity.pid).ok().as_ref() + == Some(&identity) + { + unsafe { + libc::kill(-(identity.pid as i32), libc::SIGKILL); + } + } + } + } + } + } + } + let paths: Vec = std::iter::once(self.root.as_path().to_path_buf()) + .chain( + self.hosts + .iter() + .map(|(_, host)| host.directory().to_path_buf()), + ) + .collect(); + self.hosts.clear(); + for path in &paths { + if let Ok(output) = Command::new("pgrep") + .args(["-f", &path.to_string_lossy()]) + .output() + { + for pid in String::from_utf8_lossy(&output.stdout).split_whitespace() { + if let Ok(pid) = pid.parse::() { + if pid != std::process::id() as i32 { + unsafe { + libc::kill(pid, libc::SIGKILL); + } + } + } + } + } + } + std::thread::sleep(Duration::from_millis(200)); + for path in &paths { + if let Ok(output) = Command::new("pgrep") + .args(["-af", &path.to_string_lossy()]) + .output() + { + eprintln!( + "cleanup pgrep {}: {}", + path.display(), + String::from_utf8_lossy(&output.stdout).trim() + ); + if !std::thread::panicking() { + assert!(!output.status.success(), "fixture process survived cleanup"); + } + } + } + let _ = fs::remove_dir_all(&self.root); + eprintln!("fixture stopped; isolated homes and large logs removed"); + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[ignore = "live browser fixture; run tests/fixtures/engine-ui.sh and interrupt to stop"] +async fn live_engine_dashboard() -> Result<()> { + ensure!( + std::env::var_os("ORX_FIXTURE_HOST_BIN_DIR").is_some(), + "start with sh tests/fixtures/engine-ui.sh" + ); + unsafe { + libc::signal(libc::SIGINT, stop as *const () as libc::sighandler_t); + libc::signal(libc::SIGTERM, stop as *const () as libc::sighandler_t); + } + let reservation = std::net::TcpListener::bind("127.0.0.1:4930") + .context("fixture requires unused localhost port 4930")?; + let root = PathBuf::from(format!("/tmp/orx-ui-fixture-{}", uuid::Uuid::new_v4())); + fs::create_dir(&root)?; + #[allow(clippy::disallowed_methods)] + // Integration tests cannot access the binary's loopback client. + let client = reqwest::Client::builder() + .no_proxy() + .timeout(Duration::from_secs(20)) + .build()?; + let mut f = Fixture { + server: None, + hosts: vec![ + ("gpu-box", Sshd::start()?), + ("lab-login", Sshd::start()?), + ("expired-key", Sshd::start()?), + ( + "mfa-box", + SshdBuilder { + extra_client_keys: vec![Some("fixture-passphrase".into())], + identity_files: vec!["client_key_1".into()], + ..Default::default() + } + .start()?, + ), + ], + root, + client, + url: "http://localhost:4930".into(), + }; + fs::create_dir(f.root.as_path().join(".ssh"))?; + fs::write(f.hosts[1].1.directory().join("authorized_keys"), "")?; + let mut config = String::new(); + for (alias, host) in &f.hosts { + config.push_str( + &fs::read_to_string(host.config_path())? + .replace("Host orx-test\n", &format!("Host {alias}\n")), + ); + } + fs::write(f.root.as_path().join(".ssh/config"), config)?; + println!( + "fixture pid={} home={}", + std::process::id(), + f.root.as_path().display() + ); + for (alias, host) in &f.hosts { + println!( + "{alias}: sshd pid={} home={}", + host.pid(), + host.home().display() + ); + } + drop(reservation); + f.server = Some(Process::spawn(f.command().args([ + "up", + "--no-browser", + "--port", + "4930", + ]))?); + f.wait("/api/health", |_| true).await?; + let repo = f.root.as_path().join("project"); + fs::create_dir(&repo)?; + fs::write(repo.join("README.md"), "# Live engine dashboard fixture\n")?; + let project = f.request("/api/projects", Some(json!({"name":"Engine live fixture","path":repo,"initializeGit":true,"githubSyncEnabled":false}))).await?; + let project = project["project"]["id"] + .as_str() + .context("project id")? + .to_owned(); + let steady = f + .run( + &project, + "Steady output", + "while :; do date; echo 'gpu-box training step'; sleep 1; done", + "gpu-box", + ) + .await?; + f.wait(&format!("/api/runs/{steady}"), |r| { + r["run"]["status"] == "running" || r["status"] == "running" + }) + .await?; + let done = f + .run( + &project, + "Finished successfully", + "echo 'training complete'", + "gpu-box", + ) + .await?; + let failed = f + .run( + &project, + "Finished with failure", + "echo 'training failed' >&2; exit 7", + "gpu-box", + ) + .await?; + let auth = f + .run( + &project, + "Key rejected: NeedsAuth", + "echo 'resumes after host authentication is fixed'", + "lab-login", + ) + .await?; + let mfa = f + .run( + &project, + "Interactive Connect", + "while :; do echo 'mfa connected'; sleep 2; done", + "mfa-box", + ) + .await?; + let expired = f + .run( + &project, + "Established run: NeedsAuth", + "while :; do echo 'key expired'; sleep 2; done", + "expired-key", + ) + .await?; + f.wait(&format!("/api/runs/{expired}"), |r| { + r["run"]["status"] == "running" + }) + .await?; + fs::write(f.hosts[2].1.directory().join("authorized_keys"), "")?; + f.hosts[2].1.proxy().reset()?; + let cancelled = f + .run( + &project, + "Cancel pending during outage", + "while :; do echo 'waiting for cancel'; sleep 1; done", + "gpu-box", + ) + .await?; + f.wait(&format!("/api/projects/{project}/runs"), |v| { + v["runs"].as_array().is_some_and(|r| { + r.iter() + .any(|r| r["id"] == cancelled && r["status"] == "running") + && r.iter() + .any(|r| r["id"] == auth && r["contact"]["type"] == "needs_auth") + && r.iter() + .any(|r| r["id"] == mfa && r["contact"]["type"] == "needs_auth") + && r.iter() + .any(|r| r["id"] == expired && r["contact"]["type"] == "needs_auth") + && r.iter().any(|r| r["id"] == done && r["status"] == "done") + && r.iter() + .any(|r| r["id"] == failed && r["status"] == "failed") + }) + }) + .await?; + let large = f + .run( + &project, + "Large log with host-only middle", + "yes '0123456789 fixture training output' | head -c 1074790400 || [ \"$?\" = 141 ]", + "gpu-box", + ) + .await?; + f.wait(&format!("/api/runs/{large}/log?start=0&end=16"), |p| { + p["len"].as_u64().is_some_and(|n| n > 1 << 30) + && p["kept"].as_array().is_some_and(|r| r.len() == 2) + }) + .await?; + let page = f + .request( + &format!("/api/runs/{large}/log?start=536870912&end=536870928"), + None, + ) + .await?; + ensure!( + page["kind"] == "data" && page["start"] == 536870912u64, + "host middle page: {page}" + ); + f.hosts[0].1.proxy().set(Faults { + bytes_per_second: NonZeroU64::new(128 * 1024), + ..Default::default() + })?; + let pending = f + .run( + &project, + "Final log collection pending", + "yes 'final collection output' | head -c 8388608 || [ \"$?\" = 141 ]", + "gpu-box", + ) + .await?; + f.wait(&format!("/api/projects/{project}/runs"), |v| { + v["runs"].as_array().is_some_and(|rs| { + rs.iter().any(|r| { + r["id"] == pending && r["status"] == "done" && r["logCollection"] == "pending" + }) + }) + }) + .await?; + f.fault( + "gpu-box", + Faults { + black_hole: true, + ..Default::default() + }, + )?; + f.request(&format!("/api/runs/{cancelled}/cancel"), Some(json!({}))) + .await?; + let runs = f + .wait(&format!("/api/projects/{project}/runs"), |v| { + v["runs"].as_array().is_some_and(|rs| { + rs.iter().any(|r| { + r["id"] == cancelled + && r["cancelling"] == true + && r["contact"]["type"] == "unreachable" + }) + }) + }) + .await?; + let hosts = f + .wait("/api/compute/hosts", |v| { + v.as_array().is_some_and(|hs| { + hs.iter() + .any(|h| h["alias"] == "gpu-box" && h["status"] == "backoff") + && hs + .iter() + .any(|h| h["alias"] == "lab-login" && h["status"] == "needs_auth") + }) + }) + .await?; + let unavailable = f + .client + .get(format!( + "{}/api/runs/{large}/log?start=629145600&end=629145616", + f.url + )) + .send() + .await?; + ensure!( + unavailable.status() == 503, + "middle page outage: {}", + unavailable.status() + ); + ensure!(unavailable.json::().await?["contact"] == "unreachable"); + let fifo = f.root.as_path().join("controls"); + let cpath = std::ffi::CString::new(fifo.as_os_str().as_encoded_bytes())?; + ensure!( + unsafe { libc::mkfifo(cpath.as_ptr(), 0o600) } == 0, + "create control FIFO" + ); + let mut control = OpenOptions::new() + .read(true) + .write(true) + .custom_flags(libc::O_NONBLOCK) + .open(&fifo)?; + let disk = Command::new("du") + .arg("-sk") + .arg(f.root.as_path()) + .args(f.hosts.iter().map(|(_, h)| h.directory())) + .output()?; + let report = json!({"url":f.url,"project":project,"runs":{"steady":steady,"done":done,"failed":failed,"large":large,"needsAuth":expired,"firstContactNeedsAuth":auth,"connect":mfa,"cancelPending":cancelled,"collectionPending":pending},"hosts":hosts,"snapshot":runs,"fifo":fifo,"diskKiB":String::from_utf8_lossy(&disk.stdout)}); + fs::write( + f.root.as_path().join("ready.json"), + serde_json::to_vec_pretty(&report)?, + )?; + println!("READY {} project={project}\ncontrols: echo 'restore gpu-box' > {}\nblackhole gpu-box | restore gpu-box | restart-sshd gpu-box | quit\nmfa-box Connect passphrase: fixture-passphrase\nreport: {}\ndisk KiB:\n{}",f.url,fifo.display(),f.root.as_path().join("ready.json").display(),String::from_utf8_lossy(&disk.stdout)); + let mut buffer = String::new(); + while !STOP.load(Ordering::Relaxed) { + match control.read_to_string(&mut buffer) { + Ok(_) => {} + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {} + Err(e) => return Err(e.into()), + } + while let Some(end) = buffer.find('\n') { + let line = buffer.drain(..=end).collect::(); + let result = f.control(&line); + println!("control {}: {result:?}", line.trim()); + } + tokio::time::sleep(Duration::from_millis(100)).await; + } + Ok(()) +} + +#[allow(clippy::disallowed_methods)] +fn empty_fixture() -> Fixture { + let root = PathBuf::from(format!( + "/tmp/orx-ui-fixture-check-{}", + uuid::Uuid::new_v4() + )); + fs::create_dir(&root).unwrap(); + Fixture { + server: None, + hosts: Vec::new(), + root, + client: reqwest::Client::builder().no_proxy().build().unwrap(), + url: "http://localhost:4930".into(), + } +} + +#[test] +fn unknown_fixture_control_keeps_the_fixture_alive() { + let mut fixture = empty_fixture(); + assert_eq!( + fixture + .control("restart-sshd gpu-bxo") + .unwrap_err() + .to_string(), + "unknown host" + ); + assert!(fixture.root.exists()); + assert!(!STOP.load(Ordering::Relaxed)); +} + +#[test] +fn fixture_cleanup_does_not_abort_during_unwind() { + if std::env::var_os("ORX_FIXTURE_UNWIND_PROBE").is_some() { + let _fixture = empty_fixture(); + panic!("fixture unwind probe"); + } + let fixture = empty_fixture(); + let bin = fixture.root.join("bin"); + fs::create_dir(&bin).unwrap(); + fs::write(bin.join("pgrep"), "#!/bin/sh\nexit 0\n").unwrap(); + fs::set_permissions(bin.join("pgrep"), fs::Permissions::from_mode(0o700)).unwrap(); + let output = Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "fixture_cleanup_does_not_abort_during_unwind", + "--nocapture", + ]) + .env("ORX_FIXTURE_UNWIND_PROBE", "1") + .env( + "PATH", + format!("{}:{}", bin.display(), std::env::var("PATH").unwrap()), + ) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(101), "{output:?}"); + assert!(String::from_utf8_lossy(&output.stderr).contains("fixture stopped")); +} diff --git a/ui/messages/ar.json b/ui/messages/ar.json index 8fdb3ee96..5bb7fb532 100644 --- a/ui/messages/ar.json +++ b/ui/messages/ar.json @@ -1648,5 +1648,87 @@ "remote_agents_description": "يجب تثبيت الوكلاء وتسجيل الدخول إليهم على كل جهاز. أعِدّهم على {host}.", "remote_claude_datacenter_title": "تجنّب اشتراكات Claude على عناوين IP لمراكز البيانات", "remote_claude_datacenter_description": "يستخدم {host} عنوان IP لمركز بيانات: {ip}. قد يؤدي استخدام اشتراك Claude هنا إلى وضع علامة على حسابك لدى Anthropic. استخدم مفتاح API أو تابع على مسؤوليتك.", - "remote_claude_datacenter_continue": "المتابعة على أي حال" + "remote_claude_datacenter_continue": "المتابعة على أي حال", + "chat_panel_remove_file": "إزالة الملف", + "chat_panel_remove_image": "إزالة الصورة", + "account_local_to_app": "الحساب محلي لهذا التطبيق", + "chat_panel_requested_an_experiment_stop": "طلب إيقاف تشغيل تجربة", + "delete_pending_stop_warning": "يؤدي الحذف أيضًا إلى إلغاء طلبات الإيقاف المعلقة؛ قد تستمر المهام البعيدة في العمل.", + "status_submitting": "جارٍ الإرسال", + "status_unreachable": "تعذّر الوصول", + "status_needs_auth": "المصادقة مطلوبة", + "status_unconfirmed": "غير مؤكد", + "status_abandoned": "متروك", + "status_last_seen": "آخر ظهور في {time}", + "run_notice_rental_key_cancelled": "أُوقف تلقائيًا: رفض الجهاز مفتاح SSH لمدة 15 دقيقة.", + "run_notice_rental_outcome_unavailable": "النتيجة غير متاحة: أُطلق الجهاز المستأجر قبل جمع نتيجته النهائية.", + "run_notice_rental_billing": "لا تزال تكلفة الجهاز المستأجر تُحتسب. ألغِ التشغيل لإيقاف الجهاز.", + "run_stop_box": "إيقاف الجهاز", + "run_notice_unreachable": "تعذّر الوصول إلى {host} منذ {time}.", + "run_notice_retry_at": "ستُعاد المحاولة في {time}.", + "run_notice_provider_auth": "رفض المزوّد الوصول. تحقّق من بيانات اعتماده في الإعدادات ← البيئة.", + "run_notice_cluster_auth": "رفض Kubernetes الوصول. تحقّق من kubeconfig وصلاحيات المجموعة.", + "run_notice_needs_auth": "اتصل بـ {host} لمواصلة متابعة هذا التشغيل.", + "run_notice_unconfirmed_launch": "تعذّر تأكيد الإطلاق. جارٍ التحقق مجددًا.", + "run_notice_cancel_pending": "يتعذر الوصول إلى {host} منذ {time}.", + "run_notice_cancel_pending_auth": "اتصل بـ {host} لإرسال طلب الإلغاء.", + "run_notice_cancel_pending_later": "سيُرسَل طلب الإلغاء عندما يصبح الجهاز متاحًا مجددًا.", + "run_notice_cancel_pending_launch": "سيُرسَل طلب الإلغاء بعد تأكيد بدء التشغيل.", + "run_notice_stops_if_found": "إذا ظهرت المهمة، فسيوقفها orx.", + "run_notice_unreconciled": "يحتاج إلى انتباه.", + "run_notice_abandoned": "متروك. إذا ظهرت المهمة على {host}، فسيوقفها orx.", + "run_notice_abandoned_no_host": "متروك. إذا ظهرت المهمة، فسيوقفها orx.", + "run_notice_the_host": "المضيف", + "run_stop_again": "إيقاف مرة أخرى", + "run_abandon": "ترك…", + "run_abandon_title": "ترك هذا التشغيل؟", + "run_abandon_body": "سيتوقف OpenResearch عن تتبّع هذا التشغيل. تأكد جيدًا من إيقاف موارد الحوسبة الفعلية.", + "run_abandon_body_no_host": "يتوقف orx عن انتظاره ويضع عليه علامة متروك. إذا ظهرت المهمة لاحقًا، فسيوقفها orx حينها.", + "run_abandon_confirm": "ترك التشغيل", + "run_abandoning": "جارٍ الترك…", + "settings_host_connected": "متصل", + "settings_host_since": "منذ {time}", + "settings_host_since_next_try": "منذ {time} · المحاولة التالية {next}", + "settings_host_test": "اختبار", + "settings_ssh_host_needs_connect": "يلزم اتصالك بـ {host}", + "settings_ssh_hosts_need_connect": "مضيفون يلزم الاتصال بهم: {count}", + "log_go_start": "الانتقال إلى البداية", + "log_go_end": "الانتقال إلى النهاية", + "log_earlier": "المخرجات السابقة", + "log_later": "المخرجات اللاحقة", + "log_go_to": "الانتقال إلى موضع", + "log_go_to_placeholder": "2.5 GB أو 60%", + "log_position": "{start} من {total}", + "log_position_end": "نهاية {total}", + "log_follow": "متابعة", + "log_following": "جارٍ المتابعة", + "log_paused": "المخرجات المباشرة متوقفة مؤقتًا", + "log_range": "الموضع في السجل", + "log_loading_from": "جارٍ التحميل من {host}…", + "log_unavailable": "هذا الجزء من السجل على {host}، الذي تعذّر الوصول إليه منذ {time}.", + "log_unavailable_auth": "هذا الجزء من السجل على {host}. اتصل به لتحميل هذا الجزء.", + "run_notice_log_pending": "جارٍ حفظ السجل من {host}…", + "run_notice_log_failed": "تعذّر حفظ السجل من {host}. يواصل orx المحاولة؛ ولا يزال السجل يُفتح من المضيف.", + "run_notice_post_failed": "تعذّر نشر نتيجة هذا التشغيل في المحادثة: {error}", + "log_generation_unstable": "The log keeps changing. Reload to try again.", + "status_not_fully_stopped": "لم يتوقف بالكامل", + "run_stop_now": "إيقاف الآن", + "hover_not_fully_stopped_count": "{count} لم تتوقف بالكامل", + "run_notice_cancel_unreadable": "تعذّر على المضيف فحص العمليات {pids} للتأكد من توقفها.", + "run_notice_cancel_uncovered": "تعذّر فحص العمليات داخل الحاوية أو خارج نطاق فحص المضيف.", + "status_cancelled_unconfirmed": "أُلغي · تعذّر التأكد", + "status_stopping_zero": "لم يتوقف بالكامل · {count} من العمليات لا تزال تعمل على {host}", + "status_stopping_one": "لم يتوقف بالكامل · عملية واحدة ({count}) لا تزال تعمل على {host}", + "status_stopping_two": "لم يتوقف بالكامل · عمليتان ({count}) لا تزالان تعملان على {host}", + "status_stopping_few": "لم يتوقف بالكامل · {count} عمليات لا تزال تعمل على {host}", + "status_stopping_many": "لم يتوقف بالكامل · {count} عملية لا تزال تعمل على {host}", + "status_stopping_other": "لم يتوقف بالكامل · {count} عملية لا تزال تعمل على {host}", + "status_cancellation_pending": "الإلغاء قيد الانتظار", + "run_abandon_unreachable": "يتعذر الوصول إلى الجهاز.", + "run_abandon_keep": "مواصلة التتبع", + "settings_run_engine_label": "محرك التجارب الجديد", + "settings_run_engine_description": "يحافظ المحرك الجديد على التشغيلات البعيدة عند انقطاع الاتصال وإعادة تشغيل التطبيق، ويتحقق من الإلغاء، ويصلح العديد من مشكلات استقرار SSH.", + "settings_run_engine_override": "يتحكم ORX_RUN_ENGINE في هذا الإعداد للخادم.", + "settings_run_engine_canary": "تستخدم إصدارات Canary المحرك الجديد دائمًا.", + "settings_run_engine_note": "لا يزال قيد الاختبار. ينطبق على التشغيلات الجديدة." } diff --git a/ui/messages/en.json b/ui/messages/en.json index 999493ddc..47a112b9f 100644 --- a/ui/messages/en.json +++ b/ui/messages/en.json @@ -582,7 +582,7 @@ "status_failed": "Failed", "status_running": "Running", "status_starting": "Starting", - "status_cancelling": "Cancelling", + "status_cancelling": "Cancelling…", "status_lost": "Outcome unavailable", "status_cancelled": "Cancelled", "status_editing": "Editing", @@ -1648,5 +1648,87 @@ "remote_agents_description": "Agents must be installed and signed in on each machine. Set them up on {host}.", "remote_claude_datacenter_title": "Avoid Claude subscriptions on datacenter IPs", "remote_claude_datacenter_description": "{host} uses datacenter IP {ip}. Using a Claude subscription here may cause Anthropic to flag your account. Use an API key instead, or continue at your own risk.", - "remote_claude_datacenter_continue": "Continue anyway" + "remote_claude_datacenter_continue": "Continue anyway", + "chat_panel_remove_file": "Remove file", + "chat_panel_remove_image": "Remove image", + "account_local_to_app": "Account is local to this app", + "chat_panel_requested_an_experiment_stop": "Requested an experiment stop", + "delete_pending_stop_warning": "Deleting also cancels pending stop requests; remote jobs may keep running.", + "status_submitting": "Submitting", + "status_unreachable": "Unreachable", + "status_needs_auth": "Authentication needed", + "status_unconfirmed": "Unconfirmed", + "status_abandoned": "Abandoned", + "status_last_seen": "Last seen at {time}", + "run_notice_rental_key_cancelled": "Stopped automatically: the box rejected its SSH key for 15 minutes.", + "run_notice_rental_outcome_unavailable": "Outcome unavailable: the rental was released before its final outcome was collected.", + "run_notice_rental_billing": "The rented box is still billing. Cancel the run to stop the box.", + "run_stop_box": "Stop box", + "run_notice_unreachable": "Can't reach {host} since {time}.", + "run_notice_retry_at": "Trying again at {time}.", + "run_notice_provider_auth": "The provider rejected access. Check its credentials in Settings → Environment.", + "run_notice_cluster_auth": "Kubernetes rejected access. Check your kubeconfig and cluster permissions.", + "run_notice_needs_auth": "Connect to {host} to keep following this run.", + "run_notice_unconfirmed_launch": "Couldn't confirm the launch. Checking again.", + "run_notice_cancel_pending": "{host} has been unreachable since {time}.", + "run_notice_cancel_pending_auth": "Connect to {host} to send the cancel.", + "run_notice_cancel_pending_later": "The cancel will be sent when the machine is reachable again.", + "run_notice_cancel_pending_launch": "The cancel will be sent once the launch is confirmed.", + "run_notice_stops_if_found": "If the job turns up, orx stops it.", + "run_notice_unreconciled": "Needs attention.", + "run_notice_abandoned": "Abandoned. If the job turns up on {host}, orx stops it.", + "run_notice_abandoned_no_host": "Abandoned. If the job turns up, orx stops it.", + "run_notice_the_host": "the host", + "run_stop_again": "Stop again", + "run_abandon": "Abandon…", + "run_abandon_title": "Abandon this run?", + "run_abandon_body": "OpenResearch will stop tracking this run. Double-check that the actual compute is shut down.", + "run_abandon_body_no_host": "orx stops waiting for it and marks it Abandoned. If the job turns up later, orx stops it then.", + "run_abandon_confirm": "Abandon run", + "run_abandoning": "Abandoning…", + "settings_host_connected": "Connected", + "settings_host_since": "since {time}", + "settings_host_since_next_try": "since {time} · next try {next}", + "settings_host_test": "Test", + "settings_ssh_host_needs_connect": "{host} needs you to connect", + "settings_ssh_hosts_need_connect": "{count} hosts need you to connect", + "log_go_start": "Go to start", + "log_go_end": "Go to end", + "log_earlier": "Earlier output", + "log_later": "Later output", + "log_go_to": "Go to position", + "log_go_to_placeholder": "2.5 GB or 60%", + "log_position": "{start} of {total}", + "log_position_end": "End of {total}", + "log_follow": "Follow", + "log_following": "Following", + "log_paused": "Live output paused", + "log_range": "Log position", + "log_loading_from": "Loading from {host}…", + "log_unavailable": "This part of the log is on {host}, which is unreachable since {time}.", + "log_unavailable_auth": "This part of the log is on {host}. Connect to it to load this part.", + "run_notice_log_pending": "Saving the log from {host}…", + "run_notice_log_failed": "Couldn't save the log from {host}. orx keeps trying; the log still opens from the host.", + "run_notice_post_failed": "Couldn't post this run's result to the chat: {error}", + "log_generation_unstable": "The log keeps changing. Reload to try again.", + "status_not_fully_stopped": "Not fully stopped", + "run_stop_now": "Stop now", + "hover_not_fully_stopped_count": "{count} not fully stopped", + "run_notice_cancel_unreadable": "The host couldn't inspect processes {pids} to confirm the stop.", + "run_notice_cancel_uncovered": "In-container processes or processes outside the host scan couldn't be checked.", + "status_cancelled_unconfirmed": "Cancelled · couldn't confirm", + "status_stopping_zero": "Not fully stopped · {count} processes still running on {host}", + "status_stopping_one": "Not fully stopped · {count} process still running on {host}", + "status_stopping_two": "Not fully stopped · {count} processes still running on {host}", + "status_stopping_few": "Not fully stopped · {count} processes still running on {host}", + "status_stopping_many": "Not fully stopped · {count} processes still running on {host}", + "status_stopping_other": "Not fully stopped · {count} processes still running on {host}", + "status_cancellation_pending": "Cancellation pending", + "run_abandon_unreachable": "The machine is unreachable.", + "run_abandon_keep": "Keep tracking", + "settings_run_engine_label": "New experiment engine", + "settings_run_engine_description": "The new engine keeps remote runs going through disconnects and app restarts, verifies cancellation, and fixes many SSH stability issues.", + "settings_run_engine_override": "ORX_RUN_ENGINE controls this setting for the server.", + "settings_run_engine_canary": "Canary builds always use the new engine.", + "settings_run_engine_note": "Still in testing. Applies to new runs." } diff --git a/ui/messages/es.json b/ui/messages/es.json index 915777c41..4094d2d0e 100644 --- a/ui/messages/es.json +++ b/ui/messages/es.json @@ -1648,5 +1648,87 @@ "remote_agents_description": "Los agentes deben instalarse e iniciar sesión en cada máquina. Configúralos en {host}.", "remote_claude_datacenter_title": "Evita las suscripciones de Claude en IP de centros de datos", "remote_claude_datacenter_description": "{host} usa la IP de centro de datos {ip}. Usar aquí una suscripción de Claude puede hacer que Anthropic marque tu cuenta. Usa una clave API o continúa bajo tu responsabilidad.", - "remote_claude_datacenter_continue": "Continuar de todos modos" + "remote_claude_datacenter_continue": "Continuar de todos modos", + "chat_panel_remove_file": "Quitar archivo", + "chat_panel_remove_image": "Quitar imagen", + "account_local_to_app": "La cuenta es local a esta aplicación", + "chat_panel_requested_an_experiment_stop": "Solicitó detener un experimento", + "delete_pending_stop_warning": "Al eliminar también se cancelan las solicitudes de parada pendientes; los trabajos remotos pueden seguir ejecutándose.", + "status_submitting": "Enviando", + "status_unreachable": "Inaccesible", + "status_needs_auth": "Autenticación necesaria", + "status_unconfirmed": "Sin confirmar", + "status_abandoned": "Abandonada", + "status_last_seen": "Visto por última vez a las {time}", + "run_notice_rental_key_cancelled": "Detenido automáticamente: la máquina rechazó su clave SSH durante 15 minutos.", + "run_notice_rental_outcome_unavailable": "Resultado no disponible: se liberó la máquina alquilada antes de recopilar su resultado final.", + "run_notice_rental_billing": "La máquina alquilada sigue generando cargos. Cancela la ejecución para detenerla.", + "run_stop_box": "Detener máquina", + "run_notice_unreachable": "No se puede acceder a {host} desde las {time}.", + "run_notice_retry_at": "Se volverá a intentar a las {time}.", + "run_notice_provider_auth": "El proveedor rechazó el acceso. Revisa sus credenciales en Ajustes → Entorno.", + "run_notice_cluster_auth": "Kubernetes rechazó el acceso. Revisa tu kubeconfig y los permisos del clúster.", + "run_notice_needs_auth": "Conéctate a {host} para seguir esta ejecución.", + "run_notice_unconfirmed_launch": "No se pudo confirmar el lanzamiento. Se volverá a comprobar.", + "run_notice_cancel_pending": "No se puede acceder a {host} desde {time}.", + "run_notice_cancel_pending_auth": "Conéctate a {host} para enviar la cancelación.", + "run_notice_cancel_pending_later": "La cancelación se enviará cuando la máquina vuelva a estar accesible.", + "run_notice_cancel_pending_launch": "La cancelación se enviará cuando se confirme el inicio.", + "run_notice_stops_if_found": "Si el trabajo aparece, orx lo detiene.", + "run_notice_unreconciled": "Requiere atención.", + "run_notice_abandoned": "Abandonada. Si el trabajo aparece en {host}, orx lo detiene.", + "run_notice_abandoned_no_host": "Abandonada. Si el trabajo aparece, orx lo detiene.", + "run_notice_the_host": "el host", + "run_stop_again": "Detener de nuevo", + "run_abandon": "Abandonar…", + "run_abandon_title": "¿Abandonar esta ejecución?", + "run_abandon_body": "OpenResearch dejará de seguir esta ejecución. Comprueba que los recursos de cómputo estén realmente apagados.", + "run_abandon_body_no_host": "orx deja de esperarla y la marca como abandonada. Si el trabajo aparece más tarde, orx lo detiene entonces.", + "run_abandon_confirm": "Abandonar ejecución", + "run_abandoning": "Abandonando…", + "settings_host_connected": "Conectado", + "settings_host_since": "desde las {time}", + "settings_host_since_next_try": "desde las {time} · próximo intento {next}", + "settings_host_test": "Probar", + "settings_ssh_host_needs_connect": "{host} necesita que te conectes", + "settings_ssh_hosts_need_connect": "{count} hosts necesitan que te conectes", + "log_go_start": "Ir al inicio", + "log_go_end": "Ir al final", + "log_earlier": "Salida anterior", + "log_later": "Salida posterior", + "log_go_to": "Ir a una posición", + "log_go_to_placeholder": "2,5 GB o 60%", + "log_position": "{start} de {total}", + "log_position_end": "Final de {total}", + "log_follow": "Seguir", + "log_following": "Siguiendo", + "log_paused": "Salida en directo en pausa", + "log_range": "Posición en el registro", + "log_loading_from": "Cargando desde {host}…", + "log_unavailable": "Esta parte del registro está en {host}, inaccesible desde las {time}.", + "log_unavailable_auth": "Esta parte del registro está en {host}. Conéctate para cargarla.", + "run_notice_log_pending": "Guardando el registro de {host}…", + "run_notice_log_failed": "No se pudo guardar el registro de {host}. orx lo sigue intentando; el registro aún se abre desde el host.", + "run_notice_post_failed": "No se pudo publicar el resultado de esta ejecución en el chat: {error}", + "log_generation_unstable": "The log keeps changing. Reload to try again.", + "status_not_fully_stopped": "No se ha detenido por completo", + "run_stop_now": "Detener ahora", + "hover_not_fully_stopped_count": "{count} sin detener por completo", + "run_notice_cancel_unreadable": "El host no pudo inspeccionar los procesos {pids} para confirmar que se detuvieron.", + "run_notice_cancel_uncovered": "No se pudieron comprobar los procesos dentro del contenedor o fuera del alcance del análisis del host.", + "status_cancelled_unconfirmed": "Cancelado · no se pudo confirmar", + "status_stopping_zero": "No se ha detenido por completo · {count} procesos siguen en ejecución en {host}", + "status_stopping_one": "No se ha detenido por completo · {count} proceso sigue en ejecución en {host}", + "status_stopping_two": "No se ha detenido por completo · {count} procesos siguen en ejecución en {host}", + "status_stopping_few": "No se ha detenido por completo · {count} procesos siguen en ejecución en {host}", + "status_stopping_many": "No se ha detenido por completo · {count} procesos siguen en ejecución en {host}", + "status_stopping_other": "No se ha detenido por completo · {count} procesos siguen en ejecución en {host}", + "status_cancellation_pending": "Cancelación pendiente", + "run_abandon_unreachable": "No se puede acceder a la máquina.", + "run_abandon_keep": "Seguir rastreando", + "settings_run_engine_label": "Nuevo motor de experimentos", + "settings_run_engine_description": "El nuevo motor mantiene ejecuciones remotas tras desconexiones y reinicios de la app, verifica cancelaciones y corrige muchos problemas de estabilidad de SSH.", + "settings_run_engine_override": "ORX_RUN_ENGINE controla este ajuste del servidor.", + "settings_run_engine_canary": "Las versiones canary siempre usan el nuevo motor.", + "settings_run_engine_note": "Aún en pruebas. Se aplica a nuevas ejecuciones." } diff --git a/ui/messages/fa.json b/ui/messages/fa.json index f05dd4e07..ac14a95c5 100644 --- a/ui/messages/fa.json +++ b/ui/messages/fa.json @@ -1648,5 +1648,87 @@ "remote_agents_description": "عامل‌ها باید روی هر دستگاه نصب شوند و وارد حساب شوند. آن‌ها را در {host} راه‌اندازی کنید.", "remote_claude_datacenter_title": "از اشتراک Claude روی IP مرکز داده استفاده نکنید", "remote_claude_datacenter_description": "{host} از IP مرکز داده {ip} استفاده می‌کند. استفاده از اشتراک Claude در اینجا ممکن است باعث علامت‌گذاری حساب شما توسط Anthropic شود. از کلید API استفاده کنید یا با مسئولیت خود ادامه دهید.", - "remote_claude_datacenter_continue": "ادامه با پذیرش خطر" + "remote_claude_datacenter_continue": "ادامه با پذیرش خطر", + "chat_panel_remove_file": "حذف فایل", + "chat_panel_remove_image": "حذف تصویر", + "account_local_to_app": "حساب محلی این برنامه است", + "chat_panel_requested_an_experiment_stop": "درخواست توقف یک آزمایش را داد", + "delete_pending_stop_warning": "حذف، درخواست‌های توقف معلق را نیز لغو می‌کند؛ ممکن است کارهای راه دور همچنان اجرا شوند.", + "status_submitting": "در حال ارسال", + "status_unreachable": "دسترس‌ناپذیر", + "status_needs_auth": "احراز هویت لازم است", + "status_unconfirmed": "تأییدنشده", + "status_abandoned": "رهاشده", + "status_last_seen": "آخرین بار در {time} دیده شد", + "run_notice_rental_key_cancelled": "خودکار متوقف شد: دستگاه به‌مدت ۱۵ دقیقه کلید SSH خود را رد کرد.", + "run_notice_rental_outcome_unavailable": "نتیجه در دسترس نیست: دستگاه اجاره‌ای پیش از دریافت نتیجهٔ نهایی آزاد شد.", + "run_notice_rental_billing": "هزینهٔ دستگاه اجاره‌ای همچنان محاسبه می‌شود. برای توقف دستگاه، اجرا را لغو کنید.", + "run_stop_box": "توقف دستگاه", + "run_notice_unreachable": "از {time} به {host} دسترسی نیست.", + "run_notice_retry_at": "در {time} دوباره تلاش می‌شود.", + "run_notice_provider_auth": "ارائه‌دهنده دسترسی را رد کرد. اطلاعات ورود را در تنظیمات ← محیط بررسی کنید.", + "run_notice_cluster_auth": "Kubernetes دسترسی را رد کرد. kubeconfig و مجوزهای خوشه را بررسی کنید.", + "run_notice_needs_auth": "برای ادامهٔ دنبال‌کردن این اجرا به {host} وصل شوید.", + "run_notice_unconfirmed_launch": "تأیید راه‌اندازی ممکن نشد. دوباره بررسی می‌شود.", + "run_notice_cancel_pending": "از {time} دسترسی به {host} ممکن نیست.", + "run_notice_cancel_pending_auth": "برای ارسال درخواست لغو به {host} متصل شوید.", + "run_notice_cancel_pending_later": "وقتی دستگاه دوباره در دسترس باشد، درخواست لغو ارسال می‌شود.", + "run_notice_cancel_pending_launch": "پس از تأیید شروع اجرا، درخواست لغو ارسال می‌شود.", + "run_notice_stops_if_found": "اگر کار پیدا شود، orx آن را متوقف می‌کند.", + "run_notice_unreconciled": "نیاز به توجه دارد.", + "run_notice_abandoned": "رهاشده. اگر کار روی {host} پیدا شود، orx آن را متوقف می‌کند.", + "run_notice_abandoned_no_host": "رهاشده. اگر کار پیدا شود، orx آن را متوقف می‌کند.", + "run_notice_the_host": "میزبان", + "run_stop_again": "توقف دوباره", + "run_abandon": "رها کردن…", + "run_abandon_title": "این اجرا رها شود؟", + "run_abandon_body": "OpenResearch پیگیری این اجرا را متوقف می‌کند. دوباره بررسی کنید که منابع محاسباتی واقعاً خاموش شده باشند.", + "run_abandon_body_no_host": "orx دیگر منتظر آن نمی‌ماند و آن را رهاشده علامت می‌زند. اگر کار بعداً پیدا شود، orx همان موقع آن را متوقف می‌کند.", + "run_abandon_confirm": "رها کردن اجرا", + "run_abandoning": "در حال رها کردن…", + "settings_host_connected": "متصل", + "settings_host_since": "از {time}", + "settings_host_since_next_try": "از {time} · تلاش بعدی {next}", + "settings_host_test": "آزمایش", + "settings_ssh_host_needs_connect": "{host} نیاز به اتصال شما دارد", + "settings_ssh_hosts_need_connect": "{count} میزبان نیاز به اتصال شما دارند", + "log_go_start": "رفتن به ابتدا", + "log_go_end": "رفتن به انتها", + "log_earlier": "خروجی قبلی", + "log_later": "خروجی بعدی", + "log_go_to": "رفتن به موقعیت", + "log_go_to_placeholder": "2.5 GB یا 60%", + "log_position": "{start} از {total}", + "log_position_end": "انتهای {total}", + "log_follow": "دنبال کردن", + "log_following": "در حال دنبال کردن", + "log_paused": "خروجی زنده متوقف شده", + "log_range": "موقعیت در گزارش", + "log_loading_from": "در حال بارگیری از {host}…", + "log_unavailable": "این بخش از گزارش روی {host} است که از {time} دسترس‌ناپذیر است.", + "log_unavailable_auth": "این بخش از گزارش روی {host} است. برای بارگیری آن وصل شوید.", + "run_notice_log_pending": "در حال ذخیرهٔ گزارش از {host}…", + "run_notice_log_failed": "ذخیرهٔ گزارش از {host} ممکن نشد. orx همچنان تلاش می‌کند؛ گزارش هنوز از میزبان باز می‌شود.", + "run_notice_post_failed": "ارسال نتیجهٔ این اجرا به گفتگو ممکن نشد: {error}", + "log_generation_unstable": "The log keeps changing. Reload to try again.", + "status_not_fully_stopped": "کاملاً متوقف نشده", + "run_stop_now": "اکنون متوقف کن", + "hover_not_fully_stopped_count": "{count} کاملاً متوقف نشده", + "run_notice_cancel_unreadable": "میزبان نتوانست فرایندهای {pids} را برای تأیید توقف بررسی کند.", + "run_notice_cancel_uncovered": "امکان بررسی فرایندهای داخل کانتینر یا خارج از محدودهٔ بررسی میزبان وجود نداشت.", + "status_cancelled_unconfirmed": "لغو شد · تأیید ممکن نبود", + "status_stopping_zero": "کاملاً متوقف نشده · {count} فرایند هنوز روی {host} در حال اجرا هستند", + "status_stopping_one": "کاملاً متوقف نشده · {count} فرایند هنوز روی {host} در حال اجراست", + "status_stopping_two": "کاملاً متوقف نشده · {count} فرایند هنوز روی {host} در حال اجرا هستند", + "status_stopping_few": "کاملاً متوقف نشده · {count} فرایند هنوز روی {host} در حال اجرا هستند", + "status_stopping_many": "کاملاً متوقف نشده · {count} فرایند هنوز روی {host} در حال اجرا هستند", + "status_stopping_other": "کاملاً متوقف نشده · {count} فرایند هنوز روی {host} در حال اجرا هستند", + "status_cancellation_pending": "لغو در انتظار است", + "run_abandon_unreachable": "دستگاه در دسترس نیست.", + "run_abandon_keep": "ادامهٔ پیگیری", + "settings_run_engine_label": "موتور جدید آزمایش", + "settings_run_engine_description": "موتور جدید اجراهای راه‌دور را هنگام قطع اتصال و راه‌اندازی مجدد برنامه ادامه می‌دهد. لغو را بررسی می‌کند و بسیاری از مشکلات پایداری SSH را برطرف می‌کند.", + "settings_run_engine_override": "این تنظیم سرور با ORX_RUN_ENGINE کنترل می‌شود.", + "settings_run_engine_canary": "نسخه‌های Canary همیشه از موتور جدید استفاده می‌کنند.", + "settings_run_engine_note": "هنوز در حال آزمایش است. برای اجراهای جدید اعمال می‌شود." } diff --git a/ui/messages/hi.json b/ui/messages/hi.json index c663641b0..7da684c7d 100644 --- a/ui/messages/hi.json +++ b/ui/messages/hi.json @@ -1648,5 +1648,87 @@ "remote_agents_description": "हर मशीन पर एजेंट इंस्टॉल करके साइन इन करना ज़रूरी है। उन्हें {host} पर सेट अप करें।", "remote_claude_datacenter_title": "डेटासेंटर IP पर Claude सदस्यता का उपयोग करने से बचें", "remote_claude_datacenter_description": "{host} डेटासेंटर IP {ip} का उपयोग करता है। यहाँ Claude सदस्यता का उपयोग करने पर Anthropic आपके खाते को फ़्लैग कर सकता है। API कुंजी का उपयोग करें या अपने जोखिम पर जारी रखें।", - "remote_claude_datacenter_continue": "फिर भी जारी रखें" + "remote_claude_datacenter_continue": "फिर भी जारी रखें", + "chat_panel_remove_file": "फ़ाइल हटाएं", + "chat_panel_remove_image": "इमेज हटाएं", + "account_local_to_app": "खाता इस ऐप के लिए स्थानीय है", + "chat_panel_requested_an_experiment_stop": "प्रयोग रोकने का अनुरोध किया", + "delete_pending_stop_warning": "हटाने से लंबित रोकने के अनुरोध भी रद्द हो जाते हैं; रिमोट जॉब चलते रह सकते हैं।", + "status_submitting": "सबमिट हो रहा है", + "status_unreachable": "पहुँच से बाहर", + "status_needs_auth": "प्रमाणीकरण आवश्यक है", + "status_unconfirmed": "अपुष्ट", + "status_abandoned": "छोड़ा गया", + "status_last_seen": "आख़िरी बार {time} पर देखा", + "run_notice_rental_key_cancelled": "अपने आप रोका गया: मशीन ने 15 मिनट तक अपनी SSH कुंजी अस्वीकार की।", + "run_notice_rental_outcome_unavailable": "परिणाम उपलब्ध नहीं है: अंतिम परिणाम एकत्र होने से पहले किराए की मशीन रिलीज़ हो गई।", + "run_notice_rental_billing": "किराए की मशीन का शुल्क अभी भी लग रहा है। मशीन रोकने के लिए रन रद्द करें।", + "run_stop_box": "मशीन रोकें", + "run_notice_unreachable": "{time} से {host} तक नहीं पहुँच पा रहे।", + "run_notice_retry_at": "{time} पर फिर कोशिश होगी।", + "run_notice_provider_auth": "प्रदाता ने पहुँच अस्वीकार कर दी। सेटिंग्स → एनवायरनमेंट में उसके क्रेडेंशियल जाँचें।", + "run_notice_cluster_auth": "Kubernetes ने पहुँच अस्वीकार कर दी। अपना kubeconfig और क्लस्टर की अनुमतियाँ जाँचें।", + "run_notice_needs_auth": "इस रन को फ़ॉलो करते रहने के लिए {host} से कनेक्ट करें।", + "run_notice_unconfirmed_launch": "लॉन्च की पुष्टि नहीं हो सकी। फिर से जाँच रहे हैं।", + "run_notice_cancel_pending": "{time} से {host} तक पहुँचना संभव नहीं है।", + "run_notice_cancel_pending_auth": "रद्द करने का अनुरोध भेजने के लिए {host} से कनेक्ट करें।", + "run_notice_cancel_pending_later": "मशीन फिर से उपलब्ध होने पर रद्द करने का अनुरोध भेजा जाएगा।", + "run_notice_cancel_pending_launch": "लॉन्च की पुष्टि होने पर रद्द करने का अनुरोध भेजा जाएगा।", + "run_notice_stops_if_found": "अगर जॉब मिलता है, तो orx उसे रोक देगा।", + "run_notice_unreconciled": "ध्यान देने की ज़रूरत है।", + "run_notice_abandoned": "छोड़ा गया। अगर जॉब {host} पर मिलता है, तो orx उसे रोक देगा।", + "run_notice_abandoned_no_host": "छोड़ा गया। अगर जॉब मिलता है, तो orx उसे रोक देगा।", + "run_notice_the_host": "होस्ट", + "run_stop_again": "फिर से रोकें", + "run_abandon": "छोड़ें…", + "run_abandon_title": "इस रन को छोड़ें?", + "run_abandon_body": "OpenResearch इस रन को ट्रैक करना बंद कर देगा। दोबारा जाँच लें कि कंप्यूट संसाधन वास्तव में बंद हैं।", + "run_abandon_body_no_host": "orx इसका इंतज़ार बंद करके इसे छोड़ा गया मार्क कर देगा। अगर जॉब बाद में मिलता है, तो orx उसे तब रोक देगा।", + "run_abandon_confirm": "रन छोड़ें", + "run_abandoning": "छोड़ा जा रहा है…", + "settings_host_connected": "कनेक्टेड", + "settings_host_since": "{time} से", + "settings_host_since_next_try": "{time} से · अगली कोशिश {next}", + "settings_host_test": "टेस्ट करें", + "settings_ssh_host_needs_connect": "{host} से कनेक्ट करना ज़रूरी है", + "settings_ssh_hosts_need_connect": "{count} होस्ट से कनेक्ट करना ज़रूरी है", + "log_go_start": "शुरुआत पर जाएँ", + "log_go_end": "अंत पर जाएँ", + "log_earlier": "पहले का आउटपुट", + "log_later": "बाद का आउटपुट", + "log_go_to": "स्थिति पर जाएँ", + "log_go_to_placeholder": "2.5 GB या 60%", + "log_position": "{total} में से {start}", + "log_position_end": "{total} का अंत", + "log_follow": "फ़ॉलो करें", + "log_following": "फ़ॉलो कर रहे हैं", + "log_paused": "लाइव आउटपुट रुका हुआ है", + "log_range": "लॉग की स्थिति", + "log_loading_from": "{host} से लोड हो रहा है…", + "log_unavailable": "लॉग का यह हिस्सा {host} पर है, जो {time} से पहुँच से बाहर है।", + "log_unavailable_auth": "लॉग का यह हिस्सा {host} पर है। इसे लोड करने के लिए कनेक्ट करें।", + "run_notice_log_pending": "{host} से लॉग सेव हो रहा है…", + "run_notice_log_failed": "{host} से लॉग सेव नहीं हो सका। orx कोशिश करता रहेगा; लॉग अब भी होस्ट से खुलता है।", + "run_notice_post_failed": "इस रन का परिणाम चैट में पोस्ट नहीं हो सका: {error}", + "log_generation_unstable": "The log keeps changing. Reload to try again.", + "status_not_fully_stopped": "पूरी तरह बंद नहीं हुआ", + "run_stop_now": "अभी बंद करें", + "hover_not_fully_stopped_count": "{count} पूरी तरह बंद नहीं हुए", + "run_notice_cancel_unreadable": "होस्ट रुकने की पुष्टि के लिए प्रक्रियाओं {pids} की जाँच नहीं कर सका।", + "run_notice_cancel_uncovered": "कंटेनर के अंदर या होस्ट की जाँच के दायरे से बाहर की प्रक्रियाओं की जाँच नहीं हो सकी।", + "status_cancelled_unconfirmed": "रद्द किया गया · पुष्टि नहीं हो सकी", + "status_stopping_zero": "पूरी तरह बंद नहीं हुआ · {host} पर {count} प्रक्रियाएँ अभी भी चल रही हैं", + "status_stopping_one": "पूरी तरह बंद नहीं हुआ · {host} पर {count} प्रक्रिया अभी भी चल रही है", + "status_stopping_two": "पूरी तरह बंद नहीं हुआ · {host} पर {count} प्रक्रियाएँ अभी भी चल रही हैं", + "status_stopping_few": "पूरी तरह बंद नहीं हुआ · {host} पर {count} प्रक्रियाएँ अभी भी चल रही हैं", + "status_stopping_many": "पूरी तरह बंद नहीं हुआ · {host} पर {count} प्रक्रियाएँ अभी भी चल रही हैं", + "status_stopping_other": "पूरी तरह बंद नहीं हुआ · {host} पर {count} प्रक्रियाएँ अभी भी चल रही हैं", + "status_cancellation_pending": "रद्द करना लंबित है", + "run_abandon_unreachable": "मशीन तक पहुँचना संभव नहीं है।", + "run_abandon_keep": "ट्रैक करना जारी रखें", + "settings_run_engine_label": "नया प्रयोग इंजन", + "settings_run_engine_description": "नया इंजन कनेक्शन टूटने और ऐप रीस्टार्ट होने पर भी रिमोट रन जारी रखता है। यह रद्द होने की पुष्टि करता है और SSH की कई स्थिरता समस्याएँ ठीक करता है।", + "settings_run_engine_override": "ORX_RUN_ENGINE सर्वर की इस सेटिंग को नियंत्रित करता है।", + "settings_run_engine_canary": "Canary बिल्ड हमेशा नए इंजन का उपयोग करते हैं।", + "settings_run_engine_note": "अभी परीक्षण में है। नए रन पर लागू होता है।" } diff --git a/ui/messages/ja.json b/ui/messages/ja.json index 20f3de186..59377d304 100644 --- a/ui/messages/ja.json +++ b/ui/messages/ja.json @@ -1648,5 +1648,87 @@ "remote_agents_description": "各マシンでエージェントのインストールとサインインが必要です。{host} で設定してください。", "remote_claude_datacenter_title": "データセンターの IP では Claude のサブスクリプションを避けてください", "remote_claude_datacenter_description": "{host} はデータセンターの IP {ip} を使用しています。ここで Claude のサブスクリプションを使うと、Anthropic がアカウントにフラグを付ける可能性があります。API キーを使うか、リスクを理解して続行してください。", - "remote_claude_datacenter_continue": "リスクを理解して続行" + "remote_claude_datacenter_continue": "リスクを理解して続行", + "chat_panel_remove_file": "ファイルを削除", + "chat_panel_remove_image": "画像を削除", + "account_local_to_app": "アカウントはこのアプリのローカルアカウントです", + "chat_panel_requested_an_experiment_stop": "実験の停止をリクエスト", + "delete_pending_stop_warning": "削除すると保留中の停止要求も取り消されます。リモートジョブは実行を続ける場合があります。", + "status_submitting": "送信中", + "status_unreachable": "接続不可", + "status_needs_auth": "認証が必要", + "status_unconfirmed": "未確認", + "status_abandoned": "放棄済み", + "status_last_seen": "最終確認 {time}", + "run_notice_rental_key_cancelled": "自動停止しました。マシンが15分間SSHキーを拒否しました。", + "run_notice_rental_outcome_unavailable": "結果を取得できません。最終結果を収集する前にレンタルが解放されました。", + "run_notice_rental_billing": "レンタル中のマシンへの課金が続いています。実行をキャンセルしてマシンを停止してください。", + "run_stop_box": "マシンを停止", + "run_notice_unreachable": "{time} から {host} に接続できません。", + "run_notice_retry_at": "{time} に再試行します。", + "run_notice_provider_auth": "プロバイダーがアクセスを拒否しました。設定 → 環境で認証情報を確認してください。", + "run_notice_cluster_auth": "Kubernetes がアクセスを拒否しました。kubeconfig とクラスターの権限を確認してください。", + "run_notice_needs_auth": "この実行を引き続き追跡するには {host} に接続してください。", + "run_notice_unconfirmed_launch": "起動を確認できませんでした。再確認しています。", + "run_notice_cancel_pending": "{time} から {host} に接続できません。", + "run_notice_cancel_pending_auth": "キャンセルを送信するには {host} に接続してください。", + "run_notice_cancel_pending_later": "マシンに再び接続できるようになると、キャンセルが送信されます。", + "run_notice_cancel_pending_launch": "起動が確認されると、キャンセルが送信されます。", + "run_notice_stops_if_found": "ジョブが見つかれば orx が停止します。", + "run_notice_unreconciled": "確認が必要です。", + "run_notice_abandoned": "放棄済み。{host} でジョブが見つかれば orx が停止します。", + "run_notice_abandoned_no_host": "放棄済み。ジョブが見つかれば orx が停止します。", + "run_notice_the_host": "ホスト", + "run_stop_again": "もう一度停止", + "run_abandon": "放棄…", + "run_abandon_title": "この実行を放棄しますか?", + "run_abandon_body": "OpenResearch はこの実行の追跡を停止します。実際の計算リソースが停止していることを再確認してください。", + "run_abandon_body_no_host": "orx は待機をやめ、放棄済みとしてマークします。後でジョブが現れた場合は、その時点で orx が停止します。", + "run_abandon_confirm": "実行を放棄", + "run_abandoning": "放棄しています…", + "settings_host_connected": "接続済み", + "settings_host_since": "{time} から", + "settings_host_since_next_try": "{time} から · 次の試行 {next}", + "settings_host_test": "テスト", + "settings_ssh_host_needs_connect": "{host} への接続が必要です", + "settings_ssh_hosts_need_connect": "{count} 台のホストへの接続が必要です", + "log_go_start": "先頭へ移動", + "log_go_end": "末尾へ移動", + "log_earlier": "前の出力", + "log_later": "後の出力", + "log_go_to": "位置へ移動", + "log_go_to_placeholder": "2.5 GB または 60%", + "log_position": "{start} / {total}", + "log_position_end": "末尾 / {total}", + "log_follow": "追従", + "log_following": "追従中", + "log_paused": "ライブ出力は一時停止中", + "log_range": "ログの位置", + "log_loading_from": "{host} から読み込み中…", + "log_unavailable": "ログのこの部分は {host} にあり、{time} から接続できません。", + "log_unavailable_auth": "ログのこの部分は {host} にあります。読み込むには接続してください。", + "run_notice_log_pending": "{host} からログを保存中…", + "run_notice_log_failed": "{host} からログを保存できませんでした。orx は再試行を続けます。ログは引き続きホストから開けます。", + "run_notice_post_failed": "この実行の結果をチャットに投稿できませんでした: {error}", + "log_generation_unstable": "The log keeps changing. Reload to try again.", + "status_not_fully_stopped": "完全には停止していません", + "run_stop_now": "今すぐ停止", + "hover_not_fully_stopped_count": "{count} 件が完全には停止していません", + "run_notice_cancel_unreadable": "ホストがプロセス {pids} を調べられず、停止を確認できませんでした。", + "run_notice_cancel_uncovered": "コンテナ内やホストのスキャン範囲外のプロセスは確認できませんでした。", + "status_cancelled_unconfirmed": "キャンセル済み · 確認できませんでした", + "status_stopping_zero": "完全には停止していません · {host} で {count} 個のプロセスがまだ実行中です", + "status_stopping_one": "完全には停止していません · {host} で {count} 個のプロセスがまだ実行中です", + "status_stopping_two": "完全には停止していません · {host} で {count} 個のプロセスがまだ実行中です", + "status_stopping_few": "完全には停止していません · {host} で {count} 個のプロセスがまだ実行中です", + "status_stopping_many": "完全には停止していません · {host} で {count} 個のプロセスがまだ実行中です", + "status_stopping_other": "完全には停止していません · {host} で {count} 個のプロセスがまだ実行中です", + "status_cancellation_pending": "キャンセル待ち", + "run_abandon_unreachable": "マシンに接続できません。", + "run_abandon_keep": "追跡を続ける", + "settings_run_engine_label": "新しい実験エンジン", + "settings_run_engine_description": "新しいエンジンは、切断やアプリの再起動があってもリモート実行を継続し、キャンセルを確認して、SSHの安定性に関する多くの問題を修正します。", + "settings_run_engine_override": "このサーバーの設定は ORX_RUN_ENGINE で制御されています。", + "settings_run_engine_canary": "Canary ビルドでは常に新しいエンジンを使用します。", + "settings_run_engine_note": "現在テスト中です。新しい実行に適用されます。" } diff --git a/ui/messages/ko.json b/ui/messages/ko.json index b1d303e7f..d155d027e 100644 --- a/ui/messages/ko.json +++ b/ui/messages/ko.json @@ -1648,5 +1648,87 @@ "remote_agents_description": "각 컴퓨터에서 에이전트를 설치하고 로그인해야 합니다. {host}에서 설정하세요.", "remote_claude_datacenter_title": "데이터센터 IP에서 Claude 구독 사용을 피하세요", "remote_claude_datacenter_description": "{host}에서 데이터센터 IP {ip}를 사용합니다. 여기서 Claude 구독을 사용하면 Anthropic이 계정을 신고 대상으로 표시할 수 있습니다. API 키를 사용하거나 위험을 감수하고 계속하세요.", - "remote_claude_datacenter_continue": "위험을 감수하고 계속" + "remote_claude_datacenter_continue": "위험을 감수하고 계속", + "chat_panel_remove_file": "파일 제거", + "chat_panel_remove_image": "이미지 제거", + "account_local_to_app": "계정은 이 앱의 로컬 계정입니다", + "chat_panel_requested_an_experiment_stop": "실험 중지 요청", + "delete_pending_stop_warning": "삭제하면 대기 중인 중지 요청도 취소됩니다. 원격 작업은 계속 실행될 수 있습니다.", + "status_submitting": "제출 중", + "status_unreachable": "연결 불가", + "status_needs_auth": "인증 필요", + "status_unconfirmed": "미확인", + "status_abandoned": "포기됨", + "status_last_seen": "마지막 확인 {time}", + "run_notice_rental_key_cancelled": "자동으로 중지됨: 머신이 15분 동안 SSH 키를 거부했습니다.", + "run_notice_rental_outcome_unavailable": "결과를 확인할 수 없습니다. 최종 결과를 수집하기 전에 대여가 해제되었습니다.", + "run_notice_rental_billing": "대여한 머신에 계속 요금이 부과되고 있습니다. 실행을 취소하여 머신을 중지하세요.", + "run_stop_box": "머신 중지", + "run_notice_unreachable": "{time}부터 {host}에 연결할 수 없습니다.", + "run_notice_retry_at": "{time}에 다시 시도합니다.", + "run_notice_provider_auth": "제공자가 접근을 거부했습니다. 설정 → 환경에서 인증 정보를 확인하세요.", + "run_notice_cluster_auth": "Kubernetes가 접근을 거부했습니다. kubeconfig와 클러스터 권한을 확인하세요.", + "run_notice_needs_auth": "이 실행을 계속 추적하려면 {host}에 연결하세요.", + "run_notice_unconfirmed_launch": "실행 시작을 확인하지 못했습니다. 다시 확인하는 중입니다.", + "run_notice_cancel_pending": "{time}부터 {host}에 연결할 수 없습니다.", + "run_notice_cancel_pending_auth": "취소 요청을 보내려면 {host}에 연결하세요.", + "run_notice_cancel_pending_later": "머신에 다시 연결할 수 있게 되면 취소 요청이 전송됩니다.", + "run_notice_cancel_pending_launch": "실행 시작이 확인되면 취소 요청이 전송됩니다.", + "run_notice_stops_if_found": "작업이 나타나면 orx가 중지합니다.", + "run_notice_unreconciled": "확인이 필요합니다.", + "run_notice_abandoned": "포기됨. {host}에 작업이 나타나면 orx가 중지합니다.", + "run_notice_abandoned_no_host": "포기됨. 작업이 나타나면 orx가 중지합니다.", + "run_notice_the_host": "호스트", + "run_stop_again": "다시 중지", + "run_abandon": "포기…", + "run_abandon_title": "이 실행을 포기할까요?", + "run_abandon_body": "OpenResearch가 이 실행의 추적을 중단합니다. 실제 컴퓨팅 리소스가 종료되었는지 다시 확인하세요.", + "run_abandon_body_no_host": "orx가 기다리기를 멈추고 포기됨으로 표시합니다. 나중에 작업이 나타나면 그때 orx가 중지합니다.", + "run_abandon_confirm": "실행 포기", + "run_abandoning": "포기하는 중…", + "settings_host_connected": "연결됨", + "settings_host_since": "{time}부터", + "settings_host_since_next_try": "{time}부터 · 다음 시도 {next}", + "settings_host_test": "테스트", + "settings_ssh_host_needs_connect": "{host}에 연결해야 합니다", + "settings_ssh_hosts_need_connect": "호스트 {count}개에 연결해야 합니다", + "log_go_start": "처음으로", + "log_go_end": "끝으로", + "log_earlier": "이전 출력", + "log_later": "이후 출력", + "log_go_to": "위치로 이동", + "log_go_to_placeholder": "2.5 GB 또는 60%", + "log_position": "{start} / {total}", + "log_position_end": "끝 / {total}", + "log_follow": "따라가기", + "log_following": "따라가는 중", + "log_paused": "실시간 출력 일시 중지됨", + "log_range": "로그 위치", + "log_loading_from": "{host}에서 불러오는 중…", + "log_unavailable": "로그의 이 부분은 {host}에 있으며, {time}부터 연결할 수 없습니다.", + "log_unavailable_auth": "로그의 이 부분은 {host}에 있습니다. 불러오려면 연결하세요.", + "run_notice_log_pending": "{host}에서 로그를 저장하는 중…", + "run_notice_log_failed": "{host}에서 로그를 저장하지 못했습니다. orx가 계속 시도하며, 로그는 여전히 호스트에서 열립니다.", + "run_notice_post_failed": "이 실행 결과를 채팅에 게시하지 못했습니다: {error}", + "log_generation_unstable": "The log keeps changing. Reload to try again.", + "status_not_fully_stopped": "완전히 중지되지 않음", + "run_stop_now": "지금 중지", + "hover_not_fully_stopped_count": "{count}개가 완전히 중지되지 않음", + "run_notice_cancel_unreadable": "호스트가 프로세스 {pids}을(를) 검사하지 못해 중지를 확인할 수 없습니다.", + "run_notice_cancel_uncovered": "컨테이너 내부 또는 호스트 검사 범위 밖의 프로세스를 확인할 수 없습니다.", + "status_cancelled_unconfirmed": "취소됨 · 확인할 수 없음", + "status_stopping_zero": "완전히 중지되지 않음 · {host}에서 프로세스 {count}개가 아직 실행 중", + "status_stopping_one": "완전히 중지되지 않음 · {host}에서 프로세스 {count}개가 아직 실행 중", + "status_stopping_two": "완전히 중지되지 않음 · {host}에서 프로세스 {count}개가 아직 실행 중", + "status_stopping_few": "완전히 중지되지 않음 · {host}에서 프로세스 {count}개가 아직 실행 중", + "status_stopping_many": "완전히 중지되지 않음 · {host}에서 프로세스 {count}개가 아직 실행 중", + "status_stopping_other": "완전히 중지되지 않음 · {host}에서 프로세스 {count}개가 아직 실행 중", + "status_cancellation_pending": "취소 대기 중", + "run_abandon_unreachable": "머신에 연결할 수 없습니다.", + "run_abandon_keep": "계속 추적", + "settings_run_engine_label": "새 실험 엔진", + "settings_run_engine_description": "새 엔진은 연결 끊김과 앱 재시작에도 원격 실행을 유지하고, 취소를 검증하며, 여러 SSH 안정성 문제를 해결합니다.", + "settings_run_engine_override": "ORX_RUN_ENGINE이 이 서버 설정을 제어합니다.", + "settings_run_engine_canary": "Canary 빌드는 항상 새 엔진을 사용합니다.", + "settings_run_engine_note": "아직 테스트 중입니다. 새 실행에 적용됩니다." } diff --git a/ui/messages/pl.json b/ui/messages/pl.json index bf0273d44..58ff0e05c 100644 --- a/ui/messages/pl.json +++ b/ui/messages/pl.json @@ -1648,5 +1648,87 @@ "remote_agents_description": "Na każdym komputerze trzeba zainstalować agentów i się zalogować. Skonfiguruj ich na {host}.", "remote_claude_datacenter_title": "Unikaj subskrypcji Claude na adresach IP centrów danych", "remote_claude_datacenter_description": "{host} używa adresu IP centrum danych {ip}. Korzystanie tu z subskrypcji Claude może spowodować oznaczenie konta przez Anthropic. Użyj klucza API lub kontynuuj na własne ryzyko.", - "remote_claude_datacenter_continue": "Kontynuuj mimo ryzyka" + "remote_claude_datacenter_continue": "Kontynuuj mimo ryzyka", + "chat_panel_remove_file": "Usuń plik", + "chat_panel_remove_image": "Usuń obraz", + "account_local_to_app": "Konto jest lokalne dla tej aplikacji", + "chat_panel_requested_an_experiment_stop": "Zażądano zatrzymania eksperymentu", + "delete_pending_stop_warning": "Usunięcie anuluje też oczekujące żądania zatrzymania; zadania zdalne mogą nadal działać.", + "status_submitting": "Wysyłanie", + "status_unreachable": "Nieosiągalny", + "status_needs_auth": "Wymagane uwierzytelnienie", + "status_unconfirmed": "Niepotwierdzone", + "status_abandoned": "Porzucone", + "status_last_seen": "Ostatnio widziane o {time}", + "run_notice_rental_key_cancelled": "Zatrzymano automatycznie: maszyna odrzucała swój klucz SSH przez 15 minut.", + "run_notice_rental_outcome_unavailable": "Wynik niedostępny: wynajęta maszyna została zwolniona przed zebraniem końcowego wyniku.", + "run_notice_rental_billing": "Wynajęta maszyna nadal nalicza opłaty. Anuluj uruchomienie, aby ją zatrzymać.", + "run_stop_box": "Zatrzymaj maszynę", + "run_notice_unreachable": "Brak połączenia z {host} od {time}.", + "run_notice_retry_at": "Kolejna próba o {time}.", + "run_notice_provider_auth": "Dostawca odrzucił dostęp. Sprawdź dane uwierzytelniające w Ustawienia → Środowisko.", + "run_notice_cluster_auth": "Kubernetes odrzucił dostęp. Sprawdź kubeconfig i uprawnienia klastra.", + "run_notice_needs_auth": "Połącz się z {host}, aby dalej śledzić to uruchomienie.", + "run_notice_unconfirmed_launch": "Nie udało się potwierdzić uruchomienia. Sprawdzanie ponownie.", + "run_notice_cancel_pending": "Host {host} jest nieosiągalny od {time}.", + "run_notice_cancel_pending_auth": "Połącz się z {host}, aby wysłać żądanie anulowania.", + "run_notice_cancel_pending_later": "Żądanie anulowania zostanie wysłane, gdy maszyna będzie znów osiągalna.", + "run_notice_cancel_pending_launch": "Żądanie anulowania zostanie wysłane po potwierdzeniu uruchomienia.", + "run_notice_stops_if_found": "Jeśli zadanie się pojawi, orx je zatrzyma.", + "run_notice_unreconciled": "Wymaga uwagi.", + "run_notice_abandoned": "Porzucone. Jeśli zadanie pojawi się na {host}, orx je zatrzyma.", + "run_notice_abandoned_no_host": "Porzucone. Jeśli zadanie się pojawi, orx je zatrzyma.", + "run_notice_the_host": "host", + "run_stop_again": "Zatrzymaj ponownie", + "run_abandon": "Porzuć…", + "run_abandon_title": "Porzucić to uruchomienie?", + "run_abandon_body": "OpenResearch przestanie śledzić to uruchomienie. Sprawdź ponownie, czy zasoby obliczeniowe zostały rzeczywiście wyłączone.", + "run_abandon_body_no_host": "orx przestaje na nie czekać i oznacza je jako porzucone. Jeśli zadanie pojawi się później, orx je wtedy zatrzyma.", + "run_abandon_confirm": "Porzuć uruchomienie", + "run_abandoning": "Porzucanie…", + "settings_host_connected": "Połączono", + "settings_host_since": "od {time}", + "settings_host_since_next_try": "od {time} · kolejna próba {next}", + "settings_host_test": "Testuj", + "settings_ssh_host_needs_connect": "{host} wymaga połączenia", + "settings_ssh_hosts_need_connect": "Hosty wymagające połączenia: {count}", + "log_go_start": "Przejdź na początek", + "log_go_end": "Przejdź na koniec", + "log_earlier": "Wcześniejsze dane", + "log_later": "Późniejsze dane", + "log_go_to": "Przejdź do pozycji", + "log_go_to_placeholder": "2,5 GB lub 60%", + "log_position": "{start} z {total}", + "log_position_end": "Koniec z {total}", + "log_follow": "Śledź", + "log_following": "Śledzenie", + "log_paused": "Dane na żywo wstrzymane", + "log_range": "Pozycja w logu", + "log_loading_from": "Wczytywanie z {host}…", + "log_unavailable": "Ta część logu jest na {host}, nieosiągalnym od {time}.", + "log_unavailable_auth": "Ta część logu jest na {host}. Połącz się, aby ją wczytać.", + "run_notice_log_pending": "Zapisywanie logu z {host}…", + "run_notice_log_failed": "Nie udało się zapisać logu z {host}. orx próbuje dalej; log nadal otwiera się z hosta.", + "run_notice_post_failed": "Nie udało się opublikować wyniku tego uruchomienia w czacie: {error}", + "log_generation_unstable": "The log keeps changing. Reload to try again.", + "status_not_fully_stopped": "Nie zatrzymano całkowicie", + "run_stop_now": "Zatrzymaj teraz", + "hover_not_fully_stopped_count": "{count} nie zatrzymano całkowicie", + "run_notice_cancel_unreadable": "Host nie mógł sprawdzić procesów {pids}, aby potwierdzić ich zatrzymanie.", + "run_notice_cancel_uncovered": "Nie można było sprawdzić procesów wewnątrz kontenera lub poza zakresem skanowania hosta.", + "status_cancelled_unconfirmed": "Anulowano · nie udało się potwierdzić", + "status_stopping_zero": "Nie zatrzymano w pełni · {count} procesu nadal działa na {host}", + "status_stopping_one": "Nie zatrzymano w pełni · {count} proces nadal działa na {host}", + "status_stopping_two": "Nie zatrzymano w pełni · {count} procesu nadal działa na {host}", + "status_stopping_few": "Nie zatrzymano w pełni · {count} procesy nadal działają na {host}", + "status_stopping_many": "Nie zatrzymano w pełni · {count} procesów nadal działa na {host}", + "status_stopping_other": "Nie zatrzymano w pełni · {count} procesu nadal działa na {host}", + "status_cancellation_pending": "Anulowanie oczekuje", + "run_abandon_unreachable": "Maszyna jest nieosiągalna.", + "run_abandon_keep": "Śledź dalej", + "settings_run_engine_label": "Nowy silnik eksperymentów", + "settings_run_engine_description": "Nowy silnik utrzymuje zdalne uruchomienia po rozłączeniu i restarcie aplikacji, weryfikuje anulowanie i rozwiązuje wiele problemów ze stabilnością SSH.", + "settings_run_engine_override": "ORX_RUN_ENGINE steruje tym ustawieniem serwera.", + "settings_run_engine_canary": "Wersje canary zawsze korzystają z nowego silnika.", + "settings_run_engine_note": "Wciąż w fazie testów. Dotyczy nowych uruchomień." } diff --git a/ui/messages/ru.json b/ui/messages/ru.json index 2f999e835..70e1da6bc 100644 --- a/ui/messages/ru.json +++ b/ui/messages/ru.json @@ -1648,5 +1648,87 @@ "remote_agents_description": "Агентов нужно установить и войти в их учётные записи на каждом компьютере. Настройте их на {host}.", "remote_claude_datacenter_title": "Избегайте подписок Claude на IP дата-центров", "remote_claude_datacenter_description": "{host} использует IP дата-центра {ip}. При использовании подписки Claude здесь Anthropic может пометить вашу учётную запись. Используйте API-ключ или продолжайте на свой риск.", - "remote_claude_datacenter_continue": "Всё равно продолжить" + "remote_claude_datacenter_continue": "Всё равно продолжить", + "chat_panel_remove_file": "Удалить файл", + "chat_panel_remove_image": "Удалить изображение", + "account_local_to_app": "Аккаунт действует только в этом приложении", + "chat_panel_requested_an_experiment_stop": "Запрошена остановка эксперимента", + "delete_pending_stop_warning": "Удаление также отменяет ожидающие запросы остановки; удалённые задания могут продолжить работу.", + "status_submitting": "Отправка", + "status_unreachable": "Недоступен", + "status_needs_auth": "Требуется аутентификация", + "status_unconfirmed": "Не подтверждён", + "status_abandoned": "Оставлен", + "status_last_seen": "Последний ответ в {time}", + "run_notice_rental_key_cancelled": "Остановлено автоматически: машина отклоняла свой SSH-ключ в течение 15 минут.", + "run_notice_rental_outcome_unavailable": "Результат недоступен: аренда была прекращена до получения окончательного результата.", + "run_notice_rental_billing": "Плата за арендованную машину продолжает начисляться. Отмените запуск, чтобы остановить машину.", + "run_stop_box": "Остановить машину", + "run_notice_unreachable": "Хост {host} недоступен с {time}.", + "run_notice_retry_at": "Следующая попытка в {time}.", + "run_notice_provider_auth": "Провайдер отклонил доступ. Проверьте учётные данные в Настройки → Окружение.", + "run_notice_cluster_auth": "Kubernetes отклонил доступ. Проверьте kubeconfig и права доступа к кластеру.", + "run_notice_needs_auth": "Подключитесь к {host}, чтобы продолжить отслеживание запуска.", + "run_notice_unconfirmed_launch": "Не удалось подтвердить запуск. Проверяем ещё раз.", + "run_notice_cancel_pending": "{host} недоступен с {time}.", + "run_notice_cancel_pending_auth": "Подключитесь к {host}, чтобы отправить запрос на отмену.", + "run_notice_cancel_pending_later": "Запрос на отмену будет отправлен, когда машина снова станет доступна.", + "run_notice_cancel_pending_launch": "Запрос на отмену будет отправлен после подтверждения запуска.", + "run_notice_stops_if_found": "Если задание обнаружится, orx остановит его.", + "run_notice_unreconciled": "Требует внимания.", + "run_notice_abandoned": "Запуск оставлен. Если задание обнаружится на {host}, orx остановит его.", + "run_notice_abandoned_no_host": "Запуск оставлен. Если задание обнаружится, orx остановит его.", + "run_notice_the_host": "хост", + "run_stop_again": "Остановить снова", + "run_abandon": "Оставить…", + "run_abandon_title": "Оставить этот запуск?", + "run_abandon_body": "OpenResearch перестанет отслеживать этот запуск. Убедитесь ещё раз, что вычислительные ресурсы действительно выключены.", + "run_abandon_body_no_host": "orx перестанет ждать завершения запуска и отметит его как оставленный. Если задание позже обнаружится, orx остановит его.", + "run_abandon_confirm": "Оставить запуск", + "run_abandoning": "Оставляем запуск…", + "settings_host_connected": "Подключён", + "settings_host_since": "с {time}", + "settings_host_since_next_try": "с {time} · следующая попытка {next}", + "settings_host_test": "Проверить", + "settings_ssh_host_needs_connect": "Подключитесь к {host}", + "settings_ssh_hosts_need_connect": "Требуется подключение к хостам: {count}", + "log_go_start": "К началу", + "log_go_end": "К концу", + "log_earlier": "Предыдущий вывод", + "log_later": "Следующий вывод", + "log_go_to": "Перейти к позиции", + "log_go_to_placeholder": "2,5 GB или 60%", + "log_position": "{start} из {total}", + "log_position_end": "Конец из {total}", + "log_follow": "Следить", + "log_following": "Отслеживание", + "log_paused": "Обновление вывода приостановлено", + "log_range": "Позиция в журнале", + "log_loading_from": "Загрузка с {host}…", + "log_unavailable": "Эта часть журнала находится на хосте {host}, который недоступен с {time}.", + "log_unavailable_auth": "Эта часть журнала находится на хосте {host}. Подключитесь к нему, чтобы загрузить её.", + "run_notice_log_pending": "Сохранение журнала с {host}…", + "run_notice_log_failed": "Не удалось сохранить журнал с {host}. orx продолжит попытки; журнал по-прежнему можно открыть с хоста.", + "run_notice_post_failed": "Не удалось отправить результат запуска в чат: {error}", + "log_generation_unstable": "The log keeps changing. Reload to try again.", + "status_not_fully_stopped": "Остановлено не полностью", + "run_stop_now": "Остановить сейчас", + "hover_not_fully_stopped_count": "{count} остановлено не полностью", + "run_notice_cancel_unreadable": "Хост не смог проверить процессы {pids}, чтобы подтвердить остановку.", + "run_notice_cancel_uncovered": "Не удалось проверить процессы внутри контейнера или вне области сканирования хоста.", + "status_cancelled_unconfirmed": "Отменено · не удалось подтвердить", + "status_stopping_zero": "Остановлено не полностью · {count} процесса всё ещё работают на {host}", + "status_stopping_one": "Остановлено не полностью · {count} процесс всё ещё работает на {host}", + "status_stopping_two": "Остановлено не полностью · {count} процесса всё ещё работают на {host}", + "status_stopping_few": "Остановлено не полностью · {count} процесса всё ещё работают на {host}", + "status_stopping_many": "Остановлено не полностью · {count} процессов всё ещё работают на {host}", + "status_stopping_other": "Остановлено не полностью · {count} процесса всё ещё работают на {host}", + "status_cancellation_pending": "Отмена ожидает отправки", + "run_abandon_unreachable": "Машина недоступна.", + "run_abandon_keep": "Продолжить отслеживание", + "settings_run_engine_label": "Новый движок экспериментов", + "settings_run_engine_description": "Новый движок сохраняет удалённые запуски при разрывах связи и перезапусках приложения, проверяет отмену и исправляет многие проблемы стабильности SSH.", + "settings_run_engine_override": "Эта настройка сервера управляется переменной ORX_RUN_ENGINE.", + "settings_run_engine_canary": "Сборки Canary всегда используют новый движок.", + "settings_run_engine_note": "Ещё тестируется. Применяется к новым запускам." } diff --git a/ui/messages/tr.json b/ui/messages/tr.json index c2757ec32..ef8a7c18b 100644 --- a/ui/messages/tr.json +++ b/ui/messages/tr.json @@ -1648,5 +1648,87 @@ "remote_agents_description": "Ajanlar her makinede ayrı ayrı yüklenmeli ve giriş yapılmalıdır. Bunları {host} üzerinde kurun.", "remote_claude_datacenter_title": "Veri merkezi IP'lerinde Claude aboneliği kullanmayın", "remote_claude_datacenter_description": "{host}, {ip} veri merkezi IP adresini kullanıyor. Burada Claude aboneliği kullanmak Anthropic'in hesabınızı işaretlemesine yol açabilir. Bunun yerine bir API anahtarı kullanın ya da riski göze alarak devam edin.", - "remote_claude_datacenter_continue": "Yine de devam et" + "remote_claude_datacenter_continue": "Yine de devam et", + "chat_panel_remove_file": "Dosyayı kaldır", + "chat_panel_remove_image": "Görseli kaldır", + "account_local_to_app": "Hesap bu uygulamaya özel", + "run_abandon_body_no_host": "orx beklemeyi bırakır ve çalıştırmayı Terk edildi olarak işaretler. İş daha sonra ortaya çıkarsa orx onu durdurur.", + "run_abandoning": "Terk ediliyor…", + "run_notice_stops_if_found": "İş ortaya çıkarsa orx onu durdurur.", + "chat_panel_requested_an_experiment_stop": "Bir deneyin durdurulması istendi", + "status_cancellation_pending": "İptal bekleniyor", + "delete_pending_stop_warning": "Silme işlemi, bekleyen durdurma isteklerini de iptal eder; uzak işler çalışmaya devam edebilir.", + "status_submitting": "Gönderiliyor", + "status_unreachable": "Erişilemiyor", + "status_needs_auth": "Kimlik doğrulama gerekli", + "status_unconfirmed": "Doğrulanmadı", + "status_abandoned": "Takip bırakıldı", + "status_last_seen": "Son görülme: {time}", + "run_notice_rental_key_cancelled": "Otomatik olarak durduruldu: kiralık makine SSH anahtarını 15 dakika boyunca reddetti.", + "run_notice_rental_outcome_unavailable": "Sonuç alınamadı: kiralık makine, nihai sonucu alınmadan serbest bırakıldı.", + "run_notice_rental_billing": "Kiralık makine için ücret alınmaya devam ediyor. Makineyi durdurmak için çalıştırmayı iptal edin.", + "run_stop_box": "Makineyi durdur", + "run_notice_unreachable": "{host} sunucusuna {time} zamanından beri erişilemiyor.", + "run_notice_retry_at": "Yeniden deneme zamanı: {time}.", + "run_notice_needs_auth": "Bu çalıştırmayı izlemeye devam etmek için {host} ile bağlantı kurun.", + "run_notice_unconfirmed_launch": "Başlatma doğrulanamadı. Yeniden kontrol ediliyor.", + "run_notice_cancel_pending": "{host} sunucusuna {time} zamanından beri erişilemiyor.", + "run_notice_cancel_pending_auth": "İptal isteğini göndermek için {host} ile bağlantı kurun.", + "run_notice_cancel_pending_later": "Makineye yeniden erişilebildiğinde iptal isteği gönderilecek.", + "run_notice_cancel_pending_launch": "Başlatma doğrulandığında iptal isteği gönderilecek.", + "run_notice_unreconciled": "İlgilenmeniz gerekiyor.", + "run_notice_abandoned": "Takip bırakıldı. İş {host} üzerinde bulunursa orx işi durdurur.", + "run_notice_abandoned_no_host": "Takip bırakıldı. İş bulunursa orx işi durdurur.", + "run_notice_the_host": "sunucu", + "run_stop_again": "Yeniden durdur", + "run_abandon": "Takibi bırak…", + "run_abandon_title": "Bu çalıştırmanın takibi bırakılsın mı?", + "run_abandon_body": "OpenResearch bu çalıştırmayı izlemeyi bırakacak. Gerçek hesaplama kaynağının kapatıldığını tekrar kontrol edin.", + "run_abandon_unreachable": "Makineye erişilemiyor.", + "run_abandon_confirm": "Takibi bırak", + "run_abandon_keep": "İzlemeye devam et", + "settings_host_connected": "Bağlandı", + "settings_host_since": "{time} zamanından beri", + "settings_host_since_next_try": "{time} zamanından beri · sonraki deneme: {next}", + "settings_host_test": "Test et", + "settings_ssh_host_needs_connect": "{host} için bağlantı kurmanız gerekiyor", + "settings_ssh_hosts_need_connect": "{count} sunucu için bağlantı kurmanız gerekiyor", + "log_go_start": "Başa git", + "log_go_end": "Sona git", + "log_earlier": "Önceki çıktı", + "log_later": "Sonraki çıktı", + "log_go_to": "Konuma git", + "log_go_to_placeholder": "2.5 GB veya 60%", + "log_position": "{start} / {total}", + "log_position_end": "{total} sonu", + "log_follow": "Takip et", + "log_following": "Takip ediliyor", + "log_paused": "Canlı çıktı duraklatıldı", + "log_range": "Günlük konumu", + "log_loading_from": "{host} üzerinden yükleniyor…", + "log_unavailable": "Günlüğün bu bölümü {host} üzerinde; sunucuya {time} zamanından beri erişilemiyor.", + "log_unavailable_auth": "Günlüğün bu bölümü {host} üzerinde. Bu bölümü yüklemek için bağlantı kurun.", + "run_notice_log_pending": "{host} üzerindeki günlük kaydediliyor…", + "run_notice_log_failed": "{host} üzerindeki günlük kaydedilemedi. orx denemeye devam ediyor; günlük sunucu üzerinden hâlâ açılabilir.", + "run_notice_post_failed": "Bu çalıştırmanın sonucu sohbete gönderilemedi: {error}", + "log_generation_unstable": "Günlük sürekli değişiyor. Yeniden denemek için tekrar yükleyin.", + "status_not_fully_stopped": "Tam durmadı", + "run_stop_now": "Şimdi durdur", + "hover_not_fully_stopped_count": "{count} tam durmadı", + "run_notice_cancel_unreadable": "Sunucu, durdurmayı doğrulamak için {pids} işlemlerini inceleyemedi.", + "run_notice_cancel_uncovered": "Kapsayıcı içindeki veya sunucu taraması dışındaki işlemler kontrol edilemedi.", + "status_cancelled_unconfirmed": "İptal edildi · doğrulanamadı", + "status_stopping_zero": "Tam durmadı · {host} üzerinde {count} işlem hâlâ çalışıyor", + "status_stopping_one": "Tam durmadı · {host} üzerinde {count} işlem hâlâ çalışıyor", + "status_stopping_two": "Tam durmadı · {host} üzerinde {count} işlem hâlâ çalışıyor", + "status_stopping_few": "Tam durmadı · {host} üzerinde {count} işlem hâlâ çalışıyor", + "status_stopping_many": "Tam durmadı · {host} üzerinde {count} işlem hâlâ çalışıyor", + "status_stopping_other": "Tam durmadı · {host} üzerinde {count} işlem hâlâ çalışıyor", + "settings_run_engine_label": "Yeni deney motoru", + "settings_run_engine_description": "Yeni motor, bağlantı kesintileri ve uygulama yeniden başlatmalarında uzak çalıştırmaları sürdürür, iptali doğrular ve birçok SSH kararlılık sorununu giderir.", + "settings_run_engine_override": "Bu sunucu ayarı ORX_RUN_ENGINE tarafından kontrol edilir.", + "settings_run_engine_canary": "Canary derlemeleri her zaman yeni motoru kullanır.", + "settings_run_engine_note": "Hâlâ test ediliyor. Yeni çalıştırmalar için geçerlidir.", + "run_notice_provider_auth": "Sağlayıcı erişimi reddetti. Ayarlar → Ortam bölümünde kimlik bilgilerinizi kontrol edin.", + "run_notice_cluster_auth": "Kubernetes erişimi reddetti. Kubeconfig dosyanızı ve küme izinlerini kontrol edin." } diff --git a/ui/messages/zh-CN.json b/ui/messages/zh-CN.json index c2d07f0e2..f6025adea 100644 --- a/ui/messages/zh-CN.json +++ b/ui/messages/zh-CN.json @@ -1648,5 +1648,87 @@ "remote_agents_description": "每台机器都需要安装代理并分别登录。请在 {host} 上完成设置。", "remote_claude_datacenter_title": "避免在数据中心 IP 上使用 Claude 订阅", "remote_claude_datacenter_description": "{host} 使用数据中心 IP {ip}。在此使用 Claude 订阅可能导致 Anthropic 标记你的账户。请改用 API 密钥,或自行承担风险继续。", - "remote_claude_datacenter_continue": "仍然继续" + "remote_claude_datacenter_continue": "仍然继续", + "chat_panel_remove_file": "移除文件", + "chat_panel_remove_image": "移除图片", + "account_local_to_app": "账户属于此应用的本地账户", + "chat_panel_requested_an_experiment_stop": "已请求停止实验", + "delete_pending_stop_warning": "删除也会取消待处理的停止请求;远程任务可能会继续运行。", + "status_submitting": "正在提交", + "status_unreachable": "无法连接", + "status_needs_auth": "需要身份验证", + "status_unconfirmed": "未确认", + "status_abandoned": "已放弃", + "status_last_seen": "最后一次看到:{time}", + "run_notice_rental_key_cancelled": "已自动停止:机器连续 15 分钟拒绝其 SSH 密钥。", + "run_notice_rental_outcome_unavailable": "结果不可用:在收集最终结果之前,租用的机器已被释放。", + "run_notice_rental_billing": "租用的机器仍在计费。取消运行以停止机器。", + "run_stop_box": "停止机器", + "run_notice_unreachable": "自 {time} 起无法连接 {host}。", + "run_notice_retry_at": "将于 {time} 重试。", + "run_notice_provider_auth": "提供商拒绝了访问。请在设置 → 环境中检查其凭据。", + "run_notice_cluster_auth": "Kubernetes 拒绝了访问。请检查 kubeconfig 和集群权限。", + "run_notice_needs_auth": "连接到 {host} 以继续跟踪此运行。", + "run_notice_unconfirmed_launch": "无法确认启动。正在重新检查。", + "run_notice_cancel_pending": "自 {time} 起无法连接到 {host}。", + "run_notice_cancel_pending_auth": "连接到 {host} 以发送取消请求。", + "run_notice_cancel_pending_later": "机器恢复连接后将发送取消请求。", + "run_notice_cancel_pending_launch": "确认启动后将发送取消请求。", + "run_notice_stops_if_found": "如果作业出现,orx 会将其停止。", + "run_notice_unreconciled": "需要处理。", + "run_notice_abandoned": "已放弃。如果作业在 {host} 上出现,orx 会将其停止。", + "run_notice_abandoned_no_host": "已放弃。如果作业出现,orx 会将其停止。", + "run_notice_the_host": "主机", + "run_stop_again": "再次停止", + "run_abandon": "放弃…", + "run_abandon_title": "放弃此运行?", + "run_abandon_body": "OpenResearch 将停止跟踪此运行。请再次确认实际计算资源已关闭。", + "run_abandon_body_no_host": "orx 将停止等待并将其标记为已放弃。如果作业稍后出现,orx 会届时将其停止。", + "run_abandon_confirm": "放弃运行", + "run_abandoning": "正在放弃…", + "settings_host_connected": "已连接", + "settings_host_since": "自 {time} 起", + "settings_host_since_next_try": "自 {time} 起 · 下次尝试 {next}", + "settings_host_test": "测试", + "settings_ssh_host_needs_connect": "{host} 需要你连接", + "settings_ssh_hosts_need_connect": "{count} 台主机需要你连接", + "log_go_start": "转到开头", + "log_go_end": "转到结尾", + "log_earlier": "之前的输出", + "log_later": "之后的输出", + "log_go_to": "转到位置", + "log_go_to_placeholder": "2.5 GB 或 60%", + "log_position": "{start} / {total}", + "log_position_end": "结尾 / {total}", + "log_follow": "跟随", + "log_following": "正在跟随", + "log_paused": "实时输出已暂停", + "log_range": "日志位置", + "log_loading_from": "正在从 {host} 加载…", + "log_unavailable": "这部分日志在 {host} 上,自 {time} 起无法连接。", + "log_unavailable_auth": "这部分日志在 {host} 上。连接后即可加载。", + "run_notice_log_pending": "正在从 {host} 保存日志…", + "run_notice_log_failed": "无法从 {host} 保存日志。orx 会继续尝试;日志仍可从主机打开。", + "run_notice_post_failed": "无法将此运行的结果发布到聊天:{error}", + "log_generation_unstable": "The log keeps changing. Reload to try again.", + "status_not_fully_stopped": "尚未完全停止", + "run_stop_now": "立即停止", + "hover_not_fully_stopped_count": "{count} 个尚未完全停止", + "run_notice_cancel_unreadable": "主机无法检查进程 {pids},因此无法确认其已停止。", + "run_notice_cancel_uncovered": "无法检查容器内或主机扫描范围外的进程。", + "status_cancelled_unconfirmed": "已取消 · 无法确认", + "status_stopping_zero": "未完全停止 · {host} 上仍有 {count} 个进程在运行", + "status_stopping_one": "未完全停止 · {host} 上仍有 {count} 个进程在运行", + "status_stopping_two": "未完全停止 · {host} 上仍有 {count} 个进程在运行", + "status_stopping_few": "未完全停止 · {host} 上仍有 {count} 个进程在运行", + "status_stopping_many": "未完全停止 · {host} 上仍有 {count} 个进程在运行", + "status_stopping_other": "未完全停止 · {host} 上仍有 {count} 个进程在运行", + "status_cancellation_pending": "取消待发送", + "run_abandon_unreachable": "无法连接到机器。", + "run_abandon_keep": "继续跟踪", + "settings_run_engine_label": "新实验引擎", + "settings_run_engine_description": "新引擎让远程运行在断开连接和应用重启后继续执行,验证取消结果,并修复多项 SSH 稳定性问题。", + "settings_run_engine_override": "ORX_RUN_ENGINE 控制此服务器设置。", + "settings_run_engine_canary": "Canary 构建始终使用新引擎。", + "settings_run_engine_note": "仍在测试中。适用于新运行。" } diff --git a/ui/src/App.tsx b/ui/src/App.tsx index d10c31130..8f83a102c 100644 --- a/ui/src/App.tsx +++ b/ui/src/App.tsx @@ -258,6 +258,7 @@ const errorText = (error: unknown) => ltr(error instanceof Error ? error.message export default function App({ runtime, projectId, pane }: { runtime: RuntimeInfo; projectId: string; pane?: Pane }) { const { id: elementId } = useContext(WorkspaceDomContext); + const { onHostConnectRequest } = useWorkspace().events; const { showCustomDialog, showConfirmDialog } = useWorkspace().dialogs; @@ -1065,7 +1066,9 @@ export default function App({ runtime, projectId, pane }: { runtime: RuntimeInfo // Live store updates. useOrxEvents({ onRunLog: (event) => { - if (!event.dataBase64 || streamingRunsRef.current.has(event.runId)) return; + // Engine runs announce growth with an empty delta at the new length. + const produced = event.dataBase64 !== "" || event.offset > 0; + if (!produced || streamingRunsRef.current.has(event.runId)) return; streamingRunsRef.current.add(event.runId); const run = autoOpenRunsRef.current.get(event.runId); if (!run) return; @@ -1621,6 +1624,7 @@ export default function App({ runtime, projectId, pane }: { runtime: RuntimeInfo pendingViewFocus.current = currentView ? null : view; selectMainView(view); }; + useEffect(() => onHostConnectRequest(() => selectMainView("compute")), [selectMainView]); const focusedRegion = useSyncExternalStore(subscribeCommandRegion, commandRegion); useHotkey(appHotkeys["tab.close"], () => { diff --git a/ui/src/api.ts b/ui/src/api.ts index 452e1471e..836923e94 100644 --- a/ui/src/api.ts +++ b/ui/src/api.ts @@ -1,3 +1,4 @@ +import { LogPageUnavailable } from "./logWindow"; // Typed client for the orx up local HTTP API (/api/*). All wire JSON is camelCase. import type { WorkspaceClient } from "./queries/client"; @@ -94,11 +95,16 @@ export interface SessionExperiment { experiment: Experiment; projectName: string; /** Its newest live run, else its newest run: a forced relaunch can leave an older run live. Null until it has been run. */ - currentRun: Pick | null; + currentRun: (Pick & { cancelRequested: boolean }) | null; } -export type RunStatus = "starting" | "running" | "done" | "failed" | "cancelled" | "lost"; -export type RunDisplayStatus = RunStatus | "cancelling"; +export type RunStatus = "submitting" | "starting" | "running" | "done" | "failed" | "cancelled" | "lost"; + +/** How fresh the engine's knowledge of a run is; null means live. */ +export type RunContact = + | { type: "unreachable" | "needs_auth"; since: number; cause: string } + | { type: "unreconciled"; since: number; detail: string } + | { type: "stopping"; since: number; count: number }; export interface Run { id: string; @@ -111,31 +117,20 @@ export interface Run { resultMarkdown?: string | null; createdAt: number; updatedAt: number; + startedAt?: number | null; endedAt?: number | null; exitCode?: number | null; - cancelRequested: boolean; -} - -export function runDisplayStatus(run: Pick): RunDisplayStatus { - const live = run.status === "running" || run.status === "starting"; - return live && run.cancelRequested ? "cancelling" : run.status; -} - -/** Why the supervisor can't currently observe a live run, if it can't. */ -export function runMonitoringError(run: Pick): string | null { - if (run.status !== "running" && run.status !== "starting") return null; - const error = run.backend?.monitoringError; - return typeof error === "string" && error ? error : null; -} - -/** The newest live run's monitoring error: a forced relaunch can leave an older run live. */ -export function experimentMonitoringError( - runs: Pick[], -): string | null { - const newestFirst = [...runs].sort((a, b) => b.createdAt - a.createdAt); - return ( - newestFirst.map(runMonitoringError).find((error) => error !== null) ?? null - ); + contact: RunContact | null; + cancelling: boolean; + cancelUnconfirmed?: number[] | null; + lostReason: string | null; + /** The SSH alias or Slurm login node the run's job lives on. */ + host: string | null; + /** Why the run's latest notice batch was given up on, never reaching its chat. */ + noticeError?: string | null; + /** Copying a finished run's log to this computer; both are absent once the log is kept. */ + logCollection?: "pending" | "failed"; + logCollectionError?: string; } export class RejectedResponseError extends Error {} @@ -246,12 +241,36 @@ export interface Instance extends Run { projectName?: string; } -export interface LogChunk { - generation: string; - offset: number; - dataBase64: string; - nextOffset: number; - eof: boolean; +/** A log file's identity on its host, opaque: a different one means the file was replaced. */ +export type LogIdent = string; + +export type LogPage = + | { + kind: "data"; + ident: LogIdent; + start: number; + /** Base64. */ + data: string; + eof: boolean; + /** Null while a live run's log is still growing on its host. */ + len: number | null; + /** Byte ranges kept on this computer; the rest is read from the host on demand. */ + kept: [number, number][]; + } + | { kind: "reset"; info: { ident: LogIdent; len: number } | null }; + +export type HostStatus = "idle" | "connecting" | "live" | "backoff" | "needs_auth"; + +/** The run engine's connection to one SSH alias. */ +export interface EngineHost { + alias: string; + /** The run directory root this connection serves; one alias can have several. */ + root: string; + status: HostStatus; + class: "key" | "interactive" | null; + sinceMs: number; + nextRetryMs: number | null; + cause: string | null; } export interface DiffPayload { @@ -1560,6 +1579,11 @@ export interface ChatActiveRun { experimentName: string | null; } +export interface RunEngineSettings { + enabled: boolean; + forcedBy: "canary" | "environment" | null; +} + export function createApi( client: WorkspaceClient, invalidation: WorkspaceInvalidation, @@ -1814,8 +1838,28 @@ export function createApi( const cancelRun = (runId: string) => post<{ ok: boolean }>(`/api/runs/${runId}/cancel`).then(() => undefined); - const fetchLog = (runId: string, offset: number, generation?: string) => - get(`/api/runs/${runId}/log?offset=${offset}${generation ? `&generation=${encodeURIComponent(generation)}` : ""}`); + const cleanupRun = (runId: string) => + post<"accepted" | "nothing_lingering">(`/api/runs/${runId}/cleanup`).then(() => undefined); + + const abandonRun = (runId: string) => post(`/api/runs/${runId}/abandon`); + + async function fetchLogPage(runId: string, start: number, end: number, ident: LogIdent | null, signal?: AbortSignal): Promise { + const query = new URLSearchParams({ start: String(start), end: String(end) }); + if (ident !== null) query.set("ident", ident); + const response = await fetch(`/api/runs/${runId}/log?${query}`, { signal }); + if (response.status === 503) { + const body: unknown = await response.clone().json().catch(() => null); + if (typeof body === "object" && body !== null && "since" in body && typeof body.since === "number" && "contact" in body && (body.contact === "unreachable" || body.contact === "needs_auth")) { + const host = "host" in body && typeof body.host === "string" ? body.host : null; + throw new LogPageUnavailable(host, body.since, body.contact); + } + } + return json(response); + } + + const listEngineHosts = (signal?: AbortSignal) => get("/api/compute/hosts", signal); + + const retryEngineHost = (alias: string) => post(`/api/compute/hosts/${encodeURIComponent(alias)}/retry`); const getRunDiff = (runId: string, signal?: AbortSignal) => get(`/api/runs/${runId}/diff`, signal); @@ -2174,6 +2218,10 @@ export function createApi( const trackioPreflight = () => post("/api/settings/trackio/preflight", {}); + const getRunEngine = (signal?: AbortSignal) => get("/api/settings/run-engine", signal); + + const setRunEngine = (enabled: boolean) => post("/api/settings/run-engine", { enabled }); + const getComputeSettings = (projectId?: string, signal?: AbortSignal) => get( `/api/settings/compute${projectId ? `?projectId=${encodeURIComponent(projectId)}` : ""}`, @@ -2215,7 +2263,6 @@ export function createApi( const logoutOpenResearch = () => post<{ ok: boolean }>("/api/settings/openresearch/logout"); const addOpenResearchSshKey = () => post<{ ok: boolean }>("/api/settings/openresearch/ssh-key"); - const getOpenResearchSettings = (signal?: AbortSignal) => get("/api/settings/openresearch", signal); @@ -2634,7 +2681,11 @@ export function createApi( listRuns, listInstances, cancelRun, - fetchLog, + cleanupRun, + abandonRun, + fetchLogPage, + listEngineHosts, + retryEngineHost, getRunDiff, getExperimentDiff, getProjectFile, @@ -2711,6 +2762,8 @@ export function createApi( rayPreflight, getTrackioRuns, trackioPreflight, + getRunEngine, + setRunEngine, getComputeSettings, setComputeDefault, getLocalMachine, diff --git a/ui/src/components/ArchiveMenu.tsx b/ui/src/components/ArchiveMenu.tsx index 30151a52e..0e89e9bc0 100644 --- a/ui/src/components/ArchiveMenu.tsx +++ b/ui/src/components/ArchiveMenu.tsx @@ -110,7 +110,7 @@ export function ArchiveMenu({ id, name, actions, onArchive, onDelete, compact = {actions.remove && } onClick={() => { showConfirmDialog({ title: m.tree_delete_experiment(), - description: m.tree_delete_experiment_confirm({ name }), + description: `${m.tree_delete_experiment_confirm({ name })}\n\n${m.delete_pending_stop_warning()}`, destructive: true, confirmLabel: m.chat_panel_delete(), onConfirm: () => onDelete(id), diff --git a/ui/src/components/ChatPanel.tsx b/ui/src/components/ChatPanel.tsx index 311a88abc..f693e1b47 100644 --- a/ui/src/components/ChatPanel.tsx +++ b/ui/src/components/ChatPanel.tsx @@ -1590,7 +1590,7 @@ function computeToolActivity(part: ChatPart): ToolActivity { return { kind: "project", label: m.chat_panel_waited_for_an_experiment_run(), litCall: litCall ?? undefined }; } if (commandInvokesOrx(command, "exp\\s+cancel")) { - return { kind: "project", label: m.chat_panel_cancelled_an_experiment_run(), litCall: litCall ?? undefined }; + return { kind: "project", label: m.chat_panel_requested_an_experiment_stop(), litCall: litCall ?? undefined }; } const readsProject = commandInvokesOrx(command, "project\\s+view"); if (readsProject && readsExperimentStatus && readsExperimentNotes) { diff --git a/ui/src/components/DetailDrawer.tsx b/ui/src/components/DetailDrawer.tsx index d44545645..f0bf2f464 100644 --- a/ui/src/components/DetailDrawer.tsx +++ b/ui/src/components/DetailDrawer.tsx @@ -2,15 +2,22 @@ import { useWorkspace } from "../workspace"; import { m } from "../paraglide/messages.js"; import { ChartLine, ChevronDown, CircleStop, ExternalLink, ScrollText } from "lucide-react"; import { useEffect, useRef, useState } from "react"; -import { runDisplayStatus, runMonitoringError, timeAgo, type Experiment, type Project, type Run } from "../api"; +import { + timeAgo, + type Experiment, + type Project, + type Run, +} from "../api"; import { ExperimentOverview } from "./ExperimentOverview"; import type { CodeView } from "./CodeTab"; import { LogTerminal } from "./LogTerminal"; -import { StatusBadge } from "./StatusBadge"; +import { RunContactNotice } from "./RunContactNotice"; +import { statusLabel, StatusBadge } from "./StatusBadge"; import { tabOpenGestureHandlers, type TabOpenIntent } from "../tabPreview"; import { useResolvedTheme } from "../theme"; import { Button, ButtonLink, MenuItem } from "./ui"; import { buildHistoryNodes } from "./experimentLineageModel"; +import { runActive, runDisplay } from "../runDisplay"; export type ExperimentView = "overview" | "terminal" | "trackio"; @@ -107,8 +114,7 @@ function TerminalView({ const selectedRun = selectedRunId ? expRuns.find((run) => run.id === selectedRunId) ?? null : expRuns[0] ?? null; - const monitoringError = selectedRun ? runMonitoringError(selectedRun) : null; - const live = selectedRun?.status === "running" || selectedRun?.status === "starting"; + const live = selectedRun ? runActive(selectedRun.status) : false; const theme = useResolvedTheme(); const trackioQuery = useTrackioRuns(experiment.projectId, live); const trackio = trackioQuery.data; @@ -116,9 +122,8 @@ function TerminalView({ const trackioEmbedUrl = view === "trackio" && selectedRun ? trackioRunUrl(trackio, selectedRun.id, { theme }) : null; - const cancelling = Boolean( - selectedRun && live && (selectedRun.cancelRequested || pendingRunId === selectedRun.id), - ); + const display = selectedRun && runDisplay(pendingRunId === selectedRun.id ? { ...selectedRun, cancelling: true } : selectedRun); + const cancelling = live && Boolean(selectedRun?.cancelling || pendingRunId === selectedRun?.id); // expRuns is newest-first, so the oldest run is #1. Number a run by its // position from the end of the list. const runNumber = (id: string) => { @@ -195,13 +200,13 @@ function TerminalView({ {m.experiment_overview_visualize()} )} - {live && ( + {live && display && ( )} - {expRuns.length > 0 && selectedRun && ( + {expRuns.length > 0 && selectedRun && display && (
{historyOpen && ( @@ -229,7 +231,7 @@ function TerminalView({ }} > {m.detail_drawer_run()} {runNumber(r.id)} - + {timeAgo(r.createdAt)} ))} @@ -239,13 +241,9 @@ function TerminalView({ )}
- {monitoringError && ( -

- {monitoringError} -

- )} + {selectedRun && } -
+
{trackioEmbedUrl ? (