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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions .github/actions/setup-pnpm/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,11 @@ inputs:
required: false
default: "."

node-heap-percent:
description: "Share of total RAM given to node's --max-old-space-size, exported in NODE_OPTIONS. Skipped when NODE_OPTIONS already sets it (see node_heap.py)."
required: false
default: "75"

outputs:
store-cache-hit:
description: "'true' when the store cache was restored from an exact key match."
Expand All @@ -96,6 +101,16 @@ runs:
timeout 600 python3 "$GITHUB_ACTION_PATH/../cache-maintenance/cache_maintenance.py" \
|| echo "::warning::cache maintenance did not finish (exit $?)"

- name: Size the node heap from runner RAM
shell: bash
env:
HEAP_PERCENT: ${{ inputs.node-heap-percent }}
run: |
set -euo pipefail
py=$(command -v python3 || command -v python)
opts=$(timeout 30 "$py" "$GITHUB_ACTION_PATH/node_heap.py" --percent "$HEAP_PERCENT")
echo "NODE_OPTIONS=$opts" | tee -a "$GITHUB_ENV"

- name: Resolve pnpm settings
id: store-key
shell: bash
Expand Down
81 changes: 81 additions & 0 deletions .github/actions/setup-pnpm/node_heap.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
"""Print NODE_OPTIONS with --max-old-space-size set to a share of total RAM.

Node's default heap (~2-4 GB) kills large builds with "JavaScript heap out of
memory", while a fixed 8192 on a 7 GB hosted runner pushes the box into the
kernel OOM killer instead. Sizing from the machine fixes both. Total, not free,
RAM: the limit caps each node process and reserves nothing, and free RAM at
setup time says little about the build that follows.

A --max-old-space-size the caller already set wins, so a job that needs a
specific value keeps it. If RAM cannot be read, NODE_OPTIONS is left as is.
"""

import argparse
import ctypes
import os
import subprocess
import sys

FLAG = "--max-old-space-size"


def total_mib_linux(meminfo: str = "/proc/meminfo") -> int:
with open(meminfo) as f:
for line in f:
if line.startswith("MemTotal:"):
return int(line.split()[1]) // 1024
raise ValueError("no MemTotal")


def total_mib_macos() -> int:
out = subprocess.run(["sysctl", "-n", "hw.memsize"], capture_output=True, text=True, timeout=10, check=True).stdout
return int(out) // 1048576


def total_mib_windows() -> int:
class MemoryStatus(ctypes.Structure):
_fields_ = [("dwLength", ctypes.c_ulong), ("dwMemoryLoad", ctypes.c_ulong)] + [
(n, ctypes.c_ulonglong)
for n in ("total", "avail", "totalPage", "availPage", "totalVirtual", "availVirtual", "availExtended")
]

status = MemoryStatus()
status.dwLength = ctypes.sizeof(MemoryStatus)
if not ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(status)): # type: ignore[attr-defined]
raise OSError("GlobalMemoryStatusEx failed")
return status.total // 1048576


def total_mib(platform: str = sys.platform) -> int:
if platform.startswith("linux"):
return total_mib_linux()
if platform == "darwin":
return total_mib_macos()
if platform == "win32":
return total_mib_windows()
raise ValueError(f"unsupported platform {platform}")


def node_options(existing: str, total: int, percent: int) -> str:
if FLAG in existing:
return existing
return f"{existing} {FLAG}={total * percent // 100}".strip()


def main(argv: list[str] | None = None) -> int:
p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
p.add_argument("--percent", type=int, default=75)
a = p.parse_args(argv)
existing = os.environ.get("NODE_OPTIONS", "")
try:
total = total_mib()
except (OSError, ValueError, subprocess.SubprocessError) as e:
print(f"::warning::node heap left at default: cannot read RAM ({e})", file=sys.stderr)
print(existing)
return 0
print(node_options(existing, total, a.percent))
return 0


if __name__ == "__main__":
sys.exit(main())
68 changes: 68 additions & 0 deletions .github/actions/setup-pnpm/test_node_heap.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import io
import sys
import tempfile
import unittest
from contextlib import redirect_stderr, redirect_stdout
from pathlib import Path
from unittest import mock

sys.path.insert(0, str(Path(__file__).resolve().parent))

