ci(block): bound runner disk use and clean job workspaces

This commit is contained in:
pingqiu committed 2026-12-04 23:56:51 -08:00
1 parent 35c6faf789
commit 9bdd7f25e0
6 files changed
+369 -1

No files matched your search

@@ -0,0 +1,91 @@
"""Exercise the actual pre-checkout and always-run cleanup workflow bodies."""
import contextlib
import io
import os
from pathlib import Path
import shutil
import tempfile
import textwrap
import unittest
from unittest.mock import patch
ROOT = Path(__file__).resolve().parents[3]
WORKFLOWS = sorted((ROOT / ".github/workflows").glob("block-*.yml"))
def step(text, name):
marker = " - name: " + name + "\n"
if text.count(marker) != 1:
raise AssertionError("missing or duplicate " + name)
return text.split(marker, 1)[1].split("\n - name:", 1)[0]
def code(block):
return textwrap.dedent(block.split(" run: |\n", 1)[1]).split("python3 - <<'PY'\n", 1)[1].rsplit("\nPY", 1)[0]
def execute(source, workspace, temp, free=None):
output = io.StringIO()
with patch.dict(os.environ, {"GITHUB_WORKSPACE": str(workspace), "RUNNER_TEMP": str(temp)}), contextlib.redirect_stdout(output):
with contextlib.ExitStack() as stack:
if free is not None:
stack.enter_context(patch("shutil.disk_usage", return_value=shutil._ntuple_diskusage(100_000_000_000, 0, free)))
try:
exec(compile(source, "<workflow>", "exec"), {})
except SystemExit as err:
return err.code, output.getvalue()
return 0, output.getvalue()
class RunnerWorkspaceTests(unittest.TestCase):
def test_every_job_checks_before_checkout_and_cleans_last_even_on_failure(self):
for path in WORKFLOWS:
text = path.read_text()
before = step(text, "Runner free space")
after = step(text, "Clean job workspace")
self.assertLess(text.index("- name: Runner free space"), text.index("- name: Checkout"), path.name)
self.assertIn("if: always() && runner.environment == 'self-hosted'", after)
self.assertNotIn("continue-on-error", after)
self.assertNotIn("- name:", text.split("- name: Clean job workspace", 1)[1])
self.assertIn("working-directory: ${{ runner.temp }}", before)
self.assertIn("working-directory: ${{ runner.temp }}", after)
def test_low_space_refuses_and_boundary_admits(self):
for path in WORKFLOWS:
source = code(step(path.read_text(), "Runner free space"))
with tempfile.TemporaryDirectory() as temp:
root = Path(temp)
rc, out = execute(source, root, root, 9_999_999_999)
self.assertEqual(rc, 75)
self.assertIn("runner_disk_low", out)
self.assertIn("required_bytes=10000000000", out)
self.assertEqual(execute(source, root, root, 10_000_000_000)[0], 0)
with patch("shutil.disk_usage", side_effect=[shutil._ntuple_diskusage(100, 0, 10_000_000_000), shutil._ntuple_diskusage(100, 0, 1)]):
rc, out = execute(source, root / "work", root / "temp")
self.assertEqual(rc, 75)
self.assertIn("runner_disk_low", out)
with patch("shutil.disk_usage", side_effect=OSError("probe failed")):
rc, out = execute(source, root, root)
self.assertEqual(rc, 75)
self.assertIn("runner_disk_check_failed", out)
def test_cleanup_removes_hidden_and_build_files_but_not_symlink_targets(self):
for path in WORKFLOWS:
source = code(step(path.read_text(), "Clean job workspace"))
with tempfile.TemporaryDirectory() as temp:
root = Path(temp); work = root / "repo/repo"; work.mkdir(parents=True)
(work / ".git").mkdir(); (work / ".git/config").write_text("config")
(work / "binary").write_bytes(b"build")
outside = root / "outside"; outside.mkdir(); (outside / "keep").write_text("keep")
(work / "link").symlink_to(outside, target_is_directory=True)
rc, out = execute(source, work, root)
self.assertEqual(rc, 0, out)
self.assertEqual(list(work.iterdir()), [])
self.assertTrue((outside / "keep").is_file())
self.assertEqual(execute(source, root, root)[0], 1)
self.assertEqual(execute(source, Path(root.anchor), root)[0], 1)
alias = root / "alias"; alias.symlink_to(work, target_is_directory=True)
self.assertEqual(execute(source, alias, root)[0], 1)
if __name__ == "__main__": unittest.main()
+55
View File
@@ -26,6 +26,26 @@ jobs:
CGO_ENABLED: "0"
SEAWEED_KNOWN_BUGS: "1"
steps:
- name: Runner free space
working-directory: ${{ runner.temp }}
run: |
python3 - <<'PY'
import os
import shutil
import sys
required = 10_000_000_000
for path in dict.fromkeys((os.environ["GITHUB_WORKSPACE"], os.environ["RUNNER_TEMP"])):
try:
free = shutil.disk_usage(path).free
except OSError as err:
print(f"runner_disk_check_failed path={path!r} error={err}")
sys.exit(75)
if free < required:
print(f"runner_disk_low path={path!r} free_bytes={free} required_bytes={required}")
sys.exit(75)
print(f"runner_disk_ok path={path!r} free_bytes={free} required_bytes={required}")
PY
- name: Checkout
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
with:
@@ -68,3 +88,38 @@ jobs:
#189 ./core/storage/ TestMultiBlockRecordsRequireDistinctOnDiskImplVersion
LIST
[ "$ok" = 1 ]
- name: Clean job workspace
# Hosted runners are disposable; their setup-go cache upload runs in
# a post action and still needs the checkout. Persistent runners do not
# upload that cache, and must release their checkout/build files here.
if: always() && runner.environment == 'self-hosted'
working-directory: ${{ runner.temp }}
run: |
python3 - <<'PY'
import os
from pathlib import Path
import shutil
import sys
workspace = Path(os.environ["GITHUB_WORKSPACE"])
root = workspace.resolve()
# Only this runner's repository checkout, never a parent, temp/cache root or
# a symlink supplied in place of the checkout itself.
if workspace.is_symlink() or root == Path(root.anchor) or root.name != root.parent.name or root == Path(os.environ["RUNNER_TEMP"]).resolve():
print(f"runner_workspace_cleanup_refused path={str(workspace)!r}")
sys.exit(1)
errors = []
if root.exists():
for entry in os.scandir(root):
try:
if entry.is_dir(follow_symlinks=False):
shutil.rmtree(entry.path)
else:
os.unlink(entry.path)
except OSError as err:
errors.append(f"{entry.name}: {err}")
if errors:
print("runner_workspace_cleanup_failed " + "; ".join(errors))
sys.exit(1)
print(f"runner_workspace_clean path={str(root)!r}")
PY
@@ -39,6 +39,26 @@ jobs:
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- name: Runner free space
working-directory: ${{ runner.temp }}
run: |
python3 - <<'PY'
import os
import shutil
import sys
required = 10_000_000_000
for path in dict.fromkeys((os.environ["GITHUB_WORKSPACE"], os.environ["RUNNER_TEMP"])):
try:
free = shutil.disk_usage(path).free
except OSError as err:
print(f"runner_disk_check_failed path={path!r} error={err}")
sys.exit(75)
if free < required:
print(f"runner_disk_low path={path!r} free_bytes={free} required_bytes={required}")
sys.exit(75)
print(f"runner_disk_ok path={path!r} free_bytes={free} required_bytes={required}")
PY
- name: Not labelled
if: ${{ !contains(github.event.pull_request.labels.*.name, 'post-merge-review') }}
working-directory: ${{ github.workspace }}
@@ -64,3 +84,38 @@ jobs:
git -c fetch.fsckObjects=true fetch --no-tags origin "+refs/pull/${PR}/head:refs/remotes/pr/head"
bash ../.github/block/scripts/post-merge-review-changed.sh "$BASE" "$HEAD" >changed.bin
bash .github/scripts/post-merge-review-check.sh .github/post-merge-review-allow.txt <changed.bin
- name: Clean job workspace
# Hosted runners are disposable; their setup-go cache upload runs in
# a post action and still needs the checkout. Persistent runners do not
# upload that cache, and must release their checkout/build files here.
if: always() && runner.environment == 'self-hosted'
working-directory: ${{ runner.temp }}
run: |
python3 - <<'PY'
import os
from pathlib import Path
import shutil
import sys
workspace = Path(os.environ["GITHUB_WORKSPACE"])
root = workspace.resolve()
# Only this runner's repository checkout, never a parent, temp/cache root or
# a symlink supplied in place of the checkout itself.
if workspace.is_symlink() or root == Path(root.anchor) or root.name != root.parent.name or root == Path(os.environ["RUNNER_TEMP"]).resolve():
print(f"runner_workspace_cleanup_refused path={str(workspace)!r}")
sys.exit(1)
errors = []
if root.exists():
for entry in os.scandir(root):
try:
if entry.is_dir(follow_symlinks=False):
shutil.rmtree(entry.path)
else:
os.unlink(entry.path)
except OSError as err:
errors.append(f"{entry.name}: {err}")
if errors:
print("runner_workspace_cleanup_failed " + "; ".join(errors))
sys.exit(1)
print(f"runner_workspace_clean path={str(root)!r}")
PY
+55
View File
@@ -21,6 +21,26 @@ jobs:
if: startsWith(github.ref, 'refs/tags/seaweed-block/v')
runs-on: ubuntu-latest
steps:
- name: Runner free space
working-directory: ${{ runner.temp }}
run: |
python3 - <<'PY'
import os
import shutil
import sys
required = 10_000_000_000
for path in dict.fromkeys((os.environ["GITHUB_WORKSPACE"], os.environ["RUNNER_TEMP"])):
try:
free = shutil.disk_usage(path).free
except OSError as err:
print(f"runner_disk_check_failed path={path!r} error={err}")
sys.exit(75)
if free < required:
print(f"runner_disk_low path={path!r} free_bytes={free} required_bytes={required}")
sys.exit(75)
print(f"runner_disk_ok path={path!r} free_bytes={free} required_bytes={required}")
PY
- name: Checkout
uses: actions/checkout@v4
with:
@@ -121,3 +141,38 @@ jobs:
args=(--repo "$GITHUB_REPOSITORY" --verify-tag --latest=false --title "Seaweed Block $version" --notes-file "$NOTES")
if [[ "$version" == *-* ]]; then args+=(--prerelease); fi
gh release create "$GITHUB_REF_NAME" "$out/$asset" "$out/SHA256SUMS" "${args[@]}"
- name: Clean job workspace
# Hosted runners are disposable; their setup-go cache upload runs in
# a post action and still needs the checkout. Persistent runners do not
# upload that cache, and must release their checkout/build files here.
if: always() && runner.environment == 'self-hosted'
working-directory: ${{ runner.temp }}
run: |
python3 - <<'PY'
import os
from pathlib import Path
import shutil
import sys
workspace = Path(os.environ["GITHUB_WORKSPACE"])
root = workspace.resolve()
# Only this runner's repository checkout, never a parent, temp/cache root or
# a symlink supplied in place of the checkout itself.
if workspace.is_symlink() or root == Path(root.anchor) or root.name != root.parent.name or root == Path(os.environ["RUNNER_TEMP"]).resolve():
print(f"runner_workspace_cleanup_refused path={str(workspace)!r}")
sys.exit(1)
errors = []
if root.exists():
for entry in os.scandir(root):
try:
if entry.is_dir(follow_symlinks=False):
shutil.rmtree(entry.path)
else:
os.unlink(entry.path)
except OSError as err:
errors.append(f"{entry.name}: {err}")
if errors:
print("runner_workspace_cleanup_failed " + "; ".join(errors))
sys.exit(1)
print(f"runner_workspace_clean path={str(root)!r}")
PY
+55
View File
@@ -36,6 +36,26 @@ jobs:
runs-on: ${{ (github.event_name == 'push' || github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' || github.event.pull_request.head.repo.full_name == github.repository) && vars.BLOCK_RUNNER_LABEL || 'ubuntu-latest' }}
timeout-minutes: 5
steps:
- name: Runner free space
working-directory: ${{ runner.temp }}
run: |
python3 - <<'PY'
import os
import shutil
import sys
required = 10_000_000_000
for path in dict.fromkeys((os.environ["GITHUB_WORKSPACE"], os.environ["RUNNER_TEMP"])):
try:
free = shutil.disk_usage(path).free
except OSError as err:
print(f"runner_disk_check_failed path={path!r} error={err}")
sys.exit(75)
if free < required:
print(f"runner_disk_low path={path!r} free_bytes={free} required_bytes={required}")
sys.exit(75)
print(f"runner_disk_ok path={path!r} free_bytes={free} required_bytes={required}")
PY
- name: Checkout base
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
with:
@@ -91,3 +111,38 @@ jobs:
env:
HEAD: ${{ github.event.pull_request.head.sha }}
run: python3 -I ../.github/block/scripts/ledger_check.py "$GITHUB_WORKSPACE" "$HEAD" seaweed-block/docs/design/invariants.md seaweed-block/ || true
- name: Clean job workspace
# Hosted runners are disposable; their setup-go cache upload runs in
# a post action and still needs the checkout. Persistent runners do not
# upload that cache, and must release their checkout/build files here.
if: always() && runner.environment == 'self-hosted'
working-directory: ${{ runner.temp }}
run: |
python3 - <<'PY'
import os
from pathlib import Path
import shutil
import sys
workspace = Path(os.environ["GITHUB_WORKSPACE"])
root = workspace.resolve()
# Only this runner's repository checkout, never a parent, temp/cache root or
# a symlink supplied in place of the checkout itself.
if workspace.is_symlink() or root == Path(root.anchor) or root.name != root.parent.name or root == Path(os.environ["RUNNER_TEMP"]).resolve():
print(f"runner_workspace_cleanup_refused path={str(workspace)!r}")
sys.exit(1)
errors = []
if root.exists():
for entry in os.scandir(root):
try:
if entry.is_dir(follow_symlinks=False):
shutil.rmtree(entry.path)
else:
os.unlink(entry.path)
except OSError as err:
errors.append(f"{entry.name}: {err}")
if errors:
print("runner_workspace_cleanup_failed " + "; ".join(errors))
sys.exit(1)
print(f"runner_workspace_clean path={str(root)!r}")
PY
+58 -1
View File
@@ -58,6 +58,26 @@ jobs:
# hosted runner should not depend on a C toolchain being present.
CGO_ENABLED: "0"
steps:
- name: Runner free space
working-directory: ${{ runner.temp }}
run: |
python3 - <<'PY'
import os
import shutil
import sys
required = 10_000_000_000
for path in dict.fromkeys((os.environ["GITHUB_WORKSPACE"], os.environ["RUNNER_TEMP"])):
try:
free = shutil.disk_usage(path).free
except OSError as err:
print(f"runner_disk_check_failed path={path!r} error={err}")
sys.exit(75)
if free < required:
print(f"runner_disk_low path={path!r} free_bytes={free} required_bytes={required}")
sys.exit(75)
print(f"runner_disk_ok path={path!r} free_bytes={free} required_bytes={required}")
PY
- name: Checkout
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
with:
@@ -67,7 +87,9 @@ jobs:
fetch-depth: 2
- name: Nested module CI contracts
run: python3 -I ../.github/block/scripts/block-ci-port-test.py
run: |
python3 -I ../.github/block/scripts/block-ci-port-test.py
python3 -B ../.github/block/scripts/runner-workspace-test.py
- name: Relative documentation links
if: matrix.suite == 'unit'
@@ -369,3 +391,38 @@ jobs:
path: ${{ env.CI_EVIDENCE_DIR }}
retention-days: 14
if-no-files-found: warn
- name: Clean job workspace
# Hosted runners are disposable; their setup-go cache upload runs in
# a post action and still needs the checkout. Persistent runners do not
# upload that cache, and must release their checkout/build files here.
if: always() && runner.environment == 'self-hosted'
working-directory: ${{ runner.temp }}
run: |
python3 - <<'PY'
import os
from pathlib import Path
import shutil
import sys
workspace = Path(os.environ["GITHUB_WORKSPACE"])
root = workspace.resolve()
# Only this runner's repository checkout, never a parent, temp/cache root or
# a symlink supplied in place of the checkout itself.
if workspace.is_symlink() or root == Path(root.anchor) or root.name != root.parent.name or root == Path(os.environ["RUNNER_TEMP"]).resolve():
print(f"runner_workspace_cleanup_refused path={str(workspace)!r}")
sys.exit(1)
errors = []
if root.exists():
for entry in os.scandir(root):
try:
if entry.is_dir(follow_symlinks=False):
shutil.rmtree(entry.path)
else:
os.unlink(entry.path)
except OSError as err:
errors.append(f"{entry.name}: {err}")
if errors:
print("runner_workspace_cleanup_failed " + "; ".join(errors))
sys.exit(1)
print(f"runner_workspace_clean path={str(root)!r}")
PY