Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Admit reconstructible stable patches on version-bound release branches

pulse-triage[bot]16a783ec361f
diff --git a/.github/workflows/canonical-governance.yml b/.github/workflows/canonical-governance.yml
index 517fdb31cf..b13f515c13 100644
--- a/.github/workflows/canonical-governance.yml
+++ b/.github/workflows/canonical-governance.yml
@@ -203,6 +203,9 @@ jobs:
- name: Run release promotion policy unit tests
run: python3 scripts/release_control/release_promotion_policy_test.py
+ - name: Verify mechanical stable patch source
+ run: python3 scripts/release_control/stable_patch_test.py
+
- name: Run release convergence reconciler unit tests
run: python3 scripts/release_control/reconcile_release_convergence_test.py
diff --git a/.github/workflows/create-release.yml b/.github/workflows/create-release.yml
index ee3f525c00..7912e97807 100644
--- a/.github/workflows/create-release.yml
+++ b/.github/workflows/create-release.yml
@@ -247,6 +247,21 @@ jobs:
python3 scripts/write_github_output.py required_branch "${REQUIRED_BRANCH}"
echo "[OK] Governed release branch for ${WORKFLOW_OUTPUT_1} is ${REQUIRED_BRANCH}"
+ - name: Reconstruct stable patch source
+ if: ${{ startsWith(steps.extract.outputs.source_branch, 'release/v') }}
+ env:
+ PATCH_VERSION: ${{ steps.extract.outputs.version }}
+ PATCH_SOURCE_BRANCH: ${{ steps.extract.outputs.source_branch }}
+ run: |
+ # Historical minor lines predate the mechanical stable-patch path.
+ if [[ "${PATCH_SOURCE_BRANCH}" =~ ^release/v[0-9]+\.[0-9]+\.[1-9][0-9]*$ ]]; then
+ IFS=. read -r PATCH_MAJOR PATCH_MINOR PATCH_NUMBER <<< "${PATCH_SOURCE_BRANCH#release/v}"
+ if (( PATCH_MAJOR > 6 || (PATCH_MAJOR == 6 && PATCH_MINOR >= 5) )); then
+ python3 scripts/release_control/stable_patch.py validate \
+ --version "${PATCH_VERSION}" --source-branch "${PATCH_SOURCE_BRANCH}"
+ fi
+ fi
+
- name: Validate release-note visual plan
id: visual_plan
env:
diff --git a/.gitignore b/.gitignore
index fecdcf449f..4ec1aaba5e 100644
--- a/.gitignore
+++ b/.gitignore
@@ -235,6 +235,8 @@ scripts/release_control/*
!scripts/release_control/control_plane.py
!scripts/release_control/release_snapshot.py
!scripts/release_control/release_snapshot_test.py
+!scripts/release_control/stable_patch.py
+!scripts/release_control/stable_patch_test.py
!scripts/release_control/generate_platform_support_frontend_module.py
!scripts/release_control/control_plane_audit.py
!scripts/release_control/control_plane_audit_test.py
diff --git a/docs/release-control/v6/internal/HIGH_RISK_RELEASE_VERIFICATION_MATRIX.md b/docs/release-control/v6/internal/HIGH_RISK_RELEASE_VERIFICATION_MATRIX.md
index 04472457be..05a8f19cfb 100644
--- a/docs/release-control/v6/internal/HIGH_RISK_RELEASE_VERIFICATION_MATRIX.md
+++ b/docs/release-control/v6/internal/HIGH_RISK_RELEASE_VERIFICATION_MATRIX.md
@@ -1354,3 +1354,16 @@ as verification progresses:
boot-logger/foreground adverse control and detached launch; the production
NAS removal inventory consumes this writer. These are source fixtures, not
native Unraid lifecycle or original installed-recovery acceptance.
+
+
+## Mechanical stable patch source reconstruction
+
+- `stable_patch_test.py` uses real disposable Git history for whole merge results,
+ skipped conflicts followed by clean fixes, successive patch bases, exact control
+ copies and rejection of unrelated or tampered source. Canonical CI runs it.
+- `release_snapshot_test.py` keeps reviewed-head/target/repository ancestry binding
+ on version-bound patch targets. `control_plane_audit_test.py` preserves minor and
+ historical mappings while deriving new patch branches.
+- Source reconstruction is not private payload compatibility, successful signing,
+ a published patch or installed forward/reverse recovery. The infrastructure
+ train's no-publication rehearsal and independent exact-head CI are separate.
diff --git a/docs/release-control/v6/internal/subsystems/deployment-installability.md b/docs/release-control/v6/internal/subsystems/deployment-installability.md
index f8c7323624..26bdbbb131 100644
--- a/docs/release-control/v6/internal/subsystems/deployment-installability.md
+++ b/docs/release-control/v6/internal/subsystems/deployment-installability.md
@@ -15,6 +15,30 @@
```
## Purpose
+### Mechanical stable patch source admission
+
+Stable-regression patches are the sole main-only release exception. The release
+train selects complete main pull-request merge results that GitHub records as
+closing labelled issues, once per fix, in merge order. A disposable checkout
+starts at the current stable tag, skips only genuine content conflicts and
+copies all `.github/workflows/` and `scripts/release_control/` bytes at its fixed
+main cut. No unrelated source is added. The patch's exact Enterprise pair stays
+at the one shipped by that stable.
+
+`scripts/release_control/stable_patch.py` records and independently reconstructs
+that selection. `create-release.yml` runs reconstruction before payload creation.
+It rejects wrong tags, out-of-order or foreign merge results, changed controls
+and every extra non-metadata source byte. Version-bound `release/vX.Y.Z` targets
+are admitted by `control_plane.py` and `release_snapshot.py`; reviewed head,
+canonical repository, merged target and ancestry checks remain mandatory. Only
+rc.1 and its unchanged stable promotion use the new path. Minor releases and
+historical line mappings retain their existing source rules.
+
+The public guard proves source composition, not GitHub label collection, signing,
+installation, publication or host activation. The train's independent patch state
+owns selection, bounded retries, soak, abandonment, retirement and keeping the
+weekly minor's clock and progress unchanged.
+
### Unraid boot replacement preserves operator work
Agent setup/upgrade replaces only complete exact generated top-level go entries.
diff --git a/docs/release-control/v6/internal/subsystems/registry.json b/docs/release-control/v6/internal/subsystems/registry.json
index 15a4c3e940..93dbec5cc7 100644
--- a/docs/release-control/v6/internal/subsystems/registry.json
+++ b/docs/release-control/v6/internal/subsystems/registry.json
@@ -4676,6 +4676,9 @@
".github/workflows/test-e2e.yml",
".github/workflows/update-demo-server.yml",
".github/workflows/validate-release-assets.yml",
+ "Dockerfile",
+ "Makefile",
+ "VERSION",
"cmd/pulse-control-plane/main.go",
"cmd/pulse-control-plane/provider_msp.go",
"cmd/pulse-control-plane/provider_msp_backup.go",
@@ -4685,13 +4688,12 @@
"cmd/pulse-control-plane/provider_msp_recover.go",
"cmd/pulse-control-plane/provider_msp_status.go",
"docker-compose.yml",
- "Dockerfile",
"docs/MSP.md",
+ "docs/RELEASE_NOTES.md",
+ "docs/UPGRADE_v6.md",
"docs/release-control/v6/internal/PRE_RELEASE_CHECKLIST.md",
"docs/release-control/v6/internal/RC_TO_GA_REHEARSAL_TEMPLATE.md",
"docs/release-control/v6/internal/RELEASE_PROMOTION_POLICY.md",
- "docs/RELEASE_NOTES.md",
- "docs/UPGRADE_v6.md",
"frontend-modern/package-lock.json",
"frontend-modern/package.json",
"frontend-modern/public/docs/MSP.md",
@@ -4712,7 +4714,6 @@
"internal/cloudcp/provider_msp_backup.go",
"internal/cloudcp/provider_msp_recovery.go",
"internal/cloudcp/tenant_runtime_rollout.go",
- "Makefile",
"package-lock.json",
"package.json",
"pulse-enterprise:.github/workflows/build-pro-release.yml",
@@ -4760,10 +4761,12 @@
"scripts/release_asset_common.sh",
"scripts/release_build_targets.sh",
"scripts/release_candidate_manifest.py",
+ "scripts/release_control/control_plane.py",
"scripts/release_control/customer_promotion_lease.sh",
"scripts/release_control/internal/record_rc_to_ga_rehearsal.py",
"scripts/release_control/record_rc_to_ga_rehearsal.py",
"scripts/release_control/release_promotion_policy_support.py",
+ "scripts/release_control/release_snapshot.py",
"scripts/release_control/render_release_body.py",
"scripts/release_control/resolve_release_promotion.py",
"scripts/release_control/secure_runtime_attestation_v6.py",
@@ -4774,6 +4777,7 @@
"scripts/release_control/secure_runtime_rootless_source_manifest_v1.json",
"scripts/release_control/secure_runtime_source_manifest_v6.json",
"scripts/release_control/secure_runtime_source_manifest_v7.json",
+ "scripts/release_control/stable_patch.py",
"scripts/release_control/validate_artifact_release_line.py",
"scripts/release_ldflags.sh",
"scripts/release_lifecycle_rehearsal.sh",
@@ -4794,10 +4798,10 @@
"scripts/uninstall-sensor-proxy.sh",
"scripts/validate-release.sh",
"scripts/verify-github-release-integrity.sh",
- "tests/integration/docker-compose.test.yml",
- "tests/integration/playwright.config.ts",
"tests/integration/QUICK_START.md",
"tests/integration/README.md",
+ "tests/integration/docker-compose.test.yml",
+ "tests/integration/playwright.config.ts",
"tests/integration/scripts/bootstrap-hosted-mobile-onboarding.mjs",
"tests/integration/scripts/hosted-mobile-token-runtime.mjs",
"tests/integration/scripts/hosted-tenant-runtime.mjs",
@@ -4807,8 +4811,7 @@
"tests/integration/scripts/settings-scroll-audit.mjs",
"tests/integration/tests/helpers.ts",
"tests/integration/tests/runtime-defaults.ts",
- "tests/integration/tests/vmware-workload-fixture.ts",
- "VERSION"
+ "tests/integration/tests/vmware-workload-fixture.ts"
],
"release_cycle_artifact_globs": [
"docs/RELEASE_NOTES.md",
@@ -4996,6 +4999,7 @@
"scripts/release_control/release_promotion_policy_test.py",
"scripts/release_control/render_release_body_test.py",
"scripts/release_control/resolve_release_promotion_test.py",
+ "scripts/release_control/stable_patch_test.py",
"scripts/release_control/validate_artifact_release_line_test.py",
"scripts/release_control/verify_github_release_integrity_test.py"
]
@@ -5485,6 +5489,23 @@
"tests/integration/scripts/settings-scroll-audit.test.mjs",
"tests/integration/tests/05-settings-mobile-audit.spec.ts"
]
+ },
+ {
+ "id": "mechanical-stable-patch-source",
+ "label": "exact merge-result stable patch reconstruction proof",
+ "match_prefixes": [],
+ "match_files": [
+ "scripts/release_control/stable_patch.py",
+ "scripts/release_control/control_plane.py",
+ "scripts/release_control/release_snapshot.py"
+ ],
+ "allow_same_subsystem_tests": false,
+ "test_prefixes": [],
+ "exact_files": [
+ "scripts/release_control/stable_patch_test.py",
+ "scripts/release_control/control_plane_audit_test.py",
+ "scripts/release_control/release_snapshot_test.py"
+ ]
}
],
"match_files": null
diff --git a/scripts/release_control/control_plane.py b/scripts/release_control/control_plane.py
index 6d11184fed..6c70155cf4 100644
--- a/scripts/release_control/control_plane.py
+++ b/scripts/release_control/control_plane.py
@@ -470,6 +470,12 @@ def release_branch_for_version(
if is_prerelease_version(version)
else legacy_release_line["stable_branch"]
)
+ # Stable patches are the sole mechanical exception to main-only releases.
+ # Historical mappings above stay intact. Each new patch has its own frozen
+ # target branch; the release snapshot guard also reconstructs its source.
+ patch = re.fullmatch(r"v?(\d+)\.(\d+)\.([1-9]\d*)(?:-rc\.1)?", version)
+ if patch and tuple(map(int, patch.groups())) >= (6, 5, 1):
+ return "release/v" + ".".join(patch.groups())
return resolved["prerelease_branch"] if is_prerelease_version(version) else resolved["stable_branch"]
diff --git a/scripts/release_control/control_plane_audit_test.py b/scripts/release_control/control_plane_audit_test.py
index 5d6a64e495..0852e89057 100644
--- a/scripts/release_control/control_plane_audit_test.py
+++ b/scripts/release_control/control_plane_audit_test.py
@@ -237,13 +237,21 @@ class ControlPlaneAuditTest(unittest.TestCase):
"v6.4.6-rc.1", "6.4.6", "v6.4.6+build.1"):
with self.subTest(version=version):
self.assertEqual(release_branch_for_version(version), "release/v6.4")
- # Every release from 6.5.0 on is cut from main (founder direction,
- # 2 October 2026), so later versions need no release-line entry.
+ # Minor releases remain on main. Mechanical patches are the sole
+ # version-bound branch exception (26 October 2026).
for version in ("6.4.1", "6.4.2", "6.4.7-rc.1", "6.4.60-rc.1", "6.4.50-beta.1", "6.4.40-beta.1",
"6.4.30", "6.3.20", "6.5.0-rc.1", "6.5.0", "6.5.10-beta.1", "6.6.0-beta.1"):
with self.subTest(version=version):
self.assertEqual(release_branch_for_version(version), "main")
+ def test_mechanical_patch_uses_its_exact_version_branch(self) -> None:
+ for version in ("6.6.1-rc.1", "6.6.1", "v6.6.1", "6.6.12-rc.1"):
+ with self.subTest(version=version):
+ core = version.removeprefix("v").removesuffix("-rc.1")
+ self.assertEqual("release/v" + core, release_branch_for_version(version))
+ self.assertEqual("main", release_branch_for_version("6.7.0-rc.1"))
+ self.assertEqual("main", release_branch_for_version("6.7.0"))
+
def test_forward_patch_workflow_branch_contract(self) -> None:
# Execute the real branch-policy shell only, never dispatch a workflow.
for workflow in ("create-release.yml", "release-dry-run.yml"):
diff --git a/scripts/release_control/release_snapshot.py b/scripts/release_control/release_snapshot.py
index 153deea0d8..8af5c72cb9 100644
--- a/scripts/release_control/release_snapshot.py
+++ b/scripts/release_control/release_snapshot.py
@@ -16,7 +16,7 @@ SNAPSHOT_REF = re.compile(r"release-candidate/[0-9A-Za-z._-]+")
# them, so the release environment can admit them while unmerged
# release-candidate heads stay outside it. Each mirrors its PR's head name.
DISPATCH_REF = re.compile(r"release-dispatch/([0-9A-Za-z._-]+)")
-SOURCE_BRANCH = re.compile(r"main|release/v[0-9]+\.[0-9]+")
+SOURCE_BRANCH = re.compile(r"main|release/v[0-9]+\.[0-9]+(?:\.[1-9][0-9]*)?")
def snapshot_head(branch: str) -> str:
diff --git a/scripts/release_control/release_snapshot_test.py b/scripts/release_control/release_snapshot_test.py
index aeabf55b67..73989c4f7d 100644
--- a/scripts/release_control/release_snapshot_test.py
+++ b/scripts/release_control/release_snapshot_test.py
@@ -68,6 +68,19 @@ class SnapshotIdentityTest(unittest.TestCase):
with self.subTest(branch=branch), self.assertRaises(ValueError):
snapshot.snapshot_head(branch)
+ def test_patch_snapshot_requires_its_reviewed_version_bound_target(self):
+ ref = 'refs/heads/release-dispatch/v6.6.1-rc.1-stamp'
+ branch = 'release/v6.6.1'
+ self.assertEqual(branch, snapshot.source_branch(ref, branch, '42'))
+ pr = deepcopy(self.pr)
+ pr['head']['ref'] = 'release-candidate/v6.6.1-rc.1-stamp'
+ pr['base']['ref'] = branch
+ self.assertEqual(self.merge, snapshot.reviewed_merge(
+ pr, repository='rcourtman/Pulse', ref=ref, branch=branch, sha=self.sha))
+ with self.assertRaises(ValueError):
+ snapshot.reviewed_merge(pr, repository='rcourtman/Pulse', ref=ref,
+ branch='release/v6.6.2', sha=self.sha)
+
def test_unbound_dispatch_inputs_are_rejected(self):
dispatch = 'refs/heads/release-dispatch/packet-1'
for args in [(self.ref, '', '42'), (self.ref, 'main', ''),
diff --git a/scripts/release_control/stable_patch.py b/scripts/release_control/stable_patch.py
new file mode 100644
index 0000000000..5a20796c81
--- /dev/null
+++ b/scripts/release_control/stable_patch.py
@@ -0,0 +1,180 @@
+#!/usr/bin/env python3
+"""Reconstruct a mechanical stable patch. No network, provider or publication operations.
+
+The train supplies GitHub's closing-PR selection. Admission reconstructs that
+selection again and admits only release metadata on top, never other main work.
+"""
+from __future__ import annotations
+
+import argparse
+import json
+from pathlib import Path
+import re
+import subprocess
+import tempfile
+import sys
+
+sys.dont_write_bytecode = True
+
+SHA = re.compile(r"[0-9a-f]{40}")
+VERSION = re.compile(r"(\d+)\.(\d+)\.([1-9]\d*)")
+CONTROLS = (".github/workflows", "scripts/release_control")
+SCHEMA = 1
+
+
+def git(root: Path, *args: str, check: bool = True) -> subprocess.CompletedProcess:
+ return subprocess.run(["git", "-c", "core.hooksPath=/dev/null", "-c", "user.name=Pulse release",
+ "-c", "user.email=release@invalid", "-C", str(root), *args],
+ text=True, capture_output=True, check=check)
+
+
+def value(root: Path, *args: str) -> str:
+ return git(root, *args).stdout.strip()
+
+
+def manifest_path(version: str) -> str:
+ if not VERSION.fullmatch(version):
+ raise ValueError("a stable patch needs X.Y.Z with a positive patch number")
+ return f"docs/releases/PATCH_v{version}.json"
+
+
+def validate_selection(root: Path, selection: dict) -> None:
+ if set(selection) != {"schema_version", "version", "stable_tag", "stable_sha", "control_sha", "fixes"}:
+ raise ValueError("invalid patch selection fields")
+ if selection["schema_version"] != SCHEMA:
+ raise ValueError("unsupported patch selection schema")
+ manifest_path(selection["version"])
+ major, minor, patch = map(int, selection["version"].split("."))
+ if selection["stable_tag"] != f"v{major}.{minor}.{patch - 1}":
+ raise ValueError("a patch must immediately follow its stable base")
+ for key in ("stable_sha", "control_sha"):
+ if not isinstance(selection[key], str) or not SHA.fullmatch(selection[key]):
+ raise ValueError(f"invalid {key}")
+ if value(root, "rev-parse", selection["stable_tag"] + "^{commit}") != selection["stable_sha"]:
+ raise ValueError("stable tag does not identify the selected stable source")
+ git(root, "merge-base", selection["stable_sha"], selection["control_sha"])
+ fixes = selection["fixes"]
+ if not isinstance(fixes, list) or not fixes:
+ raise ValueError("a patch needs at least one closing pull request")
+ # First-parent order is the order merge results reached main, including squashes.
+ order = value(root, "rev-list", "--first-parent", "--reverse",
+ f"{selection['stable_sha']}..{selection['control_sha']}").splitlines()
+ indices = []
+ seen = set()
+ for fix in fixes:
+ if (not isinstance(fix, dict) or set(fix) != {"number", "merge_sha", "issues"}
+ or type(fix["number"]) is not int or fix["number"] <= 0
+ or fix["number"] in seen or not SHA.fullmatch(fix.get("merge_sha", ""))
+ or not isinstance(fix["issues"], list) or not fix["issues"]
+ or any(type(n) is not int or n <= 0 for n in fix["issues"])):
+ raise ValueError("invalid or duplicate closing-PR identity")
+ seen.add(fix["number"])
+ if fix["merge_sha"] not in order:
+ raise ValueError("fix is not an unshipped first-parent merge result on selected main")
+ indices.append(order.index(fix["merge_sha"]))
+ if indices != sorted(set(indices)):
+ raise ValueError("fixes are not in merge order")
+
+
+def commit(root: Path, message: str) -> None:
+ git(root, "commit", "--quiet", "--allow-empty", "-m", message)
+
+
+def assemble(root: Path, selection: dict) -> dict:
+ """Apply whole merge results, skip only actual conflicts, then copy exact controls."""
+ validate_selection(root, selection)
+ if value(root, "status", "--porcelain"):
+ raise ValueError("patch assembly requires a clean disposable checkout")
+ git(root, "checkout", "--quiet", "--detach", selection["stable_sha"])
+ applied, skipped = [], []
+ for fix in selection["fixes"]:
+ before = value(root, "rev-parse", "HEAD")
+ parents = value(root, "rev-list", "--parents", "-n", "1", fix["merge_sha"]).split()[1:]
+ args = ["cherry-pick", "--no-commit"]
+ if len(parents) > 1:
+ args += ["-m", "1"]
+ result = git(root, *args, fix["merge_sha"], check=False)
+ if result.returncode:
+ conflicts = value(root, "diff", "--name-only", "--diff-filter=U").splitlines()
+ # No empty/error/authentication failure is reclassified as a conflict.
+ if not conflicts:
+ raise ValueError(f"merge result #{fix['number']} failed without a content conflict")
+ git(root, "reset", "--hard", before)
+ git(root, "cherry-pick", "--quit", check=False)
+ skipped.append({**fix, "conflicts": conflicts})
+ continue
+ commit(root, f"Apply the merged fix from #{fix['number']}\n\nMerge-result: {fix['merge_sha']}")
+ applied.append(fix)
+ git(root, "restore", "--source=" + selection["control_sha"], "--staged", "--worktree", "--", *CONTROLS)
+ commit(root, "Use the reviewed release controls at " + selection["control_sha"])
+ receipt = {**selection, "applied": applied, "skipped": skipped,
+ "assembled_tree": value(root, "rev-parse", "HEAD^{tree}")}
+ target = root / manifest_path(selection["version"])
+ # Do not write through an archive's symlink or a parent directory symlink.
+ if not target.resolve().is_relative_to(root.resolve()) or target.is_symlink():
+ raise ValueError("patch manifest path escapes its disposable checkout")
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text(json.dumps(receipt, indent=2, sort_keys=True) + "\n")
+ git(root, "add", "--", manifest_path(selection["version"]))
+ commit(root, "Record the mechanical stable patch source selection")
+ return receipt
+
+
+def validate(root: Path, version: str, source_branch: str) -> dict:
+ """Rebuild the source tree and reject every extra byte outside release metadata."""
+ core = version.removeprefix("v").removesuffix("-rc.1")
+ if version.removeprefix("v") not in (core, core + "-rc.1"):
+ raise ValueError("a stable patch uses only rc.1 and its unchanged stable promotion")
+ if source_branch != "release/v" + core:
+ raise ValueError("stable patch is not on its version-bound release branch")
+ receipt = json.loads((root / manifest_path(core)).read_text())
+ selection = {key: receipt[key] for key in
+ ("schema_version", "version", "stable_tag", "stable_sha", "control_sha", "fixes")}
+ if selection["version"] != core:
+ raise ValueError("patch manifest belongs to another version")
+ validate_selection(root, selection)
+ # Source/workflow controls must have been protected on main, not a foreign branch.
+ git(root, "merge-base", "--is-ancestor", selection["control_sha"], "refs/remotes/origin/main")
+ head = value(root, "rev-parse", "HEAD")
+ with tempfile.TemporaryDirectory(prefix="pulse-patch-admission-") as raw:
+ disposable = Path(raw) / "pulse"
+ subprocess.run(["git", "clone", "--quiet", "--shared", "--no-checkout", str(root), str(disposable)],
+ check=True, capture_output=True)
+ git(disposable, "checkout", "--quiet", "--detach", selection["control_sha"])
+ rebuilt = assemble(disposable, selection)
+ if rebuilt != receipt:
+ raise ValueError("patch source receipt does not match reconstructed merge results")
+ rebuilt_head = value(disposable, "rev-parse", "HEAD")
+ # Inspect the candidate from the reconstructed checkout without executing its source.
+ from resolve_release_promotion import RELEASE_METADATA_PATH_RE, VERSION_PIN_LINE_RES
+ paths = value(disposable, "diff", "--name-only", rebuilt_head, head).splitlines()
+ for path in paths:
+ if RELEASE_METADATA_PATH_RE.fullmatch(path):
+ continue
+ pin = VERSION_PIN_LINE_RES.get(path)
+ if pin:
+ old = value(disposable, "show", f"{rebuilt_head}:{path}").splitlines()
+ new = value(disposable, "show", f"{head}:{path}").splitlines()
+ if (len([x for x in old if pin.fullmatch(x)]) == 1
+ and len([x for x in new if pin.fullmatch(x)]) == 1
+ and [x for x in old if not pin.fullmatch(x)] == [x for x in new if not pin.fullmatch(x)]):
+ continue
+ raise ValueError(f"stable patch contains unselected source: {path}")
+ return receipt
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("operation", choices=("assemble", "validate"))
+ parser.add_argument("--selection", type=Path)
+ parser.add_argument("--version")
+ parser.add_argument("--source-branch")
+ args = parser.parse_args()
+ root = Path.cwd().resolve()
+ result = assemble(root, json.loads(args.selection.read_text())) if args.operation == "assemble" \
+ else validate(root, args.version, args.source_branch)
+ print(json.dumps(result, sort_keys=True))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/release_control/stable_patch_test.py b/scripts/release_control/stable_patch_test.py
new file mode 100644
index 0000000000..489e270120
--- /dev/null
+++ b/scripts/release_control/stable_patch_test.py
@@ -0,0 +1,162 @@
+"""Whole merge results and exact controls, with real Git but no network or publishing."""
+from copy import deepcopy
+import json
+from pathlib import Path
+import subprocess
+import tempfile
+import unittest
+
+import stable_patch as patch
+
+
+class StablePatchTest(unittest.TestCase):
+ def setUp(self):
+ self.temp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.temp.cleanup)
+ self.root = Path(self.temp.name) / 'pulse'
+ self.root.mkdir()
+ self.git('init', '--quiet', '-b', 'main')
+ self.write('app', 'stable\n')
+ self.write('other', 'stable\n')
+ self.write('.github/workflows/old.yml', 'old')
+ self.write('scripts/release_control/control', 'old')
+ self.commit('stable')
+ self.base = self.head()
+ self.git('tag', 'v6.6.0')
+ self.write('app', 'fixed\n')
+ self.commit('fix')
+ self.fix = self.head()
+ self.write('other', 'unrelated main feature\n')
+ self.write('.github/workflows/old.yml', 'reviewed main control')
+ self.write('scripts/release_control/control', 'reviewed main control')
+ self.commit('main work and controls')
+ self.control = self.head()
+ self.git('update-ref', 'refs/remotes/origin/main', self.control)
+ self.selection = {'schema_version': 1, 'version': '6.6.1', 'stable_tag': 'v6.6.0',
+ 'stable_sha': self.base, 'control_sha': self.control,
+ 'fixes': [{'number': 12, 'merge_sha': self.fix, 'issues': [1]}]}
+
+ def git(self, *args):
+ return patch.value(self.root, *args)
+
+ def head(self):
+ return self.git('rev-parse', 'HEAD')
+
+ def write(self, path, text):
+ target = self.root / path
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text(text)
+
+ def commit(self, message):
+ self.git('add', '--all')
+ patch.commit(self.root, message)
+
+ def assemble(self):
+ return patch.assemble(self.root, self.selection)
+
+ def test_reconstructs_all_selected_source_but_no_other_main_work(self):
+ receipt = self.assemble()
+ self.assertEqual('fixed\n', (self.root / 'app').read_text())
+ self.assertEqual('stable\n', (self.root / 'other').read_text())
+ self.assertEqual('reviewed main control', (self.root / '.github/workflows/old.yml').read_text())
+ self.assertEqual(self.selection['fixes'], receipt['applied'])
+ self.assertEqual([], receipt['skipped'])
+ self.write('VERSION', '6.6.1-rc.1\n')
+ self.commit('release metadata')
+ self.assertEqual(receipt, patch.validate(self.root, '6.6.1-rc.1', 'release/v6.6.1'))
+ # This must not accidentally be an ancestor of main or change main's pins.
+ self.assertEqual(self.control, self.git('rev-parse', 'main'))
+
+ def test_rejects_extra_source_even_when_manifest_claims_the_right_fix(self):
+ self.assemble()
+ self.write('other', 'injected feature')
+ self.commit('extra source')
+ with self.assertRaisesRegex(ValueError, 'unselected source: other'):
+ patch.validate(self.root, '6.6.1', 'release/v6.6.1')
+
+ def test_rejects_foreign_controls_wrong_branch_and_second_rc(self):
+ self.assemble()
+ with self.assertRaisesRegex(ValueError, 'version-bound'):
+ patch.validate(self.root, '6.6.1', 'main')
+ with self.assertRaises(ValueError):
+ patch.validate(self.root, '6.6.1-rc.2', 'release/v6.6.1')
+ self.write('scripts/release_control/control', 'foreign control')
+ self.commit('control drift')
+ with self.assertRaisesRegex(ValueError, 'unselected source'):
+ patch.validate(self.root, '6.6.1', 'release/v6.6.1')
+
+ def test_whole_merge_result_not_just_the_last_individual_commit(self):
+ self.git('checkout', '--quiet', '-b', 'feature', self.control)
+ self.write('new-a', 'one')
+ self.commit('feature first')
+ self.write('new-b', 'two')
+ self.commit('feature second')
+ self.git('checkout', '--quiet', 'main')
+ self.git('merge', '--quiet', '--no-ff', 'feature', '-m', 'merged fix')
+ merge = self.head()
+ self.selection['control_sha'] = merge
+ self.selection['fixes'] = [{'number': 13, 'merge_sha': merge, 'issues': [1]}]
+ result = self.assemble()
+ self.assertEqual(self.selection['fixes'], result['applied'])
+ self.assertEqual('one', (self.root / 'new-a').read_text())
+ self.assertEqual('two', (self.root / 'new-b').read_text())
+ self.assertEqual('stable\n', (self.root / 'app').read_text())
+
+ def test_real_conflict_is_skipped_without_losing_later_clean_fixes(self):
+ self.write('app', 'third state after main fix\n')
+ self.commit('second change depends on first')
+ conflict = self.head()
+ self.write('new', 'clean fix\n')
+ self.commit('independent clean change')
+ clean = self.head()
+ self.selection['control_sha'] = clean
+ self.selection['fixes'] = [{'number': 13, 'merge_sha': conflict, 'issues': [1]},
+ {'number': 14, 'merge_sha': clean, 'issues': [2]}]
+ receipt = self.assemble()
+ self.assertEqual([14], [f['number'] for f in receipt['applied']])
+ self.assertEqual([13], [f['number'] for f in receipt['skipped']])
+ self.assertEqual(['app'], receipt['skipped'][0]['conflicts'])
+ self.assertEqual('stable\n', (self.root / 'app').read_text())
+ self.assertEqual('clean fix\n', (self.root / 'new').read_text())
+ self.git('update-ref', 'refs/remotes/origin/main', clean)
+ self.assertEqual(receipt, patch.validate(self.root, '6.6.1-rc.1', 'release/v6.6.1'))
+
+ def test_next_patch_can_start_from_non_main_patch_source(self):
+ self.assemble()
+ self.git('tag', 'v6.6.1')
+ prior = self.head()
+ self.git('checkout', '--quiet', 'main')
+ self.write('later', 'next fix')
+ self.commit('next main fix')
+ merge = self.head()
+ self.selection.update(version='6.6.2', stable_tag='v6.6.1', stable_sha=prior,
+ control_sha=merge, fixes=[{'number': 15, 'merge_sha': merge, 'issues': [2]}])
+ receipt = self.assemble()
+ self.git('update-ref', 'refs/remotes/origin/main', merge)
+ self.assertEqual(receipt, patch.validate(self.root, '6.6.2', 'release/v6.6.2'))
+ self.assertEqual('fixed\n', (self.root / 'app').read_text())
+ self.assertEqual('next fix', (self.root / 'later').read_text())
+
+ def test_incomplete_invalid_duplicate_out_of_order_selection_is_not_assembly(self):
+ for update in ({'version': '6.6.2'}, {'stable_sha': self.fix}, {'fixes': []},
+ {'fixes': self.selection['fixes'] * 2}, {'schema_version': 99}):
+ with self.subTest(update=update), self.assertRaises((ValueError, subprocess.CalledProcessError)):
+ patch.validate_selection(self.root, {**self.selection, **update})
+
+ def test_source_guard_runs_before_payload_creation_and_in_canonical_ci(self):
+ repo = Path(__file__).resolve().parents[2]
+ workflow = (repo / '.github/workflows/create-release.yml').read_text()
+ self.assertLess(workflow.index('name: Reconstruct stable patch source'), workflow.index('name: Validate release-note visual plan'))
+ self.assertIn('python3 scripts/release_control/stable_patch.py validate', workflow)
+ self.assertIn('python3 scripts/release_control/stable_patch_test.py',
+ (repo / '.github/workflows/canonical-governance.yml').read_text())
+
+ def test_dirty_checkout_is_not_discarded(self):
+ self.write('untracked', 'do not discard')
+ with self.assertRaisesRegex(ValueError, 'clean disposable'):
+ self.assemble()
+ self.assertEqual('do not discard', (self.root / 'untracked').read_text())
+
+
+if __name__ == '__main__':
+ unittest.main()