Compare commits

..
Author SHA1 Message Date
Chris Lu f35caf8be3 mq: read a recorded offset range that ends at offset 0
The broker and the Kafka gateway each scanned a partition's files for
the high water mark and counted a maximum only when it was above 0, so
a partition holding one message still read as empty. Both now share
mq.OffsetRange, which tracks whether a range was found apart from its
value.
2026-11-30 13:45:28 -08:00
Chris Lu 89f70bb012 mq: record the offset range of a partition's first window
The flush wrote offset_min/offset_max only when minOffset > 0, using 0
as "no range given". A partition's first window starts at offset 0, so
its file never got a range. A restarted broker derives the high water
mark from those ranges, so a partition whose data was all in its first
file read as empty.
2026-11-30 13:38:14 -08:00
4691 changed files with 11770 additions and 744638 deletions

No files matched your search

+2 -6
View File
@@ -1,6 +1,6 @@
[codespell]
# Ref: https://github.com/codespell-project/codespell#using-a-config-file
skip = .git,.git-meta,.gitignore,.gitattributes,*.svg,go.sum,vendor,*.lock,*.css,*.min.*,.codespellrc,*_templ.go,*.tla
skip = .git,.git-meta,.gitignore,.gitattributes,*.svg,go.sum,vendor,*.lock,*.css,*.min.*,.codespellrc,*_templ.go
check-hidden = true
# Ignore camelCase and PascalCase identifiers (very common in Go/Rust/JS
# source, e.g. allLocations, publishErr, ReadInside, FlushInterval).
@@ -21,10 +21,6 @@ ignore-regex = \b[a-z]+[A-Z]\w*\b|\b[A-Z][a-z]+[A-Z]\w*\b
# atleast: CLI mode literal string in test/benchmark/fuse_db/bin/sqlite_verify.py
# sme: local variable for a *streamMutateError in mount tests
# nin: AWS S3 Vectors "$nin" filter operator literal (API-defined, cannot rename)
# aer: NVMe Asynchronous Event Request (spec term, seaweed-block NVMe/TCP target)
# aas: iSCSI ALUA Access State; dout: iSCSI Data-Out PDU (seaweed-block iSCSI target)
# nd, readds, wonce, abd, delet, re-declare: identifiers and test fixture literals in seaweed-block
# lits: Go AST literal slices in seaweed-block tests (internal/timebound/scan_test.go)
ignore-words-list = visibles,fo,te,ser,bject,unparseable,keep-alives,tread,anc,ue,auther,thirdparty,unknwon,atleast,sme,nin,aer,aas,dout,nd,readds,wonce,abd,delet,re-declare,lits
ignore-words-list = visibles,fo,te,ser,bject,unparseable,keep-alives,tread,anc,ue,auther,thirdparty,unknwon,atleast,sme,nin
# poligon: Yandex Disk API sandbox URL path (https://yandex.ru/dev/disk/poligon/)
uri-ignore-words-list = poligon
-41
View File
@@ -1,41 +0,0 @@
# 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.
-408
View File
@@ -1,408 +0,0 @@
"""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()
-30
View File
@@ -1,30 +0,0 @@
#!/usr/bin/env bash
# Writes the old and new blob of each changed non-test Go file between two
# commits under <out>/old/<path> and <out>/new/<path>, for the spec trace's
# kind DOCS (objects only; nothing from the PR is built or run).
#
# usage: changed-go-blobs.sh <merge-base> <head> <out>
#
# 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 <out>, 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"
-13
View File
@@ -1,13 +0,0 @@
#!/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"
-33
View File
@@ -1,33 +0,0 @@
#!/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
@@ -1,142 +0,0 @@
"""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]: <docs/a b.md>\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()
-128
View File
@@ -1,128 +0,0 @@
#!/usr/bin/env python3
"""Fail when a Markdown file links to a relative path that does not exist.
Usage: doc-links-check.py <root>
"""
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))
-35
View File
@@ -1,35 +0,0 @@
#!/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
-121
View File
@@ -1,121 +0,0 @@
"""Check that every code and test anchor of the invariants ledger exists at a git ref.
usage: python -I ledger_check.py <repo-dir> <git-ref> [<ledger path in repo>]
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()
@@ -1,14 +0,0 @@
#!/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
@@ -1,70 +0,0 @@
#!/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"
@@ -1,145 +0,0 @@
"""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()
-123
View File
@@ -1,123 +0,0 @@
"""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))
@@ -1,106 +0,0 @@
"""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, "<workflow>", "exec"), {})
except SystemExit as err:
return err.code, output.getvalue()
return 0, output.getvalue()
class RunnerWorkspaceTests(unittest.TestCase):
def test_every_job_checks_before_checkout_and_cleans_last_even_on_failure(self):
for path in WORKFLOWS:
text = path.read_text()
before = step(text, "Runner free space")
after = step(text, "Clean job workspace")
self.assertLess(text.index("- name: Runner free space"), text.index("- name: Checkout"), path.name)
self.assertIn("if: always() && runner.environment == 'self-hosted'", after)
self.assertNotIn("continue-on-error", after)
self.assertNotIn("- name:", text.split("- name: Clean job workspace", 1)[1])
self.assertIn("working-directory: ${{ runner.temp }}", before)
self.assertIn("working-directory: ${{ runner.temp }}", after)
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()
-132
View File
@@ -1,132 +0,0 @@
"""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)
@@ -1,52 +0,0 @@
"""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()
-55
View File
@@ -1,55 +0,0 @@
"""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))
@@ -1,27 +0,0 @@
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"]
@@ -1,24 +0,0 @@
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
-127
View File
@@ -1,127 +0,0 @@
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
@@ -1,146 +0,0 @@
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 <host.bin
bash .github/scripts/post-merge-review-check.sh .github/post-merge-review-allow.txt <changed.bin
exit "$host"
- 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
-201
View File
@@ -1,201 +0,0 @@
name: Publish block release
on:
workflow_dispatch:
push:
tags:
- "seaweed-block/v*"
permissions:
contents: write
packages: write
env:
REGISTRY: ghcr.io
BLOCK_IMAGE: ghcr.io/seaweedfs/seaweed-block
CSI_IMAGE: ghcr.io/seaweedfs/seaweed-block-csi
jobs:
publish:
# Publish only from a version tag; a manual run from a branch must not move :alpha.
if: startsWith(github.ref, 'refs/tags/seaweed-block/v')
runs-on: ubuntu-latest
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@v4
with:
fetch-depth: 0 # the tag list decides whether :alpha moves
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Log in to GHCR
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Compute image tags
id: tags
shell: bash
run: |
set -euo pipefail
# vX.Y.Z-pre (a release candidate) publishes only its own version tag. A stable vX.Y.Z also
# publishes sha-*, and moves :alpha only when it is the highest stable version tag, so a later
# patch on an older line never moves :alpha back.
short_sha="${GITHUB_SHA::12}"
version="${GITHUB_REF_NAME#seaweed-block/}"
if [[ ! "${version}" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.]+)?$ ]]; then
echo "refusing to publish: tag ${version} is not vX.Y.Z or vX.Y.Z-pre" >&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<<EOF"
echo "${BLOCK_IMAGE}:${version}"
if [[ "${stable}" == true ]]; then echo "${BLOCK_IMAGE}:sha-${short_sha}"; fi
if [[ "${move_alpha}" == true ]]; then echo "${BLOCK_IMAGE}:alpha"; fi
echo "EOF"
echo "csi_tags<<EOF"
echo "${CSI_IMAGE}:${version}"
if [[ "${stable}" == true ]]; then echo "${CSI_IMAGE}:sha-${short_sha}"; fi
if [[ "${move_alpha}" == true ]]; then echo "${CSI_IMAGE}:alpha"; fi
echo "EOF"
} >> "$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
-164
View File
@@ -1,164 +0,0 @@
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 <changed.bin
# Internal names stay out of this public repository: added lines,
# commit messages, title and description (no PR code is run).
bash .github/scripts/public-text-check-test.sh
printf '%s' "$TITLE" >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
-445
View File
@@ -1,445 +0,0 @@
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
-65
View File
@@ -1,65 +0,0 @@
name: "FUSE Mount Handover Tests"
on:
pull_request:
paths:
- 'weed/command/mount*.go'
- 'weed/mount/**'
- 'weed/pb/mount_handover_pb/**'
- 'test/fuse_handover/**'
- '.github/workflows/fuse-handover.yml'
- '.github/actions/fix-fusermount-setuid/**'
push:
branches: [master]
paths:
- 'weed/command/mount*.go'
- 'weed/mount/**'
- 'weed/pb/mount_handover_pb/**'
- 'test/fuse_handover/**'
- '.github/actions/fix-fusermount-setuid/**'
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || (github.event_name == 'push' && github.ref) || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' || (github.event_name == 'push' && !startsWith(github.ref, 'refs/tags/')) }}
permissions:
contents: read
jobs:
fuse-handover:
name: FUSE Mount Handover Tests
runs-on: ubuntu-24.04
timeout-minutes: 30
steps:
- name: Check out code
uses: actions/checkout@v7
- name: Set up Go
uses: actions/setup-go@v7
with:
go-version-file: 'go.mod'
cache: ${{ runner.environment == 'github-hosted' }}
# The tests mount as the runner user through fusermount3, without
# allow_other: nothing to install or configure besides the setuid bit.
- name: Repair the fusermount3 setuid bit
uses: ./.github/actions/fix-fusermount-setuid
- name: Build SeaweedFS
run: go build -o weed/weed -buildvcs=false ./weed
- name: Run handover tests
timeout-minutes: 25
env:
WEED_BINARY: ${{ github.workspace }}/weed/weed
run: go test -v -count=1 -timeout=20m ./test/fuse_handover/...
# A failed test keeps the weed logs in /tmp/fuse_handover_*.
- name: Upload logs on failure
if: failure()
uses: actions/upload-artifact@v7
with:
name: fuse-handover-test-logs
path: /tmp/fuse_handover_*/*.log
retention-days: 3
-24
View File
@@ -125,28 +125,6 @@ jobs:
--health-interval 10s
--health-timeout 5s
--health-retries 5
postgres:
image: postgres:17
env:
POSTGRES_PASSWORD: postgres
ports:
- 5432:5432
options: >-
--health-cmd "pg_isready -U postgres"
--health-interval 10s
--health-timeout 5s
--health-retries 5
mysql:
image: mysql:8.4
env:
MYSQL_ROOT_PASSWORD: root
ports:
- 3306:3306
options: >-
--health-cmd "mysqladmin ping -uroot -proot"
--health-interval 10s
--health-timeout 5s
--health-retries 10
steps:
- name: Check out code into the Go module directory
uses: actions/checkout@v7
@@ -158,8 +136,6 @@ jobs:
- name: Test
env:
RUN_REDIS_TESTS: "1"
RUN_POSTGRES_TESTS: "1"
RUN_MYSQL_TESTS: "1"
run: cd weed; go test -tags "elastic gocdk sqlite ydb tarantool tikv rclone" -v ./...
test-32bit:
-138
View File
@@ -1,138 +0,0 @@
name: "postgres_flat Filer Store Tests"
on:
push:
branches: [ master ]
paths:
- 'weed/**'
- 'test/postgres_flat/**'
- 'test/s3/versioning/**'
- 'test/testutil/**'
- 'test/volume_server/framework/**'
- 'go.mod'
- 'go.sum'
- '.github/workflows/postgres-flat-tests.yml'
- '.github/actions/fix-fusermount-setuid/**'
pull_request:
paths:
- 'weed/**'
- 'test/postgres_flat/**'
- 'test/s3/versioning/**'
- 'test/testutil/**'
- 'test/volume_server/framework/**'
- 'go.mod'
- 'go.sum'
- '.github/workflows/postgres-flat-tests.yml'
- '.github/actions/fix-fusermount-setuid/**'
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || (github.event_name == 'push' && github.ref) || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' || (github.event_name == 'push' && !startsWith(github.ref, 'refs/tags/')) }}
permissions:
contents: read
jobs:
postgres-flat:
name: S3 and POSIX over postgres_flat
runs-on: ubuntu-24.04
timeout-minutes: 30
services:
postgres:
image: postgres:17
env:
POSTGRES_PASSWORD: postgres
ports:
- 5432:5432
options: >-
--health-cmd pg_isready
--health-interval 5s
--health-timeout 5s
--health-retries 20
steps:
- name: Checkout code
uses: actions/checkout@v7
- name: Set up Go
uses: actions/setup-go@v7
with:
go-version-file: 'go.mod'
cache: ${{ runner.environment == 'github-hosted' }}
- name: Repair the fusermount3 setuid bit
uses: ./.github/actions/fix-fusermount-setuid
- name: Build SeaweedFS
run: go build -o weed/weed -buildvcs=false ./weed
- name: Run tests
env:
RUN_POSTGRES_TESTS: "1"
WEED_BINARY: ${{ github.workspace }}/weed/weed
run: go test -v -count=1 -timeout=20m ./test/postgres_flat/
versioning-suite:
name: S3 versioning suite over postgres_flat
runs-on: ubuntu-24.04
timeout-minutes: 30
services:
postgres:
image: postgres:17
env:
POSTGRES_PASSWORD: postgres
ports:
- 5432:5432
options: >-
--health-cmd pg_isready
--health-interval 5s
--health-timeout 5s
--health-retries 20
steps:
- name: Checkout code
uses: actions/checkout@v7
- name: Set up Go
uses: actions/setup-go@v7
with:
go-version-file: 'go.mod'
cache: ${{ runner.environment == 'github-hosted' }}
- name: Build SeaweedFS
run: go build -o weed/weed -buildvcs=false ./weed
- name: Start weed mini on postgres_flat
run: |
mkdir -p "$RUNNER_TEMP/config" "$RUNNER_TEMP/data"
: > "$RUNNER_TEMP/config/security.toml"
cat > "$RUNNER_TEMP/config/filer.toml" <<'EOF'
[postgres_flat]
enabled = true
hostname = "127.0.0.1"
port = 5432
username = "postgres"
password = "postgres"
database = "postgres"
sslmode = "disable"
EOF
weed/weed -config_dir="$RUNNER_TEMP/config" mini -ip=127.0.0.1 -ip.bind=127.0.0.1 \
-dir="$RUNNER_TEMP/data" -s3.config="$GITHUB_WORKSPACE/docker/compose/s3.json" \
-webdav=false -admin.ui=false > "$RUNNER_TEMP/weed.log" 2>&1 &
ready() {
curl -s -o /dev/null http://127.0.0.1:8333 &&
test "$(docker exec ${{ job.services.postgres.id }} psql -U postgres -Atc "SELECT count(*) FROM information_schema.columns WHERE table_name = 'filemeta' AND column_name = 'path'")" = 1
}
for i in $(seq 90); do ready && break; sleep 1; done
ready || { cat "$RUNNER_TEMP/weed.log"; exit 1; }
- name: Run the S3 versioning suite
env:
ENABLE_STRESS_TESTS: "true"
run: go test -v -count=1 -timeout=25m ./test/s3/versioning/
- name: Show the server log
if: failure()
run: tail -200 "$RUNNER_TEMP/weed.log"
+2 -37
View File
@@ -4,11 +4,8 @@ name: "S3 digest and FIPS matrix"
# signing on, so the sha256 digest and GODEBUG=fips140=only stay working:
# md5 GODEBUG=fips140=off, the default digest
# sha256 GODEBUG=fips140=on with the filer's -digest=sha256
# fips140only GODEBUG=fips140=only and WEED_FIPS_MODE=strict, built with
# GOFIPS140=v1.0.0
# test/s3/digest_matrix/start_cluster.sh starts each cell's cluster. The
# negative-config job checks what strict mode refuses at startup
# (test/s3/digest_matrix/negative_config.sh).
# fips140only GODEBUG=fips140=only, built with GOFIPS140=v1.0.0
# test/s3/digest_matrix/start_cluster.sh starts each cell's cluster.
on:
push:
@@ -118,38 +115,6 @@ jobs:
retention-days: 1
path: digest-matrix-binaries.tar
negative-config:
name: Strict FIPS mode refusals
needs: build
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
- uses: actions/checkout@v7
- uses: actions/download-artifact@v8
with:
name: digest-matrix-binaries
- name: Restore binaries
run: |
tar xf digest-matrix-binaries.tar
chmod +x weed/weed seaweed-volume/target/release/weed-volume
- name: Short keys refused
env:
WEED: ${{ github.workspace }}/weed/weed
WEED_VOLUME: ${{ github.workspace }}/seaweed-volume/target/release/weed-volume
WORK_DIR: /tmp/negative-config
run: bash test/s3/digest_matrix/negative_config.sh
- name: Upload logs on failure
if: failure()
uses: actions/upload-artifact@v7
with:
name: negative-config-logs
path: /tmp/negative-config/**/*.log
retention-days: 3
suites:
name: S3 suites (${{ matrix.digest }}, ${{ matrix.volume }} volume server)
needs: build
@@ -73,20 +73,6 @@ jobs:
echo "=== Running S3 Prefix Object Tests ==="
go test -v -timeout=180s -run TestS3PrefixObjectKeys ./...
- name: Run S3 GetPart Tests
timeout-minutes: 15
working-directory: test/s3/normal
run: |
set -x
go test -v -timeout=180s -run TestS3GetPart ./...
- name: Run S3 Bucket Default Storage Class Tests
timeout-minutes: 15
working-directory: test/s3/normal
run: |
set -x
go test -v -timeout=180s -run TestS3BucketDefaultStorageClass ./...
- name: Run IAM Integration Tests
timeout-minutes: 15
working-directory: test/s3/normal
+2 -2
View File
@@ -93,8 +93,8 @@ RUN mkdir -p /etc/seaweedfs
COPY --from=builder /go/src/github.com/seaweedfs/seaweedfs/docker/filer.toml /etc/seaweedfs/filer.toml
COPY --from=builder /go/src/github.com/seaweedfs/seaweedfs/docker/entrypoint.sh /entrypoint.sh
# FIPS 140-3 mode is on by default for every process (entrypoint.sh)
# To disable: docker run -e WEED_FIPS_MODE=off ...
# FIPS 140-3 mode is ON by default (Go 1.24+)
# To disable: docker run -e GODEBUG=fips140=off ...
# Install dependencies and create non-root user
RUN apk upgrade --no-cache && \
+9 -44
View File
@@ -1,5 +1,14 @@
#!/bin/sh
# Enable FIPS 140-3 mode by default (Go 1.24+)
# To disable: docker run -e GODEBUG=fips140=off ...
# For strict mode: docker run -e GODEBUG=fips140=only ...
# The default goes first: Go applies the last of repeated GODEBUG settings, so
# the caller's fips140 value wins.
# Transparent huge pages are a host-wide setting this image cannot change; to
# turn them off for this process only, append GODEBUG=disablethp=1.
export GODEBUG="fips140=on${GODEBUG:+,$GODEBUG}"
# Fix permissions for mounted volumes
# If /data is mounted from host, it might have different ownership
# Fix this by ensuring seaweed user owns the directory
@@ -28,54 +37,10 @@ if [ "$(id -u)" = "0" ]; then
fi
fi
# A restrictive Docker daemon umask can leave these 0600, and the resolver
# then falls back to a nameserver on localhost once privileges are dropped.
for f in /etc/resolv.conf /etc/hosts; do
if [ -f "$f" ] && ! su-exec seaweed test -r "$f"; then
chmod a+r "$f" 2>/dev/null
fi
done
# Use su-exec to drop privileges and run as seaweed user
exec su-exec seaweed "$0" "$@"
fi
# FIPS 140-3 mode is on by default, for the Go processes and the Rust
# binaries alike. To pick another mode: docker run -e WEED_FIPS_MODE=off (or
# strict). A fips.mode in security.toml alone cannot change it, since Go
# processes would still get this mode's fips140 and refuse to start.
# WEED_FIPS_MODE_DEFAULT is the mode when nothing else sets one; set it empty
# to leave every process in its own default (fips140=off for Go, off for Rust).
# A fips140 the caller puts in GODEBUG still picks the mode, for the Rust
# binaries as well, unless WEED_FIPS_MODE is set, but is deprecated and warns;
# a Go process refuses to start when its fips140 differs from WEED_FIPS_MODE or
# fips.mode.
# Transparent huge pages are a host-wide setting this image cannot change; to
# turn them off for this process only, append GODEBUG=disablethp=1.
export WEED_FIPS_MODE_DEFAULT="${WEED_FIPS_MODE_DEFAULT-on}"
godebug_fips140="$(printf '%s\n' "$GODEBUG" | tr ',' '\n' | sed -n 's/^fips140=/=/p' | tail -n 1)"
case "$godebug_fips140" in
=off | =) WEED_FIPS_MODE_DEFAULT=off ;;
=on | =debug) WEED_FIPS_MODE_DEFAULT=on ;;
=only) WEED_FIPS_MODE_DEFAULT=strict ;;
esac
if [ -n "$godebug_fips140" ] && [ -z "$WEED_FIPS_MODE" ]; then
echo "Warning: choosing the FIPS mode with GODEBUG=fips140 is deprecated; set WEED_FIPS_MODE=off, on or strict, which also covers the Rust binaries when they start without this entrypoint." >&2
fi
case "${WEED_FIPS_MODE:-$WEED_FIPS_MODE_DEFAULT}" in
off) fips140=off ;;
on) fips140=on ;;
strict) fips140=only ;;
*) fips140= ;;
esac
export GODEBUG="${fips140:+fips140=$fips140}${fips140:+${GODEBUG:+,}}${GODEBUG}"
for f in /etc/resolv.conf /etc/hosts; do
if [ -f "$f" ] && [ ! -r "$f" ]; then
echo "Warning: $f is not readable by uid $(id -u), so host name lookups may fail. Make it world-readable (0644)." >&2
fi
done
isArgPassed() {
# Match both `-flag` and `--flag` (and their `=value` forms): the Go fla9
# library accepts both, and users may pick either form on the CLI.
+7 -9
View File
@@ -30,12 +30,10 @@ Override `SEAWEEDFS_IMAGE` to test a newer image. With metrics-enabled engines,
append `--metrics-port=9329 --metrics-ip=0.0.0.0` to the vector command and scrape
`vector:9329/metrics` inside the Compose network.
A native development setup can use `weed mini -vectorBucket=embeddings`. Mini
starts `weed-vector` and the `weed-worker` maintenance worker when it finds them
beside `weed` or on PATH, and logs and continues without one it cannot find.
`-vector.binary` selects an explicit engine binary, and `weed-worker` is also
looked up beside it. `-vector=false` leaves both out, and
`-vector.metricsPort=9329` enables HTTP readiness and metrics on a compatible
engine. The children inherit the cluster's configuration directory and stop with
mini. `weed shell` provides `s3vectors -operation <Operation> -file
request.json` for the same API operations using trusted cluster credentials.
A native development setup can use `weed mini -vector -vectorBucket=embeddings`
with `weed-vector` beside `weed` or on PATH. `-vector.binary` selects an explicit
binary, and `-vector.metricsPort=9329` enables HTTP readiness and metrics on a
compatible engine. The child inherits the cluster's configuration directory and
stops with mini. Run `weed-worker` separately for ANN maintenance. `weed shell`
provides `s3vectors -operation <Operation> -file request.json` for the same API
operations using trusted cluster credentials.
+1 -1
View File
@@ -1,7 +1,7 @@
services:
seaweedfs:
image: ${SEAWEEDFS_IMAGE:-chrislusf/seaweedfs:4.53}
command: mini -dir=/data -ip=seaweedfs -ip.bind=0.0.0.0 -admin.password=vector-demo -admin.worker.ip=0.0.0.0 -tableBucket=embeddings:LANCE -vector=false
command: mini -dir=/data -ip=seaweedfs -ip.bind=0.0.0.0 -admin.password=vector-demo -admin.worker.ip=0.0.0.0 -tableBucket=embeddings:LANCE
environment: &environment
WEED_JWT_FILER_SIGNING_KEY: vector-demo-cluster-key
AWS_ACCESS_KEY_ID: vector-demo
+12 -14
View File
@@ -12,7 +12,6 @@ require (
github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.8.3
github.com/DATA-DOG/go-sqlmock v1.5.2
github.com/Jille/raft-grpc-transport v1.6.1
github.com/KimMachineGun/automemlimit v1.0.2
github.com/Shopify/sarama v1.38.1
github.com/ThreeDotsLabs/watermill v1.5.3
github.com/a-h/templ v0.3.1100
@@ -22,12 +21,12 @@ require (
github.com/apple/foundationdb/bindings/go v0.0.0-20250911184653-27f7192f47c3
github.com/arangodb/go-driver v1.6.9
github.com/aws/aws-sdk-go v1.55.8
github.com/aws/aws-sdk-go-v2 v1.49.0
github.com/aws/aws-sdk-go-v2 v1.48.1
github.com/aws/aws-sdk-go-v2/config v1.33.9
github.com/aws/aws-sdk-go-v2/credentials v1.20.9
github.com/aws/aws-sdk-go-v2/service/s3 v1.117.1
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.10
github.com/aws/aws-sdk-go-v2/service/sts v1.51.6
github.com/aws/smithy-go v1.28.11
github.com/aws/smithy-go v1.28.10
github.com/bwmarrin/snowflake v0.3.0
github.com/cenkalti/backoff/v4 v4.3.0
github.com/cespare/xxhash/v2 v2.3.0
@@ -84,7 +83,7 @@ require (
github.com/redis/go-redis/v9 v9.23.0
github.com/schollz/progressbar/v3 v3.19.1
github.com/seaweedfs/cockroachdb-parser v0.0.0-20260225204133-2f342c5ea564
github.com/seaweedfs/go-fuse/v2 v2.9.6
github.com/seaweedfs/go-fuse/v2 v2.9.5
github.com/seaweedfs/goexif v1.0.3
github.com/seaweedfs/raft v1.2.4
github.com/shirou/gopsutil/v4 v4.26.10
@@ -179,16 +178,16 @@ require (
github.com/apache/thrift v0.25.0 // indirect
github.com/appscode/go-querystring v0.0.0-20170504095604-0126cfb3f1dc // indirect
github.com/arangodb/go-velocypack v0.0.0-20200318135517-5af53c29c67e // indirect
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.29 // indirect
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.27 // indirect
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.3 // indirect
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.22.34 // indirect
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.15 // indirect
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.15 // indirect
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.15 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.27 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.16 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.15 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.15 // indirect
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.12 // indirect
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.12 // indirect
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.12 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.25 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.13 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.12 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.12 // indirect
github.com/aws/aws-sdk-go-v2/service/signin v1.10.4 // indirect
github.com/aws/aws-sdk-go-v2/service/sns v1.47.5 // indirect
github.com/aws/aws-sdk-go-v2/service/sqs v1.52.4 // indirect
@@ -379,7 +378,6 @@ require (
github.com/parquet-go/bitpack v1.1.1 // indirect
github.com/parquet-go/jsonlite v1.5.7 // indirect
github.com/patrickmn/go-cache v2.1.0+incompatible // indirect
github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58 // indirect
github.com/pelletier/go-toml/v2 v2.4.3 // indirect
github.com/pengsrc/go-shared v0.2.1-0.20190131101655-1999055a4a14 // indirect
github.com/petermattis/goid v0.0.0-20260113132338-7c7de50cc741 // indirect
+24 -28
View File
@@ -85,8 +85,6 @@ github.com/IBM/go-sdk-core/v5 v5.23.1 h1:fxLusCG+GlGY1SM7BYAAiiSFhzKUs5zqs0P8knD
github.com/IBM/go-sdk-core/v5 v5.23.1/go.mod h1:yO+OQpByKDLTvpEcsFFexgzpeR8eRfCFWAYzxkAu4bk=
github.com/Jille/raft-grpc-transport v1.6.1 h1:gN3sjapb+fVbiebS7AfQQgbV2ecTOI7ur7NPPC7Mhoc=
github.com/Jille/raft-grpc-transport v1.6.1/go.mod h1:HbOjEdu/yzCJ/mjTF6wEOJNbAUpHfU2UOA2hVD4CNFg=
github.com/KimMachineGun/automemlimit v1.0.2 h1:DkORkhuzrwT2/b35xz8zLd7cJ6Hu2ESRGBY8HKUFIYk=
github.com/KimMachineGun/automemlimit v1.0.2/go.mod h1:n+BSXxQWDFS1DKh67Rqo0lgTsowsg6x65ak5uyngML0=
github.com/Masterminds/semver/v3 v3.2.0 h1:3MEsd0SM6jqZojhjLWWeBY+Kcjy9i6MQAeY7YgDP83g=
github.com/Masterminds/semver/v3 v3.2.0/go.mod h1:qvl/7zhW3nngYb5+80sSMF+FG2BjYrf8m9wsX0PNOMQ=
github.com/Max-Sum/base32768 v0.0.0-20230304063302-18e6ce5945fd h1:nzE1YQBdx1bq9IlZinHa+HVffy+NmVRoKr+wHN8fpLE=
@@ -173,10 +171,10 @@ github.com/armon/go-metrics v0.4.1 h1:hR91U9KYmb6bLBYLQjyM+3j+rcd/UhE+G78SFnF8gJ
github.com/armon/go-metrics v0.4.1/go.mod h1:E6amYzXo6aW1tqzoZGT755KkbgrJsSdpwZ+3JqfkOG4=
github.com/aws/aws-sdk-go v1.55.8 h1:JRmEUbU52aJQZ2AjX4q4Wu7t4uZjOu71uyNmaWlUkJQ=
github.com/aws/aws-sdk-go v1.55.8/go.mod h1:ZkViS9AqA6otK+JBBNH2++sx1sgxrPKcSzPPvQkUtXk=
github.com/aws/aws-sdk-go-v2 v1.49.0 h1:nfIScsXPSCz+vXIKz49IjNPHmC4oT72SLPVc8P0OBbU=
github.com/aws/aws-sdk-go-v2 v1.49.0/go.mod h1:XwfdWCjuiyYPbYF4ObLoa5I25KjV0ry6d105smVjNKY=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.29 h1:LfdRwpJ0Dfh+vpqHevmmnFnMoc3/lfB4pdHOfWpLfH4=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.29/go.mod h1:r6fijnrGRQ4OnSGyHYuFcC7G6wdwB4Ld8WhiIaGZHx0=
github.com/aws/aws-sdk-go-v2 v1.48.1 h1:j6ro6IvbxUe8BCulc/6uWMrhmx6+i5HNIc1GZEJRT9k=
github.com/aws/aws-sdk-go-v2 v1.48.1/go.mod h1:HP8Jzg1FDurJomtx40YM0eiLoJrwjjZ9X+4BNpy4OXc=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.27 h1:3dMP9eEmHVosFN1QiD24IJBKVY8m6iUfVYXqRCT118Q=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.27/go.mod h1:KH4PKcqtjy1m0656eqQV2v53xE04ddJzuNloEKqlHkI=
github.com/aws/aws-sdk-go-v2/config v1.33.9 h1:Hv6bcQUJVnmuWaKjqD6Ot8sE75NrWsWV20oGT5aWle0=
github.com/aws/aws-sdk-go-v2/config v1.33.9/go.mod h1:ivowmrZNfBQLcg4QkaItgi5wae4Bzot9RzIdbY1hfTg=
github.com/aws/aws-sdk-go-v2/credentials v1.20.9 h1:SNO55PnWhaDafsOcv16lCA0kdoFMl/YlegWoVsU02s0=
@@ -187,22 +185,22 @@ github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.22.34 h1:Pn7OsMwBLbkZ6OnCxWHA
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.22.34/go.mod h1:eToXR/Gk1uqpn04eSmdgVXwfS0WvH8aG4eBFr8ygbpU=
github.com/aws/aws-sdk-go-v2/feature/s3/transfermanager v0.4.16 h1:q9YuNkYR/7lxflWCcEv3C0cecUt3Zvrh2hn9ZNxieNA=
github.com/aws/aws-sdk-go-v2/feature/s3/transfermanager v0.4.16/go.mod h1:3BSeJQF55QQI+dDFHx4WTIjTvX/Lvtk8Jaaf/SGAnBM=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.15 h1:Y0fe1Hcly/OSHtSWzuQrXGt3RtRjso063UbwZgyCHyQ=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.15/go.mod h1:52lvlO6umU2TRGxZJfCtjOR6xnbJotZD11mmzhJLQzI=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.15 h1:g2qcH0dUfjjigOI+HQB3DLXDq/8c84uH1ii/SDkwatg=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.15/go.mod h1:yGE7vsxRwTs6YBSYcE1j/KNA7EmAGEgBX+TAH0AAvk0=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.15 h1:XKIkHY7yRHnTJrixMmcA1qIm3qenDe/vmOtf/xiuWYE=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.15/go.mod h1:HqYW3gHCQl0tF6dO7kXgc0wFe1Yng0hgCEI7Xa3rK54=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.27 h1:2jIfOe8ZuoStxOkRtVU45zxgvt/qeIRChhm2USOS6g8=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.27/go.mod h1:LpMjYa8iT3kMkAxsVCGfyXkBDOOKsziY6S2wSpEvY70=
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.16 h1:D2smhPZgqVLuc8rmuvb6wrG4sgut9iv1BN8W2twFtfo=
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.16/go.mod h1:HheOgBYcgoZgeKSLVEmk9whxHERlVXAKTVWK3xizKeo=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.15 h1:ds6Pm/S5xYXPmiqyebd0AeK0zHAAO7qHP1+JZauFnpA=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.15/go.mod h1:WqaHpxUhwzsE+NYp2TQitKclpwhi1XYp6wMsdg+yd/k=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.15 h1:5w2E7ndu7XOt62yvu2vGm/Rv7WDn1oQjrJ7Dt1NTVTM=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.15/go.mod h1:1WgfBCsJYL6E7T2QkkE8kQvo7uG+5+z2LpaQ9L6pjZs=
github.com/aws/aws-sdk-go-v2/service/s3 v1.117.1 h1:fOeEIKMlgwKbMFSNMM+pLo2NPRJ1dSKbaAuZYGXUVR0=
github.com/aws/aws-sdk-go-v2/service/s3 v1.117.1/go.mod h1:xHaAZkbYuIc9UtLZxdoeyhzmx06g1paDjPkHgljJU/I=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.12 h1:W0yUUzKBA8SofGQ0yZafEUuZq9UxfvijRgdc6vcRQPA=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.12/go.mod h1:xwKv6vwBNdpPFOxEm/ld4IODZK2s/1ksHvdBqLfH6Gs=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.12 h1:lqSi8qvAnKC1vfosImdmOsuiJLr/jdybZX5299beB6Q=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.12/go.mod h1:rqPQE2vqkW9YHx5+Gp55sx1wsTM4xtGQLl+TKMjxxrs=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.12 h1:uvX2yaL+aMjkmnrLPPlR/zwjoKFRMoNhhJfeGjfk6qc=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.12/go.mod h1:dicT+2eNhHHqGkxHO7LoXw3QghIUGuzgdmFqaSTopgI=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.25 h1:rKwkY3Z+fvt2W0msjdNs6uNewPmXzPayQ961oyuWhes=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.25/go.mod h1:dBuAadQKd1F4Q4ZOg8gnFmuSHMRE40Pe3IfFwbtC4lE=
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.13 h1:U5HZ8FpTr6tyvulf1nT11Nw4KG1CAsXkuQGdUrIjZ/E=
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.13/go.mod h1:dUfvCU1NaE+b3vqNENDiJncUQW7Djl5pmgUlcjesVqk=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.12 h1:wzAqMZ2O4+ij9HQqIrk+P9PBGacE0wOTuWB7Mo97//I=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.12/go.mod h1:/0TfyruByHsOlphzP26xDTRe2DKD0J1I1Uyy2TyP8EI=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.12 h1:H0IaQayT3TLiGIHiNnleQZTbndDlx7LGZ0NWZ5mDwjA=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.12/go.mod h1:YuJJNxaOjnknLIrscBmkLhIpnmg9LzHd25sQRKUboGU=
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.10 h1:WBJb2VxRzzKnuN94YWqZPiu5a5zc3IleFqgZnmVCyvU=
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.10/go.mod h1:8NhAIBVYkVHq0hIbbzujdoou0VkKwMdG+De9e5oX6qI=
github.com/aws/aws-sdk-go-v2/service/signin v1.10.4 h1:tvpDjuUvgKURf3Yk4hOaGbZ4QdY+070OWcA5d6LUv2A=
github.com/aws/aws-sdk-go-v2/service/signin v1.10.4/go.mod h1:3ibVKg5Ng82Zby8++jELTD2nHxiPk2DJRLEeW/LKp8M=
github.com/aws/aws-sdk-go-v2/service/sns v1.47.5 h1:4EezYQsIY0xPbD6u7TbQLfnpicSMQgA8n9paomVV4Zo=
@@ -215,8 +213,8 @@ github.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.4 h1:j6c+HA4AoS0EBEjArPjavFEB
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.4/go.mod h1:RhghaXUk9q66VtOQUX1FdPddQuHnqQZzbB0fEYXmPRA=
github.com/aws/aws-sdk-go-v2/service/sts v1.51.6 h1:BVjKrtRUtSYKztBCCfE1oAB+d3ViKcW2cKZfserOqMQ=
github.com/aws/aws-sdk-go-v2/service/sts v1.51.6/go.mod h1:eSukFLeLkPMm+1OxDR+F0joauZdyBkF47Ow7MqjZiJw=
github.com/aws/smithy-go v1.28.11 h1:2aArhkXe0dFld6IFMlaVy47SbSdU/ZGbDaE7X2DjZkI=
github.com/aws/smithy-go v1.28.11/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
github.com/aws/smithy-go v1.28.10 h1:SfPnj8fGCVAI/P5YC4/1JjuMsucbPp2dROnSTYNo2PE=
github.com/aws/smithy-go v1.28.10/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPnH1Wvgk=
github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg=
github.com/bazelbuild/rules_go v0.46.0 h1:CTefzjN/D3Cdn3rkrM6qMWuQj59OBcuOjyIp3m4hZ7s=
@@ -966,8 +964,6 @@ github.com/parquet-go/parquet-go v0.33.0/go.mod h1:zl2XMxzSXZ5UYGfTLK0kvW0ifgVMP
github.com/pascaldekloe/goe v0.1.0/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc=
github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc=
github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ=
github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58 h1:onHthvaw9LFnH4t2DcNVpwGmV9E1BkGknEliJkfwQj0=
github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58/go.mod h1:DXv8WO4yhMYhSNPKjeNKa5WY9YCIEBRbNzFFPJbWO6Y=
github.com/pborman/getopt v0.0.0-20170112200414-7148bc3a4c30/go.mod h1:85jBQOZwpVEaDAr341tbn15RS4fCAsIst0qp7i8ex1o=
github.com/pelletier/go-toml/v2 v2.4.3 h1:GTRvJQutkOSftxIFD5xw9aepkYNuPWmVJpffdDPYVpY=
github.com/pelletier/go-toml/v2 v2.4.3/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
@@ -1104,8 +1100,8 @@ github.com/schollz/progressbar/v3 v3.19.1 h1:iv8BgwOvdML/S3p84uBpy/IMigv4U9594vP
github.com/schollz/progressbar/v3 v3.19.1/go.mod h1:LFL7jqimKxfhero4K1eCkUr/6R39AgQeiPCJtlTWIW8=
github.com/seaweedfs/cockroachdb-parser v0.0.0-20260225204133-2f342c5ea564 h1:TgxPraf1NmF6XTcUG53ULpLQrKvhtUJxQ3hyekxSDNQ=
github.com/seaweedfs/cockroachdb-parser v0.0.0-20260225204133-2f342c5ea564/go.mod h1:JSKCh6uCHBz91lQYFYHCyTrSVIPge4SUFVn28iwMNB0=
github.com/seaweedfs/go-fuse/v2 v2.9.6 h1:sayH13ylR54GXfjqXdZ0RE074FiBNJXxVVs/HFu+t7Q=
github.com/seaweedfs/go-fuse/v2 v2.9.6/go.mod h1:zABdmWEa6A0bwaBeEOBUeUkGIZlxUhcdv+V1Dcc/U/I=
github.com/seaweedfs/go-fuse/v2 v2.9.5 h1:qz3tuAGbUJOPJtaxyP35xW3JT23utywXKer0hoTiJPU=
github.com/seaweedfs/go-fuse/v2 v2.9.5/go.mod h1:zABdmWEa6A0bwaBeEOBUeUkGIZlxUhcdv+V1Dcc/U/I=
github.com/seaweedfs/goexif v1.0.3 h1:ve/OjI7dxPW8X9YQsv3JuVMaxEyF9Rvfd04ouL+Bz30=
github.com/seaweedfs/goexif v1.0.3/go.mod h1:Oni780Z236sXpIQzk1XoJlTwqrJ02smEin9zQeff7Fk=
github.com/seaweedfs/raft v1.2.4 h1:lEBQ9seDSGrJNs2WitMgfYpaDxLgh9qukm1IJTEV1hk=
+3 -22
View File
@@ -267,18 +267,6 @@ filer:
enabled: true
```
### Message queue broker
An S3 gateway can run a message queue broker beside it, on gRPC port 17777 by default. `s3.mqBroker`, `filer.s3.mqBroker` and `allInOne.s3.mqBroker` choose it:
- `auto` (the default) runs it only with `global.seaweedfs.enableSecurity`, where the chart gives it mutual TLS through `[grpc.msg_broker]` in security.toml.
- `true` runs it either way. Without `enableSecurity` it then accepts any client that can reach the port.
- `false` never runs it.
`s3.mqBrokerPort`, `filer.s3.mqBrokerPort` and `allInOne.s3.mqBrokerPort` set the port, and 0 also turns the broker off. The `allInOne.s3` values inherit the `s3` ones when null. The container port and NetworkPolicy entry appear only when the broker runs.
Brokers register with the master under the pod IP, and clients and other brokers find them there and dial that address, so the port is deliberately left off the Services; a LoadBalancer or NodePort Service would only publish it outside the cluster. With `networkPolicy.enabled` the chart admits the port from the release's own pods; publishers and subscribers elsewhere need an `extraIngress` rule for it.
### Enabling Authentication to S3
To enable authentication for S3, you have two options:
@@ -385,16 +373,9 @@ filer:
apply without a restart. Other files in the Secret, such as an audit log config, still
need one, and so do changes to the values the chart generates its own Secret from, such
as `s3.credentials`.
- Every reload also re-creates the KMS providers configured in the identities file, and
drops the ones it no longer lists. A file whose identities don't parse changes neither.
A provider that fails to load keeps its previous instance, unless it's the one S3 uses,
which fails the KMS reload. S3 uses `default_provider`, or the first provider by name
when it isn't set, so set it when you list more than one, as adding a provider whose
name sorts first would switch S3 to it. The `local` provider reads its `keys` list
again, so objects encrypted under those keys stay readable. The keys it generates in
memory are lost on a reload, as on a restart, so list every key that protects objects
you need to keep, and give the alias `aws/s3` to the one that should serve requests
naming no key.
- Every reload also re-creates the KMS providers configured in the identities file. The
`local` provider keeps its keys in memory, so a reload replaces them, as a restart does;
use another provider for objects that must stay readable.
- The pod shares its process namespace (see [Sharing the process namespace](#sharing-the-process-namespace)),
so the sidecar can see SeaweedFS. It uses the component's image and container security
context, because it must run as the same user as SeaweedFS to signal it. If it can't
@@ -274,9 +274,6 @@ spec:
{{- if gt $s3PreStopSeconds 0 }}
-s3.preStopSeconds={{ $s3PreStopSeconds }} \
{{- end }}
{{- with (include "seaweedfs.mqBroker" (list . "allInOne") | fromJson).args }}
{{ . }} \
{{- end }}
{{- end }}
{{- if .Values.allInOne.sftp.enabled }}
-sftp \
@@ -409,10 +406,6 @@ spec:
- containerPort: {{ $httpsPort }}
name: swfs-s3-tls
{{- end }}
{{- with (include "seaweedfs.mqBroker" (list . "allInOne") | fromJson).port }}
- containerPort: {{ int . }}
name: swfs-mq-broker
{{- end }}
{{- end }}
{{- if .Values.allInOne.sftp.enabled }}
- containerPort: {{ .Values.allInOne.sftp.port | default .Values.sftp.port }}
@@ -296,9 +296,6 @@ spec:
{{- if gt $s3PreStopSeconds 0 }}
-s3.preStopSeconds={{ $s3PreStopSeconds }} \
{{- end }}
{{- with (include "seaweedfs.mqBroker" (list . "filer") | fromJson).args }}
{{ . }} \
{{- end }}
{{- end }}
-master={{ include "seaweedfs.masterServerArg" . }} \
{{- range .Values.filer.extraArgs }}
@@ -366,10 +363,6 @@ spec:
- containerPort: {{ .Values.filer.s3.httpsPort }}
name: swfs-s3-tls
{{- end }}
{{- with (include "seaweedfs.mqBroker" (list . "filer") | fromJson).port }}
- containerPort: {{ int . }}
name: swfs-mq-broker
{{- end }}
{{- end }}
{{- $jwt := (.Values.global.seaweedfs.securityConfig).jwtSigning | default dict }}
{{- $isJwtEnabled := or $jwt.filerWrite $jwt.filerRead }}
@@ -179,9 +179,6 @@ spec:
{{- end }}
{{- /* rendered even when 0: an if would drop the flag and weed would serve its default */}}
-port.lance={{ .Values.s3.lancePort | default 0 }} \
{{- with (include "seaweedfs.mqBroker" (list . "s3") | fromJson).args }}
{{ . }} \
{{- end }}
{{- range .Values.s3.extraArgs }}
{{ . }} \
{{- end }}
@@ -236,10 +233,6 @@ spec:
- containerPort: {{ .Values.s3.lancePort }}
name: swfs-lance
{{- end }}
{{- with (include "seaweedfs.mqBroker" (list . "s3") | fromJson).port }}
- containerPort: {{ int . }}
name: swfs-mq-broker
{{- end }}
{{- if .Values.s3.metricsPort }}
- containerPort: {{ .Values.s3.metricsPort }}
name: metrics
@@ -283,55 +283,6 @@ true
{{- end -}}
{{- end -}}
{{/*
The message queue broker beside an S3 gateway, for (list $ "s3"|"filer"|"allInOne"),
as JSON: "args" are its flags and "port" the port it serves, 0 when it cannot run.
Unflagged, weed starts it only with grpc.msg_broker TLS, which enableSecurity
writes, and on 17777; defaults are left out so images without these flags start.
allInOne.s3 inherits s3's mqBroker and mqBrokerPort when null.
*/}}
{{- define "seaweedfs.mqBroker" -}}
{{- $root := index . 0 -}}
{{- $component := index . 1 -}}
{{- $prefix := "" -}}
{{- $name := "s3.mqBroker" -}}
{{- $mode := $root.Values.s3.mqBroker -}}
{{- $port := $root.Values.s3.mqBrokerPort -}}
{{- if eq $component "filer" -}}
{{- $prefix = "s3." -}}
{{- $name = "filer.s3.mqBroker" -}}
{{- $mode = $root.Values.filer.s3.mqBroker -}}
{{- $port = $root.Values.filer.s3.mqBrokerPort -}}
{{- else if eq $component "allInOne" -}}
{{- if not (kindIs "invalid" $root.Values.allInOne.s3.mqBroker) -}}
{{- $name = "allInOne.s3.mqBroker" -}}
{{- $mode = $root.Values.allInOne.s3.mqBroker -}}
{{- end -}}
{{- if not (kindIs "invalid" $root.Values.allInOne.s3.mqBrokerPort) -}}
{{- $port = $root.Values.allInOne.s3.mqBrokerPort -}}
{{- end -}}
{{- end -}}
{{- $mode = ternary "auto" (toString $mode | lower) (kindIs "invalid" $mode) -}}
{{- if not (has $mode (list "auto" "true" "false")) -}}
{{- fail (printf "%s must be auto, true or false, not %q" $name $mode) -}}
{{- end -}}
{{- $port = int ($port | default 0) -}}
{{- $runs := false -}}
{{- if and (gt $port 0) (or (eq $mode "true") (and (eq $mode "auto") $root.Values.global.seaweedfs.enableSecurity)) -}}
{{- $runs = true -}}
{{- end -}}
{{- $args := list -}}
{{- if or (eq $mode "false") (eq $port 0) -}}
{{- $args = append $args (printf "-%smq.broker=false" $prefix) -}}
{{- else if eq $mode "true" -}}
{{- $args = append $args (printf "-%smq.broker=true" $prefix) -}}
{{- end -}}
{{- if and $runs (ne $port 17777) -}}
{{- $args = append $args (printf "-%smq.broker.port=%d" $prefix $port) -}}
{{- end -}}
{{- dict "args" (join " " $args) "port" (ternary $port 0 $runs) | toJson -}}
{{- end -}}
{{/* Return the proper volume image */}}
{{- define "seaweedfs.volume.image" -}}
{{- if .Values.volume.imageOverride -}}
@@ -26,9 +26,6 @@
{{- if and $https (gt (int $https) 0) }}
{{- $ports = append $ports $https }}
{{- end }}
{{- with (include "seaweedfs.mqBroker" (list $ "allInOne") | fromJson).port }}
{{- $ports = append $ports (int .) }}
{{- end }}
{{- end }}
{{- if .Values.allInOne.sftp.enabled }}
{{- $ports = append $ports (.Values.allInOne.sftp.port | default .Values.sftp.port) }}
@@ -65,9 +62,6 @@
{{- if and .Values.filer.s3.httpsPort (gt (int .Values.filer.s3.httpsPort) 0) }}
{{- $ports = append $ports .Values.filer.s3.httpsPort }}
{{- end }}
{{- with (include "seaweedfs.mqBroker" (list $ "filer") | fromJson).port }}
{{- $ports = append $ports (int .) }}
{{- end }}
{{- end }}
{{- $targets = append $targets (dict "component" "filer" "ports" $ports) }}
{{- end }}
@@ -82,9 +76,6 @@
{{- if .Values.s3.lancePort }}
{{- $ports = append $ports .Values.s3.lancePort }}
{{- end }}
{{- with (include "seaweedfs.mqBroker" (list $ "s3") | fromJson).port }}
{{- $ports = append $ports (int .) }}
{{- end }}
{{- if .Values.s3.metricsPort }}
{{- $ports = append $ports .Values.s3.metricsPort }}
{{- end }}
@@ -120,14 +120,6 @@ stringData:
cert = "/usr/local/share/ca-certificates/client/tls.crt"
key = "/usr/local/share/ca-certificates/client/tls.key"
{{- /* The broker beside each S3 gateway serves with this identity and
dials other brokers with it; weed starts that broker only when this
section has a cert and key. Same internal client cert as grpc.s3, which
every pod running a gateway already mounts. */}}
[grpc.msg_broker]
cert = "/usr/local/share/ca-certificates/client/tls.crt"
key = "/usr/local/share/ca-certificates/client/tls.key"
# use this for any place needs a grpc client
# i.e., "weed backup|benchmark|filer.copy|filer.replicate|mount|s3|upload"
[grpc.client]
@@ -1,199 +0,0 @@
package tests
import (
"fmt"
"os/exec"
"strings"
"testing"
)
const security = "global.seaweedfs.enableSecurity=true"
type brokerGateway struct {
name string
settings []string
kind string
object string
prefix string
broker string
port string
}
var brokerGateways = []brokerGateway{
{"s3", []string{"s3.enabled=true"}, "Deployment", "vector-test-seaweedfs-s3", "", "s3.mqBroker", "s3.mqBrokerPort"},
{"filer.s3", []string{"filer.s3.enabled=true"}, "StatefulSet", "vector-test-seaweedfs-filer", "s3.", "filer.s3.mqBroker", "filer.s3.mqBrokerPort"},
{"allInOne", []string{"allInOne.enabled=true", "allInOne.s3.enabled=true"}, "Deployment", "vector-test-seaweedfs-all-in-one", "", "allInOne.s3.mqBroker", "allInOne.s3.mqBrokerPort"},
}
func firstContainer(workload map[string]interface{}) map[string]interface{} {
return workload["spec"].(map[string]interface{})["template"].(map[string]interface{})["spec"].(map[string]interface{})["containers"].([]interface{})[0].(map[string]interface{})
}
// brokerFlags returns the broker flags of the workload's first container.
func brokerFlags(workload map[string]interface{}) []string {
container := firstContainer(workload)
var words []string
for _, key := range []string{"command", "args"} {
if list, ok := container[key].([]interface{}); ok {
for _, word := range list {
words = append(words, strings.Fields(word.(string))...)
}
}
}
var flags []string
for _, word := range words {
if strings.Contains(word, "mq.broker") {
flags = append(flags, word)
}
}
return flags
}
func namedPort(ports []interface{}, name, field string) int {
for _, port := range ports {
if p := port.(map[string]interface{}); p["name"] == name {
return p[field].(int)
}
}
return 0
}
func policyAllows(policy map[string]interface{}, want int) bool {
rules, _ := policy["spec"].(map[string]interface{})["ingress"].([]interface{})
for _, rule := range rules {
ports, _ := rule.(map[string]interface{})["ports"].([]interface{})
for _, port := range ports {
if port.(map[string]interface{})["port"] == want {
return true
}
}
}
return false
}
// checkBroker asserts the flags, that the broker port is declared and
// admitted exactly when the broker runs, so a broker that runs with its port
// blocked fails, and that no Service ever carries it.
func checkBroker(t *testing.T, gateway brokerGateway, label string, settings []string, wantFlags []string, wantPort int) {
t.Helper()
_, documents := render(t, append(append([]string{"networkPolicy.enabled=true"}, gateway.settings...), settings...)...)
label = fmt.Sprintf("%s %s", gateway.name, label)
workload := findDocument(documents, gateway.kind, gateway.object)
if workload == nil {
t.Fatalf("%s: no %s %s", label, gateway.kind, gateway.object)
}
if got := brokerFlags(workload); strings.Join(got, " ") != strings.Join(wantFlags, " ") {
t.Errorf("%s: broker flags %q, want %q", label, got, wantFlags)
}
containerPorts, _ := firstContainer(workload)["ports"].([]interface{})
if got := namedPort(containerPorts, "swfs-mq-broker", "containerPort"); got != wantPort {
t.Errorf("%s: containerPort %d, want %d", label, got, wantPort)
}
// Clients find brokers through the master and dial the pod, so a Service
// port would only publish the broker through a LoadBalancer or NodePort.
for _, document := range documents {
if document["kind"] != "Service" {
continue
}
for _, port := range document["spec"].(map[string]interface{})["ports"].([]interface{}) {
p := port.(map[string]interface{})
if p["name"] == "swfs-mq-broker" || p["port"] == 17777 || p["targetPort"] == 17777 || (wantPort != 0 && (p["port"] == wantPort || p["targetPort"] == wantPort)) {
t.Errorf("%s: Service %v carries the broker port: %v", label, document["metadata"].(map[string]interface{})["name"], p)
}
}
}
policy := findDocument(documents, "NetworkPolicy", gateway.object)
if policy == nil {
t.Fatalf("%s: no NetworkPolicy %s", label, gateway.object)
}
if wantPort != 0 && !policyAllows(policy, wantPort) {
t.Errorf("%s: NetworkPolicy does not admit broker port %d", label, wantPort)
}
for _, port := range []int{17777, 18887} {
if port != wantPort && policyAllows(policy, port) {
t.Errorf("%s: NetworkPolicy admits %d with no broker on it", label, port)
}
}
}
func TestMqBrokerModes(t *testing.T) {
for _, gateway := range brokerGateways {
on := "-" + gateway.prefix + "mq.broker=true"
off := "-" + gateway.prefix + "mq.broker=false"
port := "-" + gateway.prefix + "mq.broker.port=18887"
cases := []struct {
label string
settings []string
wantFlags []string
wantPort int
}{
{"auto without security", nil, nil, 0},
{"auto with security", []string{security}, nil, 17777},
{"auto with security, custom port", []string{security, gateway.port + "=18887"}, []string{port}, 18887},
{"auto without security, custom port", []string{gateway.port + "=18887"}, nil, 0},
{"true", []string{gateway.broker + "=true"}, []string{on}, 17777},
{"true, custom port", []string{gateway.broker + "=true", gateway.port + "=18887"}, []string{on, port}, 18887},
{"false with security", []string{security, gateway.broker + "=false"}, []string{off}, 0},
{"true, port 0", []string{gateway.broker + "=true", gateway.port + "=0"}, []string{off}, 0},
}
for _, c := range cases {
checkBroker(t, gateway, c.label, c.settings, c.wantFlags, c.wantPort)
}
}
}
func TestMqBrokerAllInOneInherits(t *testing.T) {
allInOne := brokerGateways[2]
cases := []struct {
label string
settings []string
wantFlags []string
wantPort int
}{
{"null inherits s3.mqBroker=true", []string{"s3.mqBroker=true"}, []string{"-mq.broker=true"}, 17777},
{"null inherits s3.mqBroker=false", []string{security, "s3.mqBroker=false"}, []string{"-mq.broker=false"}, 0},
{"explicit auto overrides s3.mqBroker=false", []string{security, "s3.mqBroker=false", "allInOne.s3.mqBroker=auto"}, nil, 17777},
{"null inherits s3.mqBrokerPort", []string{security, "s3.mqBrokerPort=18887"}, []string{"-mq.broker.port=18887"}, 18887},
{"explicit port overrides s3.mqBrokerPort=0", []string{security, "s3.mqBrokerPort=0", "allInOne.s3.mqBrokerPort=18887"}, []string{"-mq.broker.port=18887"}, 18887},
}
for _, c := range cases {
checkBroker(t, allInOne, c.label, c.settings, c.wantFlags, c.wantPort)
}
}
func TestMqBrokerTLSOnlyWithSecurity(t *testing.T) {
for _, secured := range []bool{false, true} {
// filer JWT signing writes security.toml without enableSecurity
settings := []string{"s3.enabled=true", "global.seaweedfs.securityConfig.jwtSigning.filerWrite=true"}
if secured {
settings = append(settings, security)
}
_, documents := render(t, settings...)
secret := findDocument(documents, "Secret", "vector-test-seaweedfs-security-config")
if secret == nil {
t.Fatalf("security %v: no security config Secret", secured)
}
toml := secret["stringData"].(map[string]interface{})["security.toml"].(string)
section := "[grpc.msg_broker]\ncert = \"/usr/local/share/ca-certificates/client/tls.crt\"\nkey = \"/usr/local/share/ca-certificates/client/tls.key\""
if got := strings.Contains(toml, section); got != secured {
t.Errorf("security %v: [grpc.msg_broker] with the client cert present = %v\n%s", secured, got, toml)
}
if !secured && strings.Contains(toml, "[grpc.msg_broker]") {
t.Errorf("[grpc.msg_broker] written without enableSecurity")
}
}
}
func TestMqBrokerRejectsUnknownValue(t *testing.T) {
if _, err := exec.LookPath("helm"); err != nil {
t.Skip("helm is not installed")
}
output, err := exec.Command("helm", "template", "test", "..", "--set", "s3.enabled=true", "--set", "s3.mqBroker=yes").CombinedOutput()
if err == nil || !strings.Contains(string(output), `s3.mqBroker must be auto, true or false, not "yes"`) {
t.Fatalf("s3.mqBroker=yes accepted: %v %s", err, output)
}
}
+2 -14
View File
@@ -1096,9 +1096,6 @@ filer:
port: 8333
# add additional https port
httpsPort: 0
# Message queue broker beside the gateway, see s3.mqBroker
mqBroker: auto
mqBrokerPort: 17777
# Suffix of the host name, {bucket}.{domainName}
domainName: ""
# Seconds the gateway keeps serving after SIGTERM while its health checks
@@ -1189,13 +1186,6 @@ s3:
# Lance Namespace port; weed serves 9101 by default, 0 disables it
# (and the worker's Lance container)
lancePort: 9101
# Message queue broker beside the gateway: auto runs it only with
# global.seaweedfs.enableSecurity, which gives it mTLS; true runs it either
# way, without TLS when security is off; false never does.
mqBroker: auto
# Its gRPC port, 0 turns it off. Clients and other brokers find the broker
# through the master and dial the pod IP, so no Service carries this port.
mqBrokerPort: 17777
loggingOverrideLevel: null
# enable user & permission to s3 (need to inject to all services)
enableAuth: false
@@ -1896,7 +1886,7 @@ worker:
# Worker job types - categories or comma-separated list of names/aliases
# Categories: all, default, heavy
# default: vacuum, volume_balance, ec_balance, admin_script
# heavy: erasure_coding, iceberg_maintenance, mq_topic_table
# heavy: erasure_coding, iceberg_maintenance
# all: every registered job type
# Examples: "all", "default", "heavy", "default,iceberg" (default+iceberg), "vacuum,volume_balance"
# Refer: https://github.com/seaweedfs/seaweedfs/wiki/Worker
@@ -2070,8 +2060,6 @@ allInOne:
enabled: false # Whether to enable S3 gateway
port: null # S3 gateway port (null inherits from s3.port)
httpsPort: null # S3 gateway HTTPS port (null inherits from s3.httpsPort)
mqBroker: null # Message queue broker: auto, true or false (null inherits from s3.mqBroker)
mqBrokerPort: null # Message queue broker gRPC port (null inherits from s3.mqBrokerPort, 0 turns the broker off)
domainName: null # Suffix of the host name (null inherits from s3.domainName)
enableAuth: false # Enable user & permission to S3
# Set to the name of an existing kubernetes Secret with the s3 json config file
@@ -2305,7 +2293,7 @@ allInOne:
# For more information, visit: https://container-object-storage-interface.github.io/docs/deployment-guide
cosi:
enabled: false
image: "ghcr.io/seaweedfs/seaweedfs-cosi-driver:v0.5.0"
image: "ghcr.io/seaweedfs/seaweedfs-cosi-driver:v0.1.2"
driverName: "seaweedfs.objectstorage.k8s.io"
bucketClassName: "seaweedfs"
# Optional parameters to pass to the default BucketClass (e.g., diskType for tiered storage)
+1060 -1042
View File
File diff suppressed because it is too large. Load diff

Before

Width:  |  Height:  |  Size: 54 KiB

After

Width:  |  Height:  |  Size: 54 KiB

-406
View File
@@ -15239,412 +15239,6 @@
"pluginVersion": "10.3.1"
}
]
},
{
"type": "row",
"title": "S3 Notifications",
"collapsed": true,
"id": 275,
"gridPos": {
"h": 1,
"w": 24,
"x": 0,
"y": 30
},
"panels": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"title": "Notification records delivered",
"type": "timeseries",
"id": 276,
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 31
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 10,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "never",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"unit": "ops",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"legend": {
"calcs": [
"lastNotNull",
"max"
],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "sum by (target) (rate(SeaweedFS_s3_notification_delivered_records_total{cluster=~\"$cluster\"}[$__rate_interval]))",
"range": true,
"refId": "A",
"legendFormat": "{{target}}"
}
],
"pluginVersion": "10.3.1"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"title": "Notification lag",
"description": "Undelivered bucket event records the forwarder can see: current ranges, ranges held back behind an older generation, and sealed retired ranges. An old range still being sealed after a repartition cannot be read yet and is not counted.",
"type": "timeseries",
"id": 277,
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 31
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 10,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "never",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"unit": "short",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"legend": {
"calcs": [
"lastNotNull",
"max"
],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "sum by (target) (SeaweedFS_s3_notification_lag_records{cluster=~\"$cluster\"})",
"range": true,
"refId": "A",
"legendFormat": "{{target}}"
}
],
"pluginVersion": "10.3.1"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"title": "Notification send retries",
"type": "timeseries",
"id": 278,
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 39
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 10,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "never",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"unit": "ops",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"legend": {
"calcs": [
"lastNotNull",
"max"
],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "sum by (target) (rate(SeaweedFS_s3_notification_send_retries_total{cluster=~\"$cluster\"}[$__rate_interval]))",
"range": true,
"refId": "A",
"legendFormat": "{{target}}"
}
],
"pluginVersion": "10.3.1"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"title": "Notification records skipped or lost",
"type": "timeseries",
"id": 279,
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 39
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 10,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "never",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"unit": "short",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"legend": {
"calcs": [
"lastNotNull",
"max"
],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "sum by (target, reason) (increase(SeaweedFS_s3_notification_skipped_records_total{cluster=~\"$cluster\"}[$__rate_interval]))",
"range": true,
"refId": "A",
"legendFormat": "{{target}} skipped {{reason}}"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "sum by (target) (increase(SeaweedFS_s3_notification_retention_gap_records_total{cluster=~\"$cluster\"}[$__rate_interval]))",
"range": true,
"refId": "B",
"legendFormat": "{{target}} retention gap"
}
],
"pluginVersion": "10.3.1"
}
]
}
],
"refresh": "30s",
-3
View File
@@ -1,3 +0,0 @@
*.sh text eol=lf
core/chunkkernel/chunk-kernel-2.tsv text eol=lf
.github/model-code-trace.tsv text eol=lf
-58
View File
@@ -1,58 +0,0 @@
# Model citations for mapped files
The spec-trace workflow reads `model-code-trace.tsv` and the validator from
the target branch. A PR cannot replace its own mapping or checker.
Each non-comment line has two tab-separated columns: an exact repository
path and `Module.Action`. Repeat a path to list alternative actions that
cover it. Paths are case-sensitive; directories and glob patterns are not
expanded. Missing, empty or malformed mappings refuse the check.
Source line numbers are not part of this file-wide mapping. Moving a function
or test within its file does not change its model obligations or rewrite the
table. The time-bound registry separately keys individual bounds by file,
function, bound kind and occurrence; CI scans current source locations for
diagnostics rather than committing those locations.
Git uses its built-in union merge for this table so concurrent row additions
are retained. After a merge, sort and deduplicate the non-comment rows; the
checker refuses unsorted or duplicate rows. Review removals explicitly: a
union merge does not decide whether an old mapping should be removed.
The reviewed map uses the neutral public module names: `SnapshotRemoval`,
`RestoreTarget`, `HolderInterface`, `EngineAdapter`, `StopAndRestart`,
`MoveAdmission`, `Promotion`, `ProbeRound`, `FencingRound`, `VolumeCreate`,
`ReplicationPeer` and `RestoreCommand`.
Actions name top-level definitions used by the corresponding model's `Next`.
The mapping is the source of accepted citations; private model names and
storage locations do not belong in the public map or PR description.
For every changed mapped path, including deletions, the PR's `Model:` line
must contain a listed action or `NONE (pure function of Module)` for that
module. Separate multiple citations with semicolons, for example:
```text
Model: EngineAdapter.Begin; MoveAdmission.Revoke; NONE (pure function of RestoreTarget)
```
Unmapped paths keep the existing spec-trace policy. The pure-function
declaration is a review claim; CI checks its module, not its truth.
## Adding a model or file
1. Have the model owner confirm its neutral public module name and the
top-level action definitions used by `Next`. Use those names in public
code, mapping rows and PR descriptions.
2. Add an exact-path TSV row for each implementation and enforcement file
that the action covers. Split actions get separate rows. Include receiving
guards as well as senders; a reviewer checks that each file really enforces
the cited action. Environment actions without a Go site and mutant test
obligations are not implementation mappings.
3. Add controls for accepted and refused citations when extending the
checker. For mapping additions, check the real map against representative
affected paths. Run `python3 -B .github/scripts/model-trace-check-test.py`
and `bash .github/scripts/spec-trace-check-test.sh` on Linux.
4. Submit the map and its evidence for review with the model change or before
its callers land. The PR description cites the applicable public actions.
The new rows govern later PRs once they are on the target branch; changing
a PR's own map never changes the check that evaluates that PR.
-319
View File
@@ -1,319 +0,0 @@
# Exact repository-relative path<TAB>Module.Action; repeat a path for alternatives.
cmd/blockvolume/snapshot_operation_shutdown.go SnapOps.Stall
cmd/sw-block/chunk.go CutTime.Poll
cmd/sw-block/cut_progress_poll.go CutTime.CliGiveUp
cmd/sw-block/cut_progress_poll.go CutTime.CliServerUnknown
cmd/sw-block/cut_progress_poll.go CutTime.CliSilent
cmd/sw-block/cut_progress_poll.go CutTime.HolderRestart
cmd/sw-block/cut_progress_poll.go CutTime.Poll
cmd/sw-block/snapshot_operation.go SnapOps.Send
cmd/sw-block/volume_backup.go RestoreCommand.Abort
cmd/sw-block/volume_backup.go RestoreCommand.AbortVerify
cmd/sw-block/volume_backup.go RestoreCommand.Run
cmd/sw-block/volume_backup.go RestoreCommand.Start
cmd/sw-block/volume_start_release.go StopAndRestart.IssueClean
cmd/sw-block/volume_start_release.go StopAndRestart.ReadClean
cmd/sw-block/volume_start_release.go StopAndRestart.SameEpochReopen
cmd/sw-block/volume_verbs.go CutTime.CliGiveUp
cmd/sw-block/volume_verbs.go CutTime.Poll
cmd/sw-block/workspace_show.go MoveAdmission.ReadForMove
core/authority/authority.go DeleteRetire.Retire
core/authority/authority_store_file.go DeleteRetire.Retire
core/authority/workspace.go HolderInterface.ForcedMove
core/authority/workspace.go HolderInterface.PlannedMove
core/authority/workspace.go MoveAdmission.Ack
core/authority/workspace.go MoveAdmission.IssueClean
core/authority/workspace.go MoveAdmission.IssueForced
core/authority/workspace.go MoveAdmission.Lease2Ends
core/authority/workspace.go MoveAdmission.LeaseEnds
core/authority/workspace.go MoveAdmission.ReadForMove
core/authority/workspace.go MoveAdmission.Revoke
core/authority/workspace.go StopAndRestart.IssueClean
core/authority/workspace.go StopAndRestart.IssueForced
core/authority/workspace.go StopAndRestart.LeaseEnds
core/authority/workspace.go StopAndRestart.ReadForced
core/authority/workspace_delete_reservation.go MoveAdmission.DelCheck
core/authority/workspace_delete_reservation.go MoveAdmission.Reserve
core/authority/workspace_lease_view.go HolderInterface.Grant
core/authority/workspace_lease_view.go HolderInterface.Regrant
core/authority/workspace_retirement.go DeleteRetire.Retire
core/engine/apply.go ReplicationPeer.Reconcile
core/frontend/chunkstore/catalog_b.go CleanBatch.Publish
core/frontend/chunkstore/catalog_b.go CleanBatch.Request
core/frontend/chunkstore/catalog_snapshot_operation.go CleanBatch.Publish
core/frontend/chunkstore/clean_admission.go CleanBatch.Begin
core/frontend/chunkstore/clean_admission.go CleanBatch.Close
core/frontend/chunkstore/clean_admission.go CleanBatch.Request
core/frontend/chunkstore/clean_b.go CleanBatch.BeginIn
core/frontend/chunkstore/clean_b.go CleanBatch.Close
core/frontend/chunkstore/clean_b.go CleanBatch.Effects
core/frontend/chunkstore/clean_b.go CleanBatch.PrepIn
core/frontend/chunkstore/clean_b.go CleanBatch.PrepOut
core/frontend/chunkstore/clean_b.go CutTime.Complete
core/frontend/chunkstore/clean_b.go PageChain.Sweep
core/frontend/chunkstore/clean_b.go SnapshotRemoval.BeginClean
core/frontend/chunkstore/clean_b.go SnapshotRemoval.EndClean
core/frontend/chunkstore/clean_b.go StaleClean.HeadRead
core/frontend/chunkstore/clean_intent_b.go CleanBatch.Publish
core/frontend/chunkstore/clean_intent_b.go CleanBatch.Request
core/frontend/chunkstore/clean_intent_b.go PageChain.CRead
core/frontend/chunkstore/clean_intent_b.go QueueCap.Consume
core/frontend/chunkstore/cut_verification_window.go CutTime.Complete
core/frontend/chunkstore/cut_verification_window.go CutWindow.CallTimeout
core/frontend/chunkstore/layout/claim.go EngineAdapter.Takeover
core/frontend/chunkstore/layout/claim.go MoveAdmission.ClaimB
core/frontend/chunkstore/layout/claim.go SnapshotRemoval.Claim
core/frontend/chunkstore/layout/claim.go StopAndRestart.ClaimB
core/frontend/chunkstore/layout/clean.go EngineAdapter.MaintBegin
core/frontend/chunkstore/layout/clean.go EngineAdapter.MaintEnd
core/frontend/chunkstore/layout/clean.go SnapshotRemoval.BeginClean
core/frontend/chunkstore/layout/clean.go SnapshotRemoval.EndClean
core/frontend/chunkstore/layout/clean_batch.go CleanBatch.PrepIn
core/frontend/chunkstore/layout/clean_batch.go CleanBatch.PrepOut
core/frontend/chunkstore/layout/clean_batch.go SnapshotRemoval.EndClean
core/frontend/chunkstore/layout/clean_batch.go SnapshotRemoval.Validate
core/frontend/chunkstore/layout/commit.go CutTime.Complete
core/frontend/chunkstore/layout/commit.go EngineAdapter.Apply
core/frontend/chunkstore/layout/commit.go QueueCap.TakeBack
core/frontend/chunkstore/layout/commit.go SnapshotRemoval.Commit
core/frontend/chunkstore/layout/commit.go StaleClean.CommitCheck
core/frontend/chunkstore/layout/commit.go StaleClean.HeadCommit
core/frontend/chunkstore/layout/commit.go VolumeCreate.Commit
core/frontend/chunkstore/layout/create.go RestoreTarget.CreateHead
core/frontend/chunkstore/layout/create.go RestoreTarget.CreateVol
core/frontend/chunkstore/layout/create.go VolumeCreate.Claim
core/frontend/chunkstore/layout/delete.go MoveAdmission.DelMark
core/frontend/chunkstore/layout/delete.go MoveAdmission.DelRead
core/frontend/chunkstore/layout/delete.go RestoreTarget.OpRelease
core/frontend/chunkstore/layout/delete.go RestoreTarget.OpTomb
core/frontend/chunkstore/layout/delete_intent.go CutTime.Complete
core/frontend/chunkstore/layout/delete_intent.go PageChain.CAdvance
core/frontend/chunkstore/layout/delete_intent.go PageChain.CApply
core/frontend/chunkstore/layout/delete_intent.go PageChain.CRead
core/frontend/chunkstore/layout/delete_intent.go PageChain.CResolve
core/frontend/chunkstore/layout/delete_intent.go PageChain.Resend
core/frontend/chunkstore/layout/delete_intent.go PageChain.Send
core/frontend/chunkstore/layout/delete_intent.go PageChain.WritePage
core/frontend/chunkstore/layout/delete_intent.go QueueCap.Consume
core/frontend/chunkstore/layout/delete_intent.go QueueCap.Produce
core/frontend/chunkstore/layout/delete_intent.go VolDelSweep.Land
core/frontend/chunkstore/layout/delete_intent.go VolDelSweep.Stage
core/frontend/chunkstore/layout/format_level.go FormatGate.PublishOp
core/frontend/chunkstore/layout/format_level.go FormatGate.Upgrade1
core/frontend/chunkstore/layout/head.go CleanBatch.Publish
core/frontend/chunkstore/layout/head.go CleanBatch.Request
core/frontend/chunkstore/layout/head.go SnapshotRemoval.Abort
core/frontend/chunkstore/layout/head.go SnapshotRemoval.Begin
core/frontend/chunkstore/layout/head.go StopAndRestart.Apply
core/frontend/chunkstore/layout/head.go StopAndRestart.Begin
core/frontend/chunkstore/layout/list_chain.go CutTime.Complete
core/frontend/chunkstore/layout/list_chain.go PageChain.CAdvance
core/frontend/chunkstore/layout/list_chain.go PageChain.CRead
core/frontend/chunkstore/layout/list_chain.go PageChain.CResolve
core/frontend/chunkstore/layout/list_chain.go PageChain.Resend
core/frontend/chunkstore/layout/list_chain.go PageChain.Send
core/frontend/chunkstore/layout/list_chain.go PageChain.WritePage
core/frontend/chunkstore/layout/list_chain.go QueueCap.Produce
core/frontend/chunkstore/layout/list_chain.go VolDelSweep.Land
core/frontend/chunkstore/layout/list_chain.go VolDelSweep.Stage
core/frontend/chunkstore/layout/maintenance_progress.go CutTime.Complete
core/frontend/chunkstore/layout/objects.go SnapshotRemoval.Upload
core/frontend/chunkstore/layout/read.go CutTime.Complete
core/frontend/chunkstore/layout/remove.go CleanBatch.Effects
core/frontend/chunkstore/layout/remove.go CutTime.Complete
core/frontend/chunkstore/layout/remove.go PageChain.Sweep
core/frontend/chunkstore/layout/remove.go SnapshotRemoval.Issue
core/frontend/chunkstore/layout/remove.go SnapshotRemoval.Stat
core/frontend/chunkstore/layout/remove.go SnapshotRemoval.Validate
core/frontend/chunkstore/layout/remove.go StaleClean.DeleteIt
core/frontend/chunkstore/layout/remove.go StaleClean.HeadRead
core/frontend/chunkstore/layout/remove.go StaleClean.MarkIt
core/frontend/chunkstore/layout/remove.go StaleClean.Stat
core/frontend/chunkstore/layout/snapshots.go EngineAdapter.OpWrite
core/frontend/chunkstore/layout/snapshots.go MoveAdmission.OpWrite
core/frontend/chunkstore/layout/snapshots.go RestoreTarget.AddDep
core/frontend/chunkstore/layout/snapshots.go SnapshotRemoval.DeleteSnap
core/frontend/chunkstore/layout/start.go HolderInterface.Start
core/frontend/chunkstore/layout/start.go StopAndRestart.CrashRestart
core/frontend/chunkstore/layout/start.go VolumeCreate.Claim
core/frontend/chunkstore/layout_create.go VolumeCreate.IssueHead
core/frontend/chunkstore/layout_create.go VolumeCreate.IssueVol
core/frontend/chunkstore/layout_remote.go CleanBatch.Begin
core/frontend/chunkstore/layout_remote.go CleanBatch.Publish
core/frontend/chunkstore/layout_remote.go CutTime.Complete
core/frontend/chunkstore/layout_remote.go EngineAdapter.Begin
core/frontend/chunkstore/layout_remote.go EngineAdapter.ReadHead
core/frontend/chunkstore/layout_remote.go EngineAdapter.SendCommit
core/frontend/chunkstore/layout_remote.go EngineAdapter.SettleAbort
core/frontend/chunkstore/layout_remote.go EngineAdapter.TakeAbandon
core/frontend/chunkstore/layout_remote.go FormatGate.CutPublish
core/frontend/chunkstore/layout_remote.go FormatGate.Upgrade1
core/frontend/chunkstore/layout_remote.go PageChain.CRead
core/frontend/chunkstore/layout_remote.go StopAndRestart.SendCommit
core/frontend/chunkstore/layout_remote.go StopAndRestart.SettleAbort
core/frontend/chunkstore/layout_store.go CleanBatch.Publish
core/frontend/chunkstore/layout_store.go CleanBatch.Request
core/frontend/chunkstore/layout_store.go SnapshotRemoval.ApplyDelete
core/frontend/chunkstore/layout_store.go SnapshotRemoval.ApplyMark
core/frontend/chunkstore/layout_store.go StaleClean.Adopt
core/frontend/chunkstore/maintenance_request.go CutTime.CallTimeout
core/frontend/chunkstore/retain_b.go CleanBatch.Publish
core/frontend/chunkstore/retain_b.go CleanBatch.Request
core/frontend/chunkstore/retain_b.go CutTime.Complete
core/frontend/chunkstore/snapshot_delete_operation.go FormatGate.AdmitOp
core/frontend/chunkstore/snapshot_delete_operation.go SnapDelete.Send
core/frontend/chunkstore/snapshot_delete_target.go FormatGate.AdmitOp
core/frontend/chunkstore/snapshot_operation.go SnapOps.Retire
core/frontend/chunkstore/snapshot_operation.go SnapOps.Send
core/frontend/chunkstore/snapshot_operation.go SnapOps.TornAdmit
core/frontend/chunkstore/snapshot_operation_guard.go SnapOps.Delete
core/frontend/chunkstore/snapshot_operation_guard.go SnapOps.Publish
core/frontend/chunkstore/snapshot_operation_index.go SnapOps.GC
core/frontend/chunkstore/snapshot_operation_index.go SnapOps.Poll
core/frontend/chunkstore/snapshot_operation_index.go SnapOps.TermFlag
core/frontend/chunkstore/swfs.go VolumeCreate.Land
core/frontend/durable/maintenance_progress.go CutTime.Complete
core/frontend/durable/maintenance_progress.go CutTime.Fail
core/frontend/durable/maintenance_progress.go CutTime.Tick
core/frontend/durable/provider_chunk.go CutTime.Admit
core/frontend/durable/provider_chunk.go CutWindow.Fail
core/frontend/durable/provider_chunk.go EngineAdapter.SettleResume
core/frontend/durable/provider_chunk.go EngineAdapter.StartStop
core/frontend/durable/provider_chunk.go FormatGate.CutPublish
core/frontend/durable/provider_chunk.go HolderInterface.StopBegin
core/frontend/durable/provider_chunk.go StopAndRestart.SendDetach
core/frontend/durable/provider_chunk.go StopAndRestart.SettleResume
core/frontend/durable/provider_layout.go EngineAdapter.SettleDown
core/frontend/durable/provider_layout.go StopAndRestart.SettleDown
core/frontend/durable/provider_preempt.go CutTime.Preempt
core/frontend/durable/provider_preempt.go CutTime.Settle
core/frontend/durable/storage_adapter.go EngineAdapter.GuestWrite
core/frontend/durable/storage_adapter.go HolderInterface.Write
core/frontend/durable/storage_adapter.go WALHold.Resubmit
core/frontend/iscsi/scsi.go WALHold.Stall
core/frontend/nvme/io.go WALHold.Stall
core/host/master/format_gate.go FormatGate.Finalize
core/host/master/format_gate.go FormatGate.Grant
core/host/master/format_gate.go FormatGate.Place
core/host/master/format_gate.go FormatGate.Report
core/host/master/format_gate.go FormatGate.Retire
core/host/master/journal_isolation.go DeleteRetire.HostRetire
core/host/master/layout_ready.go VolumeCreate.Place
core/host/master/observation_snapshot.go DeleteRetire.HostRetire
core/host/master/probe_round.go FencingRound.Deliver
core/host/master/probe_round.go FencingRound.Open
core/host/master/product_loop.go FencingRound.Decide
core/host/master/product_loop.go Promotion.Decide
core/host/master/services.go FormatGate.Report
core/host/master/spec_retirement.go DeleteRetire.ReadOK
core/host/master/store_attestation.go ReplicationPeer.Attest
core/host/master/workspace_binding.go FormatGate.Grant
core/host/master/workspace_binding.go MoveAdmission.Ack
core/host/master/workspace_service.go FormatGate.Place
core/host/master/workspace_service.go FormatGate.Renew
core/host/master/workspace_service.go MoveAdmission.ReadForMove
core/host/master/workspace_service.go StopAndRestart.ReadClean
core/host/volume/chunk_control.go CutTime.InProgress
core/host/volume/chunk_control.go CutWindow.Fail
core/host/volume/chunk_control.go FormatGate.Upgrade1
core/host/volume/chunk_control.go SnapOps.Start
core/host/volume/host.go FormatGate.Downgrade
core/host/volume/host.go FormatGate.Renew
core/host/volume/host.go FormatGate.Upgrade
core/host/volume/manual_cut.go CutTime.Admit
core/host/volume/manual_cut.go CutTime.InProgress
core/host/volume/manual_cut.go CutTime.Poll
core/host/volume/manual_cut.go CutTime.Retire
core/host/volume/plain_detach_handle.go CutTime.OtherEnd
core/host/volume/plain_detach_handle.go CutTime.OtherStep
core/host/volume/plain_detach_handle.go CutTime.Preempt
core/host/volume/plain_detach_handle.go CutTime.Settle
core/host/volume/plain_detach_handle.go CutTime.SettleStall
core/host/volume/primary_evidence.go FencingRound.Adopt
core/host/volume/primary_evidence.go Promotion.Adopt
core/host/volume/primary_evidence.go Promotion.Refuse
core/host/volume/probe_round.go FencingRound.Answer
core/host/volume/recovery_watchdog.go RecoveryProgress.Authority
core/host/volume/recovery_watchdog.go RecoveryProgress.Fence
core/host/volume/recovery_watchdog.go RecoveryProgress.Replay
core/host/volume/recovery_watchdog.go RecoveryProgress.Stall
core/host/volume/recovery_watchdog.go RecoveryProgress.ToFence
core/host/volume/snapshot_operation.go SnapOps.Start
core/host/volume/workspace_lease.go FormatGate.Renew
core/host/volume/workspace_lease.go HolderInterface.Expire
core/host/volume/workspace_lease.go MoveAdmission.StopOnExpiry
core/host/volume/workspace_lease.go MoveAdmission.Write
core/host/volume/workspace_lease.go SnapshotRemoval.Expire
core/host/volume/workspace_lease.go StopAndRestart.Write
core/host/volume/workspace_runtime.go FormatGate.Renew
core/host/volume/workspace_startup.go FormatGate.Renew
core/lifecycle/store.go VolumeCreate.MarkReady
core/lifecycle/store.go VolumeCreate.Record
core/replication/peer.go Promotion.Ship1
core/replication/peer.go Promotion.Ship2
core/replication/peer.go ReplicationPeer.Barrier
core/replication/peer.go ReplicationPeer.Fail
core/replication/peer.go ReplicationPeer.Heal
core/replication/peer.go ReplicationPeer.Ship
core/replication/volume.go FencingRound.Ack
core/replication/volume.go Promotion.Ack1
core/replication/volume.go Promotion.Rejoin
core/replication/volume.go Promotion.Write1
core/replication/volume.go Promotion.Write2
core/replication/volume.go ReplicationPeer.Ack
core/replication/volume.go ReplicationPeer.Write
core/storage/chunk_coverage.go SlotFence.Publish
core/storage/chunk_coverage_map.go MoveWide2.Write
core/storage/chunk_head_belt.go HolderInterface.Fence
core/storage/chunk_layer.go CutTime.Settle
core/storage/chunk_layer.go CutWindow.Publish
core/storage/chunk_layer.go CutWindow.Retry
core/storage/chunk_layer.go EngineAdapter.EngineReRead
core/storage/chunk_layer.go EngineAdapter.NoOpCut
core/storage/chunk_layer.go FormatGate.Upgrade1
core/storage/chunk_layer.go HolderInterface.Commit
core/storage/chunk_layer.go HolderInterface.StopCommit
core/storage/chunk_layer.go MoveAdmission.Detach
core/storage/chunk_layer.go MoveAdmission.Publish
core/storage/chunk_layer.go SnapshotRemoval.Write
core/storage/chunk_manual_cut.go CutTime.Busy
core/storage/chunk_manual_cut.go CutTime.PublishLost
core/storage/chunk_manual_cut.go CutTime.Settle
core/storage/chunk_manual_cut.go CutTime.SettleInherited
core/storage/chunk_manual_cut.go CutTime.SettleStall
core/storage/chunk_manual_cut.go HolderInterface.Fence
core/storage/chunk_preempt.go CutTime.OtherStep
core/storage/chunk_preempt.go CutTime.Preempt
core/storage/chunk_public.go FormatGate.Upgrade1
core/storage/chunk_seam.go FormatGate.Upgrade1
core/storage/chunk_state_upgrade.go SlotFence.Publish
core/storage/chunk_state_upgrade.go SlotFence.Sync
core/storage/chunk_upload.go CutWindow.CallTimeout
core/storage/chunk_upload.go CutWindow.Start
core/storage/cut_progress_window.go CutTime.Complete
core/storage/cut_progress_window.go CutWindow.CallTimeout
core/storage/cut_progress_window.go CutWindow.Complete
core/storage/cut_progress_window.go CutWindow.Fail
core/storage/cut_progress_window.go CutWindow.Tick
core/storage/flusher.go WALHold.Reclaim
core/storage/recovery_progress.go RecoveryProgress.Replay
core/storage/wal_admission.go WALHold.Arrive
core/storage/wal_admission_fast.go WALHold.FastArrive
core/storage/wal_admission_fast.go WALHold.FastReEnter
core/storage/wal_admission_fast.go WALHold.FastResubmit
core/storage/wal_admission_fifo.go WALHold.Admit
core/storage/wal_admission_fifo.go WALHold.Arrive
core/storage/wal_admission_fifo.go WALHold.ReEnter
core/storage/wal_hold_window.go WALHold.CapAnswer
core/storage/wal_hold_window.go WALHold.Stall
core/storage/wal_write_hold.go WALHold.CapAnswer
core/storage/wal_write_hold.go WALHold.Stall
core/storage/walstore.go WALHold.Admit
core/storage/walstore_v3.go RecoveryProgress.Fence
core/storage/walstore_v3.go SlotFence2.OpenNew
core/transport/catchup_sender.go ReplicationPeer.CatchUp
core/transport/rebuild_sender.go ReplicationPeer.Rebuild
core/transport/replica.go FencingRound.Recv
core/transport/replica.go ReplicationPeer.CatchUp
core/transport/replica.go ReplicationPeer.Rebuild
core/transport/replica.go ReplicationPeer.Ship
1 # Exact repository-relative path<TAB>Module.Action; repeat a path for alternatives.
2 cmd/blockvolume/snapshot_operation_shutdown.go SnapOps.Stall
3 cmd/sw-block/chunk.go CutTime.Poll
4 cmd/sw-block/cut_progress_poll.go CutTime.CliGiveUp
5 cmd/sw-block/cut_progress_poll.go CutTime.CliServerUnknown
6 cmd/sw-block/cut_progress_poll.go CutTime.CliSilent
7 cmd/sw-block/cut_progress_poll.go CutTime.HolderRestart
8 cmd/sw-block/cut_progress_poll.go CutTime.Poll
9 cmd/sw-block/snapshot_operation.go SnapOps.Send
10 cmd/sw-block/volume_backup.go RestoreCommand.Abort
11 cmd/sw-block/volume_backup.go RestoreCommand.AbortVerify
12 cmd/sw-block/volume_backup.go RestoreCommand.Run
13 cmd/sw-block/volume_backup.go RestoreCommand.Start
14 cmd/sw-block/volume_start_release.go StopAndRestart.IssueClean
15 cmd/sw-block/volume_start_release.go StopAndRestart.ReadClean
16 cmd/sw-block/volume_start_release.go StopAndRestart.SameEpochReopen
17 cmd/sw-block/volume_verbs.go CutTime.CliGiveUp
18 cmd/sw-block/volume_verbs.go CutTime.Poll
19 cmd/sw-block/workspace_show.go MoveAdmission.ReadForMove
20 core/authority/authority.go DeleteRetire.Retire
21 core/authority/authority_store_file.go DeleteRetire.Retire
22 core/authority/workspace.go HolderInterface.ForcedMove
23 core/authority/workspace.go HolderInterface.PlannedMove
24 core/authority/workspace.go MoveAdmission.Ack
25 core/authority/workspace.go MoveAdmission.IssueClean
26 core/authority/workspace.go MoveAdmission.IssueForced
27 core/authority/workspace.go MoveAdmission.Lease2Ends
28 core/authority/workspace.go MoveAdmission.LeaseEnds
29 core/authority/workspace.go MoveAdmission.ReadForMove
30 core/authority/workspace.go MoveAdmission.Revoke
31 core/authority/workspace.go StopAndRestart.IssueClean
32 core/authority/workspace.go StopAndRestart.IssueForced
33 core/authority/workspace.go StopAndRestart.LeaseEnds
34 core/authority/workspace.go StopAndRestart.ReadForced
35 core/authority/workspace_delete_reservation.go MoveAdmission.DelCheck
36 core/authority/workspace_delete_reservation.go MoveAdmission.Reserve
37 core/authority/workspace_lease_view.go HolderInterface.Grant
38 core/authority/workspace_lease_view.go HolderInterface.Regrant
39 core/authority/workspace_retirement.go DeleteRetire.Retire
40 core/engine/apply.go ReplicationPeer.Reconcile
41 core/frontend/chunkstore/catalog_b.go CleanBatch.Publish
42 core/frontend/chunkstore/catalog_b.go CleanBatch.Request
43 core/frontend/chunkstore/catalog_snapshot_operation.go CleanBatch.Publish
44 core/frontend/chunkstore/clean_admission.go CleanBatch.Begin
45 core/frontend/chunkstore/clean_admission.go CleanBatch.Close
46 core/frontend/chunkstore/clean_admission.go CleanBatch.Request
47 core/frontend/chunkstore/clean_b.go CleanBatch.BeginIn
48 core/frontend/chunkstore/clean_b.go CleanBatch.Close
49 core/frontend/chunkstore/clean_b.go CleanBatch.Effects
50 core/frontend/chunkstore/clean_b.go CleanBatch.PrepIn
51 core/frontend/chunkstore/clean_b.go CleanBatch.PrepOut
52 core/frontend/chunkstore/clean_b.go CutTime.Complete
53 core/frontend/chunkstore/clean_b.go PageChain.Sweep
54 core/frontend/chunkstore/clean_b.go SnapshotRemoval.BeginClean
55 core/frontend/chunkstore/clean_b.go SnapshotRemoval.EndClean
56 core/frontend/chunkstore/clean_b.go StaleClean.HeadRead
57 core/frontend/chunkstore/clean_intent_b.go CleanBatch.Publish
58 core/frontend/chunkstore/clean_intent_b.go CleanBatch.Request
59 core/frontend/chunkstore/clean_intent_b.go PageChain.CRead
60 core/frontend/chunkstore/clean_intent_b.go QueueCap.Consume
61 core/frontend/chunkstore/cut_verification_window.go CutTime.Complete
62 core/frontend/chunkstore/cut_verification_window.go CutWindow.CallTimeout
63 core/frontend/chunkstore/layout/claim.go EngineAdapter.Takeover
64 core/frontend/chunkstore/layout/claim.go MoveAdmission.ClaimB
65 core/frontend/chunkstore/layout/claim.go SnapshotRemoval.Claim
66 core/frontend/chunkstore/layout/claim.go StopAndRestart.ClaimB
67 core/frontend/chunkstore/layout/clean.go EngineAdapter.MaintBegin
68 core/frontend/chunkstore/layout/clean.go EngineAdapter.MaintEnd
69 core/frontend/chunkstore/layout/clean.go SnapshotRemoval.BeginClean
70 core/frontend/chunkstore/layout/clean.go SnapshotRemoval.EndClean
71 core/frontend/chunkstore/layout/clean_batch.go CleanBatch.PrepIn
72 core/frontend/chunkstore/layout/clean_batch.go CleanBatch.PrepOut
73 core/frontend/chunkstore/layout/clean_batch.go SnapshotRemoval.EndClean
74 core/frontend/chunkstore/layout/clean_batch.go SnapshotRemoval.Validate
75 core/frontend/chunkstore/layout/commit.go CutTime.Complete
76 core/frontend/chunkstore/layout/commit.go EngineAdapter.Apply
77 core/frontend/chunkstore/layout/commit.go QueueCap.TakeBack
78 core/frontend/chunkstore/layout/commit.go SnapshotRemoval.Commit
79 core/frontend/chunkstore/layout/commit.go StaleClean.CommitCheck
80 core/frontend/chunkstore/layout/commit.go StaleClean.HeadCommit
81 core/frontend/chunkstore/layout/commit.go VolumeCreate.Commit
82 core/frontend/chunkstore/layout/create.go RestoreTarget.CreateHead
83 core/frontend/chunkstore/layout/create.go RestoreTarget.CreateVol
84 core/frontend/chunkstore/layout/create.go VolumeCreate.Claim
85 core/frontend/chunkstore/layout/delete.go MoveAdmission.DelMark
86 core/frontend/chunkstore/layout/delete.go MoveAdmission.DelRead
87 core/frontend/chunkstore/layout/delete.go RestoreTarget.OpRelease
88 core/frontend/chunkstore/layout/delete.go RestoreTarget.OpTomb
89 core/frontend/chunkstore/layout/delete_intent.go CutTime.Complete
90 core/frontend/chunkstore/layout/delete_intent.go PageChain.CAdvance
91 core/frontend/chunkstore/layout/delete_intent.go PageChain.CApply
92 core/frontend/chunkstore/layout/delete_intent.go PageChain.CRead
93 core/frontend/chunkstore/layout/delete_intent.go PageChain.CResolve
94 core/frontend/chunkstore/layout/delete_intent.go PageChain.Resend
95 core/frontend/chunkstore/layout/delete_intent.go PageChain.Send
96 core/frontend/chunkstore/layout/delete_intent.go PageChain.WritePage
97 core/frontend/chunkstore/layout/delete_intent.go QueueCap.Consume
98 core/frontend/chunkstore/layout/delete_intent.go QueueCap.Produce
99 core/frontend/chunkstore/layout/delete_intent.go VolDelSweep.Land
100 core/frontend/chunkstore/layout/delete_intent.go VolDelSweep.Stage
101 core/frontend/chunkstore/layout/format_level.go FormatGate.PublishOp
102 core/frontend/chunkstore/layout/format_level.go FormatGate.Upgrade1
103 core/frontend/chunkstore/layout/head.go CleanBatch.Publish
104 core/frontend/chunkstore/layout/head.go CleanBatch.Request
105 core/frontend/chunkstore/layout/head.go SnapshotRemoval.Abort
106 core/frontend/chunkstore/layout/head.go SnapshotRemoval.Begin
107 core/frontend/chunkstore/layout/head.go StopAndRestart.Apply
108 core/frontend/chunkstore/layout/head.go StopAndRestart.Begin
109 core/frontend/chunkstore/layout/list_chain.go CutTime.Complete
110 core/frontend/chunkstore/layout/list_chain.go PageChain.CAdvance
111 core/frontend/chunkstore/layout/list_chain.go PageChain.CRead
112 core/frontend/chunkstore/layout/list_chain.go PageChain.CResolve
113 core/frontend/chunkstore/layout/list_chain.go PageChain.Resend
114 core/frontend/chunkstore/layout/list_chain.go PageChain.Send
115 core/frontend/chunkstore/layout/list_chain.go PageChain.WritePage
116 core/frontend/chunkstore/layout/list_chain.go QueueCap.Produce
117 core/frontend/chunkstore/layout/list_chain.go VolDelSweep.Land
118 core/frontend/chunkstore/layout/list_chain.go VolDelSweep.Stage
119 core/frontend/chunkstore/layout/maintenance_progress.go CutTime.Complete
120 core/frontend/chunkstore/layout/objects.go SnapshotRemoval.Upload
121 core/frontend/chunkstore/layout/read.go CutTime.Complete
122 core/frontend/chunkstore/layout/remove.go CleanBatch.Effects
123 core/frontend/chunkstore/layout/remove.go CutTime.Complete
124 core/frontend/chunkstore/layout/remove.go PageChain.Sweep
125 core/frontend/chunkstore/layout/remove.go SnapshotRemoval.Issue
126 core/frontend/chunkstore/layout/remove.go SnapshotRemoval.Stat
127 core/frontend/chunkstore/layout/remove.go SnapshotRemoval.Validate
128 core/frontend/chunkstore/layout/remove.go StaleClean.DeleteIt
129 core/frontend/chunkstore/layout/remove.go StaleClean.HeadRead
130 core/frontend/chunkstore/layout/remove.go StaleClean.MarkIt
131 core/frontend/chunkstore/layout/remove.go StaleClean.Stat
132 core/frontend/chunkstore/layout/snapshots.go EngineAdapter.OpWrite
133 core/frontend/chunkstore/layout/snapshots.go MoveAdmission.OpWrite
134 core/frontend/chunkstore/layout/snapshots.go RestoreTarget.AddDep
135 core/frontend/chunkstore/layout/snapshots.go SnapshotRemoval.DeleteSnap
136 core/frontend/chunkstore/layout/start.go HolderInterface.Start
137 core/frontend/chunkstore/layout/start.go StopAndRestart.CrashRestart
138 core/frontend/chunkstore/layout/start.go VolumeCreate.Claim
139 core/frontend/chunkstore/layout_create.go VolumeCreate.IssueHead
140 core/frontend/chunkstore/layout_create.go VolumeCreate.IssueVol
141 core/frontend/chunkstore/layout_remote.go CleanBatch.Begin
142 core/frontend/chunkstore/layout_remote.go CleanBatch.Publish
143 core/frontend/chunkstore/layout_remote.go CutTime.Complete
144 core/frontend/chunkstore/layout_remote.go EngineAdapter.Begin
145 core/frontend/chunkstore/layout_remote.go EngineAdapter.ReadHead
146 core/frontend/chunkstore/layout_remote.go EngineAdapter.SendCommit
147 core/frontend/chunkstore/layout_remote.go EngineAdapter.SettleAbort
148 core/frontend/chunkstore/layout_remote.go EngineAdapter.TakeAbandon
149 core/frontend/chunkstore/layout_remote.go FormatGate.CutPublish
150 core/frontend/chunkstore/layout_remote.go FormatGate.Upgrade1
151 core/frontend/chunkstore/layout_remote.go PageChain.CRead
152 core/frontend/chunkstore/layout_remote.go StopAndRestart.SendCommit
153 core/frontend/chunkstore/layout_remote.go StopAndRestart.SettleAbort
154 core/frontend/chunkstore/layout_store.go CleanBatch.Publish
155 core/frontend/chunkstore/layout_store.go CleanBatch.Request
156 core/frontend/chunkstore/layout_store.go SnapshotRemoval.ApplyDelete
157 core/frontend/chunkstore/layout_store.go SnapshotRemoval.ApplyMark
158 core/frontend/chunkstore/layout_store.go StaleClean.Adopt
159 core/frontend/chunkstore/maintenance_request.go CutTime.CallTimeout
160 core/frontend/chunkstore/retain_b.go CleanBatch.Publish
161 core/frontend/chunkstore/retain_b.go CleanBatch.Request
162 core/frontend/chunkstore/retain_b.go CutTime.Complete
163 core/frontend/chunkstore/snapshot_delete_operation.go FormatGate.AdmitOp
164 core/frontend/chunkstore/snapshot_delete_operation.go SnapDelete.Send
165 core/frontend/chunkstore/snapshot_delete_target.go FormatGate.AdmitOp
166 core/frontend/chunkstore/snapshot_operation.go SnapOps.Retire
167 core/frontend/chunkstore/snapshot_operation.go SnapOps.Send
168 core/frontend/chunkstore/snapshot_operation.go SnapOps.TornAdmit
169 core/frontend/chunkstore/snapshot_operation_guard.go SnapOps.Delete
170 core/frontend/chunkstore/snapshot_operation_guard.go SnapOps.Publish
171 core/frontend/chunkstore/snapshot_operation_index.go SnapOps.GC
172 core/frontend/chunkstore/snapshot_operation_index.go SnapOps.Poll
173 core/frontend/chunkstore/snapshot_operation_index.go SnapOps.TermFlag
174 core/frontend/chunkstore/swfs.go VolumeCreate.Land
175 core/frontend/durable/maintenance_progress.go CutTime.Complete
176 core/frontend/durable/maintenance_progress.go CutTime.Fail
177 core/frontend/durable/maintenance_progress.go CutTime.Tick
178 core/frontend/durable/provider_chunk.go CutTime.Admit
179 core/frontend/durable/provider_chunk.go CutWindow.Fail
180 core/frontend/durable/provider_chunk.go EngineAdapter.SettleResume
181 core/frontend/durable/provider_chunk.go EngineAdapter.StartStop
182 core/frontend/durable/provider_chunk.go FormatGate.CutPublish
183 core/frontend/durable/provider_chunk.go HolderInterface.StopBegin
184 core/frontend/durable/provider_chunk.go StopAndRestart.SendDetach
185 core/frontend/durable/provider_chunk.go StopAndRestart.SettleResume
186 core/frontend/durable/provider_layout.go EngineAdapter.SettleDown
187 core/frontend/durable/provider_layout.go StopAndRestart.SettleDown
188 core/frontend/durable/provider_preempt.go CutTime.Preempt
189 core/frontend/durable/provider_preempt.go CutTime.Settle
190 core/frontend/durable/storage_adapter.go EngineAdapter.GuestWrite
191 core/frontend/durable/storage_adapter.go HolderInterface.Write
192 core/frontend/durable/storage_adapter.go WALHold.Resubmit
193 core/frontend/iscsi/scsi.go WALHold.Stall
194 core/frontend/nvme/io.go WALHold.Stall
195 core/host/master/format_gate.go FormatGate.Finalize
196 core/host/master/format_gate.go FormatGate.Grant
197 core/host/master/format_gate.go FormatGate.Place
198 core/host/master/format_gate.go FormatGate.Report
199 core/host/master/format_gate.go FormatGate.Retire
200 core/host/master/journal_isolation.go DeleteRetire.HostRetire
201 core/host/master/layout_ready.go VolumeCreate.Place
202 core/host/master/observation_snapshot.go DeleteRetire.HostRetire
203 core/host/master/probe_round.go FencingRound.Deliver
204 core/host/master/probe_round.go FencingRound.Open
205 core/host/master/product_loop.go FencingRound.Decide
206 core/host/master/product_loop.go Promotion.Decide
207 core/host/master/services.go FormatGate.Report
208 core/host/master/spec_retirement.go DeleteRetire.ReadOK
209 core/host/master/store_attestation.go ReplicationPeer.Attest
210 core/host/master/workspace_binding.go FormatGate.Grant
211 core/host/master/workspace_binding.go MoveAdmission.Ack
212 core/host/master/workspace_service.go FormatGate.Place
213 core/host/master/workspace_service.go FormatGate.Renew
214 core/host/master/workspace_service.go MoveAdmission.ReadForMove
215 core/host/master/workspace_service.go StopAndRestart.ReadClean
216 core/host/volume/chunk_control.go CutTime.InProgress
217 core/host/volume/chunk_control.go CutWindow.Fail
218 core/host/volume/chunk_control.go FormatGate.Upgrade1
219 core/host/volume/chunk_control.go SnapOps.Start
220 core/host/volume/host.go FormatGate.Downgrade
221 core/host/volume/host.go FormatGate.Renew
222 core/host/volume/host.go FormatGate.Upgrade
223 core/host/volume/manual_cut.go CutTime.Admit
224 core/host/volume/manual_cut.go CutTime.InProgress
225 core/host/volume/manual_cut.go CutTime.Poll
226 core/host/volume/manual_cut.go CutTime.Retire
227 core/host/volume/plain_detach_handle.go CutTime.OtherEnd
228 core/host/volume/plain_detach_handle.go CutTime.OtherStep
229 core/host/volume/plain_detach_handle.go CutTime.Preempt
230 core/host/volume/plain_detach_handle.go CutTime.Settle
231 core/host/volume/plain_detach_handle.go CutTime.SettleStall
232 core/host/volume/primary_evidence.go FencingRound.Adopt
233 core/host/volume/primary_evidence.go Promotion.Adopt
234 core/host/volume/primary_evidence.go Promotion.Refuse
235 core/host/volume/probe_round.go FencingRound.Answer
236 core/host/volume/recovery_watchdog.go RecoveryProgress.Authority
237 core/host/volume/recovery_watchdog.go RecoveryProgress.Fence
238 core/host/volume/recovery_watchdog.go RecoveryProgress.Replay
239 core/host/volume/recovery_watchdog.go RecoveryProgress.Stall
240 core/host/volume/recovery_watchdog.go RecoveryProgress.ToFence
241 core/host/volume/snapshot_operation.go SnapOps.Start
242 core/host/volume/workspace_lease.go FormatGate.Renew
243 core/host/volume/workspace_lease.go HolderInterface.Expire
244 core/host/volume/workspace_lease.go MoveAdmission.StopOnExpiry
245 core/host/volume/workspace_lease.go MoveAdmission.Write
246 core/host/volume/workspace_lease.go SnapshotRemoval.Expire
247 core/host/volume/workspace_lease.go StopAndRestart.Write
248 core/host/volume/workspace_runtime.go FormatGate.Renew
249 core/host/volume/workspace_startup.go FormatGate.Renew
250 core/lifecycle/store.go VolumeCreate.MarkReady
251 core/lifecycle/store.go VolumeCreate.Record
252 core/replication/peer.go Promotion.Ship1
253 core/replication/peer.go Promotion.Ship2
254 core/replication/peer.go ReplicationPeer.Barrier
255 core/replication/peer.go ReplicationPeer.Fail
256 core/replication/peer.go ReplicationPeer.Heal
257 core/replication/peer.go ReplicationPeer.Ship
258 core/replication/volume.go FencingRound.Ack
259 core/replication/volume.go Promotion.Ack1
260 core/replication/volume.go Promotion.Rejoin
261 core/replication/volume.go Promotion.Write1
262 core/replication/volume.go Promotion.Write2
263 core/replication/volume.go ReplicationPeer.Ack
264 core/replication/volume.go ReplicationPeer.Write
265 core/storage/chunk_coverage.go SlotFence.Publish
266 core/storage/chunk_coverage_map.go MoveWide2.Write
267 core/storage/chunk_head_belt.go HolderInterface.Fence
268 core/storage/chunk_layer.go CutTime.Settle
269 core/storage/chunk_layer.go CutWindow.Publish
270 core/storage/chunk_layer.go CutWindow.Retry
271 core/storage/chunk_layer.go EngineAdapter.EngineReRead
272 core/storage/chunk_layer.go EngineAdapter.NoOpCut
273 core/storage/chunk_layer.go FormatGate.Upgrade1
274 core/storage/chunk_layer.go HolderInterface.Commit
275 core/storage/chunk_layer.go HolderInterface.StopCommit
276 core/storage/chunk_layer.go MoveAdmission.Detach
277 core/storage/chunk_layer.go MoveAdmission.Publish
278 core/storage/chunk_layer.go SnapshotRemoval.Write
279 core/storage/chunk_manual_cut.go CutTime.Busy
280 core/storage/chunk_manual_cut.go CutTime.PublishLost
281 core/storage/chunk_manual_cut.go CutTime.Settle
282 core/storage/chunk_manual_cut.go CutTime.SettleInherited
283 core/storage/chunk_manual_cut.go CutTime.SettleStall
284 core/storage/chunk_manual_cut.go HolderInterface.Fence
285 core/storage/chunk_preempt.go CutTime.OtherStep
286 core/storage/chunk_preempt.go CutTime.Preempt
287 core/storage/chunk_public.go FormatGate.Upgrade1
288 core/storage/chunk_seam.go FormatGate.Upgrade1
289 core/storage/chunk_state_upgrade.go SlotFence.Publish
290 core/storage/chunk_state_upgrade.go SlotFence.Sync
291 core/storage/chunk_upload.go CutWindow.CallTimeout
292 core/storage/chunk_upload.go CutWindow.Start
293 core/storage/cut_progress_window.go CutTime.Complete
294 core/storage/cut_progress_window.go CutWindow.CallTimeout
295 core/storage/cut_progress_window.go CutWindow.Complete
296 core/storage/cut_progress_window.go CutWindow.Fail
297 core/storage/cut_progress_window.go CutWindow.Tick
298 core/storage/flusher.go WALHold.Reclaim
299 core/storage/recovery_progress.go RecoveryProgress.Replay
300 core/storage/wal_admission.go WALHold.Arrive
301 core/storage/wal_admission_fast.go WALHold.FastArrive
302 core/storage/wal_admission_fast.go WALHold.FastReEnter
303 core/storage/wal_admission_fast.go WALHold.FastResubmit
304 core/storage/wal_admission_fifo.go WALHold.Admit
305 core/storage/wal_admission_fifo.go WALHold.Arrive
306 core/storage/wal_admission_fifo.go WALHold.ReEnter
307 core/storage/wal_hold_window.go WALHold.CapAnswer
308 core/storage/wal_hold_window.go WALHold.Stall
309 core/storage/wal_write_hold.go WALHold.CapAnswer
310 core/storage/wal_write_hold.go WALHold.Stall
311 core/storage/walstore.go WALHold.Admit
312 core/storage/walstore_v3.go RecoveryProgress.Fence
313 core/storage/walstore_v3.go SlotFence2.OpenNew
314 core/transport/catchup_sender.go ReplicationPeer.CatchUp
315 core/transport/rebuild_sender.go ReplicationPeer.Rebuild
316 core/transport/replica.go FencingRound.Recv
317 core/transport/replica.go ReplicationPeer.CatchUp
318 core/transport/replica.go ReplicationPeer.Rebuild
319 core/transport/replica.go ReplicationPeer.Ship
-94
View File
@@ -1,94 +0,0 @@
# What a PR labelled "post-merge-review" may touch.
#
# A labelled PR passes the "post-merge-review paths" check only if EVERY
# changed file (both names of a rename) matches an allow line and no "!"
# line. Anything not allowed is denied: new files start denied. A PR that
# fails keeps the full review before merge. Without the label the check
# passes and nothing changes.
#
# One bash glob per line, matched against the repo-relative path; "*" also
# matches "/". A line starting with "!" denies, and wins over any allow line.
# Blank lines and text after "#" are ignored. The check reads this file from
# the base branch, so a PR cannot loosen its own check; a missing or empty
# file fails the check.
# ---- Allowed ----
# Docs.
docs/*
*.md
# Tests: added or modified, never deleted or moved (the check enforces
# that); a test file in a denied directory stays denied.
*_test.go
# Status, metrics and observation files, by name.
core/host/master/observation_service.go
core/host/master/observation_snapshot.go
core/host/volume/memory_status.go
core/ops/observation.go
core/ops/observation_bundle.go
core/ops/observation_dashboard.go
core/ops/observation_report.go
core/ops/volume_status_artifacts.go
core/ops/volume_status_report.go
core/ops/volume_status_report_collector.go
core/ops/volume_status_summary.go
# ---- Denied even if allowed above ----
# The check itself and CI.
!.github/*
# The test gates: the testops engine, its CLI and the gate definitions
# (their docs stay allowed).
!internal/testops/*.go
!internal/testops/*.json
!cmd/sw-testops/*
# Data path and replication.
!core/storage/*
!core/frontend/*
!core/transport/*
!core/replication/*
!core/recovery/*
!core/engine/*
!core/adapter/*
# Authority: lease, epoch, fencing, move.
!core/authority/*
!core/host/master/workspace_*
!core/host/volume/workspace_*
!cmd/blockvolume/workspace_lease*
# Wire and persisted formats.
!*.proto
!*.pb.go
!core/host/master/journal_isolation*
!core/lifecycle/store*
!cmd/sparrow/persist*
# GC and delete paths.
!cmd/sw-block/chunk_gc*
!cmd/sw-block/chunk_volume_delete*
!core/lifecycle/deletion_reservations*
!core/ops/delete_safety_contract*
!*/gc[_.]*
!*_gc[_.]*
# Lease, epoch, claim, admission, GC, delete or format code (tests included)
# wherever it lives, by file name.
!*/lease*.go
!*_lease*.go
!*epoch*.go
!*fenc*.go
!*claim*.go
!*admission*.go
!*/gc_*.go
!*_gc.go
!*_gc_*.go
!*delet*.go
!*purge*.go
!*persist*.go
!*journal*.go
!*format*.go
-47
View File
@@ -1,47 +0,0 @@
# Seconds each process-level test took on the CI runner (main 032eb197, run 45972669823),
# used only to balance the parallel shards (.github/scripts/shard-named-tests.py). A test
# missing here counts as 60 s; a stale time unbalances the shards but never skips a test.
TestAVolumeThatServedBeforeItsFirstGateTickFailsOver 31.4
TestClaimedTargetAfterAMasterRestartIsNotNeverStarted 18.7
TestCutoverCreateFromSnapshot 25.4
TestCutoverWriteSnapshotKillRestartRestore 34.1
TestDoubleFailoverReadsBackEveryAckedWrite 10.2
TestFencingRoundHealContinuesThePrimary 13.4
TestFencingRoundSurvivorRejoins 17.0
TestKnownZeroAcceptance 27.1
TestKnownZeroTargetReservesBeforeHarness 0.0
TestNeverAttachedRestoreTargetIsDeletable 16.5
TestNeverStartedDeleteAfterAMasterRestart 166.8
TestNeverStartedDeleteFencesALateStart 53.6
TestNeverStartedDeleteRacesAStart 42.4
TestNeverStartedLineDeleteFencesALateStart 240.3
TestNeverStartedLineDeleteRacesAStart 458.9
TestNeverStartedLineIsDeletableWithoutARevoke 335.1
TestProcedureDeleteAVolume 79.1
TestProcedureDeleteAfterASignalStop 116.1
TestProcedureForcedMoveWithTheOldHostReturning 100.2
TestProcedureMasterKilledAfterMoveBeforeTargetStarts 23.2
TestProcedureMasterUnreachableFencesBeforeForcedMove 159.4
TestProcedurePlannedHandoffToAnotherHost 16.8
TestProcedureReturnAfterALapsedLease 81.4
TestProcedureRevokeWithoutACKThenForcedMove 79.6
TestProcedureSameHostCrashRestartInsideTheLease 17.5
TestProcedureSameHostRestartInsideTheLease 17.5
TestProcedureStartInsideTheBarrierWaitIsReGranted 80.0
TestSnapshotLadderA1OneBlockOneSnapshot 18.8
TestSnapshotLadderA2IncrementalSnapshot 20.9
TestSnapshotLadderA3WritesDuringASnapshot 26.1
TestSnapshotLadderA4ContentReturnsToAnOldValue 23.6
TestSnapshotLadderB1SnapshotQuery 19.1
TestSnapshotLadderC1FullRestore 18.8
TestSnapshotLadderC2IncrementalRestore 21.3
TestSnapshotLadderC3KilledHydrating 35.6
TestSnapshotLadderC3RestoreThenWriteThenSnapshotIt 21.3
TestSnapshotLadderD1DeleteTheNewest 21.4
TestSnapshotLadderD2DeleteAMiddleOne 23.9
TestSnapshotLadderD3DeleteWhenContentRecurs 21.3
TestSnapshotLadderD4DeleteAllButOneThenCollect 19.4
TestSnapshotLadderE1CrashDuringASnapshot 31.1
TestSnapshotLadderF1VolumesOneHost 528.4
TestStandaloneCleanMoveWithoutTheACKIsRefused 16.6
TestStandalonePlannedHandoffToTheSameHost 17.7
-99
View File
@@ -1,99 +0,0 @@
# Process-level tests (cmd/blockvolume with build tags subprocess and
# chunkstore_integration, linux) named as release evidence. CI runs them
# against real blockmaster, blockvolume and sw-block binaries and the pinned
# SeaweedFS release. Every name here must PASS: a skip, a failure or a test
# that never ran fails the job (.github/scripts/required-tests-check.py).
#
# Not here, and why: the three headroom tests (TestHeadroom*), the power-loss
# replay (TestPowerLossReplayChunkVolume, a dm-log-writes harness) and the
# tests tagged systemd_integration need root, a loop or mapped device, or
# systemd; the CI runners have none of these. They run as root outside CI,
# and their counts are recorded there.
# Known-zero acceptance, small shape in CI (KZ_RUN=1 KZ_SIZE=1G, user-space
# client, no device); the 1 TiB run is lab only.
TestKnownZeroAcceptance
TestKnownZeroTargetReservesBeforeHarness
# The procedure gate, delete and master loss.
TestProcedurePlannedHandoffToAnotherHost
TestProcedureSameHostRestartInsideTheLease
TestProcedureSameHostCrashRestartInsideTheLease
TestProcedureReturnAfterALapsedLease
TestProcedureForcedMoveWithTheOldHostReturning
TestProcedureRevokeWithoutACKThenForcedMove
TestProcedureStartInsideTheBarrierWaitIsReGranted
TestProcedureDeleteAVolume
TestANewClustersRealHolderReportsLevel1AndIsGranted
TestProcedureDeleteAfterASignalStop
TestProcedureMasterKilledAfterMoveBeforeTargetStarts
TestProcedureMasterUnreachableFencesBeforeForcedMove
TestStandalonePlannedHandoffToTheSameHost
TestStandaloneCleanMoveWithoutTheACKIsRefused
# Failover and the fencing round.
TestDoubleFailoverReadsBackEveryAckedWrite
# The replicated preview's fencing round runs and is reported on every job but
# does not gate it (#920: a sync-quorum flush under shared-runner load); it
# gates the nightly run on a quiet lab box.
TestFencingRoundHealContinuesThePrimary # nongating=#920
TestFencingRoundSurvivorRejoins # nongating=#920
TestAVolumeThatServedBeforeItsFirstGateTickFailsOver
# Many volumes on one host (F1_RUN=1).
TestSnapshotLadderF1VolumesOneHost
# Never-started delete.
TestNeverAttachedRestoreTargetIsDeletable
TestNeverStartedDeleteFencesALateStart
TestNeverStartedDeleteRacesAStart
TestNeverStartedLineIsDeletableWithoutARevoke
TestNeverStartedLineDeleteFencesALateStart
TestNeverStartedLineDeleteRacesAStart
TestNeverStartedDeleteAfterAMasterRestart
TestClaimedTargetAfterAMasterRestartIsNotNeverStarted
# Snapshot ladders and cutover.
TestSnapshotLadderA1OneBlockOneSnapshot
TestSnapshotLadderA2IncrementalSnapshot
TestSnapshotLadderA3WritesDuringASnapshot
TestSnapshotLadderA4ContentReturnsToAnOldValue
TestSnapshotLadderB1SnapshotQuery
TestSnapshotLadderC1FullRestore
TestSnapshotLadderC2IncrementalRestore
TestSnapshotLadderC3RestoreThenWriteThenSnapshotIt
# A first write after the holder reports its frontend ready can be answered
# namespace-not-ready for longer than a host retries (#905, a v1.1 release
# gate); it runs and is reported on every job until the fix removes this.
TestSnapshotLadderC3KilledHydrating # nongating=#905
TestSnapshotLadderD1DeleteTheNewest
TestSnapshotLadderD2DeleteAMiddleOne
TestSnapshotLadderD3DeleteWhenContentRecurs
TestSnapshotLadderD4DeleteAllButOneThenCollect
TestSnapshotLadderE1CrashDuringASnapshot
TestCutoverCreateFromSnapshot
TestCutoverWriteSnapshotKillRestartRestore
# CSI real-binary seams: dispatched to blockcsi.test in the same process job.
# package=blockcsi is routing metadata; the required-test checker needs all names.
TestBlockCSI_BinaryStartsAndServesIdentity # package=blockcsi
TestG15a_BlockCSIControllerPublishUsesMasterFrontendFact # package=blockcsi
TestG15c_BlockCSICreateVolumeWritesMasterLifecycleIntent # package=blockcsi
# Typed delete stdout remains separate from HEAD diagnostics.
TestDeleteNoRevokeKeepsTheTypedStdoutSeparate
# Procedure ordering compares the UTC log instant including its fraction.
TestProcedureLogTimesUseTheUTCInstant
# Snapshot operation intent and publication receipts survive real holder kills.
TestSnapshotOperationIntentAndPublicationCrashBoundaries
TestSnapshotOperationKillReceiptRejectsOrdinaryExit
# Two weed clusters side by side: a filer of one that reaches the other's master
# is in its own filer group, so the other's single-filer census still passes.
TestWeedClustersSideBySideKeepTheirOwnFilerCensus
# Kubernetes state: a holder on a wiped state directory never comes up empty.
TestRF1HolderOnAWipedStateDirectoryRefusesStoreLost
TestRF3WipedPrimaryRefusesAndASurvivorServesItsData
-44
View File
@@ -1,44 +0,0 @@
Feature: <roadmap item>
Machine/INV: <kind> / <INV rows>
Model: <Module.Action; OtherModule.Action, or NONE (pure function of Module) for mapped files>
Red-first: <commit + test that failed on the base, or NONE: reason>
Simplest: <the simplest version, and what this PR did not add>
Time bounds: <none, or each fixed time bound this PR adds or changes, with its class and model row as listed in docs/time-bounds.tsv>
Five questions, answered in plain words before review:
Serves: <which statement of the specification or the docs this change serves>
Decided by: <whose decision this is, and where it is recorded>
Layer use: <conventional: the layer below is used the usual way; or the deviation>
Deviation buys: <what the deviation buys, measured; or none: no deviation>
Weakens: <which existing guarantee this weakens (its cost, the way it fails, a mode it leaves out, whether its proof runs on the production type), or none and why>
Facts: <per fact this change adds or changes, its one placement class: DURABLE; MEMORY-REBUILT-FAST (its rebuild cost, bounded by the change since the last durable point, or constant); or MEMORY-MAY-BE-LOST (its loss only delays or repeats bounded idempotent work, and resets to refuse). Also where it lives and what a restart and an abort do. Or none -- and why>
<!--
The spec-trace check reads the lines above.
Machine/INV starts with exactly one kind:
IMPL <machine>.<transition> implements an existing transition; no new state, flag or reason.
FIX <INV-ID> the red test is that invariant failing on the base.
CHANGE <machine> new or changed states, transitions or invariants; the automaton
text and rows land with or before the code.
A fix without an invariant, or a guard term without a transition, is a CHANGE.
A PR that changes no behaviour uses one of these instead, checked against its files:
DOCS docs (not docs/spec), tests, and Go whose tokens are unchanged
(comments only; directive comments count as code).
TEST only tests, testdata and test helpers.
CI only .github/ (scripts/ ships install and deploy scripts).
DOCS may still change contract text (docs/design/invariants.md): the reviewer is the gate for that.
NONE needs a reason of at least 10 characters. Simplest is required when the PR
changes non-test Go under core/ or cmd/.
Weakens and Facts are required on every PR that changes product code: a review
is refused without them. "none" needs its reason.
A fact that fits none of the three placement classes is a finding: the review
is refused.
Mapped files in .github/model-code-trace.tsv require a listed Module.Action
or NONE (pure function of Module). Separate citations for multiple modules
with semicolons. Unmapped files retain the existing Model trace policy.
-->
-53
View File
@@ -1,53 +0,0 @@
#!/usr/bin/env bash
# Self-test of changed-go-blobs.sh and of the fetch setting the PR checks use:
# a PR tree that names a '..' entry must neither write outside the output
# directory nor be fetched at all.
set -euo pipefail
script=$(cd "$(dirname "$0")" && pwd)/changed-go-blobs.sh
t=$(mktemp -d)
trap 'rm -rf "$t"' EXIT
fail() { echo "changed-go-blobs-test: FAIL: $*" >&2; exit 1; }
git init -q "$t/r"
cd "$t/r"
git config user.email t@example.com
git config user.name t
mkdir -p a
printf 'package a\n' >a/a.go
printf 'package a\n' >a/a_test.go
git add . && git commit -q -m base
base=$(git rev-parse HEAD)
# 1. An ordinary change: the old and new blobs land under the output directory.
printf 'package a\n\nvar X = 1\n' >a/a.go
printf 'package b\n' >b.go
git add . && git commit -q -m change
bash "$script" "$base" HEAD "$t/out1"
grep -q 'var X' "$t/out1/new/a/a.go" || fail "new blob of a/a.go missing"
[ -f "$t/out1/old/a/a.go" ] || fail "old blob of a/a.go missing"
[ -f "$t/out1/new/b.go" ] && [ ! -e "$t/out1/old/b.go" ] || fail "added file b.go not new-only"
[ ! -e "$t/out1/new/a/a_test.go" ] || fail "a test file was written"
# 2. A crafted tree: '..' nested three times, holding x.go. git writes such
# a tree only with --literally; the diff still lists '../../../x.go', and
# writing blobs by that path would create new/../../../x.go, outside the
# output directory (the inline loop this script replaced did exactly that).
blob=$(printf 'package evil\n' | git hash-object -w --stdin)
entry() { perl -e 'print $ARGV[0], "\0", pack("H*", $ARGV[1])' "$1" "$2"; }
tr=$(entry "100644 x.go" "$blob" | git hash-object -t tree --literally -w --stdin)
for _ in 1 2 3; do tr=$(entry "40000 .." "$tr" | git hash-object -t tree --literally -w --stdin); done
evil=$(git commit-tree "$tr" -p "$base" -m evil)
mkdir -p "$t/deep/ws/out2"
if bash "$script" "$base" "$evil" "$t/deep/ws/out2" 2>"$t/err"; then fail "a '..' path was accepted"; fi
grep -q 'refusing path' "$t/err" || fail "refusal not reported: $(cat "$t/err")"
[ -z "$(find "$t/deep" -name x.go)" ] || fail "a file was written outside the output directory"
# 3. The checks fetch the PR head with fetch.fsckObjects=true: the crafted
# tree is refused at the fetch.
git update-ref refs/pull/1/head "$evil"
git init -q "$t/c"
cd "$t/c"
if git -c fetch.fsckObjects=true fetch -q --no-tags "$t/r" "+refs/pull/1/head:refs/remotes/pr/head" 2>"$t/err2"; then
fail "fetch with fsckObjects accepted a '..' tree"
fi
echo "changed-go-blobs-test: PASS (3 cases)"
-29
View File
@@ -1,29 +0,0 @@
#!/usr/bin/env bash
# Writes the old and new blob of each changed non-test Go file between two
# commits under <out>/old/<path> and <out>/new/<path>, for the spec trace's
# kind DOCS (objects only; nothing from the PR is built or run).
#
# usage: changed-go-blobs.sh <merge-base> <head> <out>
#
# 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 <out>, so it is refused before anything is
# written (exit 1).
set -euo pipefail
mb=$1 head=$2 out=$3
mkdir -p "$out"
git diff --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:$p" >"$out/old/$p" 2>/dev/null || rm -f "$out/old/$p"
git show "$head:$p" >"$out/new/$p" 2>/dev/null || rm -f "$out/new/$p"
done <"$out/.paths"
rm -f "$out/.paths"
-53
View File
@@ -1,53 +0,0 @@
#!/usr/bin/env bash
# Tests chunkstore-scope.sh against real commits. Any failure exits nonzero.
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)
scope="$here/chunkstore-scope.sh"
fail=0
check() { # name want got
if [ "$2" = "$3" ]; then echo "ok $1"; else echo "FAIL $1: want [$2], got [$3]"; fail=1; fi
}
repo=$(mktemp -d)
trap 'rm -rf "$repo"' EXIT
cd "$repo"
git init -q
git config user.email t@example.invalid
git config user.name t
git config core.autocrlf false
mkdir -p core/frontend/chunkstore core/frontend/durable core/storage core/other docs
echo c >core/frontend/chunkstore/c.go
echo p >core/frontend/durable/p.go
echo s >core/storage/s.go
echo o >core/other/o.go
echo d >docs/d.md
git add -A
git commit -qm base
base=$(git rev-parse HEAD)
case_of() { # name want: commit the current tree, classify against base, reset
git add -A
git commit -qm "$1" --allow-empty
check "$1" "$2" "$(bash "$scope" "$base" HEAD)"
git reset -q --hard "$base"
}
echo c2 >core/frontend/chunkstore/c.go
case_of "a chunkstore file" "run 1 core/frontend/chunkstore/c.go"
echo p2 >core/frontend/durable/p.go
case_of "a durable provider file only" "run 1 core/frontend/durable/p.go"
echo s2 >core/storage/s.go; echo o2 >core/other/o.go
case_of "storage and another package" "run 2 core/storage/s.go"
echo o2 >core/other/o.go; echo d2 >docs/d.md
case_of "neither path" "skip 2"
case_of "no file changed" "skip 0"
mkdir -p core/storage-old; echo x >core/storage-old/x.go
case_of "a storage-like prefix" "skip 1"
git rm -q core/storage/s.go
case_of "a storage deletion" "run 1 core/storage/s.go"
for i in $(seq 1 20000); do printf 'x\n' >"docs/f$i.md"; done
echo late >core/storage/zz_late.go
case_of "20000 other files and one storage file, listed last" "run 20001 core/storage/zz_late.go"
if out=$(bash "$scope" "$base" no-such-revision 2>/dev/null); then
check "an unknown revision is an error" "nonzero exit" "exit 0: $out"
else
check "an unknown revision is an error" "nonzero exit" "nonzero exit"
fi
exit "$fail"
-33
View File
@@ -1,33 +0,0 @@
#!/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 --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
-41
View File
@@ -1,41 +0,0 @@
# Failed-job evidence
Both test suites keep one `ci-<suite>-<run>-<attempt>` artifact on failure for
14 days. `go-test.json` contains Go's timestamped events and per-test `Elapsed`
values; process shards also keep their original JSON, logs and exit receipts.
`go-test.stderr` keeps build/tool errors outside Go's JSON event stream. The
console still shows the original test output. Recording/rendering errors are
best effort: they report the missing evidence and keep draining Go, whose own
exit code alone decides the wrapper's result. Test arguments, scope, timeouts,
exit-code handling and the required-tests gate are unchanged.
`load.tsv` begins immediately after checkout and samples once per second until
the final collection step. It covers setup, builds and tests; the checkout
itself and the artifact upload are outside the sampling interval. The sampler
has the job's maximum lifetime if cancellation prevents its stop step. The
stop receipt includes the process start time, so a recycled PID is not killed.
Columns:
- `ts_utc`: UTC timestamp with milliseconds. Scheduling gaps remain visible;
delayed sampling does not invent backfilled one-second rows.
- `load1`: machine load average.
- `steal_pct`, `iowait_pct`: interval percentages from `/proc/stat` (the first
row has no baseline and is null). Guest counters are not counted twice.
- `psi_cpu`, `psi_io`, `psi_mem`: JSON objects containing the kernel's `some`
and, when available, `full` pressure averages and cumulative microseconds.
- `disk_await_ms`: JSON map by device, calculated as the interval's read/write
milliseconds divided by completed reads/writes from `/proc/diskstats`.
Devices are kept separate, including partitions and device-mapper layers;
do not sum them. No completed IO, reset counters or a new device yields null.
Discard and flush-only operations are not included in this read/write mean.
- `cgroup_cpu_max`: JSON map of `cpu.max` for the sampler's current cgroup and
every visible ancestor. The sampler inherits the job's cgroup. Parent quotas
matter even when the leaf says `max`. Cgroup v1/unavailable data is null.
- `errors`: read/parse errors; missing or inaccessible counters are null,
never fabricated zero load. Consult `load.sampler.log` for sampler errors.
No package installation, sudo, or `iostat` executable is required. `/proc`
CPU/PSI/disk observations are machine-wide; these are correlation evidence,
not proof that the job itself caused contention. Sampling is diagnostic and
does not revoke, retry or change a test's result.
-129
View File
@@ -1,129 +0,0 @@
"""Fixed Linux counter fixtures; no host load or privileged runner needed."""
import importlib.util
import json
import pathlib
import subprocess
import sys
import tempfile
import time
import unittest
spec = importlib.util.spec_from_file_location('ci_load', pathlib.Path(__file__).with_name('ci-load.py'))
load = importlib.util.module_from_spec(spec)
spec.loader.exec_module(load)
class LoadTest(unittest.TestCase):
@unittest.skipUnless(sys.platform == 'linux', 'real /proc lifecycle is Linux-only')
def test_cli_samples_and_stops_its_own_process(self):
with tempfile.TemporaryDirectory() as name:
output = pathlib.Path(name)/'load.tsv'
command = [sys.executable, '-I', str(pathlib.Path(__file__).with_name('ci-load.py'))]
try:
subprocess.run(command+['start', str(output), '--duration', '30'], check=True, timeout=10)
deadline = time.monotonic()+10
while time.monotonic() < deadline:
if output.exists() and len(output.read_text().splitlines()) >= 3:
break
time.sleep(0.05)
finally:
subprocess.run(command+['stop', str(output)], check=True, timeout=5)
lines = output.read_text().splitlines()
self.assertGreaterEqual(len(lines), 3)
self.assertTrue(lines[0].startswith('ts_utc\tload1\tsteal_pct'))
for line in lines[1:]:
fields = line.split('\t')
self.assertEqual(len(fields), 10)
self.assertTrue(fields[0].endswith('+00:00'))
for field in fields[1:]:
json.loads(field)
# The sampler exited: its pid is gone, and no incomplete note.
pid = json.loads(output.with_suffix('.pid.json').read_text())['pid']
self.assertFalse(pathlib.Path(f'/proc/{pid}').exists() and
pathlib.Path(f'/proc/{pid}/stat').read_text().split(')')[1].split()[0] != 'Z')
self.assertFalse(output.with_suffix('.incomplete').exists())
@unittest.skipUnless(sys.platform == 'linux', 'real /proc lifecycle is Linux-only')
def test_stop_records_a_sampler_that_does_not_exit(self):
with tempfile.TemporaryDirectory() as name:
output = pathlib.Path(name)/'load.tsv'
ready = pathlib.Path(name)/'ready'
stubborn = subprocess.Popen([sys.executable, '-c',
'import pathlib,signal,sys,time; signal.signal(signal.SIGTERM, signal.SIG_IGN); '
'pathlib.Path(sys.argv[1]).touch(); time.sleep(30)', str(ready)])
try:
deadline = time.monotonic()+10
while not ready.exists():
self.assertIsNone(stubborn.poll(), 'the stand-in exited before it was ready')
self.assertLess(time.monotonic(), deadline, 'the stand-in never became ready')
time.sleep(0.01)
output.with_suffix('.pid.json').write_text(json.dumps(dict(pid=stubborn.pid, start=load.identity(stubborn.pid))))
began = time.monotonic()
done = subprocess.run([sys.executable, '-I', str(pathlib.Path(__file__).with_name('ci-load.py')), 'stop', str(output)],
capture_output=True, text=True, timeout=10)
self.assertEqual(done.returncode, 0)
self.assertLess(time.monotonic()-began, 5)
self.assertIn('did not exit', output.with_suffix('.incomplete').read_text())
self.assertIn('load evidence incomplete', done.stderr)
finally:
stubborn.kill()
stubborn.wait()
def test_cpu_and_disk_interval_not_since_boot(self):
# CPU: 100 ticks, 10 iowait, 5 stolen. guest ticks are already in user.
before = {'cpu': [100, 0, 20, 800, 20, 0, 0, 10, 3, 0],
'disks': {'nvme0n1': [10, 30]}}
after = {'cpu': [130, 0, 25, 850, 30, 0, 0, 15, 7, 0],
'disks': {'nvme0n1': [14, 50], 'new': [1000, 9000]}}
cpu, disks = load.interval(before, after)
self.assertEqual(cpu, {'steal_pct': 5.0, 'iowait_pct': 10.0})
self.assertEqual(disks, {'nvme0n1': 5.0, 'new': None})
def test_reset_or_no_io_is_unknown_not_zero_latency(self):
before = {'cpu': [10]*8, 'disks': {'sda': [10, 100], 'sdb': [20, 200]}}
after = {'cpu': [1]*8, 'disks': {'sda': [10, 100], 'sdb': [1, 3]}}
cpu, disks = load.interval(before, after)
self.assertEqual(cpu, {'steal_pct': None, 'iowait_pct': None})
self.assertEqual(disks, {'sda': None, 'sdb': None})
def test_proc_fields_and_cgroup_ancestor_quota(self):
with tempfile.TemporaryDirectory() as name:
root = pathlib.Path(name)
(root/'pressure').mkdir()
(root/'self').mkdir()
mount = root/'cg'
(mount/'runner/job').mkdir(parents=True)
(mount/'cpu.max').write_text('max 100000\n')
(mount/'runner/cpu.max').write_text('200000 100000\n')
(mount/'runner/job/cpu.max').write_text('max 100000\n')
(root/'self/cgroup').write_text('0::/slice/runner/job\n')
(root/'self/mountinfo').write_text(f'1 0 0:1 /slice {mount.as_posix()} rw - cgroup2 cgroup rw\n')
(root/'loadavg').write_text('3.25 2.00 1.00 1/1 1\n')
(root/'stat').write_text('cpu 100 0 20 800 20 0 0 10 3 0\n')
(root/'diskstats').write_text('259 0 nvme0n1 2 0 0 6 3 0 0 9 0 0 0\n')
for kind in ('cpu', 'io', 'memory'):
(root/'pressure'/kind).write_text('some avg10=1.25 avg60=0.50 avg300=0.20 total=12345\n')
snapshot = load.read_snapshot(root)
self.assertEqual(snapshot['load1'], 3.25)
self.assertEqual(snapshot['disks'], {'nvme0n1': [5, 15]})
self.assertEqual(snapshot['psi']['cpu']['some']['total'], 12345)
self.assertEqual(snapshot['cpu_max'][str(mount/'runner/cpu.max')], '200000 100000')
self.assertEqual(snapshot['errors'], [])
(mount/'cpu.max').unlink()
snapshot = load.read_snapshot(root)
self.assertEqual(snapshot['cpu_max'][str(mount/'runner/cpu.max')], '200000 100000')
self.assertIsNone(snapshot['cpu_max'][str(mount/'cpu.max')])
self.assertTrue(snapshot['errors'])
def test_missing_inputs_explicitly_reported(self):
with tempfile.TemporaryDirectory() as name:
snapshot = load.read_snapshot(pathlib.Path(name))
self.assertIsNone(snapshot['load1'])
self.assertIsNone(snapshot['cpu'])
self.assertTrue(snapshot['errors'])
self.assertIsNone(snapshot['psi']['cpu'])
self.assertIsNone(snapshot['cpu_max'])
if __name__ == '__main__':
unittest.main()
-176
View File
@@ -1,176 +0,0 @@
"""One-second Linux job-load evidence. Missing counters are null, never zero.
Disk await is delta(read_ms + write_ms) / delta(completed reads + writes),
per device from diskstats (the r_await/w_await weighted mean, not a sum across
stacked devices). PSI retains the kernel's avg10/60/300 and total microseconds.
cpu.max includes every visible ancestor, since a parent may impose the quota.
The sampler is diagnostic only; it has a job-sized lifetime even if stop is lost.
"""
import argparse
import datetime
import json
import os
import pathlib
import re
import select
import signal
import subprocess
import sys
import threading
import time
def read_snapshot(proc=pathlib.Path('/proc')):
errors = []
def read(path, parse):
try:
return parse(path.read_text())
except (OSError, ValueError, IndexError, StopIteration) as error:
errors.append(str(path)+': '+str(error))
return None
def pressure(text):
return {parts[0]: {k: (int(v) if k == 'total' else float(v))
for k, v in (item.split('=') for item in parts[1:])}
for parts in (line.split() for line in text.splitlines()) if parts}
def diskstats(text):
result = {}
for line in text.splitlines():
fields = line.split()
# fields after the device name: reads, merges, sectors, ms,
# writes, merges, sectors, ms (present on all supported kernels).
result[fields[2]] = [int(fields[3])+int(fields[7]), int(fields[6])+int(fields[10])]
return result
def quotas(_):
group = next(line.split('::', 1)[1] for line in (proc/'self/cgroup').read_text().splitlines()
if line.startswith('0::'))
for line in (proc/'self/mountinfo').read_text().splitlines():
fields, filesystem = line.split(' - ', 1)
if filesystem.split()[0] != 'cgroup2':
continue
# mountinfo escapes whitespace and backslash with octal codes.
unescape = lambda value: re.sub(r'\\([0-7]{3})', lambda m: chr(int(m[1], 8)), value)
fields = fields.split()
base, mount = unescape(fields[3]), pathlib.Path(unescape(fields[4]))
if base != '/' and (group == base or group.startswith(base+'/')):
relative = group[len(base):].lstrip('/')
else:
# cgroup namespace: membership is relative to its visible root.
relative = group.lstrip('/')
current = mount / relative
current.relative_to(mount)
result = {}
while True:
path = current/'cpu.max'
# The real hierarchy root need not expose cpu.max. Preserve
# readable leaf/parent quotas even if another level is absent.
result[str(path)] = read(path, str.strip)
if current == mount:
return result
current = current.parent
raise ValueError('no visible cgroup v2 mount (v1 or unavailable)')
return dict(load1=read(proc/'loadavg', lambda text: float(text.split()[0])),
cpu=read(proc/'stat', lambda text: [int(v) for v in next(
line for line in text.splitlines() if line.startswith('cpu ')).split()[1:]]),
disks=read(proc/'diskstats', diskstats),
psi={kind: read(proc/'pressure'/filename, pressure) for kind, filename in
[('cpu', 'cpu'), ('io', 'io'), ('mem', 'memory')]},
cpu_max=read(proc/'self/cgroup', quotas), errors=errors)
def interval(before, after):
cpu = dict(steal_pct=None, iowait_pct=None)
old, new = before['cpu'], after['cpu']
if old is not None and new is not None and len(old) >= 8 and len(new) >= 8:
deltas = [new[i]-old[i] for i in range(8)] # guest already included in user/nice
total = sum(deltas)
if min(deltas) >= 0 and total > 0:
cpu = dict(steal_pct=100*deltas[7]/total, iowait_pct=100*deltas[4]/total)
disks = None
if after['disks'] is not None:
disks = {}
for name, values in after['disks'].items():
previous = (before['disks'] or {}).get(name)
disks[name] = None
if previous and values[0] > previous[0] and values[1] >= previous[1]:
disks[name] = (values[1]-previous[1])/(values[0]-previous[0])
return cpu, disks
def sample(output, duration):
output.parent.mkdir(parents=True, exist_ok=True)
previous = dict(cpu=None, disks=None)
end, due = time.monotonic()+duration, time.monotonic()
stopped = threading.Event()
signal.signal(signal.SIGTERM, lambda *_: stopped.set())
with output.open('w', buffering=1) as stream:
stream.write('ts_utc\tload1\tsteal_pct\tiowait_pct\tpsi_cpu\tpsi_io\tpsi_mem\tdisk_await_ms\tcgroup_cpu_max\terrors\n')
while not stopped.is_set() and time.monotonic() < end:
timestamp = datetime.datetime.now(datetime.timezone.utc).isoformat(timespec='milliseconds')
current = read_snapshot()
cpu, disks = interval(previous, current)
fields = [timestamp, current['load1'], cpu['steal_pct'], cpu['iowait_pct'],
current['psi']['cpu'], current['psi']['io'], current['psi']['mem'],
disks, current['cpu_max'], current['errors']]
stream.write('\t'.join(json.dumps(v, separators=(',', ':')) if not isinstance(v, str) else v
for v in fields)+'\n')
previous = current
due += 1
stopped.wait(max(0, min(due, end)-time.monotonic()))
# Do not emit a burst of fictitious one-second samples after a stall.
due = max(due, time.monotonic())
def identity(pid):
# comm may contain spaces or parentheses; starttime is field 22.
return pathlib.Path(f'/proc/{pid}/stat').read_text().rsplit(')', 1)[1].split()[19]
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('action', choices=['start', 'sample', 'stop'])
parser.add_argument('output', type=pathlib.Path)
parser.add_argument('--duration', type=int, default=5400)
args = parser.parse_args()
receipt = args.output.with_suffix('.pid.json')
if args.action == 'sample':
sample(args.output, args.duration)
elif args.action == 'start':
args.output.parent.mkdir(parents=True, exist_ok=True)
with args.output.with_suffix('.sampler.log').open('w') as log:
child = subprocess.Popen([sys.executable, '-I', str(pathlib.Path(__file__).resolve()),
'sample', str(args.output), '--duration', str(args.duration)],
stdin=subprocess.DEVNULL, stdout=log, stderr=log, start_new_session=True)
receipt.write_text(json.dumps(dict(pid=child.pid, start=identity(child.pid))))
elif receipt.exists():
owner = json.loads(receipt.read_text())
handle = None
try:
# A pidfd makes the identity-check/signal pair safe even if the
# process exits and its numeric PID is recycled between the two.
handle = os.pidfd_open(owner['pid'])
if identity(owner['pid']) == owner['start']:
signal.pidfd_send_signal(handle, signal.SIGTERM)
# Flush the last row before the uploader reads the file. Never
# signal a reused PID and never wait indefinitely for evidence.
# The pidfd turns readable when the sampler exits; one still
# alive after 2 s leaves load.incomplete beside its rows.
if not select.select([handle], [], [], 2)[0]:
note = args.output.with_suffix('.incomplete')
note.write_text('the sampler did not exit within 2 s of SIGTERM; its last rows may be missing\n')
print('load evidence incomplete: '+str(note), file=sys.stderr)
except ProcessLookupError:
pass
except FileNotFoundError:
pass
finally:
if handle is not None:
os.close(handle)
if __name__ == '__main__':
main()
-59
View File
@@ -1,59 +0,0 @@
#!/usr/bin/env bash
# Tests docs-only-scope.sh against real commits, and that test.yml applies it
# only to the process suite of a pull request. Any failure exits nonzero.
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)
scope="$here/docs-only-scope.sh"
workflow="$here/../workflows/test.yml"
fail=0
check() { # name want got
if [ "$2" = "$3" ]; then echo "ok $1"; else echo "FAIL $1: want [$2], got [$3]"; fail=1; fi
}
repo=$(mktemp -d)
trap 'rm -rf "$repo"' EXIT
cd "$repo"
git init -q
git config user.email t@example.invalid
git config user.name t
git config core.autocrlf false
mkdir -p docs cmd
echo a >docs/a.md
echo r >README.md
echo g >cmd/main.go
git add -A
git commit -qm base
base=$(git rev-parse HEAD)
case_of() { # name want: commit the current tree, classify against base, reset
git add -A
git commit -qm "$1" --allow-empty
check "$1" "$2" "$(bash "$scope" "$base" HEAD)"
git reset -q --hard "$base"
}
echo b >docs/b.md; echo a2 >docs/a.md
case_of "two docs files" "docs_only 2"
echo b >docs/b.md; echo t >cmd/x_test.go
case_of "docs and a test file" "run 2 cmd/x_test.go"
case_of "no file changed" "run 0"
mkdir -p docs-old; echo x >docs-old/x.md
case_of "a docs-like prefix" "run 1 docs-old/x.md"
echo r2 >README.md
case_of "README outside docs" "run 1 README.md"
git mv docs/a.md cmd/a.md
case_of "a move out of docs" "run 2 cmd/a.md"
git rm -q docs/a.md
case_of "a docs deletion" "docs_only 1"
for i in $(seq 1 20000); do printf 'x\n' >"docs/f$i.md"; done
echo late >zz-late.go
case_of "20000 docs files and one other, listed last" "run 20001 zz-late.go"
if out=$(bash "$scope" "$base" no-such-revision 2>/dev/null); then
check "an unknown revision is an error" "nonzero exit" "exit 0: $out"
else
check "an unknown revision is an error" "nonzero exit" "nonzero exit"
fi
# test.yml: the scope step runs only for a pull request's process suite, and
# every process step it can skip names its output.
step=$(grep -n -A3 'name: Docs-only pull request' "$workflow" | grep "if:" || true)
check "scope step condition" "1" "$(printf '%s' "$step" | grep -c "matrix.suite == 'process' && github.event_name == 'pull_request'" || true)"
check "process steps gated" "5" "$(grep -c "if: matrix.suite == 'process' && steps.scope.outputs.docs_only != '1'" "$workflow" || true)"
check "no ungated process step" "0" "$(grep -c "if: matrix.suite == 'process'$" "$workflow" || true)"
exit "$fail"
-32
View File
@@ -1,32 +0,0 @@
#!/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 --name-only --no-renames -z "$1" "$2" >"$list"; then
echo "docs-only-scope: git diff $1 $2 failed" >&2
exit 2
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
-58
View File
@@ -1,58 +0,0 @@
"""Drain a Go stream even when recording/rendering fails; never judge tests."""
import json
import os
import sys
sys.stdin.reconfigure(encoding='utf-8', errors='replace')
def warn(error):
try:
print('test evidence unavailable: '+str(error), file=sys.stderr)
except OSError:
pass
archive = None
try:
archive = open(sys.argv[1], 'a', encoding='utf-8', buffering=1)
except OSError as error:
warn(error)
raw = len(sys.argv) > 2 and sys.argv[2] == '--raw'
console = True
for line in sys.stdin:
if archive is not None:
try:
archive.write(line)
except OSError as error:
warn(error)
try:
archive.close()
except OSError:
pass
archive = None
output = line
if not raw:
try:
output = json.loads(line).get('Output', '')
except (ValueError, AttributeError) as error:
# Keep and display unexpected text, but keep draining the producer.
warn(error)
if console:
try:
sys.stdout.write(output)
sys.stdout.flush()
except OSError:
console = False
# Avoid an interpreter-exit BrokenPipe flush; the stream still
# drains Go to EOF so a dead console cannot send SIGPIPE upstream.
try:
with open(os.devnull, 'w') as sink:
os.dup2(sink.fileno(), sys.stdout.fileno())
except OSError:
pass
if archive is not None:
try:
archive.close()
except OSError as error:
warn(error)
-36
View File
@@ -1,36 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)
root=$(mktemp -d)
trap 'rm -rf "$root"' EXIT
mkdir -p "$root/bin"
cat >"$root/bin/go" <<'EOF'
#!/usr/bin/env bash
printf '%s\n' "$FAKE_GO_OUTPUT"
exit "$FAKE_GO_STATUS"
EOF
chmod +x "$root/bin/go"
export PATH="$root/bin:$PATH"
cd "$root"
check() {
local name=$1 status=$2 output=$3 want=$4 message=$5 actual=0
FAKE_GO_STATUS="$status" FAKE_GO_OUTPUT="$output" bash "$here/known-bugs.sh" >result 2>&1 <<'LIST' || actual=$?
#1 ./fixture TestKnown
LIST
if [ "$actual" != "$want" ] || ! grep -q "$message" result; then
echo "FAIL: $name (exit $actual, expected $want)"; cat result; exit 1
fi
if [ "$message" != 'now PASSES' ] && grep -q 'now PASSES' result; then
echo "FAIL: $name falsely called fixed"; cat result; exit 1
fi
}
check failure 1 '--- FAIL: TestKnown (0.00s)' 0 'still fails'
check pass 0 '--- PASS: TestKnown (0.00s)' 1 'now PASSES'
check missing 0 'ok fixture [no tests to run]' 1 'did not run'
check skipped 0 '--- SKIP: TestKnown (0.00s)' 1 'did not run'
check build 1 'FAIL fixture [build failed]' 1 'failed to build'
check other 1 '--- FAIL: TestKnownOther (0.00s)' 1 'did not run'
check subtest 1 ' --- FAIL: TestKnown/child (0.00s)' 1 'did not run'
check interrupted 1 '=== RUN TestKnown' 1 'did not run'
check inconsistent 0 '--- FAIL: TestKnown (0.00s)' 1 'did not run'
echo 'known-bugs: exact failure, pass, missing, skip, build, other test and interruption controls PASS'
-22
View File
@@ -1,22 +0,0 @@
#!/usr/bin/env bash
# Read "issue package test" rows. Only an observed failure of that exact test
# proves the reproduction still runs; a missing/skipped test is not a fix.
set -uo pipefail
ok=1
while read -r issue pkg test; do
[ -n "$issue" ] || continue
out="out-${test}.txt"
status=0
go test -v -count=1 -run "^${test}\$" "$pkg" >"$out" 2>&1 || status=$?
if [ "$status" -ne 0 ] && grep -q "^--- FAIL: ${test} (" "$out"; then
echo "${test} (${issue}) still fails, as expected"
elif [ "$status" = 0 ] && grep -q "^--- PASS: ${test} (" "$out"; then
echo "::error::${test} (${pkg}) now PASSES: ${issue} looks fixed, remove its skip"
ok=0
else
echo "::error::${test} (${pkg}) did not run to a verdict or failed to build (exit ${status}):"
tail -20 "$out"
ok=0
fi
done
[ "$ok" = 1 ]
-73
View File
@@ -1,73 +0,0 @@
#!/usr/bin/env bash
# Controls for lab-tag-check.sh and scripts/refuse-lab-binary.sh. Each case
# builds a small git repository from the real image recipes and publish
# workflow with one contamination, and expects a refusal; the unchanged copy
# passes. The refusal script is driven with stand-in binaries. Exit 0 when
# every control holds.
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)
src=$(cd "$here/../.." && pwd)
check="$here/lab-tag-check.sh"
refuse="$src/scripts/refuse-lab-binary.sh"
t=$(mktemp -d); trap 'rm -rf -- "${t:?}"' EXIT
tag=swblock_lab_bigvol
sw=deploy/k8s/g15b/Dockerfile.sw-block
csi=deploy/k8s/g15b/Dockerfile.blockcsi
pub=.github/workflows/publish-alpha-images.yml
n=0
gadd() { git -C "$r" -c core.autocrlf=false -c core.safecrlf=false add -A; }
repo() { # the real recipes and publish workflow, plus one allowed file, in $t/r<n>
n=$((n+1)); r="$t/r$n"
mkdir -p "$r/deploy/k8s/g15b" "$r/.github/workflows" "$r/core/geometry" "$r/core/x"
tr -d '\r' < "$src/$sw" > "$r/$sw"
tr -d '\r' < "$src/$csi" > "$r/$csi"
tr -d '\r' < "$src/$pub" > "$r/$pub"
printf '//go:build %s\npackage geometry\n' "$tag" > "$r/core/geometry/volume_size_lab.go"
printf 'package x\n' > "$r/core/x/x.go"
git -C "$r" init -q && gadd
}
edit() { # edit FILE SED: change one file of the current repository
sed -i "$2" "$r/$1" && gadd
}
expect() { # expect pass|fail name
local want=$1 name=$2 rc=0
bash "$check" "$r" >/dev/null 2>&1 || rc=$?
if [ "$want" = pass ] && [ $rc -ne 0 ]; then echo "FAIL: $name: refused"; bash "$check" "$r" || true; exit 1; fi
if [ "$want" = fail ] && [ $rc -eq 0 ]; then echo "FAIL: $name: passed"; exit 1; fi
}
repo; expect pass "the real recipes, unchanged"
repo; printf '// %s\npackage x\n' "$tag" > "$r/core/x/x.go"; gadd; expect fail "the tag outside the allowlist"
repo; printf '// swblock_v11_format
package x
' > "$r/core/x/x.go"; gadd; expect fail "the format tag outside the allowlist"
repo; edit "$sw" "s#go build -o /out/blockvolume#go build -tags swblock_v11_format -o /out/blockvolume#"; expect fail "the format tag in a real recipe's build"
repo; edit "$sw" "s#go build -o /out/blockvolume#go build -tags $tag -o /out/blockvolume#"; expect fail "the tag in a real recipe's build"
repo; edit "$sw" '/^RUN bash scripts\/refuse-lab-binary.sh/d'; expect fail "the real recipe's RUN guard deleted, its comment kept"
repo; edit "$csi" '/^RUN bash scripts\/refuse-lab-binary.sh/d'; expect fail "the CSI recipe's RUN guard deleted, its comment kept"
repo; edit "$sw" 's#^RUN bash scripts/refuse-lab-binary.sh#\# RUN bash scripts/refuse-lab-binary.sh#'; expect fail "the RUN guard commented out"
repo; edit "$sw" 's#^\(RUN bash scripts/refuse-lab-binary.sh.*\) /out/sw-block#\1#'; expect fail "a built binary left out of the refusal"
repo; edit "$sw" 's#/out/blockvolume ./cmd/blockvolume#/out/blockvolume ./cmd/blockvolume \&\& \\n CGO_ENABLED=0 go build -o /out/extra ./cmd/extra#'; expect fail "a new binary built and not refused"
repo; guard=$(grep '^RUN bash scripts/refuse-lab-binary.sh' "$r/$sw"); edit "$sw" '/^RUN bash scripts\/refuse-lab-binary.sh/d'; sed -i "s#^RUN CGO_ENABLED=0 go build#$guard\nRUN CGO_ENABLED=0 go build#" "$r/$sw"; gadd; expect fail "the refusal before the build"
repo; printf ' - run: go build ./...\n' >> "$r/$pub"; gadd; expect fail "a go build in the publish workflow"
repo; edit "$pub" "s#file: $csi#file: Dockerfile.root#"; printf 'RUN go build -o /out/b ./cmd/b\n' > "$r/Dockerfile.root"; gadd; expect fail "publishing from a Dockerfile outside deploy/"
repo; rm -f "$r/$pub"; gadd; expect fail "no readable publish workflow"
repo; ln -s missing-target "$r/deploy/k8s/g15b/Dockerfile.dangling" 2>/dev/null || true
if [ -L "$r/deploy/k8s/g15b/Dockerfile.dangling" ]; then gadd; expect fail "an image Dockerfile that cannot be read"; else echo "note: no symlinks here; the unreadable-recipe control runs on Linux"; fi
r="$t/missing"; expect fail "a missing repository"
r="$t/notgit"; mkdir -p "$r"; expect fail "a directory the scan cannot read as a repository"
b="$t/bin"; mkdir -p "$b"
printf '#!/bin/sh\necho "b revision=1 modified=false"\n' > "$b/release"
printf '#!/bin/sh\necho "b revision=1 modified=false LAB BUILD(%s)"\n' "$tag" > "$b/lab"
printf '#!/bin/sh
echo "b revision=1 modified=false LAB BUILD(swblock_v11_format)"
' > "$b/draft"
printf '#!/bin/sh\nexit 3\n' > "$b/broken"
printf '#!/bin/sh\nexit 0\n' > "$b/silent"
chmod +x "$b"/*
bash "$refuse" "$b/release" >/dev/null || { echo "FAIL: refuse-lab-binary refused a release binary"; exit 1; }
for x in lab draft broken silent; do
if bash "$refuse" "$b/release" "$b/$x" >/dev/null 2>&1; then echo "FAIL: refuse-lab-binary passed a $x binary"; exit 1; fi
done
if bash "$refuse" >/dev/null 2>&1; then echo "FAIL: refuse-lab-binary passed with no binary"; exit 1; fi
echo "lab-tag-check controls: OK ($n repositories, 5 binaries)"
-90
View File
@@ -1,90 +0,0 @@
#!/usr/bin/env bash
# The lab-only build tags must never reach an image or a release build:
# swblock_lab_bigvol lifts the 256 GiB create cap and the local headroom
# refusal for scale rehearsals; swblock_v11_format turns on the draft v1.1
# store format. Two checks, both failing closed:
# 1. Allowlist: only the files below may name either tag (git grep over the
# tracked tree; a scan that cannot run is a failure, never "clean").
# 2. Wiring: every image Dockerfile under deploy/ that runs go build also runs
# scripts/refuse-lab-binary.sh after its last go build, and the publish
# workflow builds images only from such Dockerfiles, with no go build of
# its own.
# Usage: lab-tag-check.sh [REPO_ROOT] Exit 0: clean. Exit 1: a finding or an
# unreadable input (printed).
set -euo pipefail
root=${1:-.}
tags='swblock_lab_bigvol swblock_v11_format'
allowed='.github/scripts/lab-tag-check-test.sh
.github/scripts/lab-tag-check.sh
.github/workflows/test.yml
core/host/volume/status_heap_lab.go
core/host/volume/status_heap_lab_test.go
core/host/volume/status_heap_release.go
core/host/volume/status_heap_release_test.go
core/storage/chunk_v11_format_draft.go
core/storage/chunk_v11_format_release.go
core/storage/chunk_v11_format_tag_test.go
core/frontend/durable/headroom.go
core/frontend/durable/headroom_lab_test.go
core/geometry/volume_size.go
core/geometry/volume_size_lab.go
core/geometry/volume_size_lab_test.go
core/geometry/volume_size_release.go
core/geometry/volume_size_release_test.go
docs/design/invariants.md
docs/lab-heap-profiles.md
internal/buildinfo/buildinfo.go
internal/buildinfo/v11_format_draft.go
internal/buildinfo/v11_format_release.go
scripts/refuse-lab-binary.sh'
fail() { echo "lab-tag: $*" >&2; exit 1; }
[ -d "$root" ] || fail "no repository at $root"
for tag in $tags; do
set +e
hits=$(git -C "$root" grep -l -- "$tag")
rc=$?
set -e
case $rc in
0) ;;
1) hits="" ;;
*) fail "git grep failed (rc=$rc): the scan did not run" ;;
esac
bad=""
while IFS= read -r f; do
[ -n "$f" ] || continue
printf '%s\n' "$allowed" | grep -qxF -- "$f" || bad="$bad $f"
done <<< "$hits"
[ -z "$bad" ] || fail "$tag named outside the allowlist:$bad"
done
# read FILE: its whole content, once; a read that fails is a failure, never
# "no match".
read_file() { local c; c=$(cat -- "$root/$1") || fail "cannot read $1"; printf '%s\n' "$c"; }
dockerfiles=$(cd "$root" && find deploy \( -type f -o -type l \) -name 'Dockerfile*' | sort) || fail "cannot list deploy/"
[ -n "$dockerfiles" ] || fail "no image Dockerfile under deploy/"
for d in $dockerfiles; do
body=$(read_file "$d") || exit 1
# The binaries it builds (go build ... -o /out/NAME), and the line of its
# last build. A recipe that builds nothing needs no refusal.
built=$(printf '%s\n' "$body" | grep -oE 'go build[^&\]*-o /out/[A-Za-z0-9_.-]+' | grep -oE '/out/[A-Za-z0-9_.-]+$' | sort -u) || true
[ -n "$built" ] || continue
last=$(printf '%s\n' "$body" | grep -nE 'go build' | tail -1 | cut -d: -f1)
# The refusal must be an executed RUN line (not a comment) after the last
# build, naming every binary the recipe builds.
refuse=$(printf '%s\n' "$body" | grep -nE '^RUN bash scripts/refuse-lab-binary\.sh( |$)' | tail -1) || fail "$d builds ${built//$'\n'/ } without a RUN of scripts/refuse-lab-binary.sh"
at=${refuse%%:*}
[ "$at" -gt "$last" ] || fail "$d runs the refusal before its last build"
for b in $built; do
case " ${refuse#*:} " in *" $b "*) ;; *) fail "$d does not refuse $b, which it builds" ;; esac
done
done
pub=.github/workflows/publish-alpha-images.yml
pubbody=$(read_file "$pub") || exit 1
case "$pubbody" in *"go build"*) fail "the publish workflow runs its own go build" ;; esac
files=$(printf '%s\n' "$pubbody" | grep -E '^[[:space:]]*file:' | sed -E 's/^[[:space:]]*file:[[:space:]]*//') || fail "the publish workflow names no Dockerfile"
for f in $files; do
printf '%s\n' "$dockerfiles" | grep -qxF -- "$f" || fail "the publish workflow builds from $f, not an image Dockerfile under deploy/"
fbody=$(read_file "$f") || exit 1
printf '%s\n' "$fbody" | grep -qE '^RUN bash scripts/refuse-lab-binary\.sh ' || fail "the publish workflow builds from $f, which does not run the refusal"
done
echo "lab-tag: clean"
-120
View File
@@ -1,120 +0,0 @@
"""Check that every code and test anchor of the invariants ledger exists at a git ref.
usage: python -I ledger_check.py <repo-dir> <git-ref> [<ledger path in repo>]
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))
files = set(git(repo, "ls-tree", "-r", "--name-only", ref).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, "--", "*.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()
-142
View File
@@ -1,142 +0,0 @@
#!/usr/bin/env python3
import importlib.util
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
SCRIPT = Path(__file__).with_name("model-trace-check.py")
spec = importlib.util.spec_from_file_location("model_trace", SCRIPT)
checker = importlib.util.module_from_spec(spec)
spec.loader.exec_module(checker)
class ModelTraceTests(unittest.TestCase):
mapping = {"core/a.go": {"EngineAdapter.Begin", "EngineAdapter.NoOpCut"}, "core/b.go": {"MoveAdmission.Revoke"}}
def test_each_mapped_file_needs_its_own_citation(self):
problems = checker.check("EngineAdapter.Begin", ["core/a.go", "core/b.go"], self.mapping)
self.assertEqual(len(problems), 1)
self.assertIn("core/b.go", problems[0])
self.assertEqual(checker.check("EngineAdapter.Begin; MoveAdmission.Revoke", list(self.mapping), self.mapping), [])
def test_mapped_file_refuses_free_text_wrong_actions_and_lookalikes(self):
for model in ("exhausted", "EngineAdapter.Unknown", "Other.Begin", "EngineAdapter.BeginExtra",
"docs/EngineAdapter.Begin", "example: EngineAdapter.Begin", "NONE: no state changes",
"NONE (pure function of Other)", "NONE (pure function of EngineAdapter) extra"):
with self.subTest(model=model):
self.assertEqual(len(checker.check(model, ["core/a.go"], self.mapping)), 1)
def test_pure_function_exception_is_module_specific(self):
self.assertEqual(checker.check("NONE (pure function of EngineAdapter)", ["core/a.go"], self.mapping), [])
self.assertEqual(len(checker.check("NONE (pure function of EngineAdapter)", ["core/b.go"], self.mapping)), 1)
def test_unmapped_files_keep_existing_policy(self):
self.assertEqual(checker.check("existing prose", ["docs/a.md", "core/a.go.bak"], self.mapping), [])
def test_line_only_rebase_keeps_committed_mapping_and_obligations(self):
with tempfile.TemporaryDirectory() as tmp:
source = Path(tmp) / "a.go"
mapping = Path(tmp) / "model-code-trace.tsv"
mapping.write_text("core/a.go\tEngineAdapter.Begin\n", encoding="utf-8")
committed = mapping.read_bytes()
for padding in ("", "// unrelated rebase\n\n\n"):
source.write_text(padding + "package a\nfunc begin() {}\n", encoding="utf-8")
actual = checker.read_mapping(mapping)
self.assertEqual(checker.check("EngineAdapter.Begin", ["core/a.go"], actual), [])
self.assertEqual(len(checker.check("Other.Begin", ["core/a.go"], actual)), 1)
self.assertEqual(mapping.read_bytes(), committed)
def test_repository_map_covers_claimed_head_create(self):
mapping = checker.read_mapping(SCRIPT.parent.parent / "model-code-trace.tsv")
paths = ["core/frontend/chunkstore/layout/create.go"]
self.assertEqual(checker.check("VolumeCreate.Claim", paths, mapping), [])
self.assertEqual(len(checker.check("VolumeCreate.Unknown", paths, mapping)), 1)
def test_repository_map_covers_the_replica_receiver(self):
mapping = checker.read_mapping(SCRIPT.parent.parent / "model-code-trace.tsv")
paths = ["core/transport/replica.go"]
self.assertEqual(checker.check("ReplicationPeer.Ship", paths, mapping), [])
self.assertEqual(len(checker.check("VolumeCreate.Claim", paths, mapping)), 1)
def test_cli_checks_nul_paths_and_model_citations(self):
with tempfile.TemporaryDirectory() as tmp:
mapping = Path(tmp) / "map.tsv"
mapping.write_text("# exact paths\ncore/a.go\tEngineAdapter.Begin\n", encoding="utf-8")
def run(model, paths):
return subprocess.run([sys.executable, str(SCRIPT), str(mapping), model],
input=paths, capture_output=True).returncode
self.assertEqual(run("EngineAdapter.Begin", b"core/a.go\0"), 0)
self.assertEqual(run("unstructured prose", b"core/a.go\0"), 1)
self.assertEqual(run("EngineAdapter.Begin", b"core/a.go"), 2)
self.assertEqual(run("EngineAdapter.Begin", b"\0"), 2)
def test_mapping_refuses_missing_empty_and_malformed_data(self):
with tempfile.TemporaryDirectory() as tmp:
mapping = Path(tmp) / "map.tsv"
with self.assertRaises(OSError):
checker.read_mapping(mapping)
for content in ("# not populated\n", "core/a.go EngineAdapter.Begin\n",
"../core/a.go\tEngineAdapter.Begin\n", "core//a.go\tEngineAdapter.Begin\n",
"core/a.go\tKernel\n", "core/a.go\tEngineAdapter.Begin extra\n"):
with self.subTest(content=content):
mapping.write_text(content, encoding="utf-8")
with self.assertRaises(ValueError):
checker.read_mapping(mapping)
def test_mapping_requires_sorted_unique_rows_after_resolution(self):
with tempfile.TemporaryDirectory() as tmp:
mapping = Path(tmp) / "map.tsv"
a = "core/a.go\tEngineAdapter.Begin\n"
b = "core/b.go\tMoveAdmission.Revoke\n"
for content in (b + a, a + a):
with self.subTest(content=content):
mapping.write_text(content, encoding="utf-8")
with self.assertRaisesRegex(ValueError, "sorted and unique"):
checker.read_mapping(mapping)
mapping.write_text(a + b, encoding="utf-8")
self.assertEqual(set(checker.read_mapping(mapping)), {"core/a.go", "core/b.go"})
def test_model_trace_deletion_and_adjacent_addition_require_resolution(self):
attributes = (SCRIPT.parent.parent.parent / ".gitattributes").read_text(encoding="utf-8")
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
def git(*args, check=True):
return subprocess.run(["git", *args], cwd=root, capture_output=True,
check=check, text=True, timeout=15)
git("init", "-b", "base")
git("config", "user.name", "Example")
git("config", "user.email", "example@example.invalid")
git("config", "commit.gpgsign", "false")
(root / ".gitattributes").write_text(attributes, encoding="utf-8")
mapping = root / ".github" / "model-code-trace.tsv"
mapping.parent.mkdir()
a = "core/a.go\tEngineAdapter.Begin\n"
removed = "core/b.go\tMoveAdmission.Revoke\n"
added = "core/b.go\tVolumeCreate.Claim\n"
c = "core/c.go\tVolumeCreate.Claim\n"
mapping.write_text(a + removed + c, encoding="utf-8")
git("add", ".")
git("commit", "-m", "base")
git("switch", "-c", "remove")
mapping.write_text(a + c, encoding="utf-8")
git("commit", "-am", "remove obsolete binding")
git("switch", "-c", "add", "base")
mapping.write_text(a + removed + added + c, encoding="utf-8")
git("commit", "-am", "add adjacent binding")
git("switch", "remove")
merged = git("merge", "--no-edit", "add", check=False)
self.assertEqual(merged.returncode, 1, merged.stdout + merged.stderr)
self.assertIn("<<<<<<<", mapping.read_text(encoding="utf-8"))
# Resolve deliberately: keep the new binding, preserve the deletion.
mapping.write_text(a + added + c, encoding="utf-8")
self.assertNotIn(removed, mapping.read_text(encoding="utf-8"))
self.assertEqual(checker.read_mapping(mapping)["core/b.go"], {"VolumeCreate.Claim"})
attr = subprocess.run(["git", "check-attr", "merge", "--", ".github/model-code-trace.tsv"],
cwd=SCRIPT.parent.parent.parent, capture_output=True, check=True, text=True, timeout=15)
self.assertEqual(attr.stdout.strip(), ".github/model-code-trace.tsv: merge: unspecified")
if __name__ == "__main__":
unittest.main()
-76
View File
@@ -1,76 +0,0 @@
#!/usr/bin/env python3
"""Check Model citations against a base-owned, exact-path TSV mapping."""
import re
import sys
from pathlib import Path, PurePosixPath
IDENT = r"[A-Za-z_][A-Za-z0-9_]*"
ACTION = re.compile(rf"{IDENT}\.{IDENT}")
PURE = re.compile(rf"NONE \(pure function of ({IDENT})\)")
def read_mapping(path):
mapping = {}
previous = None
for number, line in enumerate(Path(path).read_text(encoding="utf-8").splitlines(), 1):
if not line.strip() or line.startswith("#"):
continue
columns = line.split("\t")
if len(columns) != 2:
raise ValueError(f"mapping line {number}: expected PATH<TAB>Module.Action")
file, action = columns
parts = PurePosixPath(file).parts
if (not file or file.startswith("/") or "\\" in file or ":" in file
or any(part in (".", "..") for part in file.split("/"))
or str(PurePosixPath(file)) != file or not parts):
raise ValueError(f"mapping line {number}: expected a repository-relative exact path")
if not ACTION.fullmatch(action):
raise ValueError(f"mapping line {number}: invalid Module.Action")
if previous is not None and line <= previous:
raise ValueError(f"mapping line {number}: rows must be sorted and unique; sort and deduplicate the union")
previous = line
mapping.setdefault(file, set()).add(action)
if not mapping:
raise ValueError("model mapping is empty; populate it before enabling this gate")
return mapping
def check(model, paths, mapping):
# A list permits one citation for each mapped file in a multi-module PR.
# Full matches prevent prose, quoted examples, or a prefixed NONE excuse
# from accidentally satisfying a mapped-file obligation.
citations = {part.strip() for part in model.split(";")}
actions = {part for part in citations if ACTION.fullmatch(part)}
pure = {match.group(1) for part in citations if (match := PURE.fullmatch(part))}
problems = []
for file in sorted(set(paths)):
expected = mapping.get(file)
if expected and not (actions & expected or any(a.split(".")[0] in pure for a in expected)):
names = "; ".join(sorted(expected))
problems.append(f"{file}: Model must cite {names} or NONE (pure function of its module)")
return problems
def main():
if len(sys.argv) != 3:
print("usage: model-trace-check.py MAPPING MODEL < nul-separated-paths", file=sys.stderr)
return 2
try:
mapping = read_mapping(sys.argv[1])
raw = sys.stdin.buffer.read()
if raw and not raw.endswith(b"\0"):
raise ValueError("unterminated changed path")
paths = [p.decode("utf-8") for p in raw.split(b"\0")[:-1]]
if any(not p for p in paths):
raise ValueError("empty changed path")
problems = check(sys.argv[2], paths, mapping)
except (OSError, UnicodeError, ValueError) as error:
print(f"spec-trace: {error}", file=sys.stderr)
return 2
for problem in problems:
print(f"spec-trace: {problem}")
return int(bool(problems))
if __name__ == "__main__":
sys.exit(main())
@@ -1,10 +0,0 @@
#!/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}
exec git diff -z --name-status --no-renames "$base...$head"
@@ -1,197 +0,0 @@
#!/usr/bin/env bash
# Self-test of the post-merge-review check: the matcher against the checked-in
# allow list, the real Git diff it consumes, and the workflow's triggers.
set -euo pipefail
shopt -s inherit_errexit
here=$(cd "$(dirname "$0")" && pwd)
check=$here/post-merge-review-check.sh
changed=$here/post-merge-review-changed.sh
allow=$here/../post-merge-review-allow.txt
workflow=$here/../workflows/post-merge-review.yml
fail=0
expect_changes() { # expect_changes WANT_EXIT NAME [STATUS PATH]...
local want=$1 name=$2
shift 2
local got=0
if (($#)); then printf '%s\0' "$@"; fi | bash "$check" "$allow" >/dev/null || got=$?
if [[ $got != "$want" ]]; then
echo "FAIL $name: exit $got, want $want"
fail=1
fi
}
expect() { # expect WANT_EXIT NAME PATH... : each path modified
local want=$1 name=$2 p
shift 2
local args=()
for p in "$@"; do args+=(M "$p"); done
expect_changes "$want" "$name" ${args[@]+"${args[@]}"}
}
# Allowed.
expect 0 "docs" docs/README.md README.md cmd/sw-block/NOTES.md
expect 0 "testops docs" internal/testops/registry-overview.md
expect 0 "test outside denied dirs" core/ops/cleanup_projection_test.go cmd/blockmaster/topology_test.go
expect 0 "named status files" core/host/master/observation_service.go core/host/volume/memory_status.go
expect 0 "release is not lease" cmd/sw-block/release_test.go
expect 0 "names with a space, tab or newline" "docs/a b.md" $'docs/a\tb.md' $'docs/a\nb.md'
expect 0 "no paths"
expect_changes 0 "test added" A cmd/foo/new_test.go
expect_changes 0 "doc deleted" D docs/old.md
# Denied by default: not on the allow list.
expect 1 "new file anywhere" core/newpkg/decide.go
expect 1 "decision code by name" core/host/master/product_loop.go core/lifecycle/planner.go
expect 1 "go.mod" go.mod
expect 1 "go.sum" go.sum
expect 1 "status-like but not named" core/ops/operator_status_controller.go
expect 1 "status server: registers a mutating endpoint" core/host/volume/status_server.go
# Denied explicitly, even where an allow line matches.
expect 1 "storage" core/storage/walstore.go
expect 1 "unicode name in storage" $'core/storage/\xc3\xa9_test.go'
expect 1 "durable test file" core/frontend/durable/provider_chunk_detach_abort_test.go
expect 1 "doc inside a denied dir" core/storage/NOTES.md
expect 1 "authority test" core/authority/lease_stats_test.go
expect 1 "master workspace test" core/host/master/workspace_binding_review_test.go
expect 1 "volume workspace runtime" core/host/volume/workspace_runtime.go
expect 1 "volume workspace runtime test" core/host/volume/workspace_runtime_test.go
expect 1 "proto" core/rpc/proto/control.proto
expect 1 "lease test by name" cmd/foo/lease_table_test.go
expect 1 "gc test by name" cmd/sw-block/chunk_gc_test.go
expect 1 "the check itself" .github/post-merge-review-allow.txt
expect 1 "a workflow" .github/workflows/test.yml
expect 1 "PR template under .github" .github/pull_request_template.md
expect 1 "mixed: allowed plus denied" docs/README.md core/storage/walstore.go
expect 1 "mixed: allowed plus unlisted" docs/README.md go.mod
# Persisted-format, GC and delete paths stay denied, tests included.
expect 1 "lifecycle store test" core/lifecycle/store_test.go
expect 1 "journal isolation test" core/host/master/journal_isolation_test.go
expect 1 "sparrow persist test" cmd/sparrow/persist_sidecar_test.go
expect 1 "chunk volume delete test" cmd/sw-block/chunk_volume_delete_test.go
expect 1 "deletion reservations test" core/lifecycle/deletion_reservations_test.go
expect 1 "delete safety contract test" core/ops/delete_safety_contract_test.go
expect 1 "gc doc" docs/spec/cfg/RED_gc_ageonly.cfg
# The test gates: engine, CLI and gate definitions (and their tests).
expect 1 "testops engine" internal/testops/control.go
expect 1 "testops engine test" internal/testops/control_test.go
expect 1 "testops gate definition" internal/testops/registry/iscsi-p2-os-smoke.json
expect 1 "testops CLI" cmd/sw-testops/main.go
# A test may be added or modified, never deleted or replaced.
expect_changes 1 "test deleted" D cmd/foo/guard_test.go
expect_changes 1 "test type changed" T cmd/foo/guard_test.go
expect_changes 1 "test moved (delete plus add)" D cmd/foo/guard_test.go A cmd/foo/renamed_test.go
# A malformed change list or a missing or empty allow list fails closed.
malformed() { # malformed NAME PRINTF-FORMAT
local got=0
printf "$2" | bash "$check" "$allow" >/dev/null 2>&1 || got=$?
[[ $got == 2 ]] || { echo "FAIL malformed list, $1: exit $got, want 2"; fail=1; }
}
malformed "status without a path" 'M\0'
malformed "bare unterminated status" 'M'
malformed "trailing partial status after a valid pair" 'M\0docs/x.md\0D'
malformed "unterminated path" 'M\0docs/x.md'
malformed "unknown status" 'BOGUS\0docs/x.md\0'
malformed "rename status (renames are off)" 'R100\0docs/x.md\0'
malformed "empty status" '\0docs/x.md\0'
malformed "empty path" 'M\0\0'
empty=$(mktemp)
for bad in "$empty" "/nonexistent/post-merge-review-allow.txt"; do
got=0
printf 'M\0docs/README.md\0' | bash "$check" "$bad" >/dev/null 2>&1 || got=$?
[[ $got == 2 ]] || { echo "FAIL allow list $bad: exit $got, want 2"; fail=1; }
done
rm -f "$empty"
# A list whose last line has no newline keeps that line (here a denial).
unterminated=$(mktemp)
printf '*_test.go\n!core/workspace/*' >"$unterminated"
got=0
printf 'M\0core/workspace/orch_test.go\0' | bash "$check" "$unterminated" >/dev/null 2>&1 || got=$?
[[ $got == 1 ]] || { echo "FAIL allow list with an unterminated last line: exit $got, want 1"; fail=1; }
got=0
printf 'M\0cmd/foo/a_test.go\0' | bash "$check" "$unterminated" >/dev/null 2>&1 || got=$?
[[ $got == 0 ]] || { echo "FAIL allow list with an unterminated last line, allowed path: exit $got, want 0"; fail=1; }
rm -f "$unterminated"
# Real Git: names that git quotes in its default output, a rename out of a
# denied directory, a retarget onto a base that differs, and test deletes.
repo=$(mktemp -d)
trap 'rm -rf "$repo" "${changes:-}"' EXIT
g() { git -C "$repo" -c user.name=t -c user.email=t@t -c core.quotePath=true -c core.protectNTFS=false "$@"; }
blob=
commit() { # commit PARENT PATH... : PARENT's tree plus PATHs (-PATH removes)
local parent=$1
shift
g read-tree "$parent"
local p
for p in "$@"; do
if [[ $p == -* ]]; then
g update-index --force-remove -- "${p#-}"
else
g update-index --add --cacheinfo "100644,$blob,$p"
fi
done
g commit-tree "$(g write-tree)" -p "$parent" -m c
}
changes=$(mktemp)
expect_diff() { # expect_diff WANT_EXIT NAME BASE HEAD
local got=0
if ! (cd "$repo" && bash "$changed" "$3" "$4") >"$changes"; then
echo "FAIL $2: listing the changes failed"
fail=1
return
fi
bash "$check" "$allow" <"$changes" >/dev/null || got=$?
if [[ $got != "$1" ]]; then
echo "FAIL $2: exit $got, want $1"
fail=1
fi
}
g init -q
blob=$(printf x | g hash-object -w --stdin)
g read-tree --empty
root=$(g commit-tree "$(g write-tree)" -m root)
main=$(commit "$root" core/storage/old.go docs/x.md cmd/foo/guard_test.go)
unicode=$(commit "$main" $'core/storage/\xc3\xa9_test.go')
oddnames=$(commit "$main" $'docs/tab\there.md' $'docs/new\nline.md' $'docs/\xc3\xa9.md')
moved=$(commit "$main" -core/storage/old.go docs/moved.md)
parent=$(commit "$main" core/storage/parent.go)
stacked=$(commit "$parent" docs/child.md)
later=$(commit "$main" core/storage/later.go)
testadd=$(commit "$main" cmd/foo/extra_test.go)
testdel=$(commit "$main" -cmd/foo/guard_test.go)
testmove=$(commit "$main" -cmd/foo/guard_test.go cmd/foo/renamed_test.go)
n=$( (cd "$repo" && bash "$changed" "$main" "$oddnames") | tr -cd '\000' | wc -c | tr -d ' ')
[[ $n == 6 ]] || { echo "FAIL fixture: $n NULs for 3 odd names, want 6"; fail=1; }
if ! (cd "$repo" && git diff --name-only "$main...$unicode") | grep -q '^"'; then
echo "FAIL fixture: expected git to quote the unicode name in its default output"
fail=1
fi
expect_diff 1 "git: unicode test file in storage" "$main" "$unicode"
expect_diff 0 "git: tab, newline and unicode names in docs" "$main" "$oddnames"
expect_diff 1 "git: moved out of storage into docs" "$main" "$moved"
expect_diff 0 "git: stacked PR against its parent" "$parent" "$stacked"
expect_diff 1 "git: the same PR retargeted to main" "$main" "$stacked"
expect_diff 0 "git: the base moved on with denied changes; the PR did not" "$later" "$oddnames"
expect_diff 0 "git: a test added" "$main" "$testadd"
expect_diff 1 "git: a test deleted" "$main" "$testdel"
expect_diff 1 "git: a test moved" "$main" "$testmove"
if (cd "$repo" && bash "$changed" 0000000000000000000000000000000000000001 "$main") >/dev/null 2>&1; then
echo "FAIL git: listing against an unknown base succeeded"
fail=1
fi
# The workflow reruns on every change that can change the verdict, including
# a retarget (edited).
types=$(sed -n 's/^ *types: *\[\(.*\)\].*/\1/p' "$workflow" | tr -d ' ')
for want in opened synchronize reopened labeled unlabeled edited; do
[[ ",$types," == *",$want,"* ]] || { echo "FAIL workflow does not run on $want"; fail=1; }
done
if ((fail)); then exit 1; fi
echo "post-merge-review check: self-test ok"
@@ -1,77 +0,0 @@
#!/usr/bin/env bash
# Usage: post-merge-review-check.sh ALLOW_FILE < changes
#
# changes are NUL-separated STATUS, PATH pairs (post-merge-review-changed.sh).
# A path passes only if it matches an allow pattern and no "!" pattern, and
# a test file may be added or modified but not deleted (a move deletes its
# old name). Prints every change that does not pass and exits 1 if there is
# one; exits 0 if all pass, 2 on a usage error, a malformed change or a
# missing or empty allow list.
set -euo pipefail
allow_file=${1:?usage: post-merge-review-check.sh ALLOW_FILE < changes}
if [[ ! -f $allow_file ]]; then
echo "post-merge-review: allow list $allow_file missing" >&2
exit 2
fi
allow=()
deny=()
# A last line without a newline is read too: dropping it could drop a "!".
while IFS= read -r line || [[ -n $line ]]; do
line=${line%%#*}
line=${line%"${line##*[![:space:]]}"}
line=${line#"${line%%[![:space:]]*}"}
[[ -n $line ]] || continue
if [[ $line == '!'* ]]; then
deny+=("${line#!}")
else
allow+=("$line")
fi
done <"$allow_file"
if ((${#allow[@]} == 0)); then
echo "post-merge-review: empty allow list $allow_file" >&2
exit 2
fi
denied=0
checked=0
malformed() {
echo "post-merge-review: malformed change list: $1" >&2
exit 2
}
while :; do
# Every field ends in NUL: a field cut off at the end is malformed, not
# skipped, and only the statuses git diff --no-renames writes are known.
if ! IFS= read -r -d '' status; then
[[ -z $status ]] || malformed "unterminated status ${status@Q}"
break
fi
[[ $status == [ADMT] ]] || malformed "unknown status ${status@Q}"
IFS= read -r -d '' path || malformed "status $status without a terminated path"
[[ -n $path ]] || malformed "status $status with an empty path"
checked=$((checked + 1))
why="not on the allow list"
for p in "${allow[@]}"; do
# Unquoted on the right: a glob, where * also matches /.
if [[ $path == $p ]]; then
why=""
break
fi
done
for p in ${deny[@]+"${deny[@]}"}; do
if [[ $path == $p ]]; then
why="matches !$p"
break
fi
done
# A labelled PR may not delete a test (or turn it into something else).
if [[ -z $why && $path == *_test.go && $status != [AM] ]]; then
why="test file status $status: only adding or modifying a test is allowed"
fi
if [[ -n $why ]]; then
printf 'DENY %s %q (%s)\n' "$status" "$path" "$why"
denied=1
fi
done
echo "post-merge-review: $checked changed path(s) checked against ${#allow[@]} allow and ${#deny[@]} deny pattern(s)"
exit "$denied"
-58
View File
@@ -1,58 +0,0 @@
"""Trusted-base gate contracts and a PR that replaces its own checkers."""
from pathlib import Path
import os, shutil, subprocess, tempfile, unittest
ROOT = Path(__file__).resolve().parents[2]
class BaseGateTests(unittest.TestCase):
def test_readonly_events_and_separate_base_checkout(self):
for filename in ('spec-trace.yml', 'post-merge-review.yml'):
with self.subTest(workflow=filename):
text=(ROOT/'.github/workflows'/filename).read_text()
self.assertIn(' pull_request:',text)
self.assertNotIn('pull_request_target:',text)
self.assertIn(' contents: read',text)
self.assertNotIn('secrets.',text)
self.assertIn(' runs-on: ubuntu-latest',text)
self.assertIn('ref: ${{ github.event.pull_request.base.sha }}',text)
self.assertIn('path: trusted-base',text)
self.assertIn('working-directory: trusted-base',text)
self.assertIn('persist-credentials: false',text)
self.assertNotIn('ref: ${{ github.event.pull_request.head.sha }}',text)
self.assertNotIn('ref: ${{ github.sha }}',text)
text=(ROOT/'.github/workflows/spec-trace.yml').read_text()
self.assertIn('go-version-file: trusted-base/go.mod',text)
def test_pr_cannot_replace_base_validators_or_allowlist(self):
with tempfile.TemporaryDirectory() as tmp:
root=Path(tmp); source=root/'source'; source.mkdir()
scripts=source/'.github/scripts'; scripts.mkdir(parents=True)
names=('spec-trace-check.sh','post-merge-review-check.sh','post-merge-review-changed.sh')
for name in names: shutil.copyfile(ROOT/'.github/scripts'/name,scripts/name)
allow=source/'.github/post-merge-review-allow.txt'; allow.write_text('docs/**\n')
def git(*args,cwd=source):
return subprocess.check_output(['git',*args],cwd=cwd,stderr=subprocess.PIPE,timeout=15)
git('init','-b','main'); git('config','user.name','Example'); git('config','user.email','example@example.invalid'); git('config','commit.gpgsign','false')
git('add','.'); git('commit','-m','base')
base=git('rev-parse','HEAD').decode().strip()
(source/'docs').mkdir(); (source/'docs/example.md').write_text('Documentation')
git('add','.'); git('commit','-m','documentation')
good=git('rev-parse','HEAD').decode().strip()
for name in ('spec-trace-check.sh','post-merge-review-check.sh'):
(scripts/name).write_text('#!/bin/sh\ntouch ../pr-code-ran\nexit 0\n')
allow.write_text('*\n')
git('add','.'); git('commit','-m','replace validators')
bad=git('rev-parse','HEAD').decode().strip()
checkout=root/'trusted-base'; git('clone','--quiet',str(source),str(checkout)); git('checkout','--detach',base,cwd=checkout)
self.assertEqual(git('rev-parse','HEAD',cwd=checkout).decode().strip(),base)
body=checkout/'body.txt'
valid='Feature: documentation\nMachine/INV: DOCS\nModel: NONE (documentation fixture only)\nRed-first: fixture validation\n'
for head,description,success in ((good,valid,True),(bad,'missing trace',False)):
body.write_text(description)
changes=git('diff','-z','--name-status','--no-renames',base+'...'+head,cwd=checkout)
for command in (['spec-trace-check.sh',str(body)],['post-merge-review-check.sh','.github/post-merge-review-allow.txt']):
result=subprocess.run(['bash','.github/scripts/'+command[0],*command[1:]],cwd=checkout,input=changes,capture_output=True,timeout=15)
self.assertEqual(result.returncode==0,success,result.stdout.decode()+result.stderr.decode())
self.assertFalse((root/'pr-code-ran').exists())
if __name__=='__main__': unittest.main()
-96
View File
@@ -1,96 +0,0 @@
#!/usr/bin/env bash
# Self-test of public-text-check.sh in a throwaway repository.
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)
t=$(mktemp -d); trap 'rm -rf "$t"' EXIT
cd "$t"; git init -q .; git config user.email t@example.invalid; git config user.name t
echo base > a.txt; git add a.txt; git commit -q -m "base"
mb=$(git rev-parse HEAD)
: > title; : > body
run() { bash "$here/public-text-check.sh" "$@" >out 2>&1; }
expect() { # expect RC NAME
local want=$1 name=$2 rc=0
shift 2
run "$@" || rc=$?
[ "$rc" = "$want" ] || { echo "public-text-check-test: $name: exit $rc, want $want"; cat out; exit 1; }
}
echo "plain line" >> a.txt; git commit -q -am "add a plain line"
expect 0 "clean change" "$mb" HEAD title body
# Synthetic equivalents exercise private-path and run-metadata signatures.
for leaked in \
'Parsing file /home/example/run-1/Example.tla' \
'Synthetic model run with 1 worker on 2 cores with 123MB heap [pid: 12345]' \
'[pid: 12345]' \
'pid=12345' \
'2 cores with 123MB heap'; do
echo "$leaked" >> a.txt; git commit -q -am "model output"
expect 1 "raw run metadata in added text" "$mb" HEAD title body
git reset -q --hard HEAD~1
done
echo '/home/example/run-1' > body
expect 1 "home path in description" "$mb" HEAD title body; : > body
echo 'docs/spec/example/recorded-example/RESULT.txt' > body
expect 1 "artifact reference in description" "$mb" HEAD title body; : > body
echo '[pid: 12345]' > title
expect 1 "run metadata in title" "$mb" HEAD title body; : > title
for artifact in docs/spec/example/recorded-example/RESULT.txt docs/spec/recorded-example.txt; do
mkdir -p "$(dirname "$artifact")"; echo 'all checks passed' > "$artifact"
git add "$artifact"; git commit -q -m "add model artifact"
expect 1 "artifact path even with clean contents" "$mb" HEAD title body
artifact_base=$(git rev-parse HEAD)
git rm -q "$artifact"; git commit -q -m "remove model artifact"
expect 0 "artifact removal is allowed" "$artifact_base" HEAD title body
git reset -q --hard HEAD~2
done
echo 'Model workers execute in parallel; heap limits and PID namespaces are documented.' > body
expect 0 "ordinary explanatory prose" "$mb" HEAD title body; : > body
seat="clau""de06"; path="V:/sha""re/x"; nas="share/rd""ma/y"
echo "// asked by $seat" >> a.txt; git commit -q -am "comment"
expect 1 "seat name in an added line" "$mb" HEAD title body
grep -q "a.txt:3" out || { echo "public-text-check-test: hit does not name file and line"; cat out; exit 1; }
git reset -q --hard HEAD~1
echo "ok" >> a.txt; git commit -q -am "review by $seat"
expect 1 "seat name in a commit subject" "$mb" HEAD title body
git reset -q --hard HEAD~1
echo "see $path" > title; expect 1 "share path in the title" "$mb" HEAD title body; : > title
echo "results under $nas" > body; expect 1 "share path in the description" "$mb" HEAD title body; : > body
echo "an old line with $seat" >> a.txt; git commit -q -am "old"; mb2=$(git rev-parse HEAD)
echo "new clean line" >> a.txt; git commit -q -am "new"
expect 0 "an existing line is not this change's" "$mb2" HEAD title body
# A file line that begins with "++ " shows in the diff as "+++ ...": an added line, not a header.
printf '%s
' "++ $seat" >> a.txt; git commit -q -am "plus line"
expect 1 "an added line that looks like a diff header" "$mb2" HEAD title body
git reset -q --hard HEAD~1
bs=$(printf '\')
printf '%s
' "${bs}${bs}nas${bs}sha""re${bs}rd""ma${bs}z" > title
expect 1 "backslash form of the share path in the title" "$mb2" HEAD title body; : > title
expect 2 "a missing title file is an error, not clean" "$mb2" HEAD no-such-title body
expect 2 "a missing description file is an error, not clean" "$mb2" HEAD title no-such-body
expect 2 "an unknown commit is an error, not clean" 0000000000000000000000000000000000000000 HEAD title body
# Only the NUL-separated artifact enumeration fails, after partial output;
# every other git call delegates to the real executable.
real_git=$(command -v git)
mkdir -p fakegit
cat > fakegit/git <<'EOF'
#!/usr/bin/env bash
if [[ $1 == diff && ${2:-} == --name-only && ${3:-} == -z ]]; then
printf 'docs/spec/clean.txt\0'
exit 7
fi
exec "$PUBLIC_TEXT_REAL_GIT" "$@"
EOF
chmod +x fakegit/git
rc=0
PUBLIC_TEXT_REAL_GIT="$real_git" PATH="$PWD/fakegit:$PATH" bash "$here/public-text-check.sh" "$mb2" HEAD title body >out 2>&1 || rc=$?
[ "$rc" = 2 ] || { echo "public-text-check-test: failed artifact enumeration: exit $rc, want 2"; cat out; exit 1; }
if grep -q 'public-text: clean' out; then echo 'public-text-check-test: failed artifact enumeration printed clean'; cat out; exit 1; fi
# A grep that fails (exit 2) is an error: the check must refuse and never print "clean".
mkdir -p fakebin; printf '#!/bin/sh
exit 2
' > fakebin/grep; chmod +x fakebin/grep
rc=0; PATH="$PWD/fakebin:$PATH" bash "$here/public-text-check.sh" "$mb2" HEAD title body >out 2>&1 || rc=$?
[ "$rc" = 2 ] || { echo "public-text-check-test: failing grep: exit $rc, want 2"; cat out; exit 1; }
if PATH=/usr/bin:/bin grep -q "clean" out; then echo "public-text-check-test: failing grep printed clean"; cat out; exit 1; fi
echo "public-text-check-test: ok"
-61
View File
@@ -1,61 +0,0 @@
#!/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.
if ! git diff --name-only -z --no-renames --diff-filter=ACMT "$mb" "$head" -- docs/spec/ >"$paths"; then
echo 'public-text: cannot enumerate artifact paths' >&2
exit 2
fi
while IFS= read -r -d '' path; do
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 --no-color --no-renames -U0 "$mb" "$head" -- . \
':(exclude).github/scripts/public-text-check.sh' ':(exclude).github/scripts/public-text-check-test.sh' |
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"
-75
View File
@@ -1,75 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)
root=$(mktemp -d)
trap 'rm -rf "$root"' EXIT
mkdir -p "$root/bin"
cat >"$root/bin/go" <<'EOF'
#!/usr/bin/env bash
set -e
test "$1" = test && test "$2" = -json || exit 99
printf '%s\n' '{"Time":"2026-12-02T00:00:01Z","Action":"run","Test":"TestX"}'
printf '%s\n' '{"Time":"2026-12-02T00:00:02Z","Action":"output","Test":"TestX","Output":"fixture output\n"}'
printf '%s\n' '{"Time":"2026-12-02T00:00:02Z","Action":"fail","Test":"TestX","Elapsed":1}'
if [ "${FAKE_GO_LARGE:-0}" = 1 ]; then
for ((i=0; i<10000; i++)); do printf '%s\n' '{"Action":"output","Output":"draining after recorder failure\n"}'; done
fi
echo 'fixture stderr' >&2
if [ "${FAKE_GO_LARGE_STDERR:-0}" = 1 ]; then
for ((i=0; i<10000; i++)); do echo 'stderr draining after recorder failure' >&2; done
fi
exit "${FAKE_GO_EXIT:-0}"
EOF
chmod +x "$root/bin/go"
export PATH="$root/bin:$PATH"
code=0
FAKE_GO_EXIT=7 bash "$here/record-go-test.sh" "$root/go-test.json" -run TestX >"$root/console" 2>"$root/stderr" || code=$?
test "$code" = 7
grep -q 'fixture output' "$root/console"
grep -q 'fixture stderr' "$root/go-test.stderr"
"${PYTHON:-python3}" -c 'import json,sys; events=[json.loads(s) for s in open(sys.argv[1])]; assert len(events)==3; assert events[-1]["Elapsed"]==1; assert events[-1]["Time"]=="2026-12-02T00:00:02Z"' "$root/go-test.json"
FAKE_GO_EXIT=0 bash "$here/record-go-test.sh" "$root/go-test.json" -run TestX >"$root/console" 2>"$root/stderr"
test "$(wc -l <"$root/go-test.json")" = 6
# The evidence destination cannot be opened (a file where its parent belongs).
# The original Go success/failure must still be the command's answer.
echo occupied >"$root/not-a-directory"
code=0
FAKE_GO_EXIT=0 bash "$here/record-go-test.sh" "$root/not-a-directory/go-test.json" >"$root/console" 2>"$root/stderr" || code=$?
test "$code" = 0
grep -q 'fixture output' "$root/console"
code=0
FAKE_GO_EXIT=7 bash "$here/record-go-test.sh" "$root/not-a-directory/go-test.json" >"$root/console" 2>"$root/stderr" || code=$?
test "$code" = 7
if [ "$(uname -s)" = Linux ] && [ -c /dev/full ]; then
ln -s /dev/full "$root/full.json"
FAKE_GO_LARGE=1 FAKE_GO_EXIT=0 bash "$here/record-go-test.sh" "$root/full.json" >"$root/console" 2>"$root/stderr"
grep -q 'draining after recorder failure' "$root/console"
grep -q 'test evidence unavailable' "$root/stderr"
fi
# The recorder itself dies after its first bytes (a crash, an OOM kill): the
# rest of a large stream still drains and Go's own status is the answer.
cat >"$root/bin/dead-recorder" <<'EOF2'
#!/usr/bin/env bash
head -c 100 >/dev/null
exit 3
EOF2
chmod +x "$root/bin/dead-recorder"
for want in 0 7; do
code=0
PYTHON="$root/bin/dead-recorder" FAKE_GO_LARGE=1 FAKE_GO_EXIT=$want bash "$here/record-go-test.sh" "$root/dead.json" >"$root/console" 2>"$root/stderr" || code=$?
test "$code" = "$want"
grep -q 'draining after recorder failure' "$root/console"
grep -q 'the recorder exited' "$root/stderr"
# The stderr reader dies with a large stderr still to come.
code=0
PYTHON="$root/bin/dead-recorder" FAKE_GO_LARGE_STDERR=1 FAKE_GO_EXIT=$want bash "$here/record-go-test.sh" "$root/dead.json" >"$root/console" 2>"$root/stderr" || code=$?
test "$code" = "$want"
grep -q 'stderr draining after recorder failure' "$root/stderr"
# The recorder cannot start at all (no such interpreter).
code=0
PYTHON="$root/bin/no-such-python" FAKE_GO_LARGE=1 FAKE_GO_LARGE_STDERR=1 FAKE_GO_EXIT=$want bash "$here/record-go-test.sh" "$root/dead.json" >"$root/console" 2>"$root/stderr" || code=$?
test "$code" = "$want"
grep -q 'draining after recorder failure' "$root/console"
grep -q 'stderr draining after recorder failure' "$root/stderr"
done
echo 'record-go-test: output, timestamp, elapsed, append, dead-recorder and exit-status controls PASS'
-22
View File
@@ -1,22 +0,0 @@
#!/usr/bin/env bash
# Keep timestamped Go events, while preserving the existing human output and
# nonzero pipeline status. One caller at a time appends to a job's event file.
set -euo pipefail
out=$1
shift
mkdir -p "$(dirname "$out")" || true
capture="$(dirname "$0")/go-test-output.py"
# A recorder that dies (or cannot start) hands the rest of its stream to cat,
# so Go never writes into a closed pipe.
exec 3> >({ "${PYTHON:-python3}" -u "$capture" "${out%.json}.stderr" --raw || cat; } >&2)
stderr_pid=$!
# Only Go judges the test. The readers keep draining after evidence IO errors,
# so a disk-full recorder cannot turn Go's PASS into a pipeline/SIGPIPE failure.
set +e
go test -json "$@" 2>&3 |
{ "${PYTHON:-python3}" -u "$capture" "$out" || { echo "test evidence unavailable: the recorder exited" >&2; cat; }; }
status=${PIPESTATUS[0]}
set -e
exec 3>&-
wait "$stderr_pid" || true
exit "$status"
@@ -1,92 +0,0 @@
"""Exercise release packaging without Docker, GitHub writes or product builds."""
from pathlib import Path
import json, os, subprocess, tarfile, tempfile, unittest
HERE = Path(__file__).resolve().parent
REV = "a" * 40
DIGEST = "example.invalid/block@sha256:" + "b" * 64
class ReleaseAssets(unittest.TestCase):
def run_case(self, bad=None, mode="revision", existing=True, tag="v1.1.1",
docker_rm_rc=0, rm_rc=0, publish_rc=0):
with tempfile.TemporaryDirectory() as tmp:
root=Path(tmp); tools=root/"tools"; tools.mkdir(); image=root/"image"; image.mkdir()
expected={}
for name in ("blockmaster", "blockvolume", "sw-block"):
revision=REV; modified="false"; suffix=""; status=0
if bad == name:
if mode == "revision": revision="c"*40
elif mode == "dirty": modified="true"
elif mode == "unknown": revision="unknown"
elif mode == "lab": suffix=" LAB BUILD(example)"
elif mode == "provenance-failure": status=17
else: self.fail("invalid fixture mode")
data=(f"#!/bin/sh\necho '{name} revision={revision} modified={modified}{suffix}'\nexit {status}\n").encode()
(image/name).write_bytes(data); (image/name).chmod(0o755); expected[name]=data
log=root/"calls.jsonl"; state=root/"release.json"; state.write_text(json.dumps({"prerelease":"-" not in tag}))
common="""#!/usr/bin/env python3
import json,os,pathlib,shutil,sys
args=sys.argv[1:]
with open(os.environ['CALLS'],'a') as f: f.write(json.dumps([pathlib.Path(sys.argv[0]).name,*args])+chr(10))
"""
(tools/"docker").write_text(common+"""
if args[0]=='create': print('owned-container')
elif args[0]=='cp': shutil.copy2(pathlib.Path(os.environ['IMAGE'])/args[1].rsplit('/',1)[1],args[2])
elif args[0]=='rm': sys.exit(int(os.environ['DOCKER_RM_RC']))
""")
(tools/"rm").write_text(common+"""
if os.environ['RM_RC']!='0': sys.exit(int(os.environ['RM_RC']))
shutil.rmtree(args[-1])
""")
(tools/"gh").write_text(common+"""
if args[:2]==['release','view']: sys.exit(0 if os.environ['EXISTING']=='1' else 1)
if args[1] in ('edit','create'):
flag=next((a for a in args if a.startswith('--prerelease')), '--prerelease=false')
pathlib.Path(os.environ['STATE']).write_text(json.dumps({'prerelease':flag in ('--prerelease','--prerelease=true')}))
if args[1] in ('upload','create'): sys.exit(int(os.environ['PUBLISH_RC']))
""")
for tool in tools.iterdir(): tool.chmod(0o755)
out=root/"assets"
env=dict(os.environ,PATH=str(tools)+os.pathsep+os.environ['PATH'],CALLS=str(log),IMAGE=str(image),
EXISTING=str(int(existing)),STATE=str(state),GITHUB_REPOSITORY='example/block',
DOCKER_RM_RC=str(docker_rm_rc),RM_RC=str(rm_rc),PUBLISH_RC=str(publish_rc))
result=subprocess.run(['bash',str(HERE/'release-binary-assets.sh'),DIGEST,REV,tag,str(out)],
env=env,capture_output=True,text=True,timeout=15)
calls=[json.loads(line) for line in log.read_text().splitlines()] if log.exists() else []
primary=(17 if mode=='provenance-failure' else 1) if bad else publish_rc
self.assertEqual(result.returncode,primary or docker_rm_rc or rm_rc,result.stderr)
if bad:
self.assertFalse(any(c[0]=='gh' for c in calls),calls)
self.assertFalse((out/'SHA256SUMS').exists())
elif not publish_rc:
archive=out/f'sw-block-{tag}-linux-amd64.tar.gz'
with tarfile.open(archive) as tar:
self.assertEqual(set(tar.getnames()),set(expected))
for name,data in expected.items(): self.assertEqual(tar.extractfile(name).read(),data)
subprocess.run(['sha256sum','--check','SHA256SUMS'],cwd=out,check=True,capture_output=True)
command='upload' if existing else 'create'
self.assertTrue(any(c[:3]==['gh','release',command] for c in calls),calls)
self.assertEqual(json.loads(state.read_text())['prerelease'],'-' in tag)
self.assertEqual(calls[0],['docker','pull',DIGEST])
self.assertIn(['docker','create',DIGEST],calls)
self.assertEqual(calls[-2],['docker','rm','owned-container'])
self.assertEqual(calls[-1][:4],['rm','-rf','--',calls[-1][-1]])
if not rm_rc: self.assertFalse(Path(calls[-1][-1]).exists())
def test_release_kind_on_create_and_existing(self):
for existing in (False,True):
for tag in ('v1.1.1','v1.1.1-rc1'):
with self.subTest(existing=existing,tag=tag): self.run_case(existing=existing,tag=tag)
def test_every_binary_refuses_invalid_provenance(self):
for name in ('blockmaster','blockvolume','sw-block'):
for mode in ('revision','dirty','unknown','lab','provenance-failure'):
with self.subTest(binary=name,mode=mode): self.run_case(bad=name,mode=mode)
def test_cleanup_preserves_primary_error_and_tries_both(self):
self.run_case(publish_rc=37,docker_rm_rc=41,rm_rc=43)
self.run_case(bad='blockmaster',mode='provenance-failure',docker_rm_rc=41,rm_rc=43)
self.run_case(docker_rm_rc=41)
self.run_case(rm_rc=43)
if __name__=='__main__': unittest.main()
-49
View File
@@ -1,49 +0,0 @@
#!/usr/bin/env bash
# Copy release executables unchanged from the exact published Linux image.
set -euo pipefail
[ "$#" = 4 ] || { echo "usage: release-binary-assets.sh IMAGE@DIGEST REVISION TAG OUT" >&2; exit 2; }
image=$1; revision=$2; tag=$3; out=$4
[[ "$image" =~ @sha256:[a-f0-9]{64}$ ]] || { echo "an immutable image digest is required" >&2; exit 2; }
[[ "$revision" =~ ^[a-f0-9]{40}$ ]] || { echo "a full Git revision is required" >&2; exit 2; }
[[ "$tag" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.]+)?$ ]] || { echo "invalid release tag" >&2; exit 2; }
work=$(mktemp -d)
container=
cleanup() {
local status=$? cleanup_status=0 next_status=0
trap - EXIT
if [ -n "$container" ]; then
docker rm "$container" >/dev/null || cleanup_status=$?
fi
rm -rf -- "${work:?}" || {
next_status=$?
if [ "$cleanup_status" = 0 ]; then cleanup_status=$next_status; fi
}
if [ "$status" = 0 ]; then status=$cleanup_status; fi
exit "$status"
}
trap cleanup EXIT
mkdir -p "$work/bin"
docker pull "$image"
container=$(docker create "$image")
for binary in blockmaster blockvolume sw-block; do
docker cp "$container:/usr/local/bin/$binary" "$work/bin/$binary"
version=$("$work/bin/$binary" -version)
if [ "$version" != "$binary revision=$revision modified=false" ]; then
echo "$binary revision mismatch: expected $revision modified=false, got $version" >&2
exit 1
fi
done
mkdir -p "$out"
asset="sw-block-${tag}-linux-amd64.tar.gz"
tar -C "$work/bin" -czf "$out/$asset" blockmaster blockvolume sw-block
(cd "$out" && sha256sum "$asset" >SHA256SUMS)
prerelease=false
if [[ "$tag" == *-* ]]; then prerelease=true; fi
if gh release view "$tag" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then
gh release edit "$tag" --repo "$GITHUB_REPOSITORY" --prerelease="$prerelease"
gh release upload "$tag" "$out/$asset" "$out/SHA256SUMS" --repo "$GITHUB_REPOSITORY" --clobber
else
args=(--repo "$GITHUB_REPOSITORY" --verify-tag --title "Seaweed Block $tag" --generate-notes)
args+=(--prerelease="$prerelease")
gh release create "$tag" "$out/$asset" "$out/SHA256SUMS" "${args[@]}"
fi
-45
View File
@@ -1,45 +0,0 @@
#!/usr/bin/env bash
# Tests require-nvme.sh with df and lsblk replaced by stubs on PATH.
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)
t=$(mktemp -d)
trap 'rm -rf "$t"' EXIT
mkdir -p "$t/bin" "$t/nvme" "$t/sata" "$t/mem" "$t/raid" "$t/share" "$t/half"
# df --output=source,fstype DIR: the stub answers by the directory's name.
cat >"$t/bin/df" <<STUB
#!/usr/bin/env bash
printf 'Filesystem Type\n'
case "\$2" in
$t/nvme*) echo '/dev/nvme0n1p1 ext4' ;;
$t/mem*) echo 'shm tmpfs' ;;
$t/raid*) echo '/dev/md0 ext4' ;;
$t/share*) echo '//nas/work cifs' ;;
$t/half*) echo '/dev/nvme1n1p1 ext4' ;;
*) echo '/dev/sda2 ext4' ;;
esac
STUB
# lsblk -nrso TYPE,TRAN SOURCE: the source and the devices under it.
cat >"$t/bin/lsblk" <<'STUB'
#!/usr/bin/env bash
case "$3" in
/dev/nvme0n1p1) printf 'part \ndisk nvme\n' ;;
/dev/sda2) printf 'part \ndisk sata\n' ;;
/dev/md0) printf 'raid1 \npart \ndisk nvme\npart \ndisk sata\n' ;;
/dev/nvme1n1p1) printf 'part \ndisk nvme\n'; echo "lsblk: read error" >&2; exit 32 ;;
*) echo "lsblk: $3: not a block device" >&2; exit 32 ;;
esac
STUB
chmod +x "$t/bin/df" "$t/bin/lsblk"
run() { PATH="$t/bin:$PATH" RUNNER_NAME=r1 bash "$here/require-nvme.sh" "$@" >"$t/out" 2>&1; }
fail() { echo "FAIL: $*"; cat "$t/out"; exit 1; }
run "$t/nvme" "$t/mem" "" || fail "nvme + tmpfs (any source name) + empty arg must pass"
run "$t/nvme/not/made/yet" || fail "a missing dir is judged by its nearest existing parent"
! run "$t/nvme" "$t/sata" || fail "a SATA dir must fail"
grep -q "runner r1" "$t/out" || fail "the failure must name the runner"
grep -q "FAIL $t/sata" "$t/out" || fail "the failure must name the directory"
! run "$t/raid" || fail "an array with a SATA member must fail"
! run "$t/share" || fail "a network share must fail"
grep -q "not a block device" "$t/out" || fail "a network share must say why"
! run "$t/half" || fail "an lsblk error after partial NVMe output must fail"
echo "require-nvme tests: ok"
-36
View File
@@ -1,36 +0,0 @@
#!/usr/bin/env bash
# Fails a self-hosted job whose workspace, temp or Go cache directory is not
# on an NVMe disk. The process-level tests write and fsync real files; on a
# box whose system disk is SATA, a default runner install puts _work there and
# the tests time out under the disk load instead of failing on a real bug.
# A tmpfs directory is accepted (memory, not a slow disk).
# Usage: require-nvme.sh DIR...
set -euo pipefail
bad=0
for p in "$@"; do
[ -n "$p" ] || continue
d=$p
while [ ! -e "$d" ]; do d=$(dirname "$d"); done
read -r src fstype < <(df --output=source,fstype "$d" | tail -n 1)
if [ "$fstype" = tmpfs ]; then
echo "ok $p: $src (tmpfs)"
continue
fi
# Every disk under the source (all members of an array) must be NVMe; an
# lsblk error voids whatever it printed.
disks=
if tree=$(lsblk -nrso TYPE,TRAN "$src" 2>/dev/null); then
disks=$(printf '%s\n' "$tree" |
awk '$1 == "disk" { print ($2 == "" ? "unknown" : $2) }' | sort -u | tr '\n' ' ')
fi
if [ "$disks" = "nvme " ]; then
echo "ok $p: $src (nvme)"
else
echo "FAIL $p: $src (disk: ${disks:-not a block device})"
bad=1
fi
done
if [ "$bad" -ne 0 ]; then
echo "runner ${RUNNER_NAME:-?}: work, temp and Go cache directories must be on NVMe; move them before this runner takes jobs" >&2
exit 1
fi
@@ -1,128 +0,0 @@
"""Self-test of required-tests-check.py: event streams against the exit code
they must give. A gate that cannot fail is the defect this check exists to
prevent, so every way a named test can fail to pass is here."""
import json
import os
import subprocess
import sys
import tempfile
HERE = os.path.dirname(os.path.abspath(__file__))
CHECK = os.path.join(HERE, 'required-tests-check.py')
def ev(action, test=None, elapsed=None):
e = {'Action': action, 'Package': 'example/cmd/blockvolume'}
if test:
e['Test'] = test
if elapsed is not None:
e['Elapsed'] = elapsed
return json.dumps(e)
def ran(test, end='pass', secs=1.5):
return [ev('run', test), ev('output', test), ev(end, test, secs)]
def run(names, *streams, status=None):
with tempfile.TemporaryDirectory() as d:
nf = os.path.join(d, 'names')
with open(nf, 'w', encoding='utf-8') as f:
f.write(names)
files = []
for i, lines in enumerate(streams):
p = os.path.join(d, 'events%d' % i)
with open(p, 'w', encoding='utf-8') as f:
f.write('\n'.join(lines) + '\n')
files.append(p)
extra = []
if status is not None:
sf = os.path.join(d, 'status')
with open(sf, 'w', encoding='utf-8') as f:
f.write(status)
extra = ['--status', sf]
r = subprocess.run([sys.executable, '-I', CHECK] + extra + [nf] + files, capture_output=True, text=True)
return r.returncode, r.stdout + r.stderr
NG = 'TestA\nTestB # nongating=#920\n'
CASES = [
# (name, want exit, names file, streams)
('a non-gating test that passed', 0, NG, [ran('TestA') + ran('TestB')]),
('a non-gating test that failed does not fail the run', 0, NG, [ran('TestA') + ran('TestB', 'fail')]),
('a non-gating failure, then its process failed: still its own', 0, NG,
[ran('TestA'), ran('TestB', 'fail') + [ev('fail')]]),
('a gating test still fails the run beside a non-gating one', 1, NG, [ran('TestA', 'fail') + ran('TestB')]),
('a process failure after a gating test still fails the run', 1, NG, [ran('TestA') + [ev('fail')], ran('TestB')]),
('a non-gating test that never ran fails (not run is not reported)', 1, NG, [ran('TestA')]),
('nongating without an issue is refused', 2, 'TestA\nTestB # nongating\n', [ran('TestA') + ran('TestB')]),
('every named test passed', 0, 'TestA\nTestB # a comment\n', [ran('TestA') + ran('TestB')]),
('passes spread over two streams', 0, 'TestA\nTestB\n', [ran('TestA'), ran('TestB')]),
('an unnamed test may fail', 0, 'TestA\n', [ran('TestA') + ran('TestOther', 'fail')]),
('a passing subtest does not stand for a skipped parent', 1, 'TestA\n',
[[ev('run', 'TestA'), ev('pass', 'TestA/sub', 1), ev('skip', 'TestA', 0)]]),
('a skip is a failure', 1, 'TestA\nTestB\n', [ran('TestA') + ran('TestB', 'skip', 0)]),
('a failed test', 1, 'TestA\n', [ran('TestA', 'fail')]),
('a test that never ran', 1, 'TestA\nTestB\n', [ran('TestA')]),
('a test that started and never ended (killed by the timeout)', 1, 'TestA\n', [[ev('run', 'TestA'), ev('output', 'TestA')]]),
('passed in one stream, failed in another', 1, 'TestA\n', [ran('TestA'), ran('TestA', 'fail')]),
('no events at all (the build failed)', 1, 'TestA\n', [['# example/cmd/blockvolume', 'build failed']]),
('a package-level failure after every named test passed', 1, 'TestA\n', [ran('TestA') + [ev('fail', None, 3)]]),
('a name listed twice', 2, 'TestA\nTestA\n', [ran('TestA')]),
('a subtest name in the list', 2, 'TestA/sub\n', [ran('TestA')]),
('an empty names file', 2, '# nothing\n', [ran('TestA')]),
]
def main():
fail = 0
for name, want, names, streams in CASES:
got, out = run(names, *streams)
if got != want:
print('FAIL %s: exit %d, want %d\n%s' % (name, got, want, out))
fail = 1
STATUS = [
('PASS events and every process exited 0', 0, 'TestA 0\nTestB 0\n'),
('PASS, then the process exited 1', 1, 'TestA 0\nTestB 1\n'),
('PASS, then the process was killed by the timeout', 1, 'TestA 0\nTestB 124\n'),
('a named test with no exit status', 1, 'TestA 0\n'),
('a named test ran twice', 1, 'TestA 0\nTestB 0\nTestB 0\n'),
('a malformed status line', 2, 'TestA 0\nTestB\n'),
]
for name, want, status in STATUS:
got, out = run('TestA\nTestB\n', ran('TestA') + ran('TestB'), status=status)
if got != want:
print('FAIL %s: exit %d, want %d\n%s' % (name, got, want, out))
fail = 1
got, out = run('TestA\n', [ev('run', 'TestA'), json.dumps({'Action': 'output', 'Test': 'TestA', 'Output': ' x_test.go:7: the reason\n'})] + [json.dumps({'Action': 'output', 'Test': 'TestA', 'Output': ' h_test.go:578: blockvolume-r%d log:\n' % i}) for i in range(20)] + [json.dumps({'Action': 'output', 'Test': 'TestA', 'Output': ' w_test.go:128: ---- master log tail ----\n'})] + [json.dumps({'Action': 'output', 'Test': 'TestA', 'Output': ' I1126 harness log line %d\n' % i}) for i in range(60)] + [ev('fail', 'TestA', 1)])
if got != 1 or 'x_test.go:7: the reason' not in out:
print('FAIL a failed test''s output is shown: %s' % out)
fail = 1
# A message whose reason is on its continuation lines (a holder's log
# tail after "its log ends:"), followed by a harness dump: the message's
# last continuation lines are shown, the dump is not.
o = lambda s: json.dumps({'Action': 'output', 'Test': 'TestA', 'Output': s + '\n'})
got, out = run('TestA\n', [ev('run', 'TestA'),
o(' f1_test.go:178: blockvolume-v5r2 exited (exit status 1) before logging "adopted"; its log ends:')]
+ [o(' holder line %d' % i) for i in range(40)]
+ [o(' holder: fatal: the reason it exited')]
+ [o(' w_test.go:128: ---- master log tail ----')]
+ [o(' I1201 harness log line %d' % i) for i in range(60)] + [ev('fail', 'TestA', 1)])
if got != 1 or 'holder: fatal: the reason it exited' not in out or 'holder line 39' not in out:
print('FAIL a failed message\'s continuation lines are shown: %s' % out)
fail = 1
if 'holder line 0\n' in out or 'harness log line 0\n' in out:
print('FAIL continuation lines are bounded and a dump\'s are not kept: %s' % out)
fail = 1
got, out = run('TestA\n', ran('TestA', secs=2.25))
if got != 0 or '2.2s' not in out and '2.3s' not in out:
print('FAIL the elapsed time is reported: %s' % out)
fail = 1
if not fail:
print('required-tests-check: %d cases ok' % (len(CASES) + len(STATUS) + 3))
return fail
if __name__ == '__main__':
sys.exit(main())
-214
View File
@@ -1,214 +0,0 @@
"""Every named test must have run and passed.
Usage: required-tests-check.py [--status STATUS_FILE] NAMES_FILE EVENTS_FILE...
NAMES_FILE holds one top-level test name per line (# starts a comment). A
name whose comment says `nongating=#N` (an open issue) is non-gating: it runs
and is reported like every other, but its failure does not fail the run; its
line says NON-GATING and names the issue, and a failure-process exit after it
is its own, not the binary's. A non-gating test that never ran still fails:
a test that is not run is not reported.
EVENTS_FILE is `go test -json` (or `go tool test2json`) output. A named test
that skipped, failed, never started or never ended is a failure: a test that
cannot start proves nothing, so it is not allowed to read as a pass. A name
listed twice, or a test that passed in one stream and failed in another, is a
failure too. A package-level failure event fails the run.
STATUS_FILE (run-named-tests.sh) holds one line per named test, NAME and the
exit status of the process that ran it. With it, a named test passes only if it
also has exactly one line and that status is 0: a test that reports PASS and
then fails, panics or hangs on its way out is not a pass. Prints one line per named test with its outcome and elapsed
seconds, then the total.
For every named test that did not pass, its own reported lines (the test's
file:line messages with the last lines of each one's continuation, not the
harness's log dumps) and its last lines follow the table, so a run's log
carries its own reasons.
Exit 0: every named test passed. 1: at least one did not. 2: usage or an
unreadable input.
"""
import json
import re
import sys
OWN = 12 # a failed test's own file:line messages shown (the last ones)
TAIL = 5 # and its last output lines
OWN_LINE = re.compile(r'^ [^ \t]+\.go:\d+: ') # the test's own t.Log/t.Error lines
# Not reasons: the harness's cleanup headers ("<process> log:", "---- <x> log
# tail ----") and the echo of a command that succeeded ("...: exit 0").
NOISE = re.compile(r' log:\s*$|---- .* ----\s*$|: exit 0\s*$')
CONT = 20 # the last continuation lines shown of each own message
CONT_LINE = re.compile(r'^ ') # a message's next line, as go test indents it
def own_messages(text):
"""The test's own messages, each its file:line line and the last CONT of
the continuation lines after it (a reason, such as a process's log tail,
is often on those). A harness header's lines are not kept, nor its dump."""
msgs, cur = [], None
for line in text:
if OWN_LINE.match(line):
cur = None
if not NOISE.search(line):
cur = [line, []]
msgs.append(cur)
elif cur is not None and CONT_LINE.match(line):
cur[1].append(line)
else:
cur = None
return [[head] + cont[-CONT:] for head, cont in msgs]
NONGATING = re.compile(r'\bnongating=(#\d+)')
def names_of(path):
"""The named tests, in order, and the non-gating ones with their issue."""
names, seen, nongating = [], set(), {}
with open(path, encoding='utf-8') as f:
for n, raw in enumerate(f, 1):
line, _, comment = raw.partition('#')
line = line.strip()
if not line:
continue
m = NONGATING.search('#' + comment)
if m:
nongating[line] = m.group(1)
elif 'nongating' in comment:
raise ValueError('%s:%d: %r: nongating needs an issue, nongating=#N' % (path, n, raw.strip()))
if not line.startswith('Test') or '/' in line or ' ' in line:
raise ValueError('%s:%d: %r is not a top-level test name' % (path, n, line))
if line in seen:
raise ValueError('%s:%d: %s is listed twice' % (path, n, line))
seen.add(line)
names.append(line)
if not names:
raise ValueError('%s: no test names' % path)
return names, nongating
def statuses_of(path):
"""Test name -> list of exit statuses."""
out = {}
with open(path, encoding='utf-8') as f:
for n, raw in enumerate(f, 1):
parts = raw.split()
if not parts:
continue
if len(parts) != 2 or not parts[1].lstrip('-').isdigit():
raise ValueError('%s:%d: %r is not NAME EXIT_STATUS' % (path, n, raw.strip()))
out.setdefault(parts[0], []).append(int(parts[1]))
return out
def outcomes(paths):
"""Test name -> list of (action, elapsed) for its terminal events, the
names that started (action run), the package-level failure events (each
with the test last started in its stream before it, or None), and each
test's output."""
ends, started, pkg_fail, output = {}, set(), [], {}
for path in paths:
last = None
with open(path, encoding='utf-8', errors='replace') as f:
for raw in f:
raw = raw.strip()
if not raw.startswith('{'):
continue # build output or a panic line between events
try:
ev = json.loads(raw)
except ValueError:
continue
test = ev.get('Test')
if not test:
if ev.get('Action') == 'fail':
pkg_fail.append(last) # the binary failed outside any test (or after one)
continue # other package events; a subtest's name never matches a top-level one
action = ev.get('Action')
if action == 'output':
output.setdefault(test.split('/')[0], []).append(ev.get('Output', ''))
continue
if action == 'run':
started.add(test)
if '/' not in test:
last = test
elif action in ('pass', 'fail', 'skip'):
ends.setdefault(test, []).append((action, ev.get('Elapsed')))
return ends, started, pkg_fail, output
def main(argv):
args = argv[1:]
status_file = None
if args[:1] == ['--status']:
if len(args) < 2:
print(__doc__.strip().splitlines()[2], file=sys.stderr)
return 2
status_file, args = args[1], args[2:]
if len(args) < 2:
print(__doc__.strip().splitlines()[2], file=sys.stderr)
return 2
try:
names, nongating = names_of(args[0])
ends, started, pkg_fail, output = outcomes(args[1:])
statuses = statuses_of(status_file) if status_file else None
except (OSError, ValueError) as e:
print('required-tests: %s' % e, file=sys.stderr)
return 2
# A package-level failure right after a non-gating test is that test's
# (each named test runs in its own process); any other fails the run.
pkg_own = {}
for after in pkg_fail:
if after in nongating:
pkg_own[after] = pkg_own.get(after, 0) + 1
pkg_fail = [a for a in pkg_fail if a not in nongating]
bad, total, failed, ng_failed = 0, 0.0, [], 0
for name in names:
got = ends.get(name, [])
actions = {a for a, _ in got}
secs = sum(e for _, e in got if isinstance(e, (int, float)))
total += secs
rcs = statuses.get(name, []) if statuses is not None else [0]
if actions == {'pass'} and len(got) == 1 and rcs == [0] and not pkg_own.get(name):
print('PASS %-70s %7.1fs' % (name, secs))
continue
failed.append(name)
issue = nongating.get(name)
ran_at_all = bool(got) or name in started
if issue and ran_at_all:
ng_failed += 1
else:
bad += 1
if actions == {'pass'} and len(got) == 1:
why = ('NO EXIT STATUS' if not rcs else
'PASSED, THEN EXIT %s' % ','.join(str(r) for r in rcs))
elif not got:
why = 'STARTED, NEVER ENDED' if name in started else 'NEVER RAN'
elif len(got) > 1:
why = 'RAN %d TIMES (%s)' % (len(got), ', '.join(a for a, _ in got))
else:
why = got[0][0].upper()
if pkg_own.get(name):
why += ', THEN THE PROCESS FAILED'
if issue and ran_at_all:
print('%-8s %-70s %7.1fs' % ('FAIL', name, secs) + ' ' + why + ' NON-GATING (%s): reported, does not fail the run' % issue)
else:
print('%-8s %-70s %7.1fs' % ('FAIL', name, secs) + ' ' + why)
for name in failed:
text = ''.join(output.get(name, [])).splitlines()
own = own_messages(text)[-OWN:]
print('---- %s: its own messages (%d), then its last %d lines' % (name, len(own), min(TAIL, len(text))))
for line in [l for m in own for l in m] + [' ...'] + text[-TAIL:]:
print(' ' + line[:300])
if pkg_fail:
print('FAIL the test binary reported %d package-level failure(s)' % len(pkg_fail))
print('required-tests: %d named, %d not passed, %.1fs in named tests' % (len(names), bad, total))
if nongating:
print('required-tests: %d non-gating (%s), %d of them failed' % (len(nongating), ', '.join('%s %s' % (n, nongating[n]) for n in names if n in nongating), ng_failed))
return 1 if bad or pkg_fail else 0
if __name__ == '__main__':
sys.exit(main(sys.argv))
-49
View File
@@ -1,49 +0,0 @@
#!/usr/bin/env bash
# Self-test of run-named-tests.sh with the gate (required-tests-check.py
# --status), through a real shell and test2json, with fake test binaries:
# a test that reports PASS and then exits nonzero, or hangs until the
# timeout, must fail the gate; an honest pass must not. Needs go (test2json).
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
fail=0
# fake NAME BEHAVIOUR: a test binary that prints a passing verbose run of
# whatever -test.run names, then behaves as told.
fake() {
local f=$tmp/$1
cat >"$f" <<EOF
#!/usr/bin/env bash
for a in "\$@"; do case "\$a" in -test.run=*) re=\${a#-test.run=} ;; esac; done
prev=""
for a in "\$@"; do [ "\$prev" = -test.run ] && re=\$a; prev=\$a; done
name=\${re#^}; name=\${name%\\\$}
echo "=== RUN \$name"
echo "--- PASS: \$name (0.01s)"
echo "PASS"
$2
EOF
chmod +x "$f"
echo "$f"
}
# expect WANT_EXIT NAME BINARY
expect() {
local want=$1 name=$2 bin=$3 got=0
printf 'TestA\nTestB\n' >"$tmp/names"
TEST_PKG=example/fake bash "$here/run-named-tests.sh" "$bin" "$tmp/names" "$tmp/events" "$tmp/status" 3s "$tmp" >/dev/null
"${PYTHON:-python3}" -I "$here/required-tests-check.py" --status "$tmp/status" "$tmp/names" "$tmp/events" >"$tmp/out" || got=$?
if [[ $got != "$want" ]]; then
echo "FAIL $name: exit $got, want $want"
cat "$tmp/out"
fail=1
fi
}
expect 0 "PASS and exit 0" "$(fake ok 'exit 0')"
expect 1 "PASS, then exit 1" "$(fake exit1 'exit 1')"
expect 1 "PASS, then a hang until the timeout" "$(fake hang 'sleep 30')"
if ((fail == 0)); then echo "run-named-tests: 3 cases ok"; fi
exit "$fail"
-30
View File
@@ -1,30 +0,0 @@
#!/usr/bin/env bash
# Runs each test named in NAMES_FILE in its own process of TEST_BINARY, in
# sequence, so a panic or a hang in one cannot hide the others. Each process
# is bounded by TIMEOUT (the test binary's own timeout, then killed). Every
# process's exit status is kept: a test that reports PASS and then fails or
# hangs on its way out is not a pass (required-tests-check.py --status).
#
# Usage: run-named-tests.sh TEST_BINARY NAMES_FILE EVENTS_OUT STATUS_OUT TIMEOUT [DIR]
# TEST_BINARY absolute path of a binary built with go test -c
# EVENTS_OUT go test -json events of every process, appended in order
# STATUS_OUT one line per named test: NAME EXIT_STATUS
# DIR the directory each process runs in (default .)
# TEST_PKG names the package in the events (default the blockvolume command).
# Exits 0 once every named test has run; the verdict is the checker's.
set -euo pipefail
[ "$#" -ge 5 ] || { echo "usage: run-named-tests.sh TEST_BINARY NAMES_FILE EVENTS_OUT STATUS_OUT TIMEOUT [DIR]" >&2; exit 2; }
bin=$1 names=$2 out=$3 status=$4 to=$5 dir=${6:-.}
case "$bin" in /*) ;; *) echo "run-named-tests: TEST_BINARY must be absolute" >&2; exit 2 ;; esac
pkg=${TEST_PKG:-github.com/seaweedfs/seaweed-block/cmd/blockvolume}
: >"$out"
: >"$status"
while read -r name; do
start=$(date +%s)
rc=0
(cd "$dir" && timeout -k 30 "$to" "$bin" -test.v=test2json -test.count=1 \
-test.timeout "$to" -test.run "^${name}\$" 2>&1) |
go tool test2json -t -p "$pkg" >>"$out" || rc=$?
echo "$name $rc" >>"$status"
echo "$name: exit $rc, $(($(date +%s) - start))s"
done < <(sed 's/#.*//' "$names" | tr -d ' \t' | grep .)
-144
View File
@@ -1,144 +0,0 @@
"""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)
leader = Mock(pid=12345)
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(12345, signal.SIGTERM), killpg.call_args_list)
self.assertIn(unittest.mock.call(12345, 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()
-123
View File
@@ -1,123 +0,0 @@
"""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))
-111
View File
@@ -1,111 +0,0 @@
// Command sametokens reports whether two versions of a Go source file have the
// same tokens in the same order, ignoring comments that the compiler ignores.
//
// Usage: go run sametokens.go OLD NEW
//
// A missing file counts as empty. Directive comments are compared as tokens:
// //go:..., // +build, //line, /*line, //export; in a file that uses cgo
// (any "C" string literal, as in import "C"), every comment counts, since the
// preamble is code. Exit 0: same tokens; 1: different
// (the first difference is printed); 2: usage error or a file that does not scan.
package main
import (
"fmt"
"go/scanner"
"go/token"
"os"
"strings"
)
type tok struct {
t token.Token
lit string
}
func main() {
if len(os.Args) != 3 {
fmt.Fprintln(os.Stderr, "usage: sametokens OLD NEW")
os.Exit(2)
}
a, err := tokens(os.Args[1])
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(2)
}
b, err := tokens(os.Args[2])
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(2)
}
for i := 0; i < len(a) || i < len(b); i++ {
if i >= len(a) || i >= len(b) || a[i] != b[i] {
fmt.Printf("token %d differs: %v vs %v\n", i, at(a, i), at(b, i))
os.Exit(1)
}
}
}
func at(ts []tok, i int) string {
if i >= len(ts) {
return "end of file"
}
return fmt.Sprintf("%s %q", ts[i].t, ts[i].lit)
}
// tokens scans a file and keeps every token except comments the compiler
// ignores. An automatic semicolon is compared by kind only.
func tokens(path string) ([]tok, error) {
src, err := os.ReadFile(path)
if os.IsNotExist(err) {
return nil, nil
} else if err != nil {
return nil, err
}
fset := token.NewFileSet()
file := fset.AddFile(path, -1, len(src))
var s scanner.Scanner
var scanErr error
s.Init(file, src, func(pos token.Position, msg string) {
if scanErr == nil {
scanErr = fmt.Errorf("%s: %s", pos, msg)
}
}, scanner.ScanComments)
var all []tok
for {
_, t, lit := s.Scan()
if t == token.EOF {
break
}
if t == token.SEMICOLON {
lit = ""
}
all = append(all, tok{t, lit})
}
if scanErr != nil {
return nil, scanErr
}
cgo := false
for _, x := range all {
if x.t == token.STRING && x.lit == "\"C\"" {
cgo = true
}
}
var out []tok
for _, x := range all {
if x.t == token.COMMENT && !cgo && !directive(x.lit) {
continue
}
out = append(out, x)
}
return out, nil
}
func directive(c string) bool {
for _, p := range []string{"//go:", "// +build", "//+build", "//line ", "/*line ", "//export "} {
if strings.HasPrefix(c, p) {
return true
}
}
return false
}
-55
View File
@@ -1,55 +0,0 @@
"""Tests shard-named-tests.py: every name in exactly one shard, longest first
into the least-loaded shard, the same split on every run, unknown names
counted, and a duplicate or empty list refused."""
import importlib.util
import os
import subprocess
import sys
import tempfile
HERE = os.path.dirname(os.path.abspath(__file__))
SCRIPT = os.path.join(HERE, "shard-named-tests.py")
spec = importlib.util.spec_from_file_location("shard", SCRIPT)
shard = importlib.util.module_from_spec(spec)
spec.loader.exec_module(shard)
fail = 0
def check(name, ok):
global fail
print(("ok " if ok else "FAIL ") + name)
if not ok:
fail = 1
secs = {"A": 500, "B": 400, "C": 300, "D": 100, "E": 100}
parts, load = shard.shard(list(secs), secs, 2)
check("every name once", sorted(sum(parts, [])) == sorted(secs))
check("longest first, least loaded", parts == [["A", "D", "E"], ["B", "C"]] and load == [700, 700])
check("same split on every run", shard.shard(list(secs), secs, 2) == (parts, load))
parts, load = shard.shard(["A", "Z"], {"A": 10}, 2)
check("an unknown name counts as the default", load == [shard.DEFAULT, 10.0])
parts, _ = shard.shard(["A", "B"], {}, 4)
check("more shards than names leaves some empty", sum(len(p) for p in parts) == 2 and [] in parts)
with tempfile.TemporaryDirectory() as d:
names = os.path.join(d, "names.txt")
seconds = os.path.join(d, "seconds.txt")
with open(seconds, "w") as f:
f.write("# times\nTestA 30\nTestB 20\n")
with open(names, "w") as f:
f.write("# list\nTestA\nTestB # note\n\nTestC\n")
rc = subprocess.run([sys.executable, "-I", SCRIPT, names, seconds, "2", os.path.join(d, "out")], capture_output=True, text=True).returncode
got = sorted(open(os.path.join(d, "out", f)).read().split() for f in ("1.txt", "2.txt"))
check("the files hold every name once", rc == 0 and sorted(sum(got, [])) == ["TestA", "TestB", "TestC"])
with open(names, "w") as f:
f.write("TestA\nTestA\n")
rc = subprocess.run([sys.executable, "-I", SCRIPT, names, seconds, "2", os.path.join(d, "o2")], capture_output=True, text=True).returncode
check("a name listed twice is refused", rc == 2)
with open(names, "w") as f:
f.write("# nothing\n")
rc = subprocess.run([sys.executable, "-I", SCRIPT, names, seconds, "2", os.path.join(d, "o3")], capture_output=True, text=True).returncode
check("an empty list is refused", rc == 2)
sys.exit(fail)
-69
View File
@@ -1,69 +0,0 @@
"""Split the named process-level tests into N balanced shards.
Usage: shard-named-tests.py NAMES_FILE SECONDS_FILE N OUT_DIR
Writes OUT_DIR/1.txt .. OUT_DIR/N.txt, one test name per line. Every name in
NAMES_FILE (# starts a comment) lands in exactly one shard. SECONDS_FILE holds
"Name seconds" lines from an earlier run; a name missing there counts as
DEFAULT seconds. Longest first, each into the shard with the least time so
far (ties to the lowest shard), so the result is the same on every run.
Prints each shard's names count and its estimated seconds.
Exit 0, or 2 on a usage error, a duplicate name or an empty names list.
"""
import os
import sys
DEFAULT = 60.0
def names_of(path):
out = []
for line in open(path, encoding="utf-8"):
name = line.split("#", 1)[0].strip()
if name:
out.append(name)
return out
def seconds_of(path):
out = {}
for line in open(path, encoding="utf-8"):
fields = line.split("#", 1)[0].split()
if len(fields) == 2:
out[fields[0]] = float(fields[1])
return out
def shard(names, seconds, n):
load = [0.0] * n
shards = [[] for _ in range(n)]
for name in sorted(names, key=lambda x: (-seconds.get(x, DEFAULT), x)):
k = min(range(n), key=lambda i: (load[i], i))
shards[k].append(name)
load[k] += seconds.get(name, DEFAULT)
return shards, load
def main(argv):
if len(argv) != 5:
print(__doc__.strip().splitlines()[2], file=sys.stderr)
return 2
names = names_of(argv[1])
if not names or len(set(names)) != len(names):
print("shard-named-tests: empty names list or a name listed twice", file=sys.stderr)
return 2
n = int(argv[3])
if n < 1:
return 2
shards, load = shard(names, seconds_of(argv[2]), n)
os.makedirs(argv[4], exist_ok=True)
for i, part in enumerate(shards, 1):
with open(os.path.join(argv[4], "%d.txt" % i), "w", encoding="utf-8") as f:
f.write("".join(x + "\n" for x in part))
print("shard %d: %d tests, about %d s" % (i, len(part), load[i - 1]))
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
-151
View File
@@ -1,151 +0,0 @@
#!/usr/bin/env bash
# Self-test of the spec-trace check: PR descriptions and change lists against
# the exit code they must give.
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)
check=$here/spec-trace-check.sh
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
fail=0
# expect WANT_EXIT NAME BODY [STATUS PATH]...
expect() {
local want=$1 name=$2 body=$3 got=0
shift 3
printf '%s' "$body" >"$tmp/body"
if (($#)); then printf '%s\0' "$@"; fi | bash "$check" "$tmp/body" >/dev/null || got=$?
if [[ $got != "$want" ]]; then
echo "FAIL $name: exit $got, want $want"
fail=1
fi
}
ok='Feature: O-SNAP-2
Machine/INV: IMPL M5.Quiesce>Copy / INV-MAINT-ONE-OWNER
Model: docs/spec/MaintenanceOwner.tla, exhausted
Red-first: 7f542dbc TestMaintenanceHeldPass failed on base'
simplest='Simplest: one owner per volume on the existing cut path; no new machine.'
expect 0 "all four lines, docs only" "$ok" M docs/a.md
expect 0 "FIX kind" "${ok/IMPL M5.Quiesce>Copy/FIX INV-GC-SKEW-001}"
expect 0 "CHANGE kind" "${ok/IMPL M5.Quiesce>Copy/CHANGE M5}"
expect 0 "core change with Simplest" "$ok
$simplest" M core/storage/gc.go
expect 0 "core test only needs no Simplest" "$ok" M core/storage/gc_test.go
expect 0 "CRLF body" "$(printf '%s\n' "$ok" | sed 's/$/\r/')"
expect 0 "CHANGE of two machines" "${ok/IMPL M5.Quiesce>Copy/CHANGE M4, M6}"
expect 0 "list markers and bold keys" "$(printf '%s\n' "$ok" | sed "s/^Feature:/- **Feature:**/; s/^Model:/* Model:/")"
expect 0 "Model NONE with a reason" "${ok/Model: docs\/spec\/MaintenanceOwner.tla, exhausted/Model: NONE: CI wiring only, no state}"
expect 1 "empty body" ""
expect 1 "missing Red-first" "$(printf '%s\n' "$ok" | grep -v Red-first)"
expect 1 "short NONE" "${ok/Model: docs\/spec\/MaintenanceOwner.tla, exhausted/Model: NONE: n/a}"
expect 1 "no kind" "${ok/IMPL M5.Quiesce>Copy/B,D,E}"
expect 1 "IMPL without transition" "${ok/IMPL M5.Quiesce>Copy/IMPL M5}"
expect 1 "NONE is not a kind" "${ok/IMPL M5.Quiesce>Copy \/ INV-MAINT-ONE-OWNER/NONE: tooling only, no machine}"
expect 1 "core file deleted without Simplest" "$ok" D core/storage/old.go
expect 1 "two kinds" "${ok/IMPL M5.Quiesce>Copy/IMPL M5.Quiesce>Copy FIX INV-MAINT-ONE-OWNER}"
expect 1 "second Machine/INV line with another kind" "$ok
Machine/INV: FIX INV-MAINT-ONE-OWNER"
expect 1 "second Machine/INV line in list and bold form" "$ok
- **Machine/INV:** CHANGE M5"
expect 1 "Simplest declared twice" "$ok
$simplest
$simplest" M core/storage/gc.go
expect 1 "kind token with a trailing junk" "${ok/IMPL M5.Quiesce>Copy/FIX INV-GC-SKEW-001x}"
expect 1 "transition with a stray character" "${ok/IMPL M5.Quiesce>Copy/IMPL M5.Quiesce>Copy;x}"
expect 1 "key inside another word" "${ok/Feature: O-SNAP-2/Not-Feature: O-SNAP-2}"
expect 1 "placeholder left in Feature" "${ok/Feature: O-SNAP-2/Feature: <roadmap item>}"
expect 1 "placeholder left in Red-first" "$(printf '%s\n' "$ok" | sed "s/^Red-first:.*/Red-first: <commit + test>/")"
expect 1 "placeholder left in Simplest" "$ok
Simplest: <the simplest version, and what this PR did not add>" M core/storage/gc.go
expect 1 "unfilled template" "$(cat "$here/../pull_request_template.md")"
expect 1 "core change without Simplest" "$ok" M core/storage/gc.go
expect 1 "cmd change, short Simplest" "$ok
Simplest: small" A cmd/sw-block/new.go
# expect_raw WANT_EXIT NAME BYTES: a change list given as printf format.
expect_raw() {
local want=$1 name=$2 got=0
printf "%s" "$ok" >"$tmp/body"
printf "$3" | bash "$check" "$tmp/body" >/dev/null 2>&1 || got=$?
if [[ $got != "$want" ]]; then
echo "FAIL $name: exit $got, want $want"
fail=1
fi
}
expect_raw 2 "record cut off before its NUL" "M\0core/storage/gc.go"
expect_raw 2 "status without a path" "M\0"
expect_raw 2 "status cut off before its NUL" "M\0docs/a.md\0M"
expect_raw 2 "unknown status" "R100\0core/a.go\0"
expect_raw 0 "well-formed docs change" "M\0docs/a.md\0"
# Kinds for PRs that change no behaviour: each is checked against its paths;
# DOCS also compares the old and new tokens of each changed non-test Go file.
# expect_kind WANT_EXIT NAME KIND OLD_GO NEW_GO [STATUS PATH]...
# OLD_GO/NEW_GO are core/x/s.go before and after ("-" = no blob for that side).
expect_kind() {
local want=$1 name=$2 k=$3 old=$4 new=$5 got=0
shift 5
printf '%s' "${ok/IMPL M5.Quiesce>Copy/$k}
$simplest" >"$tmp/body"
rm -rf "$tmp/blobs"; mkdir -p "$tmp/blobs/old/core/x" "$tmp/blobs/new/core/x"
[[ $old == - ]] || printf '%s' "$old" >"$tmp/blobs/old/core/x/s.go"
[[ $new == - ]] || printf '%s' "$new" >"$tmp/blobs/new/core/x/s.go"
if (($#)); then printf '%s\0' "$@"; fi | bash "$check" "$tmp/body" "$tmp/blobs" >/dev/null || got=$?
if [[ $got != "$want" ]]; then
echo "FAIL $name: exit $got, want $want"
fail=1
fi
}
P=$'package x\n'
expect_kind 0 "DOCS: comment-only Go" DOCS "${P}var A = 1"$'\n' "${P}"$'// A is one.\nvar A = 1 // one\n' M docs/a.md M core/x/s.go A core/x/s_test.go
expect_kind 0 "DOCS: gofmt realignment" DOCS "${P}var A = 1"$'\n' "${P}var A = 1"$'\n' M core/x/s.go
expect_kind 0 "DOCS: block comment" DOCS "${P}var A = 1"$'\n' "${P}"$'/* doc */\nvar A = 1\n' M core/x/s.go
expect_kind 1 "DOCS: reorder" DOCS "${P}func f() { u(); p() }"$'\n' "${P}func f() { p(); u() }"$'\n' M core/x/s.go
expect_kind 1 "DOCS: build constraint comment" DOCS "$P" $'//go:build never\n\npackage x\n' M core/x/s.go
expect_kind 1 "DOCS: rune quote then // in a string" DOCS "${P}var _ = f('\"', \"http://a\")"$'\n' "${P}var _ = f('\"', \"http://b\")"$'\n' M core/x/s.go
expect_kind 1 "DOCS: line inside a raw string" DOCS "${P}var s = \`a"$'\n'"curl http://old | sh"$'\n'"\`"$'\n' "${P}var s = \`a"$'\n'"curl http://new | sh"$'\n'"\`"$'\n' M core/x/s.go
expect_kind 1 "DOCS: spaces inside a string" DOCS "${P}var s = \"a b\""$'\n' "${P}var s = \"a b\""$'\n' M core/x/s.go
expect_kind 1 "DOCS: cgo preamble" DOCS "${P}// #include <a.h>"$'\nimport "C"\n' "${P}// #include <b.h>"$'\nimport "C"\n' M core/x/s.go
expect_kind 1 "DOCS: cgo preamble, grouped import" DOCS "${P}// #include <a.h>"$'\nimport (\n\t"C"\n)\n' "${P}// #include <b.h>"$'\nimport (\n\t"C"\n)\n' M core/x/s.go
expect_kind 1 "DOCS: Go changed, no blob" DOCS - - M core/x/s.go
expect_kind 1 "DOCS: a model under docs/spec" DOCS - - M docs/spec/X.tla
expect_kind 1 "DOCS: a non-docs, non-Go file" DOCS - - M deploy/x.env
expect_kind 0 "TEST: tests and testdata" TEST - - M core/x/s_test.go A core/x/testdata/in.bin
expect_kind 1 "TEST: production Go" TEST - - M core/x/s.go
expect_kind 0 "TEST: a runner scenario only" TEST - - A testops/scenarios/gate.yaml
expect_kind 0 "TEST: a scenario next to tests" TEST - - M testops/scenarios/gate.yaml M core/x/s_test.go
expect_kind 1 "TEST: a scenario next to production Go" TEST - - M testops/scenarios/gate.yaml M core/x/s.go
expect_kind 1 "TEST: a script beside the scenarios" TEST - - A testops/scenarios/run.sh
expect_kind 1 "TEST: a yaml outside testops/scenarios" TEST - - M testops/gate.yaml
expect_kind 0 "CI: workflow" CI - - M .github/workflows/w.yml
expect_kind 1 "CI: scripts/ is shipped" CI - - A scripts/install.sh
expect_kind 1 "DOCS next to another kind" "DOCS FIX INV-X-001" - - M docs/a.md
# The workflow supplies its base-owned map as the third argument.
expect_map() {
local want=$1 name=$2 model=$3 got=0
shift 3
printf '%s\n%s\n' "${ok/Model: docs\/spec\/MaintenanceOwner.tla, exhausted/Model: $model}" "$simplest" >"$tmp/body"
if (($#)); then printf '%s\0' "$@"; fi |
bash "$check" "$tmp/body" "" "$tmp/map.tsv" >/dev/null 2>&1 || got=$?
if [[ $got != "$want" ]]; then
echo "FAIL $name: exit $got, want $want"
fail=1
fi
}
printf 'core/x/s.go\tEngineAdapter.Begin\ncore/y/s.go\tMoveAdmission.Revoke\n' >"$tmp/map.tsv"
expect_map 0 "mapped action" "EngineAdapter.Begin" M core/x/s.go
expect_map 0 "mapped pure function" "NONE (pure function of EngineAdapter)" M core/x/s.go
expect_map 0 "all mapped modules cited" "EngineAdapter.Begin; MoveAdmission.Revoke" M core/x/s.go M core/y/s.go
expect_map 1 "mapped file rejects old prose" "docs/spec/EngineAdapter.tla, exhausted" M core/x/s.go
expect_map 1 "deleted mapped file still needs model" "NONE: deletion has no new code" D core/x/s.go
expect_map 1 "one citation cannot cover another module" "EngineAdapter.Begin" M core/x/s.go M core/y/s.go
expect_map 0 "unmapped file keeps old policy" "docs/spec/EngineAdapter.tla, exhausted" M core/z/s.go
printf '# no canonical rows yet\n' >"$tmp/map.tsv"
expect_map 2 "empty map is not silently disabled" "EngineAdapter.Begin" M core/x/s.go
[[ $fail == 0 ]] && echo "spec-trace self-test: ok"
exit $fail
-171
View File
@@ -1,171 +0,0 @@
#!/usr/bin/env bash
# Usage: spec-trace-check.sh BODY_FILE [BLOBS] [MODEL_MAP] < changes
#
# Checks the spec trace in a PR description. changes are NUL-separated
# STATUS, PATH pairs (post-merge-review-changed.sh).
#
# - Feature:, Machine/INV:, Model: and Red-first: each start a line (after
# optional indentation, a list marker or bold) and carry a value that is not
# a template placeholder; "NONE:" needs a reason of at least 10 characters.
# - Machine/INV: starts with exactly one PR kind: "IMPL <machine>.<transition>",
# "FIX <INV-ID>", "CHANGE <machine>", or one of the kinds a PR that changes
# no behaviour may use, each checked against what it changes:
# DOCS (docs outside docs/spec/, tests, and non-test Go whose tokens are
# unchanged: BLOBS holds old/<path> and new/<path> for each changed non-test
# Go file, compared by sametokens.go), TEST (only tests, testdata, test
# helpers and runner scenarios, testops/scenarios/*.yaml), CI (only
# .github/). NONE is not a kind. Known limit: a docs file that is
# go:embed-ed into a binary changes behaviour under DOCS (none today).
# - Simplest: (20+ characters) is present when the PR adds, modifies or
# deletes non-test Go under core/ or cmd/.
#
# Prints every problem and exits 1 if there is one; exits 0 if none, 2 on a
# usage error or a malformed change list.
set -euo pipefail
body_file=${1:?usage: spec-trace-check.sh BODY_FILE [BLOBS] < changes}
blobs=${2-}
model_map=${3-}
here=$(cd "$(dirname "$0")" && pwd)
[[ -f $body_file ]] || { echo "spec-trace: body file $body_file missing" >&2; exit 2; }
body=$(tr -d '\r' <"$body_file")
# value KEY: the text after KEY on the first line that starts with KEY,
# trimmed. A key inside another word ("Not-Feature:") does not count.
value() {
local line
line=$(printf '%s\n' "$body" | grep -m1 -E "^[[:space:]]*([-*][[:space:]]+)?(\*\*)?$1" || true)
[[ -n $line ]] || return 0
line=${line#*"$1"}
line=${line#\*\*}
line=${line#"${line%%[![:space:]]*}"}
printf '%s' "${line%"${line##*[![:space:]]}"}"
}
bad=0
problem() { echo "spec-trace: $1"; bad=1; }
# Each trace line is declared once: a second Machine/INV line could carry a
# second kind past the check.
for key in Feature: Machine/INV: Model: Red-first: Simplest:; do
n=$(printf '%s\n' "$body" | grep -cE "^[[:space:]]*([-*][[:space:]]+)?(\*\*)?$key" || true)
((n <= 1)) || problem "$key is declared $n times; declare it once"
done
for key in Feature: Machine/INV: Model: Red-first:; do
v=$(value "$key")
if [[ -z $v ]]; then
problem "missing or empty $key"
elif [[ $v == '<'* ]]; then
problem "$key still holds the template placeholder"
elif [[ $v == NONE:* ]]; then
r=${v#NONE:}
r=${r#"${r%%[![:space:]]*}"}
((${#r} >= 10)) || problem "$key NONE needs a reason of at least 10 characters"
fi
done
# One kind token, ending at the line end, a space, a comma or a slash.
end='($|[[:space:],/])'
kind_re="^(IMPL [A-Za-z0-9_]+[.][A-Za-z0-9_>.-]+|FIX INV-[A-Z0-9]+(-[A-Z0-9]+)*|CHANGE [A-Za-z0-9_]+|DOCS|TEST|CI)$end"
kind=""
mi=$(value Machine/INV:)
if [[ -n $mi && $mi != '<'* ]]; then
if [[ ! $mi =~ $kind_re ]]; then
problem "Machine/INV: must start with IMPL <machine>.<transition>, FIX <INV-ID>, CHANGE <machine>, DOCS, TEST or CI"
else
token=${BASH_REMATCH[1]}
if [[ ${mi#"${BASH_REMATCH[0]}"} =~ (^|[^A-Za-z0-9_])(IMPL|FIX|CHANGE|DOCS|TEST|CI)([^A-Za-z0-9_]|$) ]]; then
problem "Machine/INV: names more than one kind; a PR is exactly one kind"
else
kind=${token%% *}
fi
fi
fi
# A runner scenario under testops/scenarios/ is a test definition.
is_test() { [[ $1 == *_test.go || $1 == testdata/* || $1 == */testdata/* || $1 == */testutil/* || $1 == testops/scenarios/*.yaml ]]; }
# docs/spec holds the models: changing one is not a docs change.
is_doc() { [[ $1 != docs/spec/* ]] && [[ $1 == *.md || $1 == docs/* ]]; }
core=0
paths=()
while IFS= read -r -d '' status; do
[[ $status == [ADMT] ]] || { echo "spec-trace: malformed change list: status ${status@Q}" >&2; exit 2; }
IFS= read -r -d '' path || { echo "spec-trace: malformed change list: status $status without a path" >&2; exit 2; }
[[ -n $path ]] || { echo "spec-trace: malformed change list: empty path" >&2; exit 2; }
paths+=("$path")
if [[ $path == core/*.go || $path == cmd/*.go ]] && [[ $path != *_test.go ]]; then
core=1
fi
done
# A record cut off before its NUL is malformed, not skipped.
[[ -z ${status-} ]] || { echo "spec-trace: malformed change list: unterminated record" >&2; exit 2; }
if [[ -n $model_map ]]; then
model_status=0
{ if ((${#paths[@]})); then printf '%s\0' "${paths[@]}"; fi; } |
"${PYTHON:-python3}" -B "$here/model-trace-check.py" "$model_map" "$(value Model:)" || model_status=$?
case $model_status in
0) ;;
1) bad=1 ;;
*) exit "$model_status" ;;
esac
fi
if ((core)); then
s=$(value Simplest:)
if ((${#s} < 20)) || [[ $s == '<'* ]]; then
problem "Simplest: (20+ characters) is required when non-test Go under core/ or cmd/ changes"
fi
fi
case $kind in
CI)
for p in ${paths[@]+"${paths[@]}"}; do
[[ $p == .github/* ]] || problem "kind CI: $p is outside .github/ (scripts/ holds shipped install and deploy scripts)"
done
;;
TEST)
for p in ${paths[@]+"${paths[@]}"}; do
is_test "$p" || problem "kind TEST: $p is not a test, testdata or test helper"
done
;;
DOCS)
gofiles=()
for p in ${paths[@]+"${paths[@]}"}; do
if is_doc "$p" || is_test "$p"; then continue; fi
if [[ $p == *.go ]]; then gofiles+=("$p"); continue; fi
problem "kind DOCS: $p is neither docs, a test, nor Go"
done
if ((${#gofiles[@]})); then
if [[ -z $blobs || ! -d $blobs ]]; then
problem "kind DOCS: non-test Go changed but no old/new blobs were given to compare"
else
# Built here, not run with "go run": that would take the .go
# arguments as more source files of the program.
bin=$(mktemp -d)
trap 'rm -rf "$bin"' EXIT
if ! go build -o "$bin/sametokens" "$here/sametokens.go"; then
echo "spec-trace: could not build sametokens.go; the DOCS check did not run" >&2
exit 2
fi
for p in "${gofiles[@]}"; do
if [[ ! -e $blobs/old/$p && ! -e $blobs/new/$p ]]; then
problem "kind DOCS: $p has no old or new blob, so it was not compared"
continue
fi
rc=0
"$bin/sametokens" "$blobs/old/$p" "$blobs/new/$p" >/dev/null || rc=$?
case $rc in
0) ;;
1) problem "kind DOCS: $p changes more than comments (its Go tokens differ)" ;;
*)
echo "spec-trace: sametokens failed on $p (exit $rc); the DOCS check did not run" >&2
exit 2
;;
esac
done
fi
fi
;;
esac
exit $bad
-52
View File
@@ -1,52 +0,0 @@
"""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()
-55
View File
@@ -1,55 +0,0 @@
"""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))
-53
View File
@@ -1,53 +0,0 @@
name: 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:
permissions:
contents: read
jobs:
known-bugs:
name: known-bug reproductions still fail
runs-on: tp04-seaweed-block
timeout-minutes: 15
env:
CGO_ENABLED: "0"
SEAWEED_KNOWN_BUGS: "1"
steps:
- 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: 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
#187 ./cmd/blockmaster/ TestChartDefaultAuthorityStateSurvivesPodReplacement
LIST
-53
View File
@@ -1,53 +0,0 @@
name: 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.
#
# A read-only pull_request run executes validators and the allow list from
# a separate base-commit checkout. The PR head is inspected only as objects.
on:
pull_request:
# edited: a retarget changes the base, and with it the diff.
types: [opened, synchronize, reopened, labeled, unlabeled, edited]
permissions:
contents: read
concurrency:
group: post-merge-review-${{ github.event.pull_request.number }}
cancel-in-progress: true
jobs:
paths:
name: post-merge-review paths
# Forks and same-repository PRs use the same disposable runner.
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- name: Not labelled
if: ${{ !contains(github.event.pull_request.labels.*.name, 'post-merge-review') }}
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 }}
path: trusted-base
fetch-depth: 0
persist-credentials: false
- name: Check changed paths
working-directory: trusted-base
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/scripts/post-merge-review-changed.sh "$BASE" "$HEAD" >changed.bin
bash .github/scripts/post-merge-review-check.sh .github/post-merge-review-allow.txt <changed.bin
-104
View File
@@ -1,104 +0,0 @@
name: Publish alpha images
on:
workflow_dispatch:
push:
tags:
- "v*"
permissions:
contents: write
packages: write
env:
REGISTRY: ghcr.io
BLOCK_IMAGE: ghcr.io/seaweedfs/seaweed-block
CSI_IMAGE: ghcr.io/seaweedfs/seaweed-block-csi
jobs:
publish:
# Publish only from a version tag; a manual run from a branch must not move :alpha.
if: startsWith(github.ref, 'refs/tags/v')
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0 # the tag list decides whether :alpha moves
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Log in to GHCR
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Compute image tags
id: tags
shell: bash
run: |
set -euo pipefail
# vX.Y.Z-pre (a release candidate) publishes only its own version tag. A stable vX.Y.Z also
# publishes sha-*, and moves :alpha only when it is the highest stable version tag, so a later
# patch on an older line never moves :alpha back.
short_sha="${GITHUB_SHA::12}"
version="${GITHUB_REF_NAME}"
if [[ ! "${version}" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.]+)?$ ]]; then
echo "refusing to publish: tag ${version} is not vX.Y.Z or vX.Y.Z-pre" >&2
exit 1
fi
stable=false
move_alpha=false
if [[ "${version}" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
stable=true
highest="$(git tag -l 'v*' | 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<<EOF"
echo "${BLOCK_IMAGE}:${version}"
if [[ "${stable}" == true ]]; then echo "${BLOCK_IMAGE}:sha-${short_sha}"; fi
if [[ "${move_alpha}" == true ]]; then echo "${BLOCK_IMAGE}:alpha"; fi
echo "EOF"
echo "csi_tags<<EOF"
echo "${CSI_IMAGE}:${version}"
if [[ "${stable}" == true ]]; then echo "${CSI_IMAGE}:sha-${short_sha}"; fi
if [[ "${move_alpha}" == true ]]; then echo "${CSI_IMAGE}:alpha"; fi
echo "EOF"
} >> "$GITHUB_OUTPUT"
- name: Release asset controls
run: python3 -I .github/scripts/release-binary-assets-test.py
- name: Build and push block image
id: block
uses: docker/build-push-action@v6
with:
context: .
file: deploy/k8s/g15b/Dockerfile.sw-block
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: deploy/k8s/g15b/Dockerfile.blockcsi
push: true
tags: ${{ steps.tags.outputs.csi_tags }}
- name: Attach matching Linux binaries to the release
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
BLOCK_DIGEST: ${{ steps.block.outputs.digest }}
run: |
set -euo pipefail
revision=$(git rev-parse HEAD)
bash .github/scripts/release-binary-assets.sh "${BLOCK_IMAGE}@${BLOCK_DIGEST}" \
"$revision" "$GITHUB_REF_NAME" "$RUNNER_TEMP/block-release"
-82
View File
@@ -1,82 +0,0 @@
name: spec trace
# Every PR description carries the spec trace (see the PR template); this
# check fails a PR whose description does not.
#
# A read-only pull_request run checks out the event's base commit into its
# own directory. Validators and data come from that checkout; the PR head
# is fetched only as Git objects. The body is passed as data, not shell code.
on:
pull_request:
# edited: the check reads the description and the base.
types: [opened, synchronize, reopened, edited]
permissions:
contents: read
concurrency:
group: spec-trace-${{ github.event.pull_request.number }}
cancel-in-progress: true
jobs:
trace:
name: spec trace
# Both same-repository and fork PRs use disposable hosted runners.
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- name: Checkout base
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
with:
ref: ${{ github.event.pull_request.base.sha }}
path: trusted-base
fetch-depth: 0
persist-credentials: false
# The token-comparison helper is built from the base checkout too.
- name: Set up Go
uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0
with:
go-version-file: trusted-base/go.mod
cache: false
- name: Check spec trace
working-directory: trusted-base
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/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/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 <changed.bin
# Internal names stay out of this public repository: added lines,
# commit messages, title and description (no PR code is run).
bash .github/scripts/public-text-check-test.sh
printf '%s' "$TITLE" >title.txt
bash .github/scripts/public-text-check.sh "$mb" "$HEAD" title.txt body.txt
- name: Invariants ledger anchors (report only)
working-directory: trusted-base
# 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/scripts/ledger_check.py . "$HEAD" || true
Loaded 100 of 4691 files, more files were not shown because too many files have changed in this diff. Show more