relayflowd run.get times out under CPU load and kills the run: a flow's own test suite can destroy 30 steps of journaled work

Merged
AG
2mo ago
+5954-369

A flow's CPU-heavy step could turn a delayed run.get into a terminal root failure. This change reduces read pressure, retries read timeouts, and leaves the root resumable when the daemon still cannot answer.

  • Worker completion waits use journal watch pushes, with snapshots every two seconds for live lease deadlines. Scoped watch sessions close on completion, cancellation, or failure; no new daemon verb is required.
  • Opted-in clients serialize read-only requests and retry timeouts with fresh IDs, escalating bounds, jitter, and a 300-second total budget including queue time. An unconditional lazy reader session avoids blocking behind deterministic commands. Writes and interactive clients retain their existing behavior.
  • Read interruptions skip root terminalization. Both run and resume reports retain the root ID, status: running, and the resume command. A fresh probe distinguishes daemon_unresponsive from daemon_unreachable, without claiming that a failed probe proves the daemon is dead.
  • Heartbeat timeouts become lease loss, so the kernel owns recovery. The standalone CLI's Node child preserves read interruptions across its error frame.

Retry opt-ins: runDirectFlow, declarative executeCheckedFlow, resumeFlow, and authored-node-entry. Worker peers and utility clients keep single-shot bounded requests.

The retry policy, completion wait, and diagnostic classifier live in separate small modules. The existing large transport file retains the typed verb wrappers; cli/run.ts shrinks. No Rust execution logic, journal format, workflow files, or gate definitions change.

Design notes: watches alone cannot unblock a snapshot or child-journal read queued behind a different child's deterministic command, so the unconditional reader remains necessary. The protocol has no run.unwatch; closing each scoped watch connection releases its server watcher. readChildJournal normally reads once per completed child; adopted unfinished children can reread after settling, and retry-backoff inspection can reread. This change does not add a journal cursor cache or daemon snapshot cache.

Validation details and remaining failures are recorded below. “Parked” here means execution is left resumable without a fabricated terminal journal fact; it is not a journaled human park and does not assert journal integrity without reading it.

Validation:

  • Captured commands and literal output: 20 focused files / 210 tests passed, plus the separately added real-daemon resume test. That test suspends the daemon during an actual child read, observes daemon_unresponsive without worker_error terminalization, then resumes the root and checks saved\nafter\n exactly once. The CPU-load case saturates the daemon's CPU allocation (one affinity-pinned core on Linux) while reads remain in flight.
  • Typecheck command and captured result: npx tsc --noEmit and npx tsc -p tsconfig.tests.json, exit 0 with no output.
  • Four mutations were reverted individually, tested failing, restored byte-for-byte, and tested passing: reader routing, two-second cadence, heartbeat lease classification, and root parking. Both outputs and matching source SHA256 values are pasted in the verification transcript. Reproduction script.

The full suite is not green. The final production build was tested with the explicit daemon binary after building the local Surface package; the additional resume test above was added afterward and run separately. Complete full-suite output:

$ cd packages/sdk && RELAYFLOWD_BIN=/home/daytona/.relayflows-toolchain/target/2962130851/debug/relayflowd npm test
 Test Files  6 failed | 248 passed | 1 skipped (255)
      Tests  77 failed | 3774 passed | 22 skipped (3873)
     Errors  1 error

Failing files, copied from that output:

 ❯ tests/live-kernel.test.ts (32 tests | 8 failed) 57015ms
 ❯ tests/hosted-extension-isolation.test.ts (22 tests | 14 failed) 350ms
 ❯ tests/authored-node-runtime.test.ts (16 tests | 16 skipped) 12ms
 ❯ tests/hosted-extension-protocol.test.ts (27 tests | 8 failed) 40086ms
 ❯ tests/canonical-software-factory.test.ts (25 tests | 25 failed) 152ms
 ❯ tests/stuck-run-triage.test.ts (22 tests | 22 failed) 74ms

These include unavailable bubblewrap, the standalone Bun prerequisite, hosted-extension timeouts, Surface flow-identity refusals, and live wrapper/analyzer failures. They remain unresolved here; standalone Bun integration is consequently unverified. One live stub's handshake failure also reproduces using unmodified SDK commit 3c58ee16d10a9e2400db980f5bbafac84e437f20 against the same fixture path: current probe/output, current output, baseline probe, baseline output. This baseline comparison covers that specific failure, not all six suites.

Checks

The checks fail on the base commit too, so these failures were not introduced by this change: they come from the repository itself or from the environment the checks ran in. This pull request is a draft until someone looks.

What ran (.relayflow/check.sh)
#!/bin/sh
set -e
# Fresh-machine equivalent of this repo's CI gates, in CI's own order.
#
# Mirrors, in this order:
#   .github/workflows/cloud-runtime-artifact.yml  (kernel + SDK, the main gate)
#   .github/workflows/schema-publish.yml          (its pull_request `validate` job)
#   .github/workflows/surface-package.yml         (scripts/surface-package-gate.sh)
#   .github/workflows/review-swarm-wrapper-guard.yml (the two parity checks only)
#
# Deliberately NOT run here, because this machine cannot:
#   - publish.yml's publish/pages jobs: NPM_TOKEN / OIDC / GitHub Pages
#     deployment. Its one secret-free check, scripts/publish.test.mjs, is below.
#   - review-swarm.yml and swarm-wrapper-guard.sh: need GH_TOKEN plus a real
#     pull_request_target event, and the swarm needs model credentials.
#   - actions/upload-artifact steps: no artifact store, and nothing checks them.
#   - tests/live-kernel.test.ts's live-analyzer case: needs a `claude` binary and
#     model access. RELAYFLOWS_ALLOW_ANALYZER_SKIP=1 below is exactly what CI
#     sets, and means this run is not gate-2 acceptance evidence.
#   - packages/ts-plugin's `npm test`: no CI workflow runs it today.

ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd -P)
cd "$ROOT"

for tool in node npm bun; do
  command -v "$tool" >/dev/null 2>&1 || {
    echo "check: $tool is required (CI provisions node 22 and bun 1.4.0)" >&2
    exit 127
  }
done

# ---------------------------------------------------------------- toolchains

# CI gets cargo from dtolnay/rust-toolchain: a default toolchain in the standard
# rustup home, driven by plain `cargo`. Reproduce that rather than ops/cargo.sh —
# the wrapper redirects RUSTUP_HOME to a private tree, which leaves a rustup shim
# on PATH with no toolchain to choose ("rustup could not choose a version of
# cargo to run"). That is why the kernel CI steps call cargo directly too.
if ! command -v cargo >/dev/null 2>&1; then
  [ -x "$HOME/.cargo/bin/cargo" ] || curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs \
    | sh -s -- -y --default-toolchain stable --profile minimal --no-modify-path
  PATH="$HOME/.cargo/bin:$PATH"
  export PATH
fi
cargo --version

# Hosted-extension sandbox tests exercise a real bubblewrap namespace command.
# Best-effort: the cases that need it are `it.skipIf(!existsSync('/usr/bin/bwrap'))`,
# so a machine without it still gets a meaningful (smaller) run, and a package
# install is not worth failing the whole check over.
if [ ! -x /usr/bin/bwrap ] && command -v sudo >/dev/null 2>&1 && command -v apt-get >/dev/null 2>&1; then
  sudo apt-get update \
    && sudo apt-get install --yes --no-install-recommends bubblewrap \
    || echo "check: bubblewrap unavailable; sandbox cases will skip themselves" >&2
fi
if [ -x /usr/bin/bwrap ] && sysctl kernel.apparmor_restrict_unprivileged_userns >/dev/null 2>&1; then
  # Ubuntu 24.04 blocks unprivileged user namespaces through AppArmor by default.
  sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0 || true
fi

# ------------------------------------------------------------------ installs

# --ignore-scripts throughout: each package's build is an explicit step below,
# so nothing is skipped, and npm's prepare cannot run before its devDependencies
# exist.
( cd packages/surface && bun install --frozen-lockfile --ignore-scripts && bun run build )
npm ci --prefix packages/sdk --ignore-scripts

# `npm ci` pulls @relayflows/surface from the REGISTRY, not the copy just built.
# Any SDK code importing a symbol that has not shipped yet then fails typecheck.
# `./` is load-bearing: without it npm reads the path as a GitHub shorthand.
npm install ./packages/surface --prefix packages/sdk --no-save --ignore-scripts

# workflows/*.flow.ts import @relayflows/surface from the repo root, where a
# fresh checkout has no node_modules at all; workflow-driving tests cannot load
# their subject without this link.
mkdir -p node_modules/@relayflows
ln -sfn ../../packages/sdk/node_modules/@relayflows/surface node_modules/@relayflows/surface
node -e "console.log(require.resolve('@relayflows/surface'))"

# ------------------------------------------------------- builds and codegen

( cd kernel && cargo build --locked --release -p relayflowd )

# Re-assert the executable bit on the preflight CLI fixtures (test:prep's other
# half). They are committed 100755, but an EACCES deep inside a preflight test is
# opaque enough to be worth one line.
[ ! -d testdata/preflight ] || find testdata/preflight -name '*-cli' -type f -exec chmod +x {} +

# packages/sdk/dist is required: several test files fail at collection without
# it, so a bare `vitest run` is not enough.
npm run typecheck --prefix packages/sdk
npm run build --prefix packages/sdk
npm run typecheck:tests --prefix packages/sdk

# --------------------------------------------------------------------- tests

node --test scripts/cloud-artifact.test.mjs
node --test scripts/publish.test.mjs

( cd kernel && cargo test --workspace )

# The whole SDK suite, not named files: naming files is how ~22 of ~26 test files
# went uncovered. RELAYFLOWD_BIN points at the release binary built above instead
# of compiling a second debug copy through ops/cargo.sh.
( cd packages/sdk \
  && RELAYFLOWS_ALLOW_ANALYZER_SKIP=1 \
     RELAYFLOWD_BIN="$ROOT/kernel/target/release/relayflowd" \
     ./node_modules/.bin/vitest run )

# Committed schema must be regenerable and the generator deterministic. This
# rewrites packages/schema/flows.schema.json in place, exactly as CI does.
node scripts/generate-json-schema.mjs
git diff --exit-code -- packages/schema/flows.schema.json
cp packages/schema/flows.schema.json /tmp/flows.schema.first.json
node scripts/generate-json-schema.mjs
diff -q /tmp/flows.schema.first.json packages/schema/flows.schema.json
( cd packages/schema && bun run test )

# Lens parity between the pre-swarm runner and the cloud swarm spec: pure file
# comparisons, no GitHub context needed. PRESWARM_ALLOW_MISSING_CLI=1 is what the
# guard workflow sets, because no runner has every lens CLI installed.
sh ops/preswarm-check/lens-parity-check.sh
PRESWARM_ALLOW_MISSING_CLI=1 sh ops/preswarm-check/lens-cli-parity-check.sh

# Last on purpose: this gate repacks the surface and installs the TARBALL over
# packages/sdk/node_modules/@relayflows/surface, so running it earlier would
# change the tree the SDK suite above is meant to test. Needs bash (set -o pipefail).
bash scripts/surface-package-gate.sh

# Standalone CLI and cloud artifact, with the verifier and the exact-archive
# smoke. CI uploads the archive afterwards; that upload is the omitted part.
mkdir -p dist/cloud-artifact-input
node scripts/build-standalone-cli.mjs bun-linux-x64 dist/cloud-artifact-input/flows
node scripts/cloud-artifact.mjs build \
  --relayflowd kernel/target/release/relayflowd \
  --flows-executable dist/cloud-artifact-input/flows \
  --output-dir dist/cloud-artifact \
  --source-commit "$(git rev-parse HEAD)"
archive="$(find dist/cloud-artifact -name '*.tar.gz' -type f -print -quit)"
node scripts/cloud-artifact.mjs verify \
  --archive "$archive" \
  --sha256 "$(awk '{print $1}' "$archive.sha256")"
rm -rf dist/cloud-artifact-smoke
mkdir -p dist/cloud-artifact-smoke
tar -xzf "$archive" -C dist/cloud-artifact-smoke
dist/cloud-artifact-smoke/bin/relayflowd --help
dist/cloud-artifact-smoke/bin/flows check --json testdata/hello-deterministic.flow.yaml
Output on this branch (last 80 lines)
 FAIL  tests/live-kernel.test.ts > a relayflow can be scheduled: tick source against live relayflowd > a tick spawns a real run whose step reports the SCHEDULED instant
AssertionError: expected null to deeply equal { schedule_id: 'heartbeat-1m', …(3) }

- Expected: 
Object {
  "lag_ms": 43000,
  "schedule_id": "heartbeat-1m",
  "scheduled_for_ms": 1764000000000,
  "slot": 29400000,
}

+ Received: 
null

 ❯ tests/live-kernel.test.ts:1739:39
    1737|     // The bound: the run reports the grid instant and its own lag, so…
    1738|     // backfilled run can tell it is running for a slot from the past.
    1739|     expect(completed!.payload.output).toEqual({
       |                                       ^
    1740|       schedule_id: 'heartbeat-1m',
    1741|       slot: 29_400_000,

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[22/32]⎯

 FAIL  tests/software-garden-babysitter-composition.test.ts > canonical Software Garden + Babysitter composition > propagates capability denial without a retry or fallback
AssertionError: expected Error: Hosted extension sandbox exited wi… { code: '…' } to be Error: live babysit label is absent // Object.is equality

- Expected
+ Received

- [Error: live babysit label is absent]
+ [Error: Hosted extension sandbox exited without a valid completion (exit 1): bwrap: loopback: Failed RTM_NEWADDR: Operation not permitted
+ ]

 ❯ tests/software-garden-babysitter-composition.test.ts:139:7
    137|       const refusal = new Error('live babysit label is absent');
    138|       let calls = 0;
    139|       await expect(runHostedSoftwareGardenBabysitter({
       |       ^
    140|         flowPath: installed.flowPath,
    141|         dispatch: dispatch(),

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[23/32]⎯

⎯⎯⎯⎯⎯⎯ Unhandled Errors ⎯⎯⎯⎯⎯⎯

Vitest caught 1 unhandled error during the test run.
This might cause false positive tests. Resolve unhandled errors to make sure your tests are not affected.

⎯⎯⎯⎯ Unhandled Rejection ⎯⎯⎯⎯⎯
Error: Hosted extension sandbox exited without a valid completion (exit 1): bwrap: loopback: Failed RTM_NEWADDR: Operation not permitted

 ❯ refuse src/hosted-extension-protocol.ts:135:21
    133|       : new PluginError('plugin_unsupported', 'Hosted capability rejec…
    134|     const refuse = (message: string) => {
    135|       const error = new PluginError('plugin_unsupported', message);
       |                     ^
    136|       CHILD_PROCESS_KILL(child, 'SIGKILL');
    137|       if (capabilityState === 'pending') {
 ❯ ChildProcess.<anonymous> src/hosted-extension-protocol.ts:234:21
 ❯ ChildProcess.emit node:events:520:22
 ❯ maybeClose node:internal/child_process:1084:16
 ❯ Socket.<anonymous> node:internal/child_process:456:11
 ❯ Socket.emit node:events:508:20
 ❯ Pipe.<anonymous> node:net:347:12

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
Serialized Error: { code: 'plugin_unsupported' }
This error originated in "tests/hosted-extension-protocol.test.ts" test file. It doesn't mean the error was thrown inside the file itself, but while it was running.
The latest test that might've caused the error is "rejects two forged calls after the authoritative first outcome settles". It might mean one of the following:
- The error was thrown, while Vitest was running this test.
- If the error occurred after the test had been completed, this was the last documented test before it was thrown.
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯

 Test Files  6 failed | 249 passed | 1 skipped (256)
      Tests  31 failed | 3823 passed | 20 skipped (3874)
     Errors  1 error
   Start at  11:01:00
   Duration  614.66s (transform 4.47s, setup 1.15s, collect 71.72s, tests 1636.42s, environment 33ms, prepare 10.79s)

Output on the base commit (last 80 lines)
cargo 1.99.0 (5f94df478 2026-08-27)
sysctl: permission denied on key "kernel.apparmor_restrict_unprivileged_userns"
/tmp/relayflow-recipe.TWt90j: 66: cd: can't cd to packages/surface

Fixes #522


Summary by cubic

Prevents a CPU-saturated relayflowd from turning slow journal reads into terminal root failures that discard journaled work. Flow-execution clients read on a dedicated session with retries within a 300s budget, and an exhausted read parks the root resumable instead of terminalizing it.

  • Budgeted run.get, journal.read, stream.read, and subscription.inspect run on a dedicated lazy session: serialized, retried with fresh IDs, escalating bounds, jitter, and reconnect on drops. Malformed frames fail closed as JournalFrameError; a dropped reader or primary session is a typed interruption, never worker_error. A socket error during a budgeted post-admission handshake is a non-retryable read interruption, so the authored child and verifier park the root instead of terminalizing it. Communication workers' history reads use the same budget and are scoped to the attempt's lease signal, so a lost lease or shutdown cancels an in-flight history read; an interrupted worker attempt is handed back to the kernel (as a lost lease is) instead of being completed as worker_error.
  • After budget exhaustion, a fresh probe distinguishes daemon_unresponsive from daemon_unreachable; the run stays status: running with the resume command. Only a definite daemon answer (a read refusal, or a journal without a root step) lets root detection resume declaratively; interruptions, cancellations, and daemon-side read failures propagate.
  • A completed run whose stored result can't be read back reports result_unreadable with an unconfirmed verdict (ok: false, exit 1, no completionReason) for any failure but a malformed frame or a journal with no stored result.
  • Completion waits use run.watch pushes with two-second lease snapshots; a push or dropped watch aborts in-flight reads, and a completion already folded from the replay stands even if the watch drops mid-registration (confirmed with one snapshot when the replay may have been truncated). Heartbeat timeouts are lease loss owned by the kernel; helper-effect and communication paths rethrow it instead of worker_error.
  • The lifecycle signal cancels every budgeted read, including the Bun verifier and optional reuse-summary reads, which never overwrite a known outcome. A failed-step inspection that exhausts the budget records inspection_interrupted, and a reuse-summary read is skipped when such a diagnostic exists. The root-lease signal scopes reads for a Bun child's whole attempt; top-level handshakes stay single-shot. A canceled, timed-out, or budget-exhausted read drops the reader so the next attempt opens a fresh session instead of queueing behind the abandoned request, and budget exhaustion aborts a pending reader setup so it frees the queue at once. cancelReads() ends in-flight reads as typed interruptions before the communication workers drain on shutdown, so Ctrl-C does not wait out the read budget and a torn-down worker attempt is handed back to the kernel.

Layout and evidence

  • journal-connection.ts owns framing, socket lifecycle, and request correlation; journal-client.ts keeps options, budgeted-read integration, and typed verbs. The retry policy, completion wait, and readback classification live in journal-budgeted-reads.ts, journal-read-policy.ts, running-step.ts, and authored-root-readback.ts.
  • No Rust execution logic, journal format, workflow files, or gate definitions change. The focused suite (28 files, 343 tests), mutation harness (8/8 fail-then-pass), CPU-load test, and live resume-after-suspend test pass; remaining full-suite failures reproduce on the base commit.

[!NOTE]
Medium Risk
Touches flow execution, worker leases, and CLI outcome reporting when the daemon is slow or unreachable; behavior changes are broad but guarded by tests and leave writes and non-opt-in clients on the old single-shot timeouts.

Overview
Under CPU load or slow relayflowd responses, flows run / flows resume no longer treat a stuck journal read as a terminal root failure. Flow-execution clients opt into a 300s read budget with retries (jitter, reconnect) for run.get, journal.read, stream.read, and subscription.inspect on a dedicated lazy reader session, so reads are not blocked behind long deterministic writes. Interactive clients keep the 30s default and writes are not retried.

When the budget is exhausted, the CLI probes a fresh connection and reports daemon_unresponsive or daemon_unreachable with status: running, the root id, and flows resume—parking execution without inventing a journaled terminal fact. Authored roots and the Bun child path map read interruptions to daemon_unresponsive; new codes include result_unreadable when completion succeeded but the stored result cannot be read back.

Worker completion waits use run.watch pushes with 2s lease snapshot reads; heartbeat timeouts classify as lease loss (kernel recovery) instead of worker_error. Helper effects rethrow lease loss. Optional reuse-summary reads attach after classification without overwriting a resumable outcome.

docs/SURFACE.md and kernel/DAEMON-LIFECYCLE.md document the policy. The diff adds extensive evidence/run-read-timeout/ logs, mutation tests, and focused vitest coverage; no Rust journal format changes are in scope.

Reviewed by Cursor Bugbot for commit 850d7d51611fa580f995aa864f42e69f024a4536. Bugbot is set up for automated code reviews on this repo. Configure here.