Skip to content

fix(relay): rotate relay.log in-process with a size cap - #8096

Closed
Jinwoo-H wants to merge 2 commits into
mainfrom
fix/relay-log-rotation
Closed

Jinwoo-H wants to merge 2 commits into
mainfrom
fix/relay-log-rotation

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Summary

relay.log grows unbounded on long-lived relays. The daemon is launched detached with > relay.log 2>&1 (src/main/ssh/ssh-relay-deploy.ts), which truncates the file only at relaunch. A relay that stays up for days accumulates per-stream stderr lines (fs-handler-file-read.ts stream start/end/error, reconnect flaps, etc.) with no bound, eventually filling small remote hosts' disks.

Fix & design rationale

Rotation is implemented in the relay process (it owns its own stderr; a shell redirect cannot cap size). New src/relay/rotating-log-writer.ts:

  • installRelayLogRotation(logPath) wraps process.stdout.write / process.stderr.write with a RotatingLogWriter. Wrapping the two stream functions captures all relay logging (42 process.stderr.write call sites) without touching each one, and without missing native/early output.
  • The writer opens its own O_APPEND fd to relay.log, tracks bytes, and at the cap closes, rename(relay.log → relay.log.1) (replacing any prior archive), and reopens a fresh relay.log. One archived generation is kept; total footprint ≤ ~2× cap.
  • Wired in relay.ts only for the detached daemon (--connect bridges and --orca-cli are short-lived and return earlier). Deploy passes --log-file <relay.log> on both the POSIX and Windows launch paths.

Cap = 10 MB, one archive. Enough history to diagnose reconnect/sleep-wake sequences while bounding disk on small hosts (e.g. a Raspberry Pi). Justified in a code comment.

Constraints honored

  • (a) Works when the launch fd is a pipe/redirect on all platforms: the writer uses its own append fd via portable node:fs sync calls (openSync/writeSync/renameSync) — no POSIX-only tricks. The shell redirect stays in place so pre-JS boot/crash output is still captured; once JS starts, the in-process rotator owns all subsequent logging.
  • (b) tail -100 ~/.orca-remote/relay-*/relay.log keeps working: the current log is always relay.log; rotation renames the old file to relay.log.1 and reopens relay.log, so the tail target never moves.
  • (c) Crash-safe: writes and rotation are fully guarded — a write or rotation failure disables the rotator and falls back to the original stream (logging degrades to uncapped, never lost). Rotation renames (never deletes) the live file, so there is no window without a log file. Logging can never throw and crash the relay.

Repro / evidence

src/relay/rotating-log-writer.test.ts (4 tests):

  • Writes past the cap → relay.log.1 created, relay.log reset under the cap, no relay.log.2; the newest line lands in the current relay.log (tail-ability).
  • Pre-existing boot output already in relay.log is preserved (append, not truncate).
  • Total footprint capped at ~2× maxBytes (current + one archive).
  • installRelayLogRotation routes process.stderr through the rotator and cleanly restores it.

Before: relay.log size = total lifetime output (unbounded). After: ≤ ~2× cap (20 MB with defaults), current log always at relay.log.

Screenshots

No visual change.

Testing

  • pnpm typecheck
  • oxlint on changed files clean
  • rotating-log-writer.test.ts (4), ssh-relay-deploy*.test.ts, ssh-relay-cross-version-isolation.test.ts pass (43 total)

AI Review Report

Reviewed cross-platform launch: the POSIX launch adds --log-file alongside the existing > relay.log 2>&1; the Windows launch (windowsRelayLaunchCommand, WMI/Invoke-CimMethod) adds --log-file alongside its 1>relay.log 2>relay.err.log split redirects — the rotator points at relay.log (the tail target) on both. Verified detached-mode stdout is not used for protocol (dispatcher sets stdoutAlive=false; the RELAY_SENTINEL stdout write is --connect-only), so wrapping process.stdout.write is safe. No path assumptions beyond the caller-supplied absolute log path. node:fs sync calls are portable to Linux/macOS/Windows remote hosts.

Security Audit

No new input handling, command execution, auth, secrets, or IPC surface. The log path comes from the relay's own launch args (--log-file), not remote input. Rotation only renames/reopens a file the relay already owns; guards ensure a filesystem error degrades logging rather than crashing or corrupting.

Notes

The pre-existing shell redirect is intentionally retained to capture pre-JS boot/crash output; in steady state all logging flows through the in-process rotator, so there is effectively a single active writer to relay.log.

Made with Orca 🐋

Jinwoo-H and others added 2 commits July 10, 2026 05:48
relay.log grows unbounded on long-lived relays: the detached launch redirects
> relay.log 2>&1, which truncates only at relaunch, so per-stream stderr lines
and reconnect flaps accumulate forever and can fill small remote hosts.

Add an in-process RotatingLogWriter (the relay owns its own stderr; a shell
redirect can't cap size). installRelayLogRotation wraps process.stdout/stderr so
all logging (42 call sites) flows through a writer that appends to relay.log,
tracks size, and at 10MB renames relay.log -> relay.log.1 (one archived
generation) and reopens a fresh relay.log. Wired only for the detached daemon;
deploy passes --log-file on the POSIX and Windows launch paths.

Constraints: portable node:fs sync calls (works with pipe/redirect on
Linux/macOS/Windows); the current log is always relay.log so the tail-diagnostics
workflow keeps working; writes and rotation are guarded so a filesystem error
degrades to uncapped logging rather than crashing, and rename (not delete) means
no window without a log file.

Tests cover rotation at the cap, tail-ability, boot-output preservation, ~2x cap
footprint bound, and stderr wrapping/restore.

Co-authored-by: Orca <[email protected]>
Self-review found a HIGH cross-platform bug: on Windows the launch shell holds
its own `1>relay.log` handle without FILE_SHARE_DELETE, so renameSync of the
live file fails (EPERM/EBUSY). The previous rotate() swallowed that, reopened the
un-renamed file, and re-read its full over-cap size — so the cap never held on
Windows AND every subsequent log line churned a failing close/rename/open.

On rename failure, fall back to truncating relay.log in place ('w') so the size
cap still holds and there is no per-line churn. The shell's fd keeps appending at
its own offset but truncation bounds total growth; trade-off is no archived
generation on that path. New test models the rename-blocked case (archive path is
a directory) and asserts the cap still holds (fails pre-fix: 20100 > 4096).

Also fixed a test nit: spy on process.stderr so the post-restore assertion write
does not leak to the real test-runner stderr.

Co-authored-by: Orca <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 3d8fa285-463d-4ae9-b709-445b157a175c

📥 Commits

Reviewing files that changed from the base of the PR and between b7cff03 and eb0f0db.

📒 Files selected for processing (2)
  • src/relay/rotating-log-writer.test.ts
  • src/relay/rotating-log-writer.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/relay/rotating-log-writer.test.ts
  • src/relay/rotating-log-writer.ts

📝 Walkthrough

Walkthrough

Adds a size-capped rotating writer for relay diagnostics, including append-on-start behavior, single-generation rotation, stream interception, restoration, and failure handling. Adds the optional --log-file argument and enables rotation for detached relays. Unix-like and Windows deployment commands now pass the existing relay.log path, while retaining shell redirection. Regression tests cover rotation, file limits, append behavior, rename failures, and stream restoration.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: in-process size-capped rotation for relay.log.
Description check ✅ Passed The description includes all required sections and covers summary, screenshots, testing, review, security, and notes.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
src/relay/rotating-log-writer.test.ts (2)

69-86: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider tightening the archive size assertion.

The archive file is a rotated copy of the previous current log, which was itself capped at maxBytes. Asserting archiveSize <= cap would be a tighter and more meaningful bound than cap * 2, while still validating the single-generation retention guarantee.

♻️ Suggested tighter assertion
-      expect(archiveSize).toBeLessThanOrEqual(cap * 2)
+      expect(archiveSize).toBeLessThanOrEqual(cap)

88-101: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider adding a stdout routing assertion and a failure-fallback test.

The installRelayLogRotation implementation wraps both process.stdout and process.stderr, but this test only verifies stderr routing. A brief assertion that process.stdout.write also lands in the log file would guard against a future regression that accidentally drops the stdout wrapper. Additionally, no test exercises the failure/fallback path (e.g., unwritable log directory) where writer.active is false and output falls back to the original stream.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: f07fdca5-54a0-4bb0-ab73-69fc3939aa4c

📥 Commits

Reviewing files that changed from the base of the PR and between c17d7cd and b7cff03.

📒 Files selected for processing (4)
  • src/main/ssh/ssh-relay-deploy.ts
  • src/relay/relay.ts
  • src/relay/rotating-log-writer.test.ts
  • src/relay/rotating-log-writer.ts

Comment thread src/relay/rotating-log-writer.ts Resolved
@Jinwoo-H

Copy link
Copy Markdown
Contributor Author

Follow-up (commit eb0f0db) fixes a HIGH cross-platform bug caught in self-review:

Windows: rotation never succeeded and churned on every line. On Windows the launch shell holds its own 1>relay.log handle without FILE_SHARE_DELETE, so renameSync of the live relay.log fails (EPERM/EBUSY). The original rotate() swallowed the error, reopened the un-renamed file, and re-read its full over-cap size — so the cap never held on Windows, and once the cap was first hit every subsequent log line paid a failing close/rename/open.

Fix: on rename failure, fall back to truncating relay.log in place (openSync(path, 'w')) so the size cap still holds and there's no per-line churn. The shell's fd keeps appending at its own offset, but truncation bounds total growth. Trade-off: no archived generation on that platform/path (the cap guarantee is what matters).

New test models the rename-blocked case (archive path is a directory so renameSync throws) and asserts the cap still holds — it fails pre-fix (size 20100 > cap 4096) and passes post-fix. Also fixed a test nit (spy on process.stderr so the post-restore assertion write doesn't leak to the runner's stderr).

Verified-correct in review (no change): stdout-as-transport is safe (detached mode sets stdoutAlive=false, no protocol on stdout; sentinel/CLI/connect modes return before rotation installs), no bypass writes (console.warn/error route through the patched process.stderr.write), rotation math (single oversized line lands wholly in the fresh file), and fd/crash safety.

@Jinwoo-H

Copy link
Copy Markdown
Contributor Author

Superseded by #8141, which combines all ten remote-reliability audit fixes, incorporates the valid CodeRabbit follow-ups, and has full CI plus live Electron/SSH validation. Closing this standalone PR so #8141 is the single review target; this fix remains included there.

@Jinwoo-H Jinwoo-H closed this Jul 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant