From 94e6fcf61cf1e2f3b954f88d5d983a4c5af0d180 Mon Sep 17 00:00:00 2001 From: Ping Qiu Date: Sat, 5 Dec 2026 11:30:00 -0800 Subject: [PATCH] ci: integrate the imported block module workflows (#13360) * ci: port block workflows to the shared repository * ci: preserve policy self-exclusion at the root path * ci: check block documentation relative links * ci: keep the block post-merge-review check on hosted runners The job's own comment records that it ended in 'Set up job' with no log on every self-hosted runner, and the source repository ran it on ubuntu-latest. The port made it follow BLOCK_RUNNER_LABEL, so setting the variable would bring that failure back for every labelled same-repository PR. Co-Authored-By: Claude Opus 5.5 * ci: publish block releases from hosted runners The release job holds contents: write and packages: write and logs in to GHCR, and builds its images with the runner's Docker. Following BLOCK_RUNNER_LABEL put it on the persistent pool that same-repository PR test jobs also use, whose Docker and build cache those jobs can leave state in, and whose Docker setup is still listed as unvalidated. The source repository published from ubuntu-latest; keep that. Co-Authored-By: Claude Opus 5.5 * ci: refuse a block release without notes before pushing images The notes file was first checked in the last step, after both images (and, for the highest stable tag, :alpha) were already pushed to GHCR, so a tag without docs/releases/vX.Y.Z.md left the images published and no GitHub release. Check it with the tag format, before anything is pushed. Co-Authored-By: Claude Opus 5.5 * ci: run the block documentation link check from root scripts The Relative documentation links step called .github/scripts/doc-links-check.py and its test inside seaweed-block/, but neither the imported module nor upstream seaweed-block has them, so the unit suite would fail once the step runs. Add the checker and its test under .github/block/scripts/ with the other port scripts and point the step and its contract test there. Co-Authored-By: Claude Opus 5.5 * ci: use the integrated root documentation link checker * ci(block): bound runner disk use and clean job workspaces * ci(block): pin merge evidence and refuse control changes * ci(block): refuse workspace aliases before cleanup * fix(block-ci): refresh test evidence before reporting readiness * block-ci: judge known bugs with the module helper; list only live reproductions The inline loop called an empty -run match or a skip a fix, and the list still named #188 (closed, test passes) and #189 (test absent), so every nightly run failed. Use known-bugs.sh and its controls, as the module workflow does, and keep only #186: #187's reproduction passes at this revision because values.yaml sets blockmaster.stateHostPath. Co-Authored-By: Claude Opus 5.5 * block-ci: let a release rerun replace the assets of a published tag gh release create fails once the tag's release exists, after both image pushes have already run again. Keep the imported helper's existing-release path: edit the prerelease flag and upload with --clobber. Co-Authored-By: Claude Opus 5.5 * block-ci: list both sides of a move when planning unit packages Without --no-renames a file moved out of core/storage/ shows only its new path, so the planner skipped the package it left. The sibling scope scripts already pass the flag. Co-Authored-By: Claude Opus 5.5 * block-ci: give each master push its own Block Test concurrency group A group admits one running and one pending run; a newer push cancels the pending one even with cancel-in-progress off, so a burst of merges left some without a post-merge result. Key pushes on the commit. Co-Authored-By: Claude Opus 5.5 * block-ci: refuse only control changes the PR itself makes The two-dot diff against current master listed every block workflow master changed after the PR branched, so an older docs-only PR hit workflow_review_required for good. Diff from the merge base; the gate already requires the tested base to be current master. Co-Authored-By: Claude Opus 5.5 * block-ci: check host paths in a labelled post-merge-review PR The changed-path list holds module paths and block controls only, so a labelled PR that also changed host files passed on its module part. Add every other changed path with its root name; the allow list refuses it. The spec-trace scope stays module-only. Co-Authored-By: Claude Opus 5.5 * block-ci: keep the public-text adapter in step with the module checker The root adapter carried the v1.1.0 signatures: it passed /home// paths and run metadata, and an empty docs/spec/**/recorded-* artifact, which the module checker refuses. Take the module's pattern and artifact path check, keep module-relative paths, skip the root adapter's own pattern when run from the root, and run the module self-test against the adapter so the two cannot drift. Co-Authored-By: Claude Opus 5.5 * block-ci: match doc links per paragraph, with nested parentheses and long fences A link whose label wraps onto the next line was never checked, a target such as guide(v2).md was cut at its first ')', and a three-backtick line inside a four-backtick fence closed it. Close a fence only with the same character at least as long, keep one level of balanced parentheses in a destination, and match links over each paragraph. Co-Authored-By: Claude Opus 5.5 * block-ci: test the root wiring the active workflows use The nested self-tests read the module's inactive test.yml, deploy/ Dockerfiles and chunkstore-scope.sh. Assert the docs-only gates in block-test.yml, that each root image refuses every binary it builds, and that the root classifier selects run for chunkstore, storage and durable edits. Co-Authored-By: Claude Opus 5.5 * block-ci: refuse host files in a labelled PR outside the allow list Host paths went through the module allow list, where "*_test.go", "*.md" and "docs/*" also match root files, so a labelled PR changing weed/example_test.go or README.md passed. List host changes separately and fail on any of them; the module list still runs. The port test now runs the step in a scratch repository. Co-Authored-By: Claude Opus 5.5 * block-ci: keep root block CI files clean under the public-text scan The port test fixture spelled out a recorded-artifact path, and the unit group test a pid literal, so the checker flagged both as added lines of any PR that touches them. Build the fixture path from parts, name the pid through a variable, and scan the root block CI files with the checker's own pattern. Co-Authored-By: Claude Opus 5.5 * fix(block-ci): normalize artifact paths from both checker entry points * fix(block-ci): refuse ambiguous merge bases in readiness checks * fix(block-ci): mask code spans that wrap lines before matching links Co-Authored-By: Claude Opus 5.5 * fix(block-ci): publish the draft a rerun of block-release finds An interrupted first run can leave the tag with an unpublished draft. The rerun took the existing-release branch, replaced the assets and exited 0 with the release still a draft. Publish after the uploads, keeping it off the repository's Latest. Co-Authored-By: Claude Opus 5.5 * fix(block-ci): require complete matching code-span delimiters * fix(block-ci): preserve escapes and context when masking code * fix(block-ci): preserve original link destination bytes * fix(block-ci): validate original destination syntax * test(block-ci): cover masked whitespace in reference destinations --------- Co-authored-by: pingqiu Co-authored-by: Chris Lu Co-authored-by: Claude Opus 5.5 --- .github/block/README.md | 41 ++ .github/block/scripts/block-ci-port-test.py | 408 ++++++++++++++++ .github/block/scripts/changed-go-blobs.sh | 30 ++ .github/block/scripts/check-pr-base.sh | 13 + .github/block/scripts/chunkstore-scope.sh | 33 ++ .github/block/scripts/doc-links-check-test.py | 142 ++++++ .github/block/scripts/doc-links-check.py | 128 +++++ .github/block/scripts/docs-only-scope.sh | 35 ++ .github/block/scripts/ledger_check.py | 121 +++++ .../scripts/post-merge-review-changed.sh | 14 + .github/block/scripts/public-text-check.sh | 70 +++ .github/block/scripts/run-unit-groups-test.py | 145 ++++++ .github/block/scripts/run-unit-groups.py | 123 +++++ .../block/scripts/runner-workspace-test.py | 106 +++++ .github/block/scripts/safe-merge-check.py | 132 ++++++ .../block/scripts/unit-test-shards-test.py | 52 ++ .github/block/scripts/unit-test-shards.py | 55 +++ .github/dockerfiles/block-blockcsi.Dockerfile | 27 ++ .github/dockerfiles/block-sw-block.Dockerfile | 24 + .github/workflows/block-known-bugs.yml | 127 +++++ .github/workflows/block-post-merge-review.yml | 146 ++++++ .github/workflows/block-release.yml | 201 ++++++++ .github/workflows/block-spec-trace.yml | 164 +++++++ .github/workflows/block-test.yml | 445 ++++++++++++++++++ 24 files changed, 2782 insertions(+) create mode 100644 .github/block/README.md create mode 100644 .github/block/scripts/block-ci-port-test.py create mode 100644 .github/block/scripts/changed-go-blobs.sh create mode 100644 .github/block/scripts/check-pr-base.sh create mode 100644 .github/block/scripts/chunkstore-scope.sh create mode 100644 .github/block/scripts/doc-links-check-test.py create mode 100644 .github/block/scripts/doc-links-check.py create mode 100644 .github/block/scripts/docs-only-scope.sh create mode 100644 .github/block/scripts/ledger_check.py create mode 100644 .github/block/scripts/post-merge-review-changed.sh create mode 100644 .github/block/scripts/public-text-check.sh create mode 100644 .github/block/scripts/run-unit-groups-test.py create mode 100644 .github/block/scripts/run-unit-groups.py create mode 100644 .github/block/scripts/runner-workspace-test.py create mode 100644 .github/block/scripts/safe-merge-check.py create mode 100644 .github/block/scripts/unit-test-shards-test.py create mode 100644 .github/block/scripts/unit-test-shards.py create mode 100644 .github/dockerfiles/block-blockcsi.Dockerfile create mode 100644 .github/dockerfiles/block-sw-block.Dockerfile create mode 100644 .github/workflows/block-known-bugs.yml create mode 100644 .github/workflows/block-post-merge-review.yml create mode 100644 .github/workflows/block-release.yml create mode 100644 .github/workflows/block-spec-trace.yml create mode 100644 .github/workflows/block-test.yml diff --git a/.github/block/README.md b/.github/block/README.md new file mode 100644 index 0000000000..900337da38 --- /dev/null +++ b/.github/block/README.md @@ -0,0 +1,41 @@ +# Block CI in the shared repository + +The block module stays in `seaweed-block/` with its own `go.mod` and unchanged module path. Root `block-*.yml` workflows run shell commands there; action inputs name the subdirectory explicitly. The imported subtree is unchanged: every port file lives under root `.github/`. Existing module scripts and data remain base-owned inputs; only the Git adapters, unit-group coordinator and relative documentation link check live in root `.github/block/scripts/`. The existing nested workflows are inert because GitHub only discovers root workflows. + +PR and master-push workflows select `seaweed-block/**` and their root block workflow files. All jobs default to `ubuntu-latest`. Set the repository variable `BLOCK_RUNNER_LABEL` only after the corresponding dedicated runner label is registered and available; same-repository/trusted events of the test, spec-trace and known-bugs jobs then use that label. The post-merge-review paths check and the release always run hosted. Fork PRs always use GitHub-hosted runners. GitHub Actions cannot fall back after requesting an unavailable label, so an unset variable is the explicit safe default. Unset it again if the registered pool is withdrawn. Runner discovery would require runner-management API access that the read-only workflow token does not have; no new credential is requested. + +The unit check keeps `go test (linux)` and `process-level tests (real binaries)` under workflow `Block Test`. Module-relative diff/blob adapters preserve the block model map and allow list. Root block workflow/Docker recipe changes still pass the block trace/public-text checks; unrelated host code is excluded. No imported module paths or product formats change. + +## Read-only merge checks + +From a trusted current master checkout, run inside the module: + +```sh +python3 ../.github/block/scripts/safe-merge-check.py 123 +``` + +It requires an open, ready, mergeable PR, the latest successful `Block Test` run at its exact head against current master, both successful named jobs, and the base-owned spec-trace/public-text checks. It rechecks head/base after inspection. It never merges or comments. The manager performs the authorized squash merge with `--match-head-commit`. + +For a batch, preserve its builder's exact order in a local manifest: + +```json +{"base":"BASE_SHA","batch_pr":123,"head":"BATCH_SHA","prs":[{"number":121,"head":"HEAD_121","evidence":"evidence/121.txt"},{"number":122,"head":"HEAD_122","evidence":"evidence/122.txt"}]} +``` + +```sh +python3 ../.github/block/scripts/safe-merge-check.py --batch batch.json +# After the authorized ordered squash merges, compare master with the printed tested tree: +python3 ../.github/block/scripts/safe-merge-check.py --verify-tree TESTED_TREE_SHA +``` + +The manifest and acceptance files are operator inputs from the batch builder, never files supplied by a PR. Batch readiness refuses a moved master/head, changed order or missing evidence and runs each member's base-owned local checks. Building/pushing a batch and merging remain manager operations. + +## Releases + +Only `seaweed-block/vX.Y.Z[-pre]` tags publish. Image tags omit the namespace and retain the existing block/CSI image names. Only block stable tags decide whether `alpha` advances. Root-context Docker recipes preserve Git revision metadata while building the nested module and retain the lab-binary refusal. + +The Linux amd64 tarball contains `blockmaster`, `blockvolume` and `sw-block` copied from the exact published image digest, with `SHA256SUMS`. The GitHub release uses the namespaced tag and does not replace the shared repository's latest release. Release notes must already exist in the module. No tag, image or release is created by preparation or local tests. + +## Move-window checks + +This revision targets the v1.1.0 import branch. Do not edit files under `seaweed-block/` here; development stays in its source repository until the v1.1.1 history update. The root unit-group helpers project the qualified #1001 source; refresh root CI adapters against the corresponding source when that later import arrives. Run the normal Test workflow, base-owned checks and a controlled nonproduction release rehearsal before enabling real publication. Validate organization runner registration, Docker, GHCR package access, and existing repository rulesets/check names. Existing host workflows are unchanged; their broad Go filters may also select a block-only PR. The first import needs its own reviewed bootstrap evidence: a pre-import master has no block scripts, so neither the new pull_request_target gates nor the base-owned local checker can qualify that initial import from an absent base module. Once the import/port is on the trusted base, subsequent block PRs use these checks. diff --git a/.github/block/scripts/block-ci-port-test.py b/.github/block/scripts/block-ci-port-test.py new file mode 100644 index 0000000000..e763f03a31 --- /dev/null +++ b/.github/block/scripts/block-ci-port-test.py @@ -0,0 +1,408 @@ +"""Local-only checks for the nested-module CI port; no Go suites or publishing.""" +from pathlib import Path +import copy +import importlib.util +import os +import shutil +import re +import subprocess +import tempfile +import unittest +from unittest.mock import patch + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[2] + + +class PortTests(unittest.TestCase): + def test_relative_documentation_links_are_checked(self): + text = (ROOT / ".github/workflows/block-test.yml").read_text() + marker = " - name: Relative documentation links\n" + self.assertEqual(text.count(marker), 1) + step = text.split(marker, 1)[1].split("\n - name:", 1)[0] + self.assertIn("if: matrix.suite == 'unit'", step) + self.assertIn("python3 -B ../.github/block/scripts/doc-links-check-test.py", step) + self.assertIn("python3 -I ../.github/block/scripts/doc-links-check.py .", step) + self.assertNotIn("continue-on-error", step) + self.assertNotIn("|| true", step) + + def test_root_workflows_use_module_run_and_action_paths(self): + for name in ("test", "spec-trace", "post-merge-review", "known-bugs"): + text = (ROOT / (".github/workflows/block-" + name + ".yml")).read_text() + self.assertIn("working-directory: seaweed-block", text) + if name == "post-merge-review": + self.assertIn("runs-on: ubuntu-latest", text) + self.assertNotIn("BLOCK_RUNNER_LABEL", text) + else: + self.assertIn("vars.BLOCK_RUNNER_LABEL", text) + self.assertIn("|| 'ubuntu-latest'", text) + if "go-version-file:" in text: self.assertIn("go-version-file: seaweed-block/go.mod", text) + if name != "known-bugs": + self.assertIn('"seaweed-block/**"', text) + self.assertIn('".github/workflows/block-*.yml"', text) + test = (ROOT / ".github/workflows/block-test.yml").read_text() + self.assertIn("- master", test) + self.assertIn("git diff --relative --name-only --no-renames HEAD^1 HEAD -- .", test) + self.assertIn("go test (linux)", test) + self.assertIn("process-level tests (real binaries)", test) + scope = test.split(" - name: Docs-only pull request\n", 1)[1].split("\n", 2)[1] + self.assertEqual(scope.strip(), "if: matrix.suite == 'process' && github.event_name == 'pull_request'") + self.assertEqual(test.count("if: matrix.suite == 'process' && steps.scope.outputs.docs_only != '1'"), 5) + self.assertNotRegex(test, r"if: matrix\.suite == 'process'\s*\n") + post = (ROOT / ".github/workflows/block-post-merge-review.yml").read_text() + self.assertIn("working-directory: ${{ github.workspace }}", post) + + def test_labelled_post_merge_review_refuses_host_files(self): + post = (ROOT / ".github/workflows/block-post-merge-review.yml").read_text() + step = post.split(" - name: Check changed paths\n", 1)[1].split(" run: |\n", 1)[1].split("\n\n - name:", 1)[0] + script = "\n".join(line[10:] for line in step.splitlines()) + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp); module = root / "seaweed-block" + def git(*args): return subprocess.check_output(["git", *args], cwd=root, timeout=15) + git("init", "-b", "master"); git("config", "user.name", "Example"); git("config", "user.email", "example@example.invalid"); git("config", "commit.gpgsign", "false") + for name in ("post-merge-review-check.sh", "post-merge-review-allow.txt"): + source = ROOT / "seaweed-block/.github" / ("scripts/" + name if name.endswith(".sh") else name) + target = module / ".github" / ("scripts/" + name if name.endswith(".sh") else name) + target.parent.mkdir(parents=True, exist_ok=True); target.write_bytes(source.read_bytes()) + (module / ".github/scripts/post-merge-review-check-test.sh").write_text("exit 0\n") + (root / ".github/block/scripts").mkdir(parents=True) + (root / ".github/block/scripts/post-merge-review-changed.sh").write_bytes((HERE / "post-merge-review-changed.sh").read_bytes()) + git("add", "."); git("commit", "-m", "base"); git("remote", "add", "origin", str(root)) + base = git("rev-parse", "HEAD").decode().strip() + def check(*paths): + git("reset", "-q", "--hard", base) + for path in paths: (root / path).parent.mkdir(parents=True, exist_ok=True); (root / path).write_text("changed\n") + git("add", "--", *paths); git("commit", "-m", "change") + git("update-ref", "refs/pull/1/head", "HEAD") + env = dict(os.environ, BASE=base, HEAD=git("rev-parse", "HEAD").decode().strip(), PR="1") + return subprocess.run(["bash", "-eo", "pipefail", "-c", script], cwd=module, env=env, capture_output=True, timeout=30) + self.assertEqual(check("seaweed-block/docs/a.md").returncode, 0) + for host in ("weed/example_test.go", "README.md", "docs/a.md"): + out = check("seaweed-block/docs/a.md", host) + self.assertEqual(out.returncode, 1, out) + self.assertEqual([l for l in out.stdout.splitlines() if l.startswith(b"DENY")], [b"DENY host " + host.encode() + b" (outside seaweed-block)"]) + + def test_known_bugs_use_the_module_verdict_helper(self): + text = (ROOT / ".github/workflows/block-known-bugs.yml").read_text() + self.assertIn("bash .github/scripts/known-bugs-test.sh", text) + self.assertIn("bash .github/scripts/known-bugs.sh <<'LIST'", text) + rows = text.split("<<'LIST'\n", 1)[1].split("\n LIST", 1)[0].split("\n") + self.assertTrue(rows) + for row in rows: + issue, pkg, test = row.split() + sources = (ROOT / "seaweed-block" / pkg).glob("*_test.go") + self.assertTrue(any("func " + test + "(" in s.read_text() for s in sources), row) + + def test_release_tag_namespace_and_artifact_identity(self): + text = (ROOT / ".github/workflows/block-release.yml").read_text() + self.assertIn('"seaweed-block/v*"', text) + self.assertNotIn('tags:\n - "v*"', text) + self.assertIn("git tag -l 'seaweed-block/v*'", text) + self.assertIn('docker pull "${BLOCK_IMAGE}@${BLOCK_DIGEST}"', text) + self.assertIn('gh release create "$GITHUB_REF_NAME"', text) + self.assertIn('--latest=false', text) + self.assertIn('gh release upload "$GITHUB_REF_NAME" "$out/$asset" "$out/SHA256SUMS" --repo "$GITHUB_REPOSITORY" --clobber', text) + publish = 'gh release edit "$GITHUB_REF_NAME" --repo "$GITHUB_REPOSITORY" --prerelease="$prerelease" --draft=false --latest=false' + self.assertLess(text.index("--clobber"), text.index(publish)) + self.assertIn("runs-on: ubuntu-latest", text) + self.assertNotIn("BLOCK_RUNNER_LABEL", text) + self.assertIn('sw-block-${version}-linux-amd64.tar.gz', text) + self.assertNotIn("go build", text) + self.assertLess(text.index("refusing to publish: release notes"), text.index("docker/build-push-action")) + for name in ("sw-block", "blockcsi"): + recipe = (ROOT / (".github/dockerfiles/block-" + name + ".Dockerfile")).read_text() + self.assertIn("WORKDIR /src/seaweed-block", recipe) + self.assertIn("COPY . /src", recipe) + self.assertGreater(recipe.index("RUN bash scripts/refuse-lab-binary.sh"), recipe.rindex("go build")) + built = re.findall(r"go build -o (\S+)", recipe) + refused = re.search(r"^RUN bash scripts/refuse-lab-binary\.sh (.+)$", recipe, re.M).group(1).split() + self.assertTrue(built) + self.assertEqual(sorted(built), sorted(refused)) + + def test_nested_git_paths_and_blobs_stay_module_relative(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp); module = root / "seaweed-block"; module.mkdir() + def git(*args): + return subprocess.check_output(["git", *args], cwd=root, timeout=15) + git("init", "-b", "master") + git("config", "user.name", "Example"); git("config", "user.email", "example@example.invalid") + git("config", "commit.gpgsign", "false") + (module / "core").mkdir(); (module / "docs").mkdir() + code = module / "core/a.go"; code.write_text("package a\nconst N=1\n") + (root / "host.go").write_text("package host\n") + git("add", "."); git("commit", "-m", "base") + base = git("rev-parse", "HEAD").decode().strip() + (module / "docs/a.md").write_text("documentation\n") + git("add", "."); git("commit", "-m", "docs") + docs = git("rev-parse", "HEAD").decode().strip() + def run(name, *args): + return subprocess.check_output(["bash", str(HERE / name), *args], cwd=module, timeout=20) + self.assertEqual(run("docs-only-scope.sh", base, docs), b"docs_only 1\n") + code.write_text("package a\nconst N=2\n") + (root / "host.go").write_text("package host\nconst Changed=true\n") + git("add", "."); git("commit", "-m", "code") + head = git("rev-parse", "HEAD").decode().strip() + self.assertEqual(run("post-merge-review-changed.sh", docs, head), b"M\0core/a.go\0") + self.assertTrue(run("chunkstore-scope.sh", docs, head).startswith(b"skip 1")) + for durable in ("core/frontend/chunkstore/c.go", "core/storage/s.go", "core/frontend/durable/d.go"): + (module / durable).parent.mkdir(parents=True, exist_ok=True); (module / durable).write_text("package x\n") + git("add", "."); git("commit", "-m", "durable") + self.assertEqual(run("chunkstore-scope.sh", head, "HEAD"), b"run 1 " + durable.encode() + b"\n") + git("reset", "-q", "--hard", head) + blobs = root / "blobs" + run("changed-go-blobs.sh", docs, head, str(blobs)) + self.assertEqual((blobs / "old/core/a.go").read_text(), "package a\nconst N=1\n") + self.assertEqual((blobs / "new/core/a.go").read_text(), "package a\nconst N=2\n") + self.assertFalse((blobs / "new/host.go").exists()) + control = root / ".github/workflows/block-test.yml" + control.parent.mkdir(parents=True) + control.write_text("name: Block Test\n") + git("add", ".github"); git("commit", "-m", "CI control") + control_head = git("rev-parse", "HEAD").decode().strip() + self.assertIn(b".github/workflows/block-test.yml\0", run("post-merge-review-changed.sh", docs, control_head)) + self.assertTrue(run("docs-only-scope.sh", base, control_head).startswith(b"run ")) + checker = root / ".github/block/scripts/public-text-check.sh" + checker.parent.mkdir(parents=True) + checker.write_text("pattern='disk" + "station'\n") + git("add", ".github"); git("commit", "-m", "checker pattern") + pattern_head = git("rev-parse", "HEAD").decode().strip() + title, body = root / "title.txt", root / "body.txt" + title.write_text("CI scope"); body.write_text("Checker patterns") + self.assertEqual(run("public-text-check.sh", control_head, pattern_head, str(title), str(body)), b"public-text: clean\n") + from_root = subprocess.check_output(["bash", str(HERE / "public-text-check.sh"), control_head, pattern_head, str(title), str(body)], cwd=root, timeout=20) + self.assertEqual(from_root, b"public-text: clean\n") + artifact_path = "docs/spec/" + "recorded-example.txt" + artifact = module / artifact_path + artifact.parent.mkdir(parents=True); artifact.write_text("") + git("add", "."); git("commit", "-m", "artifact") + artifact_head = git("rev-parse", "HEAD").decode().strip() + command = ["bash", str(HERE / "public-text-check.sh"), pattern_head, artifact_head, str(title), str(body)] + for cwd in (root, module): + leak = subprocess.run(command, cwd=cwd, capture_output=True, timeout=20) + self.assertEqual(leak.returncode, 1, (cwd, leak.stdout, leak.stderr)) + self.assertIn(b"artifact path: " + artifact_path.encode(), leak.stdout) + git("rm", str(artifact.relative_to(root))); git("commit", "-m", "remove artifact") + deleted = git("rev-parse", "HEAD").decode().strip() + removal = ["bash", str(HERE / "public-text-check.sh"), artifact_head, deleted, str(title), str(body)] + for cwd in (root, module): + result = subprocess.run(removal, cwd=cwd, capture_output=True, timeout=20) + self.assertEqual((result.returncode, result.stdout), (0, b"public-text: clean\n"), result.stderr) + fakebin = root / "fakebin"; fakebin.mkdir() + fakegit = fakebin / "git" + fakegit.write_text("#!/bin/sh\nfor arg; do\n if [ \"$arg\" = --diff-filter=ACMT ]; then\n printf 'docs/spec/partial.txt\\0'\n exit 23\n fi\ndone\nexec \"$PUBLIC_TEXT_REAL_GIT\" \"$@\"\n") + fakegit.chmod(0o755) + env = dict(os.environ, PUBLIC_TEXT_REAL_GIT=shutil.which("git"), PATH=str(fakebin) + os.pathsep + os.environ["PATH"]) + for cwd in (root, module): + result = subprocess.run(removal, cwd=cwd, env=env, capture_output=True, timeout=20) + self.assertEqual(result.returncode, 2, (cwd, result.stdout, result.stderr)) + self.assertIn(b"cannot enumerate artifact paths", result.stderr) + self.assertNotIn(b"public-text: clean", result.stdout) + + def test_public_text_adapter_passes_the_module_self_test(self): + module = ROOT / "seaweed-block/.github/scripts" + pattern = lambda path: [l for l in path.read_text().splitlines() if l.startswith("pat=")] + self.assertEqual(pattern(HERE / "public-text-check.sh"), pattern(module / "public-text-check.sh")) + with tempfile.TemporaryDirectory() as tmp: + for source in (module / "public-text-check-test.sh", HERE / "public-text-check.sh"): + (Path(tmp) / source.name).write_bytes(source.read_bytes()) + subprocess.run(["bash", str(Path(tmp) / "public-text-check-test.sh")], check=True, capture_output=True, timeout=60) + + + def test_root_block_ci_files_pass_the_public_text_scan(self): + pat = next(l for l in (HERE / "public-text-check.sh").read_text().splitlines() if l.startswith("pat='"))[5:-1] + files = [p for p in (ROOT / ".github/block").rglob("*") if p.is_file() and "__pycache__" not in p.parts and p.name != "public-text-check.sh"] + files += sorted((ROOT / ".github/workflows").glob("block-*.yml")) + sorted((ROOT / ".github/dockerfiles").glob("block-*.Dockerfile")) + hits = subprocess.run(["grep", "-E", "-i", "-n", "-H", "--", pat, *map(str, files)], capture_output=True, timeout=20) + self.assertEqual(hits.returncode, 1, hits.stdout.decode() + hits.stderr.decode()) + + def test_safe_merge_refuses_wrong_head_base_and_incomplete_jobs(self): + spec = importlib.util.spec_from_file_location("safe_merge", HERE / "safe-merge-check.py") + check = importlib.util.module_from_spec(spec); spec.loader.exec_module(check) + pr = {"number": 1, "state": "open", "draft": False, "mergeable": True, "base": {"ref": "master"}, "head": {"sha": "head"}} + run = {"path": ".github/workflows/block-test.yml", "name": "Block Test", "head_sha": "head", "status": "completed", "conclusion": "success", "pull_requests": [{"number": 1, "base": {"sha": "base"}}]} + jobs = [{"name": n, "conclusion": "success"} for n in check.JOBS] + check.validate(pr, run, jobs, "base") + for key, value in (("head_sha", "other"), ("conclusion", "cancelled"), ("name", "Other Test")): + wrong = copy.deepcopy(run); wrong[key] = value + with self.assertRaises(ValueError): check.validate(pr, wrong, jobs, "base") + with self.assertRaises(ValueError): check.validate(pr, run, jobs, "moved") + with self.assertRaises(ValueError): check.validate(pr, run, jobs[:1], "base") + failed = copy.deepcopy(jobs); failed[0]["conclusion"] = "failure" + with self.assertRaises(ValueError): check.validate(pr, run, failed, "base") + + def test_same_named_workflow_cannot_satisfy_the_gate(self): + spec = importlib.util.spec_from_file_location("safe_merge", HERE / "safe-merge-check.py") + check = importlib.util.module_from_spec(spec); spec.loader.exec_module(check) + pr = {"number": 1, "state": "open", "draft": False, "mergeable": True, "base": {"ref": "master"}, "head": {"sha": "head"}} + run = {"id": 1, "created_at": "1", "path": ".github/workflows/block-test.yml", "name": "Block Test", "head_sha": "head", "status": "completed", "conclusion": "success", "pull_requests": [{"number": 1, "base": {"sha": "base"}}]} + jobs = [{"name": n, "conclusion": "success"} for n in check.JOBS] + duplicate = dict(run, id=2, created_at="2", path=".github/workflows/pretend.yml") + with self.assertRaises(ValueError): check.validate(pr, duplicate, jobs, "base") + missing = dict(run); del missing["path"] + with self.assertRaises(ValueError): check.validate(pr, missing, jobs, "base") + import json + with patch.object(check, "api", return_value={"workflow_runs": [run, duplicate]}), patch.object(check.subprocess, "check_output", return_value=json.dumps([{"jobs": jobs}]).encode()): + self.assertEqual(check.successful_run(pr, "base")["id"], 1) + with patch.object(check, "api", return_value={"workflow_runs": [duplicate]}): + with self.assertRaises(ValueError): check.successful_run(pr, "base") + + def test_control_path_changes_need_independent_workflow_review(self): + spec = importlib.util.spec_from_file_location("safe_merge", HERE / "safe-merge-check.py") + check = importlib.util.module_from_spec(spec); spec.loader.exec_module(check) + real_output = subprocess.check_output + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + def git(*args): return real_output(["git", *args], cwd=root, timeout=15) + git("init", "-b", "master"); git("config", "user.name", "Example"); git("config", "user.email", "example@example.invalid"); git("config", "commit.gpgsign", "false") + (root / "code.go").write_text("package example") + git("add", "."); git("commit", "-m", "base") + base = git("rev-parse", "HEAD").decode().strip() + for name in (".github/workflows/pretend.yml", ".github/block/scripts/check.py", ".github/dockerfiles/block-image.Dockerfile", "seaweed-block/.github/scripts/record-go-test.sh"): + path = root / name; path.parent.mkdir(parents=True, exist_ok=True); path.write_text("control") + git("add", "."); git("commit", "-m", "control") + added = git("rev-parse", "HEAD").decode().strip() + with patch.object(check.subprocess, "check_output", side_effect=lambda args, **kw: real_output(args, cwd=root, **kw)): + with self.assertRaisesRegex(ValueError, "workflow_review_required"): + check.check_control_paths(base, added) + git("rm", name); git("commit", "-m", "remove") + removed = git("rev-parse", "HEAD").decode().strip() + with patch.object(check.subprocess, "check_output", side_effect=lambda args, **kw: real_output(args, cwd=root, **kw)): + with self.assertRaisesRegex(ValueError, "workflow_review_required"): + check.check_control_paths(added, removed) + (root / "code.go").write_text("package example\nconst N=2") + git("add", "."); git("commit", "-m", "code") + head = git("rev-parse", "HEAD").decode().strip() + with patch.object(check.subprocess, "check_output", side_effect=lambda args, **kw: real_output(args, cwd=root, **kw)): + check.check_control_paths(base, head) + git("checkout", "-q", "-b", "master-later", base) + (root / ".github/workflows").mkdir(parents=True, exist_ok=True) + (root / ".github/workflows/block-test.yml").write_text("master control") + git("add", "."); git("commit", "-m", "master control") + master = git("rev-parse", "HEAD").decode().strip() + with patch.object(check.subprocess, "check_output", side_effect=lambda args, **kw: real_output(args, cwd=root, **kw)): + check.check_control_paths(master, head) + with self.assertRaisesRegex(ValueError, "workflow_review_required"): + check.check_control_paths(head, master) + with patch.object(check, "check_control_paths", side_effect=ValueError("workflow_review_required")), patch.object(check.subprocess, "check_output", side_effect=["base", "head"]), patch.object(check.subprocess, "run") as run: + with self.assertRaisesRegex(ValueError, "workflow_review_required"): + check.local_checks({"number": 1, "body": "body", "title": "title", "head": {"sha": "head"}}, "base") + self.assertEqual(run.call_count, 1) # fetch only; no checker certification + + def test_control_path_diff_refuses_multiple_merge_bases(self): + spec = importlib.util.spec_from_file_location("safe_merge", HERE / "safe-merge-check.py") + check = importlib.util.module_from_spec(spec); spec.loader.exec_module(check) + real_output = subprocess.check_output + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + def git(*args): return real_output(["git", *args], cwd=root, timeout=15).decode().strip() + git("init", "-b", "master") + git("config", "user.name", "Example"); git("config", "user.email", "example@example.invalid") + git("config", "commit.gpgsign", "false") + git("commit", "--allow-empty", "-m", "base"); base = git("rev-parse", "HEAD") + git("checkout", "-q", "-b", "left") + (root / "left.txt").write_text("left") + git("add", "."); git("commit", "-m", "left"); left = git("rev-parse", "HEAD") + git("checkout", "-q", "-b", "right", base) + (root / "right.txt").write_text("right") + git("add", "."); git("commit", "-m", "right"); right = git("rev-parse", "HEAD") + git("checkout", "-q", "left"); git("merge", "--no-ff", right, "-m", "left merge") + left_merge = git("rev-parse", "HEAD") + git("checkout", "-q", "right"); git("merge", "--no-ff", left, "-m", "right merge") + right_merge = git("rev-parse", "HEAD") + self.assertEqual(set(git("merge-base", "--all", left_merge, right_merge).splitlines()), {left, right}) + with patch.object(check.subprocess, "check_output", side_effect=lambda args, **kw: real_output(args, cwd=root, **kw)): + with self.assertRaisesRegex(ValueError, "ambiguous_merge_base"): + check.check_control_paths(left_merge, right_merge) + check.check_control_paths(left, left_merge) + + def test_fork_runner_guard_is_required_not_only_the_fallback(self): + expected = "${{ (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' }}" + for name in ("test", "spec-trace", "known-bugs"): + text = (ROOT / (".github/workflows/block-" + name + ".yml")).read_text() + lines = [line.strip() for line in text.splitlines() if line.strip().startswith("runs-on:")] + self.assertEqual(lines, ["runs-on: " + expected]) + + def test_rerun_during_local_checks_cannot_report_ready(self): + import contextlib + import io + import json + spec = importlib.util.spec_from_file_location("safe_merge", HERE / "safe-merge-check.py") + check = importlib.util.module_from_spec(spec); spec.loader.exec_module(check) + def pr(number): + return {"number": number, "state": "open", "draft": False, "mergeable": True, + "base": {"ref": "master"}, "head": {"sha": str(number)}} + with tempfile.TemporaryDirectory() as tmp: + evidence = Path(tmp) / "acceptance"; evidence.write_text("accepted") + members = [pr(1), pr(2)] + manifest = {"base": "base", "head": "3", "batch_pr": 3, + "prs": [{"number": n, "head": str(n), "evidence": str(evidence)} for n in (1, 2)]} + path = Path(tmp) / "batch.json"; path.write_text(json.dumps(manifest)) + for batch in (False, True): + for outcome in ("in_progress", "failed_run", "failed_job", "new_run", "success"): + with self.subTest(batch=batch, outcome=outcome): + changed = False + observations = [] + number = 3 if batch else 1 + def api(endpoint): + if endpoint == "git/ref/heads/master": return {"object": {"sha": "base"}} + if endpoint.startswith("pulls/"): return pr(int(endpoint.split("/")[-1])) + if endpoint == "git/commits/3": return {"tree": {"sha": "tree"}} + observations.append(("run", changed)) + run = {"id": 10, "run_attempt": 2 if changed else 1, "created_at": "1", + "path": check.WORKFLOW_PATH, "name": "Block Test", "head_sha": str(number), + "status": "completed", "conclusion": "success", + "pull_requests": [{"number": number, "base": {"sha": "base"}}]} + if changed and outcome in ("in_progress", "new_run"): + run.update(status="in_progress", conclusion=None) + if outcome == "new_run": run.update(id=11, created_at="2") + if changed and outcome == "failed_run": run["conclusion"] = "failure" + return {"workflow_runs": [run]} + def jobs(*args, **kwargs): + observations.append(("jobs", changed)) + result = [{"name": name, "conclusion": "success"} for name in check.JOBS] + if changed and outcome == "failed_job": result[0]["conclusion"] = "failure" + return json.dumps([{"jobs": result}]).encode() + def local(*args): + nonlocal changed + changed = True + output = io.StringIO() + with patch.object(check, "api", side_effect=api), patch.object(check.subprocess, "check_output", side_effect=jobs), patch.object(check, "fetch_review_head"), patch.object(check, "local_checks", side_effect=local), contextlib.redirect_stdout(output): + if outcome == "success": + check.main(["--batch", str(path)] if batch else ["1"]) + else: + with self.assertRaises(ValueError): + check.main(["--batch", str(path)] if batch else ["1"]) + if outcome == "success": + self.assertTrue(json.loads(output.getvalue())["ready"]) + else: + self.assertNotIn('"ready": true', output.getvalue()) + self.assertIn(("run", True), observations) + self.assertIn(("jobs", True), observations) + + def test_batch_preserves_pinned_base_heads_order_and_evidence(self): + spec = importlib.util.spec_from_file_location("safe_merge", HERE / "safe-merge-check.py") + check = importlib.util.module_from_spec(spec); spec.loader.exec_module(check) + with tempfile.TemporaryDirectory() as tmp: + evidence = Path(tmp) / "acceptance"; evidence.write_text("review accepted") + prs = [{"number": n, "state": "open", "draft": False, "base": {"ref": "master"}, "head": {"sha": str(n)}} for n in (1, 2)] + manifest = {"base": "base", "head": "batch", "prs": [{"number": p["number"], "head": p["head"]["sha"], "evidence": str(evidence)} for p in prs]} + check.validate_batch(manifest, prs, "base") + with self.assertRaises(ValueError): check.validate_batch(manifest, prs, "moved") + with self.assertRaises(ValueError): check.validate_batch(manifest, list(reversed(prs)), "base") + wrong = copy.deepcopy(prs); wrong[0]["head"]["sha"] = "new" + with self.assertRaises(ValueError): check.validate_batch(manifest, wrong, "base") + batch_manifest = dict(manifest, batch_pr=3) + manifest_path = Path(tmp) / "batch.json" + import json + manifest_path.write_text(json.dumps(batch_manifest)) + replies = {"git/ref/heads/master": {"object": {"sha": "base"}}, "pulls/1": prs[0], "pulls/2": prs[1], "pulls/3": {"number": 3, "head": {"sha": "batch"}}} + with patch.object(check, "api", side_effect=lambda path: replies[path]), patch.object(check, "fetch_review_head", side_effect=ValueError("workflow_review_required")) as fetch, patch.object(check, "successful_run") as run: + with self.assertRaisesRegex(ValueError, "workflow_review_required"): + check.main(["--batch", str(manifest_path)]) + fetch.assert_called_once_with(replies["pulls/3"], "base") + run.assert_not_called() + evidence.write_text("") + with self.assertRaises(ValueError): check.validate_batch(manifest, prs, "base") + + +if __name__ == "__main__": unittest.main() diff --git a/.github/block/scripts/changed-go-blobs.sh b/.github/block/scripts/changed-go-blobs.sh new file mode 100644 index 0000000000..fb2c4328a1 --- /dev/null +++ b/.github/block/scripts/changed-go-blobs.sh @@ -0,0 +1,30 @@ +#!/usr/bin/env bash +# Writes the old and new blob of each changed non-test Go file between two +# commits under /old/ and /new/, for the spec trace's +# kind DOCS (objects only; nothing from the PR is built or run). +# +# usage: changed-go-blobs.sh +# +# The paths come from the PR's tree objects, which git does not check when it +# prints a diff. A path that is absolute or has an empty, '.' or '..' +# component would write outside , so it is refused before anything is +# written (exit 1). +set -euo pipefail +mb=$1 head=$2 out=$3 +prefix=$(git rev-parse --show-prefix) +mkdir -p "$out" +git diff --relative --name-only --no-renames -z "$mb" "$head" -- "*.go" ":(exclude)*_test.go" >"$out/.paths" +while IFS= read -r -d "" p; do + case "/$p/" in + *//* | */./* | */../*) + printf 'changed-go-blobs: refusing path %q\n' "$p" >&2 + exit 1 + ;; + esac +done <"$out/.paths" +while IFS= read -r -d "" p; do + mkdir -p "$out/old/$(dirname "$p")" "$out/new/$(dirname "$p")" + git show "$mb:$prefix$p" >"$out/old/$p" 2>/dev/null || rm -f "$out/old/$p" + git show "$head:$prefix$p" >"$out/new/$p" 2>/dev/null || rm -f "$out/new/$p" +done <"$out/.paths" +rm -f "$out/.paths" diff --git a/.github/block/scripts/check-pr-base.sh b/.github/block/scripts/check-pr-base.sh new file mode 100644 index 0000000000..1c19a30c61 --- /dev/null +++ b/.github/block/scripts/check-pr-base.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +# Run only from a trusted base checkout; HEAD code is inspected as Git objects. +set -euo pipefail +here=$(cd "$(dirname "$0")" && pwd) +base=${1:?BASE}; head=${2:?HEAD}; body=${3:?BODY}; title=${4:?TITLE} +[ "$(git rev-parse HEAD)" = "$(git rev-parse "$base")" ] || { echo "refusing: checkout is not the trusted base" >&2; exit 2; } +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT +mb=$(git merge-base "$base" "$head") +bash "$here/post-merge-review-changed.sh" "$mb" "$head" >"$work/changed.bin" +bash "$here/changed-go-blobs.sh" "$mb" "$head" "$work/blobs" +bash .github/scripts/spec-trace-check.sh "$body" "$work/blobs" .github/model-code-trace.tsv <"$work/changed.bin" +bash "$here/public-text-check.sh" "$mb" "$head" "$title" "$body" diff --git a/.github/block/scripts/chunkstore-scope.sh b/.github/block/scripts/chunkstore-scope.sh new file mode 100644 index 0000000000..995fd07cb6 --- /dev/null +++ b/.github/block/scripts/chunkstore-scope.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +# chunkstore-scope.sh BASE HEAD: decides whether a pull request runs the +# real-filer integration tests. It prints one line: +# "run N FIRST" at least one of the N changed files is under +# core/frontend/chunkstore/, core/storage/ or +# core/frontend/durable/ (FIRST is one) +# "skip N" none of the N changed files is +# and exits 0. Any error (git fails, the list cannot be read) exits nonzero, +# and the caller then runs the tests: an error never selects skip. +# +# The NUL-delimited list is written to a file first and read to its end, so +# no pipe can stop early and leave a writer's error looking like an answer. +set -euo pipefail +[ "$#" -eq 2 ] || { echo "usage: chunkstore-scope.sh BASE HEAD" >&2; exit 2; } +list=$(mktemp) +trap 'rm -f "$list"' EXIT +if ! git diff --relative --name-only --no-renames -z "$1" "$2" -- . >"$list"; then + echo "chunkstore-scope: git diff $1 $2 failed" >&2 + exit 2 +fi +n=0 +hit="" +while IFS= read -r -d '' f; do + n=$((n + 1)) + case $f in + core/frontend/chunkstore/* | core/storage/* | core/frontend/durable/*) [ -n "$hit" ] || hit=$f ;; + esac +done <"$list" +if [ -n "$hit" ]; then + echo "run $n $hit" +else + echo "skip $n" +fi diff --git a/.github/block/scripts/doc-links-check-test.py b/.github/block/scripts/doc-links-check-test.py new file mode 100644 index 0000000000..9635b4a426 --- /dev/null +++ b/.github/block/scripts/doc-links-check-test.py @@ -0,0 +1,142 @@ +"""Relative Markdown links must resolve; code, anchors and URLs are not paths.""" +import contextlib +import importlib.util +import io +from pathlib import Path +import tempfile +import unittest + +spec = importlib.util.spec_from_file_location("links", Path(__file__).with_name("doc-links-check.py")) +links = importlib.util.module_from_spec(spec) +spec.loader.exec_module(links) + + +class DocLinksTests(unittest.TestCase): + def check(self, files): + with tempfile.TemporaryDirectory() as root: + for name, text in files.items(): + path = Path(root, name) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text) + return [(source, target) for source, _, target in links.broken_links(root)] + + def test_existing_targets_pass(self): + broken = self.check({ + "README.md": "[guide](docs/guide.md#start) ![d](docs/d.svg) [dir](docs/) [ref][r]\n\n[r]: \n", + "docs/guide.md": "[up](../README.md) [root](/docs/d.svg) [esc](a%20b.md)\n", + "docs/d.svg": "", + "docs/a b.md": "", + }) + self.assertEqual(broken, []) + + def test_missing_targets_fail(self): + broken = self.check({ + "README.md": "[gone](docs/gone.md) [nested [x]](docs/x.md#a)\n\n[r]: missing.md\n", + "docs/guide.md": "[up](../nope.md)\n", + }) + self.assertCountEqual(broken, [ + ("README.md", "docs/gone.md"), + ("README.md", "docs/x.md#a"), + ("README.md", "missing.md"), + ("docs/guide.md", "../nope.md"), + ]) + + def test_urls_anchors_and_code_are_not_checked(self): + broken = self.check({ + "README.md": "\n".join([ + "[web](https://example.invalid/x) [mail](mailto:a@example.invalid) [top](#top) [proto](//host/x)", + "`[code](gone.md)` and ``[code](gone.md)``", + "```", + "[fenced](gone.md)", + "```", + "~~~md", + "[tilde](gone.md)", + "~~~", + ]) + "\n", + }) + self.assertEqual(broken, []) + + def test_wrapped_labels_parentheses_and_long_fences(self): + with tempfile.TemporaryDirectory() as root: + Path(root, "guide(v2).md").write_text("") + Path(root, "README.md").write_text("\n".join([ + "[guide](guide(v2).md) [old](guide(v1).md)", + "", + "see the [wrapped", + "label](wrapped.md) here", + "", + "`[wrapped", + "code](gone.md)` then [after](after.md)", + "````md", + "```", + "[example](missing.md)", + "```", + "````", + ]) + "\n") + broken = [(line, target) for _, line, target in links.broken_links(root)] + self.assertEqual(broken, [(1, "guide(v1).md"), (3, "wrapped.md"), (7, "after.md")]) + + def test_code_spans_require_complete_equal_delimiter_runs(self): + cases = [ + ("`unmatched\n[real](real.md) ``", [(2, "real.md")]), + ("``unmatched\n[real](real.md) `", [(2, "real.md")]), + ("``unmatched\n[real](real.md) ```", [(2, "real.md")]), + ("`[wrapped\ncode](hidden.md)`\n[after](after.md)", [(3, "after.md")]), + ("``[wrapped `\ncode](hidden.md)``\n[after](after.md)", [(3, "after.md")]), + ] + for text, expected in cases: + with self.subTest(text=text), tempfile.TemporaryDirectory() as root: + Path(root, "README.md").write_text(text + "\n", encoding="utf-8") + broken = [(line, target) for _, line, target in links.broken_links(root)] + self.assertEqual(broken, expected) + + def test_escaped_backticks_do_not_hide_links(self): + cases = [ + ("\\`\n[real](real.md)\n\\`", [(2, "real.md")]), + ("\\\\`[code](hidden.md)`\n[after](after.md)", [(2, "after.md")]), + ("`[code](hidden.md)\\`\n[after](after.md)", [(2, "after.md")]), + ] + for text, expected in cases: + with self.subTest(text=text): + self.assertEqual(list(links.link_targets(text)), expected) + + def test_masked_code_preserves_reference_line_context(self): + text = "Use `code\nmore`[r]: gone.md\n\n[r]: real.md\n" + self.assertEqual(list(links.link_targets(text)), [(4, "real.md")]) + + def test_code_masking_contract(self): + cases = [ + ("unequal runs", "`unmatched\n[real](real.md) ``", [], [(2, "real.md")]), + ("escaped delimiters", "\\`\n[real](real.md)\n\\`", [], [(2, "real.md")]), + ("reference context", "Use `code\nmore`[r]: gone.md\n\n[r]: real.md", [], [(4, "real.md")]), + ("wrapped span", "`[code\nhere](hidden.md)`\n[after](after.md)", [], [(3, "after.md")]), + ("hidden-space invalid target", "[example](`foo bar`)", [], []), + ("hidden-space invalid reference", "[r]: `a b`", [], []), + ("existing literal target", "[example](`foo.md`)", ["`foo.md`"], []), + ("missing literal target", "[example](`foo.md`)", [], [(1, "`foo.md`")]), + ] + for name, text, existing, expected in cases: + with self.subTest(name=name), tempfile.TemporaryDirectory() as root: + Path(root, "README.md").write_text(text + "\n", encoding="utf-8") + for target in existing: + Path(root, target).touch() + broken = [(line, target) for _, line, target in links.broken_links(root)] + self.assertEqual(broken, expected) + masked = links.mask_code_spans(text) + self.assertEqual(len(masked), len(text)) + self.assertEqual([i for i, c in enumerate(masked) if c == "\n"], + [i for i, c in enumerate(text) if c == "\n"]) + + def test_main_exit_status(self): + out = io.StringIO() + with tempfile.TemporaryDirectory() as root, contextlib.redirect_stdout(out), contextlib.redirect_stderr(out): + Path(root, "README.md").write_text("[gone](gone.md)\n") + self.assertEqual(links.main(["doc-links-check.py", root]), 1) + Path(root, "gone.md").write_text("") + self.assertEqual(links.main(["doc-links-check.py", root]), 0) + self.assertEqual(links.main(["doc-links-check.py"]), 2) + self.assertIn("README.md:1: broken relative link gone.md", out.getvalue()) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/block/scripts/doc-links-check.py b/.github/block/scripts/doc-links-check.py new file mode 100644 index 0000000000..926aa2f4e1 --- /dev/null +++ b/.github/block/scripts/doc-links-check.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python3 +"""Fail when a Markdown file links to a relative path that does not exist. + +Usage: doc-links-check.py +""" +import os +import re +import sys +import urllib.parse + +SKIP_DIRS = {".git", "node_modules", "vendor"} +FENCE = re.compile(r"^\s*(`{3,}|~{3,})(.*)$") +BACKTICKS = re.compile(r"`+") +INLINE_DESTINATION = r"<[^>\n]*>|(?:[^\s()]|\([^\s()]*\))+" +REFERENCE_DESTINATION = r"<[^>]*>|\S+" +INLINE_LINK = re.compile(r"!?\[(?:[^\[\]]|\[[^\[\]]*\])*\]\(\s*(" + INLINE_DESTINATION + r")") +REFERENCE = re.compile(r"^[ \t]{0,3}\[[^\]]+\]:\s*(" + REFERENCE_DESTINATION + r")", re.M) +SCHEME = re.compile(r"^[A-Za-z][A-Za-z0-9+.-]*:") + + +def mask_code_spans(text): + runs = list(BACKTICKS.finditer(text)) + masked = list(text) + i = 0 + while i < len(runs): + opening = runs[i] + start = opening.start() + # Only prose escapes delimiters; backslashes inside code are literal. + preceding = start + while preceding > 0 and text[preceding - 1] == "\\": + preceding -= 1 + if (start - preceding) % 2: + start += 1 + width = opening.end() - start + if not width: + i += 1 + continue + closing = next((j for j in range(i + 1, len(runs)) + if len(runs[j].group()) == width), None) + if closing is None: + i += 1 + continue + # Keep columns and non-whitespace line context as well as line numbers. + for pos in range(start, runs[closing].end()): + if text[pos] != "\n": + masked[pos] = "\0" + i = closing + 1 + return "".join(masked) + + +def paragraph_targets(first, lines): + # A link label may wrap, so links are matched per paragraph. + original = "\n".join(lines) + text = mask_code_spans(original) + # Masked bytes are context only, never a synthetic filesystem destination. + found = [] + for regex, syntax in ((INLINE_LINK, INLINE_DESTINATION), (REFERENCE, REFERENCE_DESTINATION)): + for match in regex.finditer(text): + target = original[match.start(1):match.end(1)] + if re.fullmatch(syntax, target): + found.append((match.start(), target)) + for pos, target in sorted(found): + yield first + text.count("\n", 0, pos), target + + +def link_targets(text): + fence, block, first = None, [], 1 + for lineno, line in enumerate(text.splitlines() + [""], 1): + m = FENCE.match(line) + if fence is not None: + # Only a fence of the same character, at least as long, closes it. + if m and m.group(1)[0] == fence[0] and len(m.group(1)) >= len(fence) and not m.group(2).strip(): + fence = None + continue + if m or not line.strip(): + yield from paragraph_targets(first, block) + block = [] + if m: + fence = m.group(1) + continue + if not block: + first = lineno + block.append(line) + + +def local_path(target): + if target.startswith("<") and target.endswith(">"): + target = target[1:-1] + if not target or target.startswith(("#", "//")) or SCHEME.match(target): + return None + path = urllib.parse.unquote(target.split("#", 1)[0].split("?", 1)[0]) + return path or None + + +def broken_links(root): + root = os.path.abspath(root) + for dirpath, dirnames, filenames in os.walk(root): + dirnames[:] = sorted(d for d in dirnames if d not in SKIP_DIRS) + for name in sorted(filenames): + if not name.endswith(".md"): + continue + source = os.path.join(dirpath, name) + with open(source, encoding="utf-8", errors="replace") as f: + text = f.read() + for lineno, target in link_targets(text): + path = local_path(target) + if path is None: + continue + if path.startswith("/"): + resolved = os.path.join(root, path.lstrip("/")) + else: + resolved = os.path.join(dirpath, path) + if not os.path.exists(resolved): + yield os.path.relpath(source, root), lineno, target + + +def main(argv): + if len(argv) != 2: + print(__doc__.strip(), file=sys.stderr) + return 2 + broken = list(broken_links(argv[1])) + for source, lineno, target in broken: + print(f"{source}:{lineno}: broken relative link {target}") + return 1 if broken else 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv)) diff --git a/.github/block/scripts/docs-only-scope.sh b/.github/block/scripts/docs-only-scope.sh new file mode 100644 index 0000000000..0e16b612d8 --- /dev/null +++ b/.github/block/scripts/docs-only-scope.sh @@ -0,0 +1,35 @@ +#!/usr/bin/env bash +# docs-only-scope.sh BASE HEAD: classifies the files changed between BASE and +# HEAD for the process-level suite. It prints one line: +# "docs_only N" every one of the N changed files is under docs/ +# "run N [FIRST-OTHER]" no file changed, or at least one is elsewhere +# and exits 0. Any error (git fails, the list cannot be read) exits nonzero, +# and the caller then runs the tests: an error never selects docs_only. +# +# The NUL-delimited list is written to a file first and read to its end, so +# no pipe can stop early and leave a writer's error looking like an answer. +set -euo pipefail +[ "$#" -eq 2 ] || { echo "usage: docs-only-scope.sh BASE HEAD" >&2; exit 2; } +list=$(mktemp) +trap 'rm -f "$list"' EXIT +if ! git diff --relative --name-only --no-renames -z "$1" "$2" -- . >"$list"; then + echo "docs-only-scope: git diff $1 $2 failed" >&2 + exit 2 +fi +if [ -n "$(git rev-parse --show-prefix)" ]; then + git -C "$(git rev-parse --show-toplevel)" diff --name-only --no-renames -z "$1" "$2" -- '.github/workflows/block-*.yml' '.github/dockerfiles/block-*.Dockerfile' '.github/block/**' >>"$list" +fi +n=0 +other="" +while IFS= read -r -d '' f; do + n=$((n + 1)) + case $f in + docs/*) ;; + *) [ -n "$other" ] || other=$f ;; + esac +done <"$list" +if [ "$n" -gt 0 ] && [ -z "$other" ]; then + echo "docs_only $n" +else + echo "run $n${other:+ $other}" +fi diff --git a/.github/block/scripts/ledger_check.py b/.github/block/scripts/ledger_check.py new file mode 100644 index 0000000000..d255eab967 --- /dev/null +++ b/.github/block/scripts/ledger_check.py @@ -0,0 +1,121 @@ +"""Check that every code and test anchor of the invariants ledger exists at a git ref. + +usage: python -I ledger_check.py [] + +A ledger row is a table line whose first cell holds `INV-...`. In its cells, a +backticked token that ends in .go is a FILE; a backticked identifier (or +Type.Method) is a SYMBOL of the nearest file named before it in the same cell, +or, in the test cell, of any file named in that cell. A file must exist at the +ref; a symbol must occur in its file as a whole word (for a test: `func Name(`). +A symbol with no file in its cell is looked up in the whole tree. A file may +be a glob (`volume_lock*.go`). A lower-case token with an underscore (a build +tag, a JSON key, a reason string) is not a Go symbol and is not checked. +Prints one line per missing anchor and a summary. It reads; it changes nothing. +Exit: 0 when every anchor exists; 1 when one is missing; 2 when git fails or no +row or anchor was found (an error is never read as a pass). +""" +import re +import subprocess +import sys + + +def git(repo, *args): + """git's output. A git failure ends the check with exit 2: an error must + never read as "no anchors". `git grep` finding nothing (exit 1) is not one.""" + r = subprocess.run(["git", "-C", repo] + list(args), capture_output=True, text=True, + encoding="utf-8", errors="replace") + if r.returncode != 0 and not (args and args[0] == "grep" and r.returncode == 1): + print("ledger_check: git %s failed (exit %d): %s" % (" ".join(args[:2]), r.returncode, r.stderr.strip()[:300]), + file=sys.stderr) + sys.exit(2) + return r.stdout + + +def main(): + repo, ref = sys.argv[1], sys.argv[2] + ledger = sys.argv[3] if len(sys.argv) > 3 else "docs/design/invariants.md" + text = git(repo, "show", "%s:%s" % (ref, ledger)) + prefix = sys.argv[4] if len(sys.argv) > 4 else "" + files = set(git(repo, "ls-tree", "-r", "--name-only", ref, "--", prefix or ".").split("\n")) + cache = {} + + def body(path): + if path not in cache: + cache[path] = git(repo, "show", "%s:%s" % (ref, path)) + return cache[path] + + def resolve(tok): + """A file token may be a full path or a bare file name.""" + if tok in files: + return [tok] + if "*" in tok: + rx = re.compile("^(.*/)?" + "[^/]*".join(re.escape(x) for x in tok.split("*")) + "$") + return [f for f in files if rx.match(f)] + if "/" not in tok: + return [f for f in files if f.endswith("/" + tok)] + # a path with a directory matches whole path components only + return [f for f in files if f.endswith("/" + tok)] + + ident = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)?(\(\))?$") + go_all = None + rows = missing = anchors = 0 + for n, line in enumerate(text.split("\n"), 1): + if not line.startswith("|"): + continue + cells = [c.strip() for c in line.strip().strip("|").split("|")] + m = re.match(r"`(INV-[A-Z0-9-]+)`", cells[0]) if cells else None + if not m or len(cells) < 6: + continue + rows += 1 + inv, status = m.group(1), cells[-1] + if "ARCHIVED" in status: + continue + for ci, kind in ((3, "code"), (4, "test")): + toks = re.findall(r"`([^`]+)`", cells[ci]) + cell_files = [] + for t in toks: + if t.endswith(".go"): + cell_files.append(t) + cur = None + for t in toks: + if t.endswith(".go"): + cur = t + anchors += 1 + if not resolve(t): + missing += 1 + print("%s (line %d, %s, %s): file %s does not exist" % (inv, n, kind, status, t)) + continue + if not ident.match(t): + continue + sym = t.rstrip("()").split(".")[-1] + if sym in ("nil", "true", "false") or sym.isupper() or len(sym) < 3: + continue + if "_" in sym and sym == sym.lower(): + # a build tag, a JSON key or a reason string: not a Go symbol + continue + scope = [cur] if (cur and kind == "code") else cell_files + paths = [p for f in scope for p in resolve(f)] + anchors += 1 + if kind == "test" and sym.startswith(("Test", "Fuzz", "Benchmark")): + pat = re.compile(r"func %s\(" % re.escape(sym)) + else: + pat = re.compile(r"\b%s\b" % re.escape(sym)) + if paths: + ok = any(pat.search(body(p)) for p in paths) + else: + if go_all is None: + go_all = git(repo, "grep", "-h", "-E", r"^(func|type|var|const|\s+[A-Za-z_]+\s)", ref, "--", prefix + "*.go") + ok = bool(pat.search(go_all)) + if not ok: + missing += 1 + where = ", ".join(scope) if scope else "the tree" + print("%s (line %d, %s, %s): %s not found in %s" % (inv, n, kind, status, t, where)) + print("%d rows, %d anchors, %d missing at %s" % (rows, anchors, missing, ref)) + if rows == 0 or anchors == 0: + print("ledger_check: no ledger rows or anchors found: refusing to pass", file=sys.stderr) + sys.exit(2) + sys.exit(1 if missing else 0) + + +if __name__ == "__main__": + main() diff --git a/.github/block/scripts/post-merge-review-changed.sh b/.github/block/scripts/post-merge-review-changed.sh new file mode 100644 index 0000000000..d9d261971b --- /dev/null +++ b/.github/block/scripts/post-merge-review-changed.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +# Usage: post-merge-review-changed.sh BASE HEAD +# +# Writes what a PR changes (BASE...HEAD) as NUL-separated STATUS, PATH pairs, +# unquoted, so any byte in a name reaches the check as itself. --no-renames +# reports a move as a delete of the old name and an add of the new one. +set -euo pipefail +base=${1:?usage: post-merge-review-changed.sh BASE HEAD} +head=${2:?usage: post-merge-review-changed.sh BASE HEAD} +git diff --relative -z --name-status --no-renames "$base...$head" -- . + +if [ -n "$(git rev-parse --show-prefix)" ]; then + git -C "$(git rev-parse --show-toplevel)" diff -z --name-status --no-renames "$base...$head" -- '.github/workflows/block-*.yml' '.github/dockerfiles/block-*.Dockerfile' '.github/block/**' +fi diff --git a/.github/block/scripts/public-text-check.sh b/.github/block/scripts/public-text-check.sh new file mode 100644 index 0000000000..0cebd0bbc0 --- /dev/null +++ b/.github/block/scripts/public-text-check.sh @@ -0,0 +1,70 @@ +#!/usr/bin/env bash +# Refuses internal names in what a pull request makes public: the lines it +# adds, its commit messages, its title and its description. This repository is +# public; internal names, machine paths and raw run artifacts do not belong in it. +# +# Usage: public-text-check.sh MERGE_BASE HEAD TITLE_FILE BODY_FILE +# Exit 0: clean. Exit 1: at least one hit (each printed). Exit 2: usage. +# +# The patterns live only here and in this check's own test; both files are +# excluded from the scan of added lines. +set -euo pipefail +[ "$#" -eq 4 ] || { echo "usage: public-text-check.sh MERGE_BASE HEAD TITLE_FILE BODY_FILE" >&2; exit 2; } +mb=$1; head=$2; title=$3; body=$4 +for f in "$title" "$body"; do + [ -f "$f" ] && [ -r "$f" ] || { echo "public-text: cannot read $f" >&2; exit 2; } +done +git rev-parse -q --verify "$mb^{commit}" >/dev/null && git rev-parse -q --verify "$head^{commit}" >/dev/null || + { echo "public-text: unknown commit $mb or $head" >&2; exit 2; } +# match: a grep error fails the check instead of reading as "no hit". +match() { local rc=0; grep -E -i -- "$pat" "$@" || rc=$?; [ "$rc" -le 1 ] || { echo "public-text: grep failed ($rc)" >&2; exit 2; }; } +pat='(claude|codex)0[0-9]|share[/\]rdma|V:[/\]share|diskstation|/home/[^/[:space:]]+/|(^|[^[:alnum:]_])pid[[:space:]]*[:=][[:space:]]*[0-9]+|[0-9]+[[:space:]]+cores[[:space:]]+with[[:space:]]+[0-9]+([.][0-9]+)?[[:space:]]*(KB|MB|GB|KiB|MiB|GiB)?[[:space:]]+heap|docs/spec/([^/[:space:]]+/)*recorded-[^/[:space:]]+' +out=$(mktemp); paths=; trap 'rm -f "$out" "$paths"' EXIT +paths=$(mktemp) +report() { # report WHERE < matching lines + local where=$1 line + while IFS= read -r line; do + printf 'public-text: %s: %s +' "$where" "${line:0:160}" >>"$out" + done +} +# Raw run artifacts are not public specs, even with scrubbed contents. +# Allow deletions so existing artifacts can be removed. +repo_root=$(git rev-parse --show-toplevel) +if ! (cd "$repo_root" && git diff --name-only -z --no-relative --no-renames --diff-filter=ACMT "$mb" "$head" -- docs/spec/ seaweed-block/docs/spec/) >"$paths"; then + echo 'public-text: cannot enumerate artifact paths' >&2 + exit 2 +fi +while IFS= read -r -d '' path; do + # Match the module's paths the same way from either entry point. + path=${path#seaweed-block/} + if [[ $path =~ ^docs/spec/(.*/)?recorded-[^/]+(/|$) ]]; then + printf '%s\n' "$path" | report "artifact path" + fi +done <"$paths" +# Added lines of the diff, with file and line number. +{ +git diff --relative --no-color --no-renames -U0 "$mb" "$head" -- . \ + ':(exclude).github/scripts/public-text-check.sh' ':(exclude).github/scripts/public-text-check-test.sh' \ + ':(exclude,top).github/block/scripts/public-text-check.sh' +if [ -n "$(git rev-parse --show-prefix)" ]; then + git -C "$(git rev-parse --show-toplevel)" diff --no-color --no-renames -U0 "$mb" "$head" -- '.github/workflows/block-*.yml' '.github/dockerfiles/block-*.Dockerfile' '.github/block/**' ':(exclude).github/block/scripts/public-text-check.sh' +fi +} | + awk ' + /^diff --git / { hdr = 1; next } + hdr && /^\+\+\+ / { f = substr($0, 7); next } + /^@@ / { hdr = 0; split($3, a, ","); n = substr(a[1], 2) + 0; next } + !hdr && /^\+/ { print f ":" n ": " substr($0, 2); n++ } + ' | match | report "added line" +# Commit messages (subjects and bodies) of the pull request. +git log --format='%h %s%n%b' "$mb..$head" | match | report "commit message" +match "$title" | report "title" +match "$body" | report "description" +hits=$(wc -l <"$out" | tr -d ' ') +if [ "$hits" -gt 0 ]; then + cat "$out" + echo "public-text: $hits hit(s). Say what the code or test does instead of who asked for it; keep internal paths out." >&2 + exit 1 +fi +echo "public-text: clean" diff --git a/.github/block/scripts/run-unit-groups-test.py b/.github/block/scripts/run-unit-groups-test.py new file mode 100644 index 0000000000..607fa5e88f --- /dev/null +++ b/.github/block/scripts/run-unit-groups-test.py @@ -0,0 +1,145 @@ +"""Run fake recorders through the real group executor, without product tests.""" +from pathlib import Path +import json +import os +import subprocess +import time +import sys +import tempfile +import unittest +from unittest.mock import Mock, patch +import importlib.util +import signal + +SCRIPT = Path(__file__).with_name("run-unit-groups.py") +FAKE = r'''import json, os, sys, time +from pathlib import Path +out = Path(sys.argv[1]); group = out.parent.name +root = Path(os.environ["FIXTURE_ROOT"]) +(root / (group + ".started")).write_text("started") +deadline = time.monotonic() + 5 +while not all((root / (g + ".started")).exists() for g in os.environ["EXPECTED_GROUPS"].split()): + if time.monotonic() >= deadline: sys.exit(17) + time.sleep(.01) +flags = sys.argv[2:] +assert "-p=" + ("4" if group == "g3" else "1") in flags +assert "-short" in flags and "-count=1" in flags and "20m" in flags +if sys.platform == "linux": + wal = Path(os.environ["TMPDIR"]) / "v1.bin" + with wal.open("w") as descriptor: + assert os.readlink(f"/proc/self/fd/{descriptor.fileno()}") == str(wal), "fixture WAL descriptor not found" +else: + assert Path(os.environ["TMPDIR"]) == Path(os.environ["TMPDIR"]).resolve(), "TMPDIR must identify the canonical directory" +out.write_text(json.dumps({"Action":"pass", "Package":group}) + "\n") +out.with_suffix(".stderr").write_text("fixture stderr") +(root / (group + ".finished")).write_text("finished") +sys.exit(7 if os.environ.get("FAIL_GROUP") == group else 0) +''' + + +class GroupRunnerTests(unittest.TestCase): + def run_groups(self, fail="", empty=False, alias=False): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp); plan = root / "plan"; plan.mkdir() + for group in ("g1", "g2", "g3"): + (plan / (group + ".txt")).write_text("" if empty and group != "g3" else "example/" + group + "\n") + fake = root / "fake.py"; fake.write_text(FAKE) + env = dict(os.environ, FIXTURE_ROOT=str(root), EXPECTED_GROUPS="g3" if empty else "g1 g2 g3", FAIL_GROUP=fail) + scratch = root / "tmp" + if alias: + scratch.mkdir() + link = root / "runner-temp" + link.symlink_to(scratch, target_is_directory=True) + scratch = link + result = subprocess.run([sys.executable, str(SCRIPT), str(plan), str(root / "evidence"), str(scratch), sys.executable, str(fake)], env=env, text=True, capture_output=True, timeout=20) + self.assertEqual(result.returncode, 1 if fail else 0, result.stdout + result.stderr) + expected = ["g3"] if empty else ["g1", "g2", "g3"] + for group in expected: + self.assertTrue((root / (group + ".finished")).exists(), result.stdout + result.stderr) + self.assertTrue((root / "evidence" / group / "go-test.stderr").exists()) + self.assertTrue((root / "tmp" / group).is_dir()) + events = [json.loads(line) for line in (root / "evidence" / "go-test.json").read_text().splitlines()] + self.assertCountEqual([e["Package"] for e in events], expected) + statuses = json.loads((root / "evidence" / "unit-groups.json").read_text()) + self.assertEqual(statuses["groups"]["g2"]["status"], 7 if fail == "g2" else 0) + + @unittest.skipUnless(os.name == "posix", "Linux runner temp symlink control") + def test_runner_temp_symlink_passes_canonical_scratch_paths(self): self.run_groups(alias=True) + + def test_all_groups_overlap_and_keep_separate_events(self): self.run_groups() + def test_failure_fails_job_after_every_group_finishes(self): self.run_groups(fail="g2") + def test_scope_empty_groups_launch_no_recorder(self): self.run_groups(empty=True) + + + def test_cancel_escalates_even_after_group_leader_exits(self): + spec = importlib.util.spec_from_file_location("unit_groups", SCRIPT) + module = importlib.util.module_from_spec(spec); spec.loader.exec_module(module) + group = 12345 + leader = Mock(pid=group) + leader.wait.return_value = 0 + with patch.object(module.signal, "SIGKILL", 9, create=True), patch.object(module.os, "name", "posix"), patch.object(module.os, "killpg", create=True) as killpg, patch.object(module.time, "monotonic", side_effect=[0, 6]): + module.terminate([leader]) + self.assertIn(unittest.mock.call(group, signal.SIGTERM), killpg.call_args_list) + self.assertIn(unittest.mock.call(group, 9), killpg.call_args_list) + leader.wait.assert_called() + + @unittest.skipUnless(os.name == "posix", "process-group cancellation is a Linux runner control") + def test_cancel_kills_resistant_child_after_recorder_exits(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp); plan = root / "plan"; plan.mkdir() + for group in ("g1", "g2", "g3"): + (plan / (group + ".txt")).write_text("example/g1\n" if group == "g1" else "") + child = root / "child.py" + child.write_text("import os,signal,sys,time\nfrom pathlib import Path\nsignal.signal(signal.SIGTERM,signal.SIG_IGN)\np=Path(sys.argv[1])\np.with_suffix('.tmp').write_text(str(os.getpid()))\np.with_suffix('.tmp').replace(p)\nwhile True: time.sleep(.1)\n") + fake = root / "recorder.py" + fake.write_text("import subprocess,sys,time\nsubprocess.Popen([sys.executable,sys.argv[1],sys.argv[2]])\nwhile True: time.sleep(.1)\n") + marker = root / "child" + runner = subprocess.Popen([sys.executable, str(SCRIPT), str(plan), str(root / "evidence"), str(root / "tmp"), sys.executable, str(fake), str(child), str(marker)], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) + pid = None + try: + deadline = time.monotonic() + 5 + while not marker.exists(): + if time.monotonic() >= deadline: self.fail("resistant child did not start") + time.sleep(.01) + pid = int(marker.read_text()) + runner.terminate() + self.assertEqual(runner.wait(timeout=12), 130) + deadline = time.monotonic() + 2 + while True: + stat = Path(f"/proc/{pid}/stat") + if not stat.exists() or stat.read_text().split(") ", 1)[1].startswith("Z"): break + if time.monotonic() >= deadline: self.fail("resistant child survived cancellation") + time.sleep(.01) + finally: + if pid is not None: + try: os.kill(pid, signal.SIGKILL) + except ProcessLookupError: pass + if runner.poll() is None: runner.kill() + runner.communicate(timeout=5) + + @unittest.skipUnless(os.name == "posix", "process-group cancellation is a Linux runner control") + def test_cancel_joins_every_started_group(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp); plan = root / "plan"; plan.mkdir() + for group in ("g1", "g2", "g3"): + (plan / (group + ".txt")).write_text("example/" + group + "\n") + fake = root / "held.py" + fake.write_text("import os,sys,time\nfrom pathlib import Path\np=Path(sys.argv[1]).parent\n(p/'process.tmp').write_text(str(os.getpid()))\n(p/'process.tmp').replace(p/'process')\nwhile True: time.sleep(.1)\n") + runner = subprocess.Popen([sys.executable, str(SCRIPT), str(plan), str(root / "evidence"), str(root / "tmp"), sys.executable, str(fake)], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) + try: + deadline = time.monotonic() + 5 + markers = [root / "evidence" / g / "process" for g in ("g1", "g2", "g3")] + while not all(p.exists() for p in markers): + if time.monotonic() >= deadline: self.fail("groups did not start") + time.sleep(.01) + children = [int(p.read_text()) for p in markers] + runner.terminate() + self.assertEqual(runner.wait(timeout=10), 130) + for child in children: + with self.assertRaises(ProcessLookupError): os.kill(child, 0) + finally: + if runner.poll() is None: runner.terminate() + runner.communicate(timeout=10) + + +if __name__ == "__main__": unittest.main() diff --git a/.github/block/scripts/run-unit-groups.py b/.github/block/scripts/run-unit-groups.py new file mode 100644 index 0000000000..b02b4b8391 --- /dev/null +++ b/.github/block/scripts/run-unit-groups.py @@ -0,0 +1,123 @@ +"""Run the three default unit groups concurrently on the current runner. + +Usage: run-unit-groups.py PLAN_DIR EVIDENCE_DIR TMP_DIR RECORDER [RECORDER_ARG ...] +The recorder accepts OUTPUT followed by go-test flags and packages. Each group +owns its logs/events; they are combined only after all group processes exit. +""" +from contextlib import ExitStack +import json +import os +from pathlib import Path +import signal +import subprocess +import sys +import time + + +def stop(_signum, _frame): + raise KeyboardInterrupt + + +def terminate(processes): + for process in processes: + try: + if os.name == "posix": os.killpg(process.pid, signal.SIGTERM) + elif process.poll() is None: process.terminate() + except ProcessLookupError: + pass + if os.name == "posix": + # The leader may exit on TERM while its descendants remain in the group. + # Bound the grace period by group lifetime, never by leader lifetime. + deadline = time.monotonic() + 5 + remaining = list(processes) + while remaining and time.monotonic() < deadline: + alive = [] + for process in remaining: + process.poll() # Reap an exited leader without forgetting its PGID. + try: + os.killpg(process.pid, 0) + alive.append(process) + except ProcessLookupError: + pass + remaining = alive + if remaining: time.sleep(.05) + for process in remaining: + try: os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: pass + for process in processes: + try: + process.wait(timeout=5) + except subprocess.TimeoutExpired: + process.kill() + process.wait(timeout=5) + + + +def run(plan, evidence, temp, recorder): + groups = {g: (plan / (g + ".txt")).read_text().splitlines() for g in ("g1", "g2", "g3")} + evidence.mkdir(parents=True, exist_ok=True) + started = time.monotonic() + processes, results, times = {}, {}, {} + with ExitStack() as files: + try: + for group, packages in groups.items(): + results[group] = {"packages": len(packages), "status": 0, "elapsed_seconds": 0} + if not packages: + print(f"{group}: no packages selected by scope", flush=True) + continue + out = evidence / group; out.mkdir(parents=True, exist_ok=True) + scratch = temp / group; scratch.mkdir(parents=True, exist_ok=True) + # /proc/self/fd exposes resolved paths; preserve fixture identity even + # when the runner temp directory is a symlink to its data disk. + scratch = scratch.resolve(strict=True) + log = files.enter_context((out / "console.log").open("w", encoding="utf-8")) + command = recorder + [str(out / "go-test.json"), "-p=" + ("4" if group == "g3" else "1"), "-short", "-count=1", "-timeout", "20m", *packages] + times[group] = time.monotonic() + processes[group] = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL, + env=dict(os.environ, TMPDIR=str(scratch)), start_new_session=os.name == "posix") + print(f"{group}: started {len(packages)} packages", flush=True) + remaining = set(processes) + while remaining: + for group in tuple(remaining): + status = processes[group].poll() + if status is not None: + results[group]["status"] = status + results[group]["elapsed_seconds"] = round(time.monotonic() - times[group], 3) + remaining.remove(group) + if remaining: time.sleep(.05) + except BaseException: + signal.signal(signal.SIGTERM, signal.SIG_IGN) + signal.signal(signal.SIGINT, signal.SIG_IGN) + terminate(processes.values()) + raise + for group in processes: + print(f"--- {group} ---", flush=True) + print((evidence / group / "console.log").read_text(errors="replace"), flush=True) + summary = {"elapsed_seconds": round(time.monotonic() - started, 3), "groups": results} + try: + (evidence / "unit-groups.json").write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8") + with (evidence / "go-test.json").open("ab") as combined: + for group in processes: + events = evidence / group / "go-test.json" + if events.exists(): combined.write(events.read_bytes()) + except OSError as error: + print(f"test evidence unavailable: {error}", file=sys.stderr) + print(json.dumps(summary), flush=True) + return int(any(r["status"] != 0 for r in results.values())) + + +def main(argv): + if len(argv) < 5: + print(__doc__.strip(), file=sys.stderr) + return 2 + signal.signal(signal.SIGTERM, stop) + try: + return run(Path(argv[1]), Path(argv[2]), Path(argv[3]), argv[4:]) + except KeyboardInterrupt: + return 130 + except (OSError, ValueError) as error: + print(f"unit groups: {error}", file=sys.stderr) + return 2 + + +if __name__ == "__main__": sys.exit(main(sys.argv)) diff --git a/.github/block/scripts/runner-workspace-test.py b/.github/block/scripts/runner-workspace-test.py new file mode 100644 index 0000000000..999e43d40d --- /dev/null +++ b/.github/block/scripts/runner-workspace-test.py @@ -0,0 +1,106 @@ +"""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("\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, "", "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) + self.assertIn("python3 -I -", before) + self.assertIn("python3 -I -", 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) + + def test_cleanup_refuses_symlinked_ancestors_and_preserves_external_sentinel(self): + for path in WORKFLOWS: + with self.subTest(workflow=path.name), tempfile.TemporaryDirectory() as temp: + base = Path(temp) + external = base / "external/repo/repo"; external.mkdir(parents=True) + sentinel = external / "keep"; sentinel.write_text("outside checkout") + alias = base / "alias"; alias.symlink_to(base / "external", target_is_directory=True) + source = code(step(path.read_text(), "Clean job workspace")) + rc, out = execute(source, alias / "repo/repo", base) + self.assertTrue(sentinel.is_file(), "cleanup followed a workspace ancestor outside the checkout") + self.assertEqual(rc, 1, out) + self.assertIn("runner_workspace_cleanup_refused", out) + + +if __name__ == "__main__": unittest.main() diff --git a/.github/block/scripts/safe-merge-check.py b/.github/block/scripts/safe-merge-check.py new file mode 100644 index 0000000000..b7c2567675 --- /dev/null +++ b/.github/block/scripts/safe-merge-check.py @@ -0,0 +1,132 @@ +"""Read-only block merge readiness check. Run from a trusted master checkout. + +Usage (inside seaweed-block/): python3 ../.github/block/scripts/safe-merge-check.py PR +Never merges, posts comments, changes account config or pushes refs. +""" +import json +import subprocess +import sys +import tempfile +from pathlib import Path + +REPO = "seaweedfs/seaweedfs" +WORKFLOW_PATH = ".github/workflows/block-test.yml" +JOBS = {"go test (linux)", "process-level tests (real binaries)"} + + +def validate(pr, run, jobs, current): + if pr["state"] != "open" or pr["draft"] or pr["mergeable"] is not True: + raise ValueError("PR must be open, ready and mergeable") + if pr["base"]["ref"] != "master": raise ValueError("expected master base") + if run.get("path") != WORKFLOW_PATH or run["name"] != "Block Test" or run["head_sha"] != pr["head"]["sha"]: + raise ValueError("wrong workflow or head") + if run["status"] != "completed" or run["conclusion"] != "success": + raise ValueError("Block Test is not successful") + bases = [p["base"]["sha"] for p in run["pull_requests"] if p["number"] == pr["number"]] + if bases != [current]: raise ValueError("tested base is not current master") + required = [j for j in jobs if j["name"] in JOBS] + if len(required) != 2 or {j["name"] for j in required} != JOBS or any(j["conclusion"] != "success" for j in required): + raise ValueError("both block test jobs must succeed") + + +def api(path): + return json.loads(subprocess.check_output(["gh", "api", "repos/" + REPO + "/" + path])) + + +def successful_run(pr, current): + runs = api("actions/runs?head_sha=" + pr["head"]["sha"] + "&event=pull_request&per_page=100")["workflow_runs"] + runs = [r for r in runs if r.get("path") == WORKFLOW_PATH and r["name"] == "Block Test"] + if not runs: raise ValueError("no Block Test run") + run = max(runs, key=lambda r: (r["created_at"], r["id"])) + pages = json.loads(subprocess.check_output(["gh", "api", "--paginate", "--slurp", "repos/" + REPO + "/actions/runs/" + str(run["id"]) + "/jobs?per_page=100"])) + validate(pr, run, [j for page in pages for j in page["jobs"]], current) + return run + + +def check_control_paths(base, head): + # Inspect both sides of renames and fail on enumeration errors. These PRs + # need independent workflow review; their own Actions results cannot waive it. + # Diff from the merge base: master's later control changes are not the PR's, + # and the tested merge commit already ran them. + bases = subprocess.check_output(["git", "merge-base", "--all", base, head]).decode("ascii").splitlines() + if len(bases) != 1: + raise ValueError("ambiguous_merge_base: expected exactly one merge base") + paths = subprocess.check_output(["git", "diff", "--no-renames", "--name-only", "-z", bases[0], head]).split(b"\0") + controls = [p.decode("utf-8", errors="replace") for p in paths if p.startswith((b".github/workflows/", b".github/block/", b".github/dockerfiles/block-", b"seaweed-block/.github/"))] + if controls: + raise ValueError("workflow_review_required: CI controls changed: " + ", ".join(controls)) + + +def fetch_review_head(pr, current): + if subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip() != current: + raise ValueError("run from trusted current master checkout") + subprocess.run(["git", "-c", "fetch.fsckObjects=true", "fetch", "--no-tags", "origin", "+refs/pull/" + str(pr["number"]) + "/head:refs/remotes/block-review/head"], check=True) + actual = subprocess.check_output(["git", "rev-parse", "refs/remotes/block-review/head"], text=True).strip() + if actual != pr["head"]["sha"]: raise ValueError("PR head moved; recheck") + check_control_paths(current, actual) + return actual + + +def local_checks(pr, current): + actual = fetch_review_head(pr, current) + with tempfile.TemporaryDirectory() as tmp: + body, title = Path(tmp) / "body", Path(tmp) / "title" + body.write_text(pr["body"] or "", encoding="utf-8") + title.write_text(pr["title"], encoding="utf-8") + subprocess.run(["bash", str(Path(__file__).resolve().with_name("check-pr-base.sh")), current, actual, str(body), str(title)], check=True) + + +def validate_batch(manifest, prs, current): + if manifest["base"] != current: raise ValueError("master moved since batch creation") + if not manifest["head"] or len(manifest["prs"]) < 2: raise ValueError("expected pinned batch and at least two PRs") + numbers = [p["number"] for p in manifest["prs"]] + if len(set(numbers)) != len(numbers) or numbers != [p["number"] for p in prs]: + raise ValueError("batch PR order differs or repeats") + for saved, pr in zip(manifest["prs"], prs): + if pr["state"] != "open" or pr["draft"] or pr["base"]["ref"] != "master" or pr["head"]["sha"] != saved["head"]: + raise ValueError("batch member is not ready or its head changed") + if not Path(saved["evidence"]).is_file() or not Path(saved["evidence"]).read_text().strip(): + raise ValueError("batch member has no acceptance evidence") + + +def main(args): + current = api("git/ref/heads/master")["object"]["sha"] + if len(args) == 2 and args[0] == "--verify-tree": + tree = api("git/commits/" + current)["tree"]["sha"] + if tree != args[1]: raise ValueError("master tree differs from the tested batch") + print(json.dumps({"tree_matches": True, "master": current, "tree": tree})) + return + if len(args) == 2 and args[0] == "--batch": + manifest = json.loads(Path(args[1]).read_text()) + prs = [api("pulls/" + str(p["number"])) for p in manifest["prs"]] + validate_batch(manifest, prs, current) + batch = api("pulls/" + str(manifest["batch_pr"])) + if batch["head"]["sha"] != manifest["head"]: raise ValueError("batch head changed") + fetch_review_head(batch, current) + run = successful_run(batch, current) + for pr in prs: local_checks(pr, current) + if api("git/ref/heads/master")["object"]["sha"] != current: raise ValueError("master moved; recheck") + for pr in prs + [batch]: + if api("pulls/" + str(pr["number"]))["head"]["sha"] != pr["head"]["sha"]: raise ValueError("head moved; recheck") + tree = api("git/commits/" + manifest["head"])["tree"]["sha"] + # A rerun can invalidate the earlier success while local checks execute. + run = successful_run(batch, current) + print(json.dumps({"ready": True, "base": current, "head": manifest["head"], "run": run["id"], "tree": tree, "order": [p["number"] for p in prs]})) + return + if len(args) != 1 or not args[0].isdecimal(): raise ValueError("expected PR, --batch MANIFEST or --verify-tree TREE") + pr = api("pulls/" + args[0]) + run = successful_run(pr, current) + local_checks(pr, current) + if api("git/ref/heads/master")["object"]["sha"] != current or api("pulls/" + args[0])["head"]["sha"] != pr["head"]["sha"]: + raise ValueError("base or head moved; recheck") + # Refresh the latest run and both jobs after every potentially slow check. + run = successful_run(pr, current) + print(json.dumps({"ready": True, "head": pr["head"]["sha"], "base": current, "run": run["id"], "merge_mode": "squash"})) + + +if __name__ == "__main__": + try: + main(sys.argv[1:]) + except (IndexError, KeyError, ValueError, OSError, subprocess.SubprocessError) as error: + print("REFUSED: " + str(error), file=sys.stderr) + sys.exit(1) diff --git a/.github/block/scripts/unit-test-shards-test.py b/.github/block/scripts/unit-test-shards-test.py new file mode 100644 index 0000000000..df49419e7c --- /dev/null +++ b/.github/block/scripts/unit-test-shards-test.py @@ -0,0 +1,52 @@ +"""Exact coverage before scope selection; old heavy-package rules afterward.""" +import importlib.util +from pathlib import Path +import unittest + +spec = importlib.util.spec_from_file_location("planner", Path(__file__).with_name("unit-test-shards.py")) +planner = importlib.util.module_from_spec(spec) +spec.loader.exec_module(planner) +MODULE = "example.invalid/product" +HEAVY = ("core/storage", "core/frontend/durable", "core/host/master", "core/authority") + + +class UnitShardTests(unittest.TestCase): + def setUp(self): + self.packages = [MODULE + "/" + p for p in (*HEAVY, "cmd/sw-block", "core/frontend/chunkstore", "internal/newpackage", "core/storage/child")] + self.groups = planner.partition(MODULE, self.packages) + + def test_exact_cover_and_stable_order(self): + flat = [p for group in self.groups.values() for p in group] + self.assertCountEqual(flat, self.packages) + self.assertEqual(len(flat), len(set(flat))) + self.assertEqual(self.groups, planner.partition(MODULE, list(reversed(self.packages)))) + self.assertEqual(self.groups["g1"], [MODULE + "/core/storage"]) + self.assertEqual(self.groups["g2"], [MODULE + "/" + p for p in HEAVY[1:]]) + self.assertIn(MODULE + "/internal/newpackage", self.groups["g3"]) + self.assertIn(MODULE + "/core/storage/child", self.groups["g3"]) + + def test_existing_heavy_scope_on_main_train_and_prs(self): + all_changed = [p + "/changed.go" for p in HEAVY] + for event, ref in (("push", ""), ("pull_request", "train/next")): + selected = planner.select(MODULE, self.groups, event, ref, all_changed) + self.assertEqual(selected["g1"], []) + self.assertEqual(selected["g2"], []) + self.assertEqual(selected["g3"], self.groups["g3"]) + self.assertEqual(planner.select(MODULE, self.groups, "pull_request", "fix/x", all_changed), self.groups) + for path in HEAVY: + selected = planner.select(MODULE, self.groups, "pull_request", "fix/x", [path + "/x.go"]) + heavy = selected["g1"] + selected["g2"] + self.assertEqual(heavy, [MODULE + "/" + path]) + nested = planner.select(MODULE, self.groups, "pull_request", "fix/x", ["core/storage/child/x.go", "core/storage/"]) + self.assertEqual(nested["g1"], []) + self.assertEqual(nested["g2"], []) + self.assertEqual(nested["g3"], self.groups["g3"]) + + def test_invalid_inventory_is_refused(self): + for packages in ([], self.packages + [self.packages[0]], self.packages[1:], self.packages + ["other/pkg"]): + with self.subTest(packages=packages), self.assertRaises(ValueError): + planner.partition(MODULE, packages) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/block/scripts/unit-test-shards.py b/.github/block/scripts/unit-test-shards.py new file mode 100644 index 0000000000..badb9b8791 --- /dev/null +++ b/.github/block/scripts/unit-test-shards.py @@ -0,0 +1,55 @@ +"""Plan the default unit groups from the full go-list inventory. + +Usage: go list ./... | python3 unit-test-shards.py MODULE OUT_DIR EVENT HEAD_REF CHANGED_FILE +The complete partition covers every package exactly once. Existing scope rules +then select heavy packages only on ordinary PRs that touch their direct files. +""" +from pathlib import Path +import sys + +HEAVY = ("core/storage", "core/frontend/durable", "core/host/master", "core/authority") + + +def partition(module, packages): + if not module or any(c.isspace() for c in module): + raise ValueError("expected one module path") + if not packages or len(packages) != len(set(packages)): + raise ValueError("empty package list or duplicate package") + if any(p != module and not p.startswith(module + "/") for p in packages): + raise ValueError("package outside the selected module") + heavy = [module + "/" + p for p in HEAVY] + if not set(heavy) <= set(packages): + raise ValueError("required heavy packages missing from go list") + return {"g1": heavy[:1], "g2": heavy[1:], "g3": sorted(set(packages) - set(heavy))} + + +def select(module, groups, event, head_ref, changed): + selected = set() + if event != "push" and not head_ref.startswith("train/"): + for p in HEAVY: + if any(f.startswith(p + "/") and f[len(p) + 1:] and "/" not in f[len(p) + 1:] for f in changed): + selected.add(module + "/" + p) + return {name: [p for p in packages if name == "g3" or p in selected] + for name, packages in groups.items()} + + +def main(argv): + if len(argv) != 6: + print(__doc__.strip(), file=sys.stderr) + return 2 + try: + groups = partition(argv[1], sys.stdin.read().split()) + groups = select(argv[1], groups, argv[3], argv[4], Path(argv[5]).read_text().splitlines()) + out = Path(argv[2]) + out.mkdir(parents=True, exist_ok=True) + for name, packages in groups.items(): + (out / (name + ".txt")).write_text("".join(p + "\n" for p in packages), encoding="utf-8") + print(f"{name}: {len(packages)} packages") + except (OSError, ValueError) as error: + print(f"unit-test-shards: {error}", file=sys.stderr) + return 2 + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv)) diff --git a/.github/dockerfiles/block-blockcsi.Dockerfile b/.github/dockerfiles/block-blockcsi.Dockerfile new file mode 100644 index 0000000000..7e296031c7 --- /dev/null +++ b/.github/dockerfiles/block-blockcsi.Dockerfile @@ -0,0 +1,27 @@ +FROM golang:1.25-bookworm AS build + +WORKDIR /src/seaweed-block +COPY seaweed-block/go.mod seaweed-block/go.sum ./ +RUN go mod download +COPY . /src +RUN CGO_ENABLED=0 go build -o /out/blockcsi ./cmd/blockcsi +# No lab build reaches an image (scripts/refuse-lab-binary.sh): refuse it before the +# runtime stage, so neither a build nor a push of this image can complete. +RUN bash scripts/refuse-lab-binary.sh /out/blockcsi + +FROM debian:bookworm-slim + +RUN apt-get update && \ + apt-get install -y --no-install-recommends \ + e2fsprogs \ + kmod \ + multipath-tools \ + nvme-cli \ + open-iscsi \ + sg3-utils \ + util-linux && \ + rm -rf /var/lib/apt/lists/* + +COPY --from=build /out/blockcsi /usr/local/bin/blockcsi + +ENTRYPOINT ["/usr/local/bin/blockcsi"] diff --git a/.github/dockerfiles/block-sw-block.Dockerfile b/.github/dockerfiles/block-sw-block.Dockerfile new file mode 100644 index 0000000000..01930b926e --- /dev/null +++ b/.github/dockerfiles/block-sw-block.Dockerfile @@ -0,0 +1,24 @@ +FROM golang:1.25-bookworm AS build + +WORKDIR /src/seaweed-block +COPY seaweed-block/go.mod seaweed-block/go.sum ./ +RUN go mod download +COPY . /src +RUN CGO_ENABLED=0 go build -o /out/blockmaster ./cmd/blockmaster && \ + CGO_ENABLED=0 go build -o /out/blockvolume ./cmd/blockvolume && \ + CGO_ENABLED=0 go build -o /out/sw-block ./cmd/sw-block +# No lab build reaches an image (scripts/refuse-lab-binary.sh): refuse it before the +# runtime stage, so neither a build nor a push of this image can complete. +RUN bash scripts/refuse-lab-binary.sh /out/blockmaster /out/blockvolume /out/sw-block + +FROM debian:bookworm-slim + +RUN apt-get update && \ + apt-get install -y --no-install-recommends kmod && \ + rm -rf /var/lib/apt/lists/* + +COPY --from=build /out/blockmaster /usr/local/bin/blockmaster +COPY --from=build /out/blockvolume /usr/local/bin/blockvolume +COPY --from=build /out/sw-block /usr/local/bin/sw-block + +USER 65532:65532 diff --git a/.github/workflows/block-known-bugs.yml b/.github/workflows/block-known-bugs.yml new file mode 100644 index 0000000000..64cc2d0169 --- /dev/null +++ b/.github/workflows/block-known-bugs.yml @@ -0,0 +1,127 @@ +name: Block known bugs + +# Nightly: every open-issue reproduction that is skipped by default (t.Skip unless +# SEAWEED_KNOWN_BUGS=1) runs and is EXPECTED TO FAIL. If one passes, its bug is +# fixed but its skip is still in place: this job fails and names it, so the skip +# is removed in the fix PR (or right after). A fix PR removes the test's line here +# together with its skip. +on: + schedule: + - cron: "17 6 * * *" + workflow_dispatch: + +defaults: + run: + working-directory: seaweed-block + +permissions: + contents: read + +jobs: + known-bugs: + name: known-bug reproductions still fail + 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: 15 + env: + CGO_ENABLED: "0" + SEAWEED_KNOWN_BUGS: "1" + steps: + - name: Runner free space + working-directory: ${{ runner.temp }} + run: | + python3 -I - <<'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: + persist-credentials: false + + - name: Runner disk is NVMe + # A self-hosted runner whose work, temp or Go cache directory sits on a + # SATA system disk times the process-level tests out under disk load; + # this names the runner and stops the job before it starts. + if: runner.environment == 'self-hosted' + run: | + bash .github/scripts/require-nvme-test.sh + bash .github/scripts/require-nvme.sh "$GITHUB_WORKSPACE" "$RUNNER_TEMP" "${TMPDIR:-/tmp}" "${GOCACHE:-$HOME/.cache/go-build}" + + - name: Set up Go + uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0 + with: + go-version-file: seaweed-block/go.mod + cache: false + + - name: Known-bug verdict controls + run: bash .github/scripts/known-bugs-test.sh + + - name: Each reproduction still fails + run: | + bash .github/scripts/known-bugs.sh <<'LIST' + #186 ./cmd/blockmaster/ TestChartOptInLoopbackFlagIsAcceptedByBlockmaster + LIST + + - 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 -I - <<'PY' + import os + from pathlib import Path + import shutil + import sys + root = Path(os.environ["GITHUB_WORKSPACE"]) + # Refuse aliases rather than resolving them. Open EVERY component without + # following symlinks, then keep cleanup anchored to the verified directory fd. + if not root.is_absolute() or ".." in root.parts or root == Path(root.anchor) or root.name != root.parent.name or root == Path(os.environ["RUNNER_TEMP"]): + print(f"runner_workspace_cleanup_refused path={str(root)!r}") + sys.exit(1) + flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW + fd = os.open(root.anchor, flags) + previous = os.open(".", flags) + errors = [] + try: + for part in root.parts[1:]: + child = os.open(part, flags, dir_fd=fd) + os.close(fd) + fd = child + if not shutil.rmtree.avoids_symlink_attacks: + raise OSError("descriptor-safe directory removal is unavailable") + os.fchdir(fd) + for entry in os.scandir("."): + try: + if entry.is_dir(follow_symlinks=False): + shutil.rmtree(entry.name) + else: + os.unlink(entry.name) + except OSError as err: + errors.append(f"{entry.name}: {err}") + except OSError as err: + print(f"runner_workspace_cleanup_refused path={str(root)!r} error={err}") + sys.exit(1) + finally: + os.fchdir(previous) + os.close(previous) + os.close(fd) + if errors: + print("runner_workspace_cleanup_failed " + "; ".join(errors)) + sys.exit(1) + print(f"runner_workspace_clean path={str(root)!r}") + PY diff --git a/.github/workflows/block-post-merge-review.yml b/.github/workflows/block-post-merge-review.yml new file mode 100644 index 0000000000..a004a418bc --- /dev/null +++ b/.github/workflows/block-post-merge-review.yml @@ -0,0 +1,146 @@ +name: Block post-merge-review paths + +# A PR labelled "post-merge-review" may merge before its full review only if +# every changed file is allowed by .github/post-merge-review-allow.txt. +# This check fails such a PR otherwise; without the label it passes. +# +# pull_request_target: the workflow, the allow list and the script all come +# from the base branch, so a PR cannot change its own check. The PR's code is +# never checked out or run: only its commit is fetched, for the file list. +on: + pull_request_target: + paths: + - "seaweed-block/**" + - ".github/workflows/block-*.yml" + - ".github/block/**" + - ".github/dockerfiles/block-*.Dockerfile" + # edited: a retarget changes the base, and with it the diff. + types: [opened, synchronize, reopened, labeled, unlabeled, edited] + +defaults: + run: + working-directory: seaweed-block + +permissions: + contents: read + +concurrency: + group: block-post-merge-review-${{ github.event.pull_request.number }} + cancel-in-progress: true + +jobs: + paths: + name: post-merge-review paths + # GitHub-hosted: on the self-hosted runners this job ended in 'Set up + # job' with no log on every runner (2026-11-29), while spec trace, on the + # same runners, passes. Unlabelled PRs only echo here, so the hosted + # queue costs little; the merge gate does not wait for it unless the PR + # is labelled. + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - name: Runner free space + working-directory: ${{ runner.temp }} + run: | + python3 -I - <<'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 }} + run: echo "no post-merge-review label; nothing to check" + + - name: Checkout base + if: ${{ contains(github.event.pull_request.labels.*.name, 'post-merge-review') }} + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + ref: ${{ github.event.pull_request.base.sha }} + fetch-depth: 0 + persist-credentials: false + + - name: Check changed paths + if: ${{ contains(github.event.pull_request.labels.*.name, 'post-merge-review') }} + env: + BASE: ${{ github.event.pull_request.base.sha }} + HEAD: ${{ github.event.pull_request.head.sha }} + PR: ${{ github.event.pull_request.number }} + run: | + set -euo pipefail + bash .github/scripts/post-merge-review-check-test.sh + 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 + # The allow list speaks for the module only: any host file keeps the full review. + git -C .. diff -z --name-only --no-renames "$BASE...$HEAD" -- . ':(exclude)seaweed-block/' \ + ':(exclude).github/workflows/block-*.yml' ':(exclude).github/dockerfiles/block-*.Dockerfile' ':(exclude).github/block/**' >host.bin + host=0 + while IFS= read -r -d '' path; do + printf 'DENY host %q (outside seaweed-block)\n' "$path" + host=1 + done &2 + exit 1 + fi + notes="seaweed-block/docs/releases/${version%%-*}.md" + if [[ ! -s "${notes}" ]]; then + echo "refusing to publish: release notes ${notes} are missing or empty" >&2 + exit 1 + fi + echo "notes=${notes}" >> "$GITHUB_OUTPUT" + stable=false + move_alpha=false + if [[ "${version}" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then + stable=true + highest="$(git tag -l 'seaweed-block/v*' | sed 's|^seaweed-block/||' | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$' | sort -V | tail -n 1)" + if [[ "${version}" == "${highest}" ]]; then + move_alpha=true + fi + fi + { + echo "block_tags<> "$GITHUB_OUTPUT" + + - name: Build and push block image + id: block + uses: docker/build-push-action@v6 + with: + context: . + file: .github/dockerfiles/block-sw-block.Dockerfile + platforms: linux/amd64 + push: true + tags: ${{ steps.tags.outputs.block_tags }} + + - name: Build and push CSI image + uses: docker/build-push-action@v6 + with: + context: . + file: .github/dockerfiles/block-blockcsi.Dockerfile + platforms: linux/amd64 + push: true + tags: ${{ steps.tags.outputs.csi_tags }} + + - name: Publish matching binary tarball + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + BLOCK_DIGEST: ${{ steps.block.outputs.digest }} + NOTES: ${{ steps.tags.outputs.notes }} + shell: bash + run: | + set -euo pipefail + version="${GITHUB_REF_NAME#seaweed-block/}" + out="$RUNNER_TEMP/block-release" + mkdir -p "$out/bin" + docker pull "${BLOCK_IMAGE}@${BLOCK_DIGEST}" + container=$(docker create "${BLOCK_IMAGE}@${BLOCK_DIGEST}") + trap 'docker rm "$container" >/dev/null' EXIT + for binary in blockmaster blockvolume sw-block; do + docker cp "$container:/usr/local/bin/$binary" "$out/bin/$binary" + done + bash seaweed-block/scripts/refuse-lab-binary.sh "$out/bin/"* + asset="sw-block-${version}-linux-amd64.tar.gz" + tar -C "$out/bin" -czf "$out/$asset" blockmaster blockvolume sw-block + (cd "$out" && sha256sum "$asset" >SHA256SUMS) + prerelease=false + if [[ "$version" == *-* ]]; then prerelease=true; fi + # A rerun replaces the assets, then publishes a draft an interrupted run left. + if gh release view "$GITHUB_REF_NAME" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then + gh release upload "$GITHUB_REF_NAME" "$out/$asset" "$out/SHA256SUMS" --repo "$GITHUB_REPOSITORY" --clobber + gh release edit "$GITHUB_REF_NAME" --repo "$GITHUB_REPOSITORY" --prerelease="$prerelease" --draft=false --latest=false + else + gh release create "$GITHUB_REF_NAME" "$out/$asset" "$out/SHA256SUMS" --repo "$GITHUB_REPOSITORY" --verify-tag --latest=false \ + --prerelease="$prerelease" --title "Seaweed Block $version" --notes-file "$NOTES" + fi + + - 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 -I - <<'PY' + import os + from pathlib import Path + import shutil + import sys + root = Path(os.environ["GITHUB_WORKSPACE"]) + # Refuse aliases rather than resolving them. Open EVERY component without + # following symlinks, then keep cleanup anchored to the verified directory fd. + if not root.is_absolute() or ".." in root.parts or root == Path(root.anchor) or root.name != root.parent.name or root == Path(os.environ["RUNNER_TEMP"]): + print(f"runner_workspace_cleanup_refused path={str(root)!r}") + sys.exit(1) + flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW + fd = os.open(root.anchor, flags) + previous = os.open(".", flags) + errors = [] + try: + for part in root.parts[1:]: + child = os.open(part, flags, dir_fd=fd) + os.close(fd) + fd = child + if not shutil.rmtree.avoids_symlink_attacks: + raise OSError("descriptor-safe directory removal is unavailable") + os.fchdir(fd) + for entry in os.scandir("."): + try: + if entry.is_dir(follow_symlinks=False): + shutil.rmtree(entry.name) + else: + os.unlink(entry.name) + except OSError as err: + errors.append(f"{entry.name}: {err}") + except OSError as err: + print(f"runner_workspace_cleanup_refused path={str(root)!r} error={err}") + sys.exit(1) + finally: + os.fchdir(previous) + os.close(previous) + os.close(fd) + if errors: + print("runner_workspace_cleanup_failed " + "; ".join(errors)) + sys.exit(1) + print(f"runner_workspace_clean path={str(root)!r}") + PY diff --git a/.github/workflows/block-spec-trace.yml b/.github/workflows/block-spec-trace.yml new file mode 100644 index 0000000000..43cd2e6581 --- /dev/null +++ b/.github/workflows/block-spec-trace.yml @@ -0,0 +1,164 @@ +name: Block spec trace + +# Every PR description carries the spec trace (see the PR template); this +# check fails a PR whose description does not. +# +# pull_request_target: the workflow and the script come from the base branch, +# so a PR cannot change its own check. The PR's code is never checked out or +# run: only its commit is fetched, for the file list. The description is read +# from the event through an environment variable, never interpolated. +on: + pull_request_target: + paths: + - "seaweed-block/**" + - ".github/workflows/block-*.yml" + - ".github/block/**" + - ".github/dockerfiles/block-*.Dockerfile" + # edited: the check reads the description and the base. + types: [opened, synchronize, reopened, edited] + +defaults: + run: + working-directory: seaweed-block + +permissions: + contents: read + +concurrency: + group: block-spec-trace-${{ github.event.pull_request.number }} + cancel-in-progress: true + +jobs: + trace: + name: spec trace + # The base-owned check defaults to a disposable hosted runner. Only a + # same-repository PR may opt into the registered BLOCK_RUNNER_LABEL. + 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 -I - <<'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: + # github.sha is the tip of the base branch when the event fires; the + # PR's base.sha can predate this workflow's own scripts. + ref: ${{ github.sha }} + fetch-depth: 0 + persist-credentials: false + + # spec-trace-check.sh builds the trusted sametokens.go; a self-hosted + # runner has no Go on its PATH unless the job sets it up. + - name: Set up Go + uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0 + with: + go-version-file: seaweed-block/go.mod + cache: false + + - name: Check spec trace + env: + BASE: ${{ github.event.pull_request.base.sha }} + HEAD: ${{ github.event.pull_request.head.sha }} + PR: ${{ github.event.pull_request.number }} + BODY: ${{ github.event.pull_request.body }} + TITLE: ${{ github.event.pull_request.title }} + run: | + set -euo pipefail + bash .github/scripts/spec-trace-check-test.sh + python3 -B .github/scripts/model-trace-check-test.py + bash .github/scripts/changed-go-blobs-test.sh + # fsckObjects: a PR's objects are checked as they arrive, so a tree + # with a '..' or '.git' entry is refused here. + git -c fetch.fsckObjects=true fetch --no-tags origin "+refs/pull/${PR}/head:refs/remotes/pr/head" + printf '%s' "$BODY" >body.txt + bash ../.github/block/scripts/post-merge-review-changed.sh "$BASE" "$HEAD" >changed.bin + # Old and new blobs of each changed non-test Go file, for kind DOCS + # (objects only; a path that would leave blobs/ is refused). + mb=$(git merge-base "$BASE" "$HEAD") + bash ../.github/block/scripts/changed-go-blobs.sh "$mb" "$HEAD" blobs + # Mapping and validator come from the trusted base checkout above. + bash .github/scripts/spec-trace-check.sh body.txt blobs .github/model-code-trace.tsv title.txt + bash ../.github/block/scripts/public-text-check.sh "$mb" "$HEAD" title.txt body.txt + + - name: Invariants ledger anchors (report only) + # Every code and test anchor of docs/design/invariants.md must exist at + # the PR's commit (git objects only; nothing from the PR is run). It + # reports and does not fail the check while the known imprecise + # anchors are being corrected; then this step becomes gating. + continue-on-error: true + 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 -I - <<'PY' + import os + from pathlib import Path + import shutil + import sys + root = Path(os.environ["GITHUB_WORKSPACE"]) + # Refuse aliases rather than resolving them. Open EVERY component without + # following symlinks, then keep cleanup anchored to the verified directory fd. + if not root.is_absolute() or ".." in root.parts or root == Path(root.anchor) or root.name != root.parent.name or root == Path(os.environ["RUNNER_TEMP"]): + print(f"runner_workspace_cleanup_refused path={str(root)!r}") + sys.exit(1) + flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW + fd = os.open(root.anchor, flags) + previous = os.open(".", flags) + errors = [] + try: + for part in root.parts[1:]: + child = os.open(part, flags, dir_fd=fd) + os.close(fd) + fd = child + if not shutil.rmtree.avoids_symlink_attacks: + raise OSError("descriptor-safe directory removal is unavailable") + os.fchdir(fd) + for entry in os.scandir("."): + try: + if entry.is_dir(follow_symlinks=False): + shutil.rmtree(entry.name) + else: + os.unlink(entry.name) + except OSError as err: + errors.append(f"{entry.name}: {err}") + except OSError as err: + print(f"runner_workspace_cleanup_refused path={str(root)!r} error={err}") + sys.exit(1) + finally: + os.fchdir(previous) + os.close(previous) + os.close(fd) + if errors: + print("runner_workspace_cleanup_failed " + "; ".join(errors)) + sys.exit(1) + print(f"runner_workspace_clean path={str(root)!r}") + PY diff --git a/.github/workflows/block-test.yml b/.github/workflows/block-test.yml new file mode 100644 index 0000000000..39c1d55651 --- /dev/null +++ b/.github/workflows/block-test.yml @@ -0,0 +1,445 @@ +name: Block Test + +on: + pull_request: + paths: + - "seaweed-block/**" + - ".github/workflows/block-*.yml" + - ".github/block/**" + - ".github/dockerfiles/block-*.Dockerfile" + # ready_for_review: a Draft runs no Go suite (below); marking it ready starts one. + types: [opened, synchronize, reopened, ready_for_review] + push: + paths: + - "seaweed-block/**" + - ".github/workflows/block-*.yml" + - ".github/block/**" + - ".github/dockerfiles/block-*.Dockerfile" + branches: + - master + +defaults: + run: + working-directory: seaweed-block + +permissions: + contents: read + +# One run per PR (or per commit for pushes). A new push to a PR cancels the +# superseded run; a queued master run would be replaced by a newer one in a +# shared group, so each merge gets its own group and its own result. +concurrency: + group: block-test-${{ github.workflow }}-${{ github.event.pull_request.number || github.sha }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + test: + # One job, two suites, one runner selection. 'unit' is the Go suite below; + # 'process' runs the process-level tests: real blockmaster, blockvolume and + # sw-block against a pinned SeaweedFS release. Those tests are named in + # .github/process-level-tests.txt, and every one must PASS, so a test that + # skips, fails, never starts or is cut off by the timeout fails the suite. + # Tests that need root or systemd are not in the list (see its header). + strategy: + fail-fast: false + matrix: + suite: [unit, process] + name: ${{ matrix.suite == 'unit' && 'go test (linux)' || 'process-level tests (real binaries)' }} + # The suite writes heavily to the runner disk (real files, fsync), so a + # Draft PR skips it; its author tests locally until the PR is ready. + if: github.event_name == 'push' || !github.event.pull_request.draft + # Hosted by default until this repository has a registered block pool. + # Set BLOCK_RUNNER_LABEL only for an available dedicated label. Forks + # always stay on disposable GitHub-hosted runners. + 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' }} + # process: 44 tests in 4 parallel shards of about 13 min each (55 min in sequence). + timeout-minutes: ${{ matrix.suite == 'unit' && 60 || 90 }} + env: + # Pure-Go build: no package in the default build needs cgo, and the + # 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 -I - <<'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: + persist-credentials: false + # Two commits: the PR merge commit and its base parent, so the test + # step can see which packages the PR touches. + fetch-depth: 2 + + - name: Nested module CI contracts + 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' + run: | + python3 -B ../.github/block/scripts/doc-links-check-test.py + python3 -I ../.github/block/scripts/doc-links-check.py . + + - name: Runner disk is NVMe + # A self-hosted runner whose work, temp or Go cache directory sits on a + # SATA system disk times the process-level tests out under disk load; + # this names the runner and stops the job before it starts. + if: runner.environment == 'self-hosted' + run: | + bash .github/scripts/require-nvme-test.sh + bash .github/scripts/require-nvme.sh "$GITHUB_WORKSPACE" "$RUNNER_TEMP" "${TMPDIR:-/tmp}" "${GOCACHE:-$HOME/.cache/go-build}" + + - name: Start whole-job load evidence + # Begins after checkout, before toolchain setup/build/tests. No host + # installation or privileged reads. A job-sized lifetime also bounds + # the sampler if cancellation prevents the stop step. + continue-on-error: true + env: + CI_EVIDENCE_DIR: ${{ runner.temp }}/ci-${{ matrix.suite }}-${{ github.run_id }}-${{ github.run_attempt }} + run: | + echo "CI_EVIDENCE_DIR=$CI_EVIDENCE_DIR" >>"$GITHUB_ENV" + mkdir -p "$CI_EVIDENCE_DIR" + : >"$CI_EVIDENCE_DIR/go-test.json" + python3 -I .github/scripts/ci-load.py start "$CI_EVIDENCE_DIR/load.tsv" --duration ${{ matrix.suite == 'unit' && 2400 || 5400 }} + + - name: Self-test evidence capture + run: | + python3 -B .github/scripts/ci-load-test.py + bash .github/scripts/record-go-test-test.sh + + - name: Docs-only pull request + id: scope + if: matrix.suite == 'process' && github.event_name == 'pull_request' + # A pull request that changes only files under docs/ runs no product + # code the process-level tests could exercise, so they are skipped and + # the job still reports success. HEAD is the merge commit, HEAD^1 its + # base parent (fetch-depth 2 above). Pushes to main always run them, and + # so does any error of the check (../.github/block/scripts/docs-only-scope.sh). + run: | + set -euo pipefail + bash .github/scripts/docs-only-scope-test.sh + if out=$(bash ../.github/block/scripts/docs-only-scope.sh HEAD^1 HEAD); then + case $out in + "docs_only "*) + echo "skipped: docs only (${out#docs_only } files under docs/); the process-level tests run on the merge to main" + echo "docs_only=1" >>"$GITHUB_OUTPUT" ;; + *) echo "process-level tests run: $out" ;; + esac + else + echo "process-level tests run: the docs-only check failed" + fi + + - name: Set up Go + uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0 + with: + go-version-file: seaweed-block/go.mod + # The self-hosted runner keeps GOCACHE/GOMODCACHE on its own disk; + # uploading them as an Actions cache (~4 GB) in the post step + # outlasted the job timeout after every test had passed. Only the + # GitHub-hosted (fork PR) runner uses the Actions cache. + cache: ${{ runner.environment == 'github-hosted' }} + cache-dependency-path: seaweed-block/go.sum + + - name: Go version + if: matrix.suite == 'unit' + run: go version + + - name: Build + if: matrix.suite == 'unit' + run: go build ./... + + - name: Vet + if: matrix.suite == 'unit' + run: go vet ./... + + - name: Lab build tags stay out of images and releases + if: matrix.suite == 'unit' + # swblock_lab_bigvol lifts the 1 TiB create cap and the local + # headroom refusal for scale rehearsals only; swblock_v11_format turns + # on the draft v1.1 store format. The default test run pins the + # release cap (TestReleaseBuildKeepsTheCreateCap) and the release + # format. This step checks the tags' allowlist and that every image + # Dockerfile refuses a lab binary (scripts/refuse-lab-binary.sh) after + # its build, with controls, then tests each tag alone and both. + run: | + set -euo pipefail + bash .github/scripts/lab-tag-check.sh . + bash .github/scripts/lab-tag-check-test.sh + for tags in swblock_lab_bigvol swblock_v11_format swblock_lab_bigvol,swblock_v11_format; do + go vet -tags "$tags" ./core/geometry/ ./core/frontend/durable/ ./internal/buildinfo/ ./core/storage/ + bash .github/scripts/record-go-test.sh "$CI_EVIDENCE_DIR/go-test.json" -count=1 -tags "$tags" -run 'Lab|Headroom|Revision|LegacyBound' ./core/geometry/ ./core/frontend/durable/ ./internal/buildinfo/ + bash .github/scripts/record-go-test.sh "$CI_EVIDENCE_DIR/go-test.json" -count=1 -tags "$tags" -run 'TestV11FormatFollowsItsOwnTagAlone' ./core/storage/ + done + + - name: Test default configuration + if: matrix.suite == 'unit' + # Preserve the existing scope: main/train omit the four heavy packages; + # ordinary PRs add each only when its direct package files are touched. + # Three subprocesses share this ONE runner: storage, durable plus touched + # master/authority, and the remaining selected packages at -p=4. + env: + EVENT: ${{ github.event_name }} + HEAD_REF: ${{ github.head_ref }} + run: | + set -euo pipefail + python3 -I ../.github/block/scripts/unit-test-shards-test.py + python3 -I ../.github/block/scripts/run-unit-groups-test.py + plan="$RUNNER_TEMP/unit-groups" + mkdir -p "$plan" + go list ./... >"$plan/all.txt" + mod=$(go list -m) + # Main pushes need no changed-path list; a shallow initial push may + # have no parent. Ordinary PRs use the merge commit's base parent. + : >"$plan/changed.txt" + if [ "$EVENT" != push ] && [[ "$HEAD_REF" != train/* ]]; then + git diff --relative --name-only --no-renames HEAD^1 HEAD -- . >"$plan/changed.txt" + fi + python3 -I ../.github/block/scripts/unit-test-shards.py "$mod" "$plan" "$EVENT" "$HEAD_REF" "$plan/changed.txt" <"$plan/all.txt" + python3 -I ../.github/block/scripts/run-unit-groups.py "$plan" "$CI_EVIDENCE_DIR" "$RUNNER_TEMP/unit-group-tmp" \ + bash .github/scripts/record-go-test.sh + + - name: Format v3 tagged tests + if: matrix.suite == 'unit' + # The swblock_format_v3_test tests of the four packages that carry them. + # Five durable tests are skipped by name: each installs a BASE on a chunk + # store, which no production path does (its invariant row is DORMANT); + # they are rewritten at the start of the next release, then this skip + # goes. + run: | + set -euo pipefail + skip='^(TestDurableProviderV3_AttachesCompletedChunkBASE|TestDurableProviderV3_CompletedBASEDoesNotRestoreOlderHEAD|TestDurableProviderV3_DefersBASERetirementUntilLocalPresence|TestDurableProviderV3_FreshMarkerCrashKeepsCompletedBASE|TestDurableProviderV3_FreshMarkerCaptureCrashKeepsCompletedBASE)$' + bash .github/scripts/record-go-test.sh "$CI_EVIDENCE_DIR/go-test.json" -p=1 -count=1 -timeout 20m -tags swblock_format_v3_test -skip "$skip" \ + ./core/frontend/durable/ ./core/recovery/ ./core/replication/ ./core/transport/ + + - name: Self-test of the required-tests gate + if: matrix.suite == 'process' && steps.scope.outputs.docs_only != '1' + # The gate must fail on a skip, a failure, a test that never ran, one + # cut off mid-run, and one that reports PASS and then exits nonzero or + # hangs; this proves it before it judges the real run. + run: | + python3 -I .github/scripts/required-tests-check-test.py + bash .github/scripts/chunkstore-scope-test.sh + bash .github/scripts/run-named-tests-test.sh + python3 -I .github/scripts/shard-named-tests-test.py + + - name: Pinned SeaweedFS + if: matrix.suite == 'process' && steps.scope.outputs.docs_only != '1' + # The release archive is checked against its sha256 before every use, + # also when taken from the runner's cache; a mismatch fails the step. + # Nothing else is fetched. + env: + WEED_VERSION: "4.53" + WEED_SHA256: d1a7dec9f48d8b33895a0ea8951971defc2dc5312906dcc76fa5a5f74a6ee90d + run: | + set -euo pipefail + cache="${RUNNER_TOOL_CACHE:-$RUNNER_TEMP}/seaweedfs-weed/$WEED_VERSION" + tgz="$cache/linux_amd64.tar.gz" + mkdir -p "$cache" + if ! echo "$WEED_SHA256 $tgz" | sha256sum -c --status - 2>/dev/null; then + part="$tgz.$$.part" + curl -fsSL --retry 3 -o "$part" "https://github.com/seaweedfs/seaweedfs/releases/download/$WEED_VERSION/linux_amd64.tar.gz" + echo "$WEED_SHA256 $part" | sha256sum -c - || { rm -f "$part"; exit 1; } + mv -f "$part" "$tgz" + fi + bin="$RUNNER_TEMP/weed-$WEED_VERSION" + mkdir -p "$bin" + tar -xzf "$tgz" -C "$bin" weed + echo "CHUNKSTORE_WEED=$bin/weed" >>"$GITHUB_ENV" + + - name: Real-filer integration tests + if: matrix.suite == 'process' && steps.scope.outputs.docs_only != '1' + # The chunkstore_integration tests run against the pinned weed above + # (master, volume and filer as real processes): the conditional HEAD + # writes, cut uploads and object deletes of the chunk store, and the + # layout sync crash cases of the durable provider. They fail, never + # skip, without the binary. Pushes to main and train PRs always run + # them; another PR runs them when it touches core/frontend/chunkstore/, + # core/storage/ or core/frontend/durable/. + env: + EVENT: ${{ github.event_name }} + HEAD_REF: ${{ github.head_ref }} + # ../.github/block/scripts/chunkstore-scope.sh decides; an error of that check + # runs the tests. Each filtered run must PASS at least one test, so a + # filter that matches nothing fails instead of passing empty. + run: | + set -euo pipefail + if [ "$EVENT" != push ] && [[ "$HEAD_REF" != train/* ]]; then + if out=$(bash ../.github/block/scripts/chunkstore-scope.sh HEAD^1 HEAD); then + case $out in + "skip "*) echo "skipped: the PR touches neither core/frontend/chunkstore/ nor core/storage/ ($out)"; exit 0 ;; + *) echo "real-filer integration tests run: $out" ;; + esac + else + echo "real-filer integration tests run: the scope check failed" + fi + fi + for spec in "./core/frontend/chunkstore/ ^TestIntegration" "./core/frontend/durable/ ^TestQD1LayoutSync"; do + pkg=${spec%% *}; filter=${spec#* } + log="$RUNNER_TEMP/integration-$(basename "$pkg").log" + bash .github/scripts/record-go-test.sh "$CI_EVIDENCE_DIR/go-test.json" -count=1 -v -timeout 20m -tags chunkstore_integration -run "$filter" "$pkg" 2>&1 | tee "$log" + grep -q '^--- PASS: ' "$log" || { echo "no test of $pkg matched $filter"; exit 1; } + done + + - name: Build the binaries and the test binary once + if: matrix.suite == 'process' && steps.scope.outputs.docs_only != '1' + run: | + set -euo pipefail + bins="$RUNNER_TEMP/swblock-bins" + mkdir -p "$bins" + for b in blockmaster blockvolume sw-block; do go build -o "$bins/$b" "./cmd/$b"; done + go test -c -tags 'subprocess chunkstore_integration' -o "$bins/blockvolume.test" ./cmd/blockvolume + go test -c -o "$bins/blockcsi.test" ./cmd/blockcsi + # The known-zero acceptance's first-start crash step holds a test-only + # blockvolume (build tag kzhold, never released) at a chosen point. + go build -tags kzhold -o "$RUNNER_TEMP/blockvolume-kzhold" ./cmd/blockvolume + echo "SWBLOCK_TEST_BINS=$bins" >>"$GITHUB_ENV" + echo "KZ_HOLD_BIN=$RUNNER_TEMP/blockvolume-kzhold" >>"$GITHUB_ENV" + + - name: Run the named process-level tests + if: matrix.suite == 'process' && steps.scope.outputs.docs_only != '1' + # Each named test in its own process of the one test binary, in + # sequence, so a panic or a hang in one cannot hide the others; each + # is bounded (TEST_TIMEOUT, then killed) and its exit status is kept: + # the gate needs a PASS event AND exit 0 for every named test. The known-zero acceptance + # runs its small shape (1 GiB, user-space client, no device); the + # 1 TiB run is lab only. + env: + KZ_RUN: "1" + KZ_SIZE: 1G + F1_RUN: "1" + TEST_TIMEOUT: 15m + # A failed test copies each daemon's whole log here (keepFullLog); + # the step below keeps them as the run's artifact. + SWBLOCK_TEST_LOG_DIR: ${{ env.CI_EVIDENCE_DIR }}/daemon-logs + run: | + set -euo pipefail + # SHARDS parallel shards, balanced by their last measured times + # (.github/process-level-seconds.txt). Each shard is its own sequence + # of test processes with its own slice of the test port ranges + # (SWBLOCK_TEST_PORT_SHARD) and its own TMPDIR; the gate judges every + # named test from all the shards together. + names=.github/process-level-tests.txt + # The manifest tags CSI entries; every other name uses blockvolume.test. + # The final checker still requires the complete, unsplit manifest. + awk '!/# package=blockcsi/' "$names" > "$RUNNER_TEMP/blockvolume-names.txt" + awk '/# package=blockcsi/ {sub(/#.*/, ""); if ($0 ~ /[^[:space:]]/) print}' "$names" > "$RUNNER_TEMP/blockcsi-names.txt" + test -s "$RUNNER_TEMP/blockcsi-names.txt" + shards=4 + python3 -I .github/scripts/shard-named-tests.py "$RUNNER_TEMP/blockvolume-names.txt" .github/process-level-seconds.txt "$shards" "$RUNNER_TEMP/shard" + pids=() + for k in $(seq 1 "$shards"); do + mkdir -p "$RUNNER_TEMP/tmp-$k" + SWBLOCK_TEST_PORT_SHARD=$k SWBLOCK_TEST_PORT_SHARDS=$shards TMPDIR="$RUNNER_TEMP/tmp-$k" \ + bash .github/scripts/run-named-tests.sh "$SWBLOCK_TEST_BINS/blockvolume.test" "$RUNNER_TEMP/shard/$k.txt" \ + "$RUNNER_TEMP/process-level-$k.json" "$RUNNER_TEMP/process-level-$k.status" "$TEST_TIMEOUT" cmd/blockvolume \ + >"$RUNNER_TEMP/process-level-$k.log" 2>&1 & + pids+=($!) + done + for p in "${pids[@]}"; do wait "$p" || true; done + for k in $(seq 1 "$shards"); do sed "s/^/[shard $k] /" "$RUNNER_TEMP/process-level-$k.log"; done + # CSI uses the same per-case isolation, timeout and verdict as the shards. + TEST_PKG=github.com/seaweedfs/seaweed-block/cmd/blockcsi \ + bash .github/scripts/run-named-tests.sh "$SWBLOCK_TEST_BINS/blockcsi.test" "$RUNNER_TEMP/blockcsi-names.txt" \ + "$RUNNER_TEMP/process-level-csi.json" "$RUNNER_TEMP/process-level-csi.status" "$TEST_TIMEOUT" cmd/blockcsi \ + >"$RUNNER_TEMP/process-level-csi.log" 2>&1 || true + cat "$RUNNER_TEMP/process-level-csi.log" + cat "$RUNNER_TEMP"/process-level-*.status >"$RUNNER_TEMP/process-level.status" + python3 -I .github/scripts/required-tests-check.py --status "$RUNNER_TEMP/process-level.status" \ + "$names" "$RUNNER_TEMP"/process-level-*.json + + - name: Stop load evidence and collect raw process events + if: always() + continue-on-error: true + env: + SUITE: ${{ matrix.suite }} + run: | + if [ -z "${CI_EVIDENCE_DIR:-}" ]; then exit 0; fi + python3 -I .github/scripts/ci-load.py stop "$CI_EVIDENCE_DIR/load.tsv" || true + if [ "$SUITE" = process ]; then + mkdir -p "$CI_EVIDENCE_DIR/shards" + shopt -s nullglob + for file in "$RUNNER_TEMP"/process-level-*.json "$RUNNER_TEMP"/process-level-*.log "$RUNNER_TEMP"/process-level*.status; do + cp "$file" "$CI_EVIDENCE_DIR/shards/" + done + for file in "$CI_EVIDENCE_DIR"/shards/*.json; do cat "$file" >>"$CI_EVIDENCE_DIR/go-test.json"; done + fi + + - name: Keep failed-job tests, load, daemon logs and shard results + # Both suites retain timed events and whole-job load. Process evidence + # also retains the original shard receipts and full daemon logs. + if: failure() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: ci-${{ matrix.suite }}-${{ github.run_id }}-${{ github.run_attempt }} + 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 -I - <<'PY' + import os + from pathlib import Path + import shutil + import sys + root = Path(os.environ["GITHUB_WORKSPACE"]) + # Refuse aliases rather than resolving them. Open EVERY component without + # following symlinks, then keep cleanup anchored to the verified directory fd. + if not root.is_absolute() or ".." in root.parts or root == Path(root.anchor) or root.name != root.parent.name or root == Path(os.environ["RUNNER_TEMP"]): + print(f"runner_workspace_cleanup_refused path={str(root)!r}") + sys.exit(1) + flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW + fd = os.open(root.anchor, flags) + previous = os.open(".", flags) + errors = [] + try: + for part in root.parts[1:]: + child = os.open(part, flags, dir_fd=fd) + os.close(fd) + fd = child + if not shutil.rmtree.avoids_symlink_attacks: + raise OSError("descriptor-safe directory removal is unavailable") + os.fchdir(fd) + for entry in os.scandir("."): + try: + if entry.is_dir(follow_symlinks=False): + shutil.rmtree(entry.name) + else: + os.unlink(entry.name) + except OSError as err: + errors.append(f"{entry.name}: {err}") + except OSError as err: + print(f"runner_workspace_cleanup_refused path={str(root)!r} error={err}") + sys.exit(1) + finally: + os.fchdir(previous) + os.close(previous) + os.close(fd) + if errors: + print("runner_workspace_cleanup_failed " + "; ".join(errors)) + sys.exit(1) + print(f"runner_workspace_clean path={str(root)!r}") + PY