import node_heap
from node_heap import node_options, total_mib, total_mib_linux


class NodeOptionsTest(unittest.TestCase):
def test_sets_share_of_ram(self) -> None:
self.assertEqual(node_options("", 16384, 75), "--max-old-space-size=12288")

def test_appends_to_existing(self) -> None:
self.assertEqual(node_options("--enable-source-maps", 8000, 75), "--enable-source-maps --max-old-space-size=6000")

def test_caller_value_wins(self) -> None:
self.assertEqual(node_options("--max-old-space-size=4096", 64000, 75), "--max-old-space-size=4096")


class TotalTest(unittest.TestCase):
def test_linux_meminfo(self) -> None:
with tempfile.TemporaryDirectory() as d:
f = Path(d) / "meminfo"
f.write_text("MemFree: 1 kB\nMemTotal: 16384000 kB\n")
self.assertEqual(total_mib_linux(str(f)), 16000)

def test_linux_meminfo_missing_total(self) -> None:
with tempfile.TemporaryDirectory() as d:
f = Path(d) / "meminfo"
f.write_text("MemFree: 1 kB\n")
with self.assertRaises(ValueError):
total_mib_linux(str(f))

def test_unknown_platform(self) -> None:
with self.assertRaises(ValueError):
total_mib("plan9")

def test_this_machine_reads(self) -> None:
self.assertGreater(total_mib(), 0)


class MainTest(unittest.TestCase):
def run_main(self, env: dict[str, str]) -> tuple[str, str]:
out, err = io.StringIO(), io.StringIO()
with mock.patch.dict("os.environ", env, clear=True), redirect_stdout(out), redirect_stderr(err):
self.assertEqual(node_heap.main([]), 0)
return out.getvalue().strip(), err.getvalue()

def test_prints_options(self) -> None:
with mock.patch.object(node_heap, "total_mib", return_value=8192):
out, _ = self.run_main({"NODE_OPTIONS": "--x"})
self.assertEqual(out, "--x --max-old-space-size=6144")

def test_unreadable_ram_keeps_existing(self) -> None:
with mock.patch.object(node_heap, "total_mib", side_effect=OSError("nope")):
out, err = self.run_main({"NODE_OPTIONS": "--x"})
self.assertEqual(out, "--x")
self.assertIn("::warning::", err)


if __name__ == "__main__":
unittest.main()
1 change: 0 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@ defaults:
shell: bash --noprofile --norc -euo pipefail {0}

env:
NODE_OPTIONS: --max-old-space-size=4096
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: "0"
CARGO_NET_RETRY: "10"
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ Utility action for debugging that prints various GitHub Actions contexts (github
Automatically installs the Rust toolchain based on your project's `rust-toolchain.toml` configuration. Extracts the toolchain channel, targets, and components from the config file and applies them using the dtolnay/rust-toolchain action.

### setup-pnpm
Installs node (`actions/setup-node`) and pnpm (`pnpm/action-setup`, version from `packageManager` unless given), restores the pnpm store cache under `pnpm-store-<os>-<arch>-<lockfile hash>` (hosted runners only by default) and runs `pnpm install --frozen-lockfile`. Every step is an input with a default: `node-version`/`node-version-file`, `pnpm-version`, `store-path`, `install-args`, `run-install`, `working-directory`.
Installs node (`actions/setup-node`) and pnpm (`pnpm/action-setup`, version from `packageManager` unless given), restores the pnpm store cache under `pnpm-store-<os>-<arch>-<lockfile hash>` (hosted runners only by default) and runs `pnpm install --frozen-lockfile`. Exports `NODE_OPTIONS` with `--max-old-space-size` at `node-heap-percent` (75) of total RAM unless the caller already set it (`node_heap.py`). Every step is an input with a default: `node-version`/`node-version-file`, `pnpm-version`, `store-path`, `install-args`, `run-install`, `working-directory`.

### restore-cache / save-cache
Generic pair over `actions/cache/restore` and `actions/cache/save` using the key `<name>-<os>-<arch>-<hashFiles(key-files)><suffix>`; restore falls back to the newest `<name>-<os>-<arch>-` entry. Both skip self-hosted runners unless told otherwise.
Expand Down
Loading