From ffc62c792c9a5196cb4ce7a353287dfe20db6524 Mon Sep 17 00:00:00 2001 From: Christoph Berg Date: Fri, 9 Oct 2026 14:12:35 +0200 Subject: New upstream version 3.3.0~beta1+dfsg --- .../tests/test_armhf_cross_configuration.py | 59 +- .../scripts/tests/test_armhf_sysroot_symlinks.py | 2 +- .github/scripts/tests/test_beta_scheduler.py | 1368 ++++++++++++++++++++ .github/scripts/tests/test_check_candidate_tag.py | 2 + .github/scripts/tests/test_ghcr_retention.py | 11 + .github/scripts/tests/test_linux_ccache_policy.py | 189 ++- .../tests/test_linux_image_publication_policy.py | 252 +++- .github/scripts/tests/test_native_cache_policy.py | 86 ++ .github/scripts/tests/test_package_cli_tools.py | 745 +++++++++++ .github/scripts/tests/test_release_linux_images.py | 158 +++ .github/scripts/tests/test_release_policy.py | 1156 ++++++++++++++++- .../scripts/tests/test_release_workflow_policy.py | 186 +++ 12 files changed, 4140 insertions(+), 74 deletions(-) create mode 100644 .github/scripts/tests/test_beta_scheduler.py create mode 100644 .github/scripts/tests/test_native_cache_policy.py create mode 100644 .github/scripts/tests/test_package_cli_tools.py create mode 100644 .github/scripts/tests/test_release_linux_images.py create mode 100644 .github/scripts/tests/test_release_workflow_policy.py (limited to '.github/scripts/tests') diff --git a/.github/scripts/tests/test_armhf_cross_configuration.py b/.github/scripts/tests/test_armhf_cross_configuration.py index 0893e99a..5bf78800 100644 --- a/.github/scripts/tests/test_armhf_cross_configuration.py +++ b/.github/scripts/tests/test_armhf_cross_configuration.py @@ -30,7 +30,7 @@ class ArmhfCrossConfigurationTests(unittest.TestCase): self.assertIn(setting, config) self.assertNotIn("CT_CC_GCC_LIBQUADMATH=y", config) - image_config = self.read(".github/scripts/armhf-ci-image-config.sh") + image_config = self.read(".github/scripts/armhf-toolchain-config.sh") self.assertIn("ARMHF_GCC_VERSION=13.4.0", image_config) self.assertIn("ARMHF_GLIBC_VERSION=2.36", image_config) self.assertIn("ARMHF_TARGET_TRIPLET=arm-linux-gnueabihf", image_config) @@ -42,6 +42,44 @@ class ArmhfCrossConfigurationTests(unittest.TestCase): self.assertIn("reject_private_glibc_dependency", verifier) self.assertIn("private glibc symbol", audit) + def test_toolchain_stage_is_independent_of_image_refresh_inputs(self): + builder = self.read(".github/images/linux-ci/Dockerfile.armhf-cross") + toolchain, image = builder.split("FROM debian:bookworm AS cross_builder", 1) + self.assertRegex( + toolchain.splitlines()[0], + r"^FROM debian:bookworm@sha256:[0-9a-f]{64} AS toolchain$", + ) + for unrelated_input in ( + "IMAGE_REFRESH_EPOCH", + "IMAGE_RECIPE_SHA256", + "IMAGE_GENERATION", + "armhf-ci-image-config.sh", + "linux-ci-image-config.sh", + "build-hamlib-armhf-cross.sh", + ): + self.assertNotIn(unrelated_input, toolchain) + self.assertLess( + toolchain.index('test -n "$ARMHF_TOOLCHAIN_REBUILD_REVISION"'), + toolchain.index("run-apt-get update"), + ) + self.assertIn("armhf-cross-toolchain.config", toolchain) + self.assertNotIn("target=/tmp/wsjtx-ctng-build", toolchain) + self.assertIn('mkdir "$build_dir"', toolchain) + self.assertIn('rm -rf "$build_dir"', toolchain) + self.assertIn( + "COPY --from=toolchain /opt/wsjtx/armhf-toolchain " + "/opt/wsjtx/armhf-toolchain", image, + ) + self.assertIn("IMAGE_REFRESH_EPOCH", image) + self.assertIn("IMAGE_RECIPE_SHA256", image) + + def test_shared_toolchain_config_is_copied_to_both_image_roles(self): + config = self.read(".github/scripts/armhf-ci-image-config.sh") + self.assertIn('. "$_armhf_config_dir/armhf-toolchain-config.sh"', config) + for role in ("cross", "runtime"): + dockerfile = self.read(f".github/images/linux-ci/Dockerfile.armhf-{role}") + self.assertIn(".github/scripts/armhf-toolchain-config.sh", dockerfile) + def test_armhf_cache_identity_parsing_fails_closed(self): workflow = self.read(".github/workflows/build-linux.yml") self.assertIn( @@ -84,7 +122,7 @@ class ArmhfCrossConfigurationTests(unittest.TestCase): def test_builder_and_runtime_keep_distinct_native_architectures(self): builder = self.read(".github/images/linux-ci/Dockerfile.armhf-cross") runtime = self.read(".github/images/linux-ci/Dockerfile.armhf-runtime") - self.assertTrue(builder.startswith("FROM debian:bookworm\n")) + self.assertIn("FROM debian:bookworm AS cross_builder\n", builder) self.assertIn("--architectures=armhf", builder) self.assertIn("qemu-user-static", builder) self.assertIn("normalize-armhf-sysroot-symlinks.sh", builder) @@ -108,12 +146,19 @@ class ArmhfCrossConfigurationTests(unittest.TestCase): self.assertIn("cpack -G RPM", runtime_package) self.assertIn("CPACK_INSTALL_CMAKE_PROJECTS=", runtime_package) self.assertIn("CPACK_INSTALLED_DIRECTORIES=/work/AppDir;/", runtime_package) - self.assertIn('"$ARMHF_QEMU_EXECUTABLE"', runtime_package) - self.assertIn( - 'LINUX_APPIMAGE_RUNNER="$ARMHF_QEMU_EXECUTABLE"', runtime_package - ) + self.assertNotIn("qemu", runtime_package.lower()) + self.assertNotIn("LINUX_APPIMAGE_RUNNER", runtime_package) + self.assertIn(" ./linuxdeploy.AppImage --appimage-extract-and-run \\\n", runtime_package) + self.assertIn('./"$OUTPUT" --appimage-extract >/dev/null', runtime_package) + self.assertIn("-o linuxdeploy-plugin-qt.AppImage", runtime_package) self.assertIn("armhf-static-ldd.sh", runtime_package) self.assertIn('PATH="/work/wsjtx-build/appimage-tools:$PATH"', runtime_package) + packaging = runtime_package[runtime_package.index("Package release tarballs"):] + self.assertLess(runtime_package.index("--output appimage"), runtime_package.index("package-cli-tools.sh")) + self.assertIn('PATH="/work/wsjtx-build/appimage-tools:$PATH" .github/scripts/package-cli-tools.sh', packaging) + self.assertIn("--linuxdeploy /work/linuxdeploy.AppImage", packaging) + self.assertIn(".github/scripts/smoke-release-tarballs.sh", packaging) + self.assertNotIn("--ldd", packaging) def test_hybrid_is_the_only_armhf_build_implementation(self): workflow = self.read(".github/workflows/build-linux.yml") @@ -169,7 +214,7 @@ class ArmhfCrossConfigurationTests(unittest.TestCase): properties = q65.split( "set_tests_properties (test_q65_decode_pipeline", 1 )[1].split(")", 1)[0] - self.assertIn("TIMEOUT 180", properties) + self.assertIn("TIMEOUT 360", properties) if __name__ == "__main__": diff --git a/.github/scripts/tests/test_armhf_sysroot_symlinks.py b/.github/scripts/tests/test_armhf_sysroot_symlinks.py index 991971f6..42647345 100644 --- a/.github/scripts/tests/test_armhf_sysroot_symlinks.py +++ b/.github/scripts/tests/test_armhf_sysroot_symlinks.py @@ -23,7 +23,7 @@ class ArmhfSysrootSymlinkTests(unittest.TestCase): subprocess.run(["bash", str(NORMALIZER), str(sysroot)], check=True) self.assertFalse(os.readlink(link).startswith("/")) - self.assertEqual(link.resolve(), target) + self.assertEqual(link.resolve(), target.resolve()) def test_relative_links_remain_unchanged(self): with tempfile.TemporaryDirectory() as temporary: diff --git a/.github/scripts/tests/test_beta_scheduler.py b/.github/scripts/tests/test_beta_scheduler.py new file mode 100644 index 00000000..47f74d60 --- /dev/null +++ b/.github/scripts/tests/test_beta_scheduler.py @@ -0,0 +1,1368 @@ +#!/usr/bin/env python3 +"""Scheduled beta state machine, continuation, alerts, git mechanics and workflow wiring.""" +import importlib.util +import io +import itertools +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import tempfile +from types import SimpleNamespace +import unittest +from unittest.mock import patch +import urllib.error +import urllib.parse +import zipfile + +ROOT = Path(__file__).resolve().parents[3] +SPEC = importlib.util.spec_from_file_location("beta_scheduler", Path(__file__).parents[1] / "beta-scheduler.py") +beta = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(beta) + +BOT = "wsjtx-release-bot[bot]" +BOT_EMAIL = f"41+{BOT}@users.noreply.github.com" +MAINTAINER = "maintainer@example.invalid" +LINE = "release/3.3" +TIP = "1" * 40 +OLD_LINE_TIP = "2" * 40 +DEVELOP = "d" * 40 +GREEN = "e" * 40 +CUT = "c" * 40 +RECIPES = {key: str(index) * 64 for index, key in enumerate(beta.images.IMAGES, start=3)} +DRIFTED = {key: "f" * 64 for key in beta.images.IMAGES} +STATE = beta.STATE_FILE +LOCK = beta.LOCK_FILE +RUN_IDS = itertools.count(1000) + + +def state(channel="BETA", number=2, version="3.3.0"): + lines = [f"version={version}", f"channel={channel}", f"prerelease={number if channel in ('BETA', 'RC') else ''}", + "revision=$Format:%H$"] + if channel == "BETA": + lines.append("windows_signing=unsigned") + return ("\n".join(lines) + "\n").encode() + + +OLD_CONTRACT = b"version=3.2.0\nchannel=RC\nrc=1\nrevision=$Format:%H$\nwindows_signing=unsigned\n" + + +def lock(recipes=RECIPES, generation="validated-build-20260929-600-1"): + return (json.dumps({"schema": 1, "generation": generation, "images": { + key: {"reference": f"{beta.images.PUBLIC}/{spec[0]}@sha256:{'a' * 64}", "recipe_sha256": recipes[key]} + for key, spec in beta.images.IMAGES.items() + }}, indent=2) + "\n").encode() + + +def run(workflow, *, status="completed", conclusion="success", sha=TIP, branch=LINE, event="push", title=None, + created="2026-10-06T18:00:00Z", actor=BOT, triggering_actor=None, run_id=None): + run_id = next(RUN_IDS) if run_id is None else run_id + return { + "id": run_id, "path": f".github/workflows/{workflow}", "status": status, + "conclusion": conclusion if status == "completed" else None, "head_sha": sha, "head_branch": branch, + "event": event, "display_title": title or workflow, "created_at": created, + "actor": {"login": actor, "type": "Bot" if actor.endswith("[bot]") else "User"}, + "triggering_actor": {"login": triggering_actor or actor}, + "html_url": f"https://example.invalid/runs/{run_id}", + } + + +def candidate(version="3.3.0-beta2", operation="create", **fields): + fields.setdefault("event", "workflow_dispatch") + return run(beta.CANDIDATE, title=f"Prepare Release Candidate build/v{version} ({operation})", **fields) + + +def preparation(generation, **fields): + fields.setdefault("event", "workflow_dispatch") + fields.setdefault("branch", "develop") + fields.setdefault("sha", DEVELOP) + return run(beta.PREPARATION, title=f"Prepare Release Dependencies develop {generation}", **fields) + + +class FakeRepository: + def __init__(self): + self.heads = {} + self.files = {} + self.tags = {} + self.ancestors = set() + self.absent = set() + self.missing = [] + self.recipes = {} + self.conflicts = [] + self.validation_error = None + self.push_error = None + self.merge = None + self.written = None + self.committed = None + self.pushed = [] + self.discarded = [] + self.synced = [] + + def sync(self, *, shallow=False): + self.synced.append(shallow) + + def release_heads(self): + return dict(self.heads) + + def develop(self): + return DEVELOP + + def tag(self, name): + return self.tags.get(name) + + def read(self, commit, path): + return self.files.get((commit, path)) + + def contains(self, commit): + return commit not in self.absent + + def is_ancestor(self, ancestor, descendant): + return ancestor == descendant or (ancestor, descendant) in self.ancestors + + def commits_missing_from_develop(self, tip): + return list(self.missing) + + def fingerprints(self, commit): + return self.recipes.get(commit) + + def start_merge(self, tip, commit, name, email): + self.merge = (tip, commit) + return Path("merge-worktree"), list(self.conflicts) + + def write(self, worktree, files): + self.written = dict(files) + + def validate_lock(self, worktree): + if self.validation_error: + raise RuntimeError(self.validation_error) + + def commit(self, worktree, name, email, message): + self.committed = (name, email, message) + return CUT + + def push(self, commit, branch): + if self.push_error: + raise RuntimeError(self.push_error) + self.pushed.append((commit, branch)) + + def discard(self, worktree): + self.discarded.append(worktree) + + +class FakeGitHub: + def __init__(self): + self.workflow_runs = {} + self.queries = [] + self.dispatches = [] + self.published = set() + self.artifacts = {} + self.job_lists = {} + + def add(self, *runs): + for item in runs: + self.workflow_runs.setdefault(Path(item["path"]).name, []).append(item) + + def runs(self, workflow, **filters): + self.queries.append(workflow) + selected = [] + for item in self.workflow_runs.get(workflow, []): + if "branch" in filters and item["head_branch"] != filters["branch"]: + continue + if "event" in filters and item["event"] != filters["event"]: + continue + if "head_sha" in filters and item["head_sha"] != filters["head_sha"]: + continue + if "status" in filters and filters["status"] not in (item["status"], item["conclusion"]): + continue + selected.append(item) + return selected + + def jobs(self, run_id): + return self.job_lists.get(run_id, []) + + def dispatch(self, workflow, ref, inputs): + self.dispatches.append((workflow, ref, inputs)) + + def release_published(self, tag): + return tag in self.published + + def artifact_file(self, run_id, name, member): + return self.artifacts.get(run_id) if (name, member) == (beta.PREPARED_ARTIFACT, LOCK) else None + + +class FakePackages: + def __init__(self): + self.tags = {package: set() for package in beta.IMAGE_PACKAGES} + self.calls = [] + + def list_versions(self, owner, package): + self.calls.append((owner, package)) + return [SimpleNamespace(tags=tuple(sorted(self.tags[package]))), SimpleNamespace(tags=("stable",))] + + +class SchedulerTestCase(unittest.TestCase): + """A published beta2 on release/3.3; develop moved to a green commit with unchanged recipes.""" + + def setUp(self): + self.build() + + def build(self): + self.repo = FakeRepository() + self.internal = FakeGitHub() + self.public = FakeGitHub() + self.packages = FakePackages() + self.repo.heads = {"release/3.2": OLD_LINE_TIP, LINE: TIP} + self.repo.files[(OLD_LINE_TIP, STATE)] = OLD_CONTRACT + self.repo.files[(TIP, STATE)] = state(number=2) + self.repo.files[(TIP, LOCK)] = lock() + self.repo.tags["build/v3.3.0-beta2"] = TIP + self.public.published.add("v3.3.0-beta2") + self.repo.ancestors.add((GREEN, DEVELOP)) + self.repo.recipes[GREEN] = dict(RECIPES) + self.repo.recipes[DEVELOP] = dict(RECIPES) + self.repo.missing = [ + beta.Commit(TIP, BOT_EMAIL, ("CMakeLists.txt", STATE)), + beta.Commit("3" * 40, MAINTAINER, (LOCK, STATE)), + ] + self.internal.add(run(beta.CI, sha=GREEN, branch="develop", created="2026-10-06T10:00:00Z", actor="k1jt")) + + def cut(self): + return beta.Scheduler(self.repo, self.internal, self.public, self.packages, + bot_login=BOT, bot_email=BOT_EMAIL).cut() + + def stop(self): + with self.assertRaises(beta.Stop) as raised: + self.cut() + return raised.exception + + def assertNothingDone(self): + self.assertEqual(self.internal.dispatches, []) + self.assertEqual(self.repo.pushed, []) + + +class BetaLineTest(SchedulerTestCase): + def test_no_beta_line_between_a_freeze_and_the_next_line_is_a_quiet_skip(self): + self.repo.files[(TIP, STATE)] = state("RC", 1) + with self.assertRaisesRegex(beta.Skip, "No release/X.Y branch is in BETA state"): + self.cut() + self.assertNothingDone() + + def test_lines_without_state_with_the_old_contract_or_another_name_are_not_beta(self): + self.repo.heads.update({"release/3.0": "5" * 40, "release/3.4-hotfix": "6" * 40}) + self.repo.files[("6" * 40, STATE)] = state(version="3.4.0", number=1) + self.cut() + self.assertEqual(self.repo.pushed, [(CUT, LINE)]) + + def test_several_beta_lines_stop(self): + self.repo.heads["release/3.4"] = "6" * 40 + self.repo.files[("6" * 40, STATE)] = state(version="3.4.0", number=1) + stop = self.stop() + self.assertEqual(stop.stage, "line") + self.assertIn("release/3.3, release/3.4", str(stop)) + self.assertNothingDone() + + def test_an_invalid_beta_state_stops_instead_of_reading_as_no_line(self): + self.repo.files[(TIP, STATE)] = b"version=3.3.0\nchannel=BETA\nprerelease=2\nrevision=$Format:%H$\n" + stop = self.stop() + self.assertEqual(stop.stage, "line") + self.assertIn(f"{LINE}'s {STATE} says channel=BETA but does not validate", str(stop)) + self.assertNothingDone() + + def test_beta_state_for_another_line_stops(self): + self.repo.files[(TIP, STATE)] = state(version="3.4.0") + self.assertEqual(self.stop().stage, "line") + self.assertNothingDone() + + +class RetryCutTest(SchedulerTestCase): + def setUp(self): + super().setUp() + del self.repo.tags["build/v3.3.0-beta2"] + self.public.published.clear() + + def expected_candidate(self, version="3.3.0-beta2"): + return [(beta.CANDIDATE, LINE, {"version": version, "expected_sha": TIP, "operation": "create"})] + + def test_new_line_first_run_cuts_beta1_at_its_tip_without_a_merge(self): + self.repo.files[(TIP, STATE)] = state(number=1) + self.repo.missing = [beta.Commit(TIP, MAINTAINER, (LOCK, STATE))] + self.repo.ancestors.add((GREEN, TIP)) + self.internal.add(run(beta.CI, sha=TIP, actor="k1jt")) + self.cut() + self.assertEqual(self.internal.dispatches, self.expected_candidate("3.3.0-beta1")) + self.assertIsNone(self.repo.merge) + self.assertEqual(self.repo.pushed, []) + + def test_retry_waits_while_the_tip_ci_runs(self): + self.internal.add(run(beta.CI, sha=TIP, conclusion="failure"), run(beta.CI, sha=TIP, status="in_progress")) + with self.assertRaisesRegex(beta.Skip, "still running"): + self.cut() + self.assertNothingDone() + + def test_failed_tip_ci_recuts_the_same_number_from_newer_green_develop(self): + self.internal.add(run(beta.CI, sha=TIP), + run(beta.CI, sha=TIP, conclusion="failure", created="2026-10-06T19:00:00Z")) + message = self.cut() + self.assertEqual(self.repo.merge, (TIP, GREEN)) + self.assertEqual(self.repo.written, {STATE: beta.render_state("3.3.0", 2).encode(), LOCK: lock()}) + self.assertEqual(self.repo.committed[:2], (BOT, BOT_EMAIL)) + self.assertTrue(self.repo.committed[2].startswith("Cut 3.3.0-beta2 from develop\n\n")) + self.assertEqual(self.repo.pushed, [(CUT, LINE)]) + self.assertEqual(self.internal.dispatches, []) + self.assertIn("3.3.0-beta2", message) + + def test_failed_tip_ci_without_newer_green_develop_stops(self): + failed = run(beta.CI, sha=TIP, conclusion="failure", created="2026-10-06T19:00:00Z") + for name, setup in ( + ("develop already merged", lambda: self.repo.ancestors.add((GREEN, TIP))), + ("no green develop", lambda: self.internal.workflow_runs.update({beta.CI: []})), + ): + with self.subTest(name=name): + self.setUp() + setup() + self.internal.add(run(beta.CI, sha=TIP), failed) + stop = self.stop() + self.assertEqual((stop.stage, stop.link), ("ci", failed["html_url"])) + self.assertIsNone(self.repo.merge) + self.assertNothingDone() + + def test_recut_after_failed_tip_ci_follows_the_lock_and_conflict_rules(self): + self.internal.add(run(beta.CI, sha=TIP, conclusion="cancelled")) + self.repo.recipes[GREEN] = dict(DRIFTED) + self.repo.recipes[DEVELOP] = dict(DRIFTED) + self.repo.recipes["a5" * 20] = dict(DRIFTED) + self.internal.add(run(beta.WARMER, sha="a5" * 20, branch="develop", actor="k1jt", run_id=713)) + for package in beta.IMAGE_PACKAGES: + self.packages.tags[package].add("validated-build-20261001-713-1") + with self.assertRaisesRegex(beta.Skip, "Dispatched Prepare Release Dependencies"): + self.cut() + self.assertEqual([workflow for workflow, _ref, _inputs in self.internal.dispatches], [beta.PREPARATION]) + self.assertEqual(self.repo.pushed, []) + self.setUp() + self.internal.add(run(beta.CI, sha=TIP, conclusion="failure")) + self.repo.conflicts = ["CMakeLists.txt"] + self.assertEqual(self.stop().stage, "merge") + self.assertNothingDone() + + def test_retry_stops_without_a_tip_ci_run(self): + self.assertEqual(self.stop().stage, "ci") + self.assertNothingDone() + + def test_a_running_tip_ci_or_candidate_a_person_started_alerts_because_nothing_resumes_the_cut(self): + for stage, runs in ( + ("ci", lambda: [run(beta.CI, sha=TIP, status="in_progress", actor="k1jt")]), + ("candidate", lambda: [run(beta.CI, sha=TIP), candidate(status="queued", actor="k1jt")]), + ): + with self.subTest(stage=stage): + self.setUp() + added = runs() + self.internal.add(*added) + stop = self.stop() + self.assertEqual((stop.stage, stop.link), (stage, added[-1]["html_url"])) + self.assertIn("dispatch Scheduled Beta Cut after it does", str(stop)) + self.assertNothingDone() + + def test_retry_waits_for_a_running_candidate(self): + self.internal.add(run(beta.CI, sha=TIP), candidate(status="queued")) + with self.assertRaisesRegex(beta.Skip, "candidate"): + self.cut() + self.assertNothingDone() + + def test_failed_candidate_is_retried_with_the_same_number(self): + self.internal.add( + run(beta.CI, sha=TIP), + candidate(conclusion="failure"), + candidate(operation="validate", status="in_progress", actor="k1jt"), + candidate("3.3.0-beta1", status="in_progress"), + ) + self.cut() + self.assertEqual(self.internal.dispatches, self.expected_candidate()) + + def test_retry_stops_on_a_fix_committed_only_to_the_release_branch(self): + self.internal.add(run(beta.CI, sha=TIP)) + self.repo.missing.append(beta.Commit("4" * 40, MAINTAINER, ("main.cpp",))) + stop = self.stop() + self.assertEqual(stop.stage, "fixes") + self.assertIn("4" * 40, str(stop)) + self.assertNothingDone() + + +class UnpublishedBetaTest(SchedulerTestCase): + def setUp(self): + super().setUp() + self.public.published.clear() + self.ci = run(beta.CI, sha=TIP) + self.candidate = candidate() + self.promotion = run(beta.PROMOTION, event="workflow_dispatch") + self.publication = run(beta.PUBLICATION, branch="v3.3.0-beta2", actor="KJ5HST") + + def test_unpublished_beta_waits_quietly_while_any_of_its_runs_is_in_progress(self): + for stage, running in ( + ("CI", lambda: run(beta.CI, status="waiting")), + ("candidate", lambda: candidate(status="waiting")), + ("promotion", lambda: run(beta.PROMOTION, event="workflow_dispatch", status="waiting")), + ("public release", lambda: run(beta.PUBLICATION, branch="v3.3.0-beta2", status="waiting")), + ): + with self.subTest(stage=stage): + self.setUp() + self.internal.add(self.ci, self.candidate) + target = self.public if stage == "public release" else self.internal + target.add(running()) + with self.assertRaisesRegex(beta.Skip, f"its {stage} run is still in progress"): + self.cut() + self.assertNothingDone() + + def test_unpublished_beta_alerts_on_a_running_run_a_person_started_but_waits_for_the_public_release(self): + for stage, running, alerts in ( + ("ci", lambda: run(beta.CI, status="in_progress", actor="k1jt"), True), + ("candidate", lambda: candidate(status="in_progress", actor="k1jt"), True), + ("promotion", lambda: run(beta.PROMOTION, event="workflow_dispatch", status="in_progress", actor="k1jt"), + True), + ("public release", lambda: run(beta.PUBLICATION, branch="v3.3.0-beta2", status="in_progress", + actor="KJ5HST"), False), + ): + with self.subTest(stage=stage): + self.setUp() + self.internal.add(self.ci, self.candidate) + added = running() + (self.public if stage == "public release" else self.internal).add(added) + if alerts: + stop = self.stop() + self.assertEqual((stop.stage, stop.link), (stage, added["html_url"])) + else: + with self.assertRaisesRegex(beta.Skip, "public release run is still in progress"): + self.cut() + self.assertNothingDone() + + def test_candidate_failed_after_its_tag_spends_the_number_and_cuts_the_next_from_green_develop(self): + self.internal.add(self.ci, candidate(conclusion="failure")) + scheduler = beta.Scheduler(self.repo, self.internal, self.public, self.packages, + bot_login=BOT, bot_email=BOT_EMAIL) + scheduler.cut() + self.assertEqual(self.repo.merge, (TIP, GREEN)) + self.assertEqual(self.repo.written[STATE], beta.render_state("3.3.0", 3).encode()) + self.assertTrue(self.repo.committed[2].startswith("Cut 3.3.0-beta3 from develop\n\n")) + self.assertEqual(self.repo.pushed, [(CUT, LINE)]) + self.assertTrue(any("3.3.0-beta2 is spent" in note for note in scheduler.notes)) + + def test_spent_number_without_newer_green_develop_alerts_with_the_failed_run(self): + failed = candidate(conclusion="failure") + self.internal.add(self.ci, failed) + self.repo.ancestors.add((GREEN, TIP)) + stop = self.stop() + self.assertEqual((stop.stage, stop.link), ("candidate", failed["html_url"])) + self.assertIn("3.3.0-beta2 is spent", str(stop)) + self.assertIn("3.3.0-beta3", str(stop)) + self.assertNothingDone() + + def test_a_successful_candidate_at_the_tag_outweighs_a_newer_failed_duplicate(self): + self.internal.add(self.ci, self.candidate, + candidate(conclusion="failure", created="2026-10-06T19:00:00Z")) + stop = self.stop() + self.assertEqual((stop.stage, stop.link), ("promotion", self.candidate["html_url"])) + self.assertNothingDone() + + def test_a_promoted_beta_is_never_spent_even_if_its_candidate_run_now_reads_failed(self): + failed_publication = run(beta.PUBLICATION, branch="v3.3.0-beta2", conclusion="failure") + self.internal.add(self.ci, candidate(conclusion="failure"), self.promotion) + self.public.add(failed_publication) + stop = self.stop() + self.assertEqual((stop.stage, stop.link), ("publication", failed_publication["html_url"])) + self.assertNothingDone() + + def test_candidate_and_promotion_runs_of_other_commits_do_not_count(self): + elsewhere = {"sha": GREEN} + for name, runs, stage in ( + ("successful candidate elsewhere", (candidate(conclusion="failure"), candidate(**elsewhere)), None), + ("running candidate elsewhere", (candidate(conclusion="failure"), candidate(status="queued", **elsewhere)), + None), + ("promotion elsewhere", (self.candidate, run(beta.PROMOTION, event="workflow_dispatch", **elsewhere)), + "promotion"), + ): + with self.subTest(name=name): + self.build() + self.public.published.clear() + self.internal.add(self.ci, *runs) + if stage is None: + self.cut() + self.assertEqual(self.repo.written[STATE], beta.render_state("3.3.0", 3).encode()) + else: + stop = self.stop() + self.assertEqual((stop.stage, stop.link), (stage, self.candidate["html_url"])) + self.assertNothingDone() + + def test_unpublished_beta_alerts_at_its_first_missing_or_failed_stage(self): + failed_promotion = run(beta.PROMOTION, event="workflow_dispatch", conclusion="failure") + failed_publication = run(beta.PUBLICATION, branch="v3.3.0-beta2", conclusion="failure") + promoted = (self.ci, self.candidate, self.promotion) + for internal, public, stage, link in ( + ((self.ci,), (), "candidate", None), + ((self.ci, self.candidate), (), "promotion", self.candidate["html_url"]), + ((self.ci, self.candidate, failed_promotion), (), "promotion", failed_promotion["html_url"]), + (promoted, (), "publication", self.promotion["html_url"]), + (promoted, (failed_publication,), "publication", failed_publication["html_url"]), + (promoted, (self.publication,), "publication", self.publication["html_url"]), + ): + with self.subTest(stage=stage, link=link): + self.build() + self.public.published.clear() + self.internal.add(*internal) + self.public.add(*public) + stop = self.stop() + self.assertEqual((stop.stage, stop.link), (stage, link)) + self.assertNothingDone() + + +class NextCutTest(SchedulerTestCase): + def test_published_beta_merges_the_newest_green_develop_as_the_next_number(self): + self.internal.add( + run(beta.CI, sha="9" * 40, branch="develop", conclusion="failure", created="2026-10-06T11:00:00Z"), + run(beta.CI, sha="8" * 40, branch="develop", created="2026-10-05T11:00:00Z"), + run(beta.CI, sha="7" * 40, branch="topic", created="2026-10-06T12:00:00Z"), + ) + self.repo.ancestors.update({("9" * 40, DEVELOP), ("8" * 40, DEVELOP), ("7" * 40, DEVELOP)}) + message = self.cut() + self.assertEqual(self.repo.merge, (TIP, GREEN)) + self.assertEqual(self.repo.written, {STATE: beta.render_state("3.3.0", 3).encode(), LOCK: lock()}) + name, email, commit_message = self.repo.committed + self.assertEqual((name, email), (BOT, BOT_EMAIL)) + self.assertTrue(commit_message.startswith("Cut 3.3.0-beta3 from develop\n\n")) + self.assertIn(GREEN, commit_message) + self.assertTrue(all(len(line) <= 72 for line in commit_message.splitlines())) + self.assertEqual(self.repo.pushed, [(CUT, LINE)]) + self.assertEqual(self.repo.discarded, [Path("merge-worktree")]) + self.assertEqual(self.internal.dispatches, []) + self.assertIn(CUT, message) + + def test_cut_fetches_develop_and_the_release_branches_in_full(self): + self.cut() + self.assertEqual(self.repo.synced, [False]) + + def test_green_runs_for_commits_not_on_develop_or_not_fetched_are_passed_over(self): + not_on_develop, not_fetched = "9" * 40, "8" * 40 + self.internal.add( + run(beta.CI, sha=not_on_develop, branch="develop", created="2026-10-06T12:00:00Z"), + run(beta.CI, sha=not_fetched, branch="develop", created="2026-10-06T11:00:00Z"), + ) + self.repo.ancestors.add((not_fetched, DEVELOP)) + self.repo.absent.add(not_fetched) + self.cut() + self.assertEqual(self.repo.merge, (TIP, GREEN)) + + def test_cut_state_is_a_valid_beta_state_that_keeps_the_line_version(self): + self.assertEqual(beta.policy.parse_state(beta.render_state("3.3.0", 3)), { + "version": "3.3.0", "channel": "BETA", "prerelease": "3", + "revision": "$Format:%H$", "windows_signing": "unsigned", + }) + + def test_unchanged_develop_skips_without_an_alert(self): + self.repo.ancestors.add((GREEN, TIP)) + with self.assertRaisesRegex(beta.Skip, "develop has not moved"): + self.cut() + self.assertNothingDone() + + def test_no_green_develop_stops(self): + self.internal.workflow_runs[beta.CI] = [run(beta.CI, sha=GREEN, branch="develop", conclusion="failure")] + self.assertEqual(self.stop().stage, "develop") + self.assertNothingDone() + + +class FixesOnDevelopTest(SchedulerTestCase): + def test_bot_merges_and_metadata_only_commits_are_not_fixes(self): + self.repo.missing += [beta.Commit("7" * 40, MAINTAINER, (LOCK,)), beta.Commit("8" * 40, MAINTAINER, ())] + self.cut() + self.assertEqual(self.repo.pushed, [(CUT, LINE)]) + + def test_release_branch_commits_missing_from_develop_stop_the_cut(self): + for files, email in ( + (("main.cpp",), MAINTAINER), + (("main.cpp", STATE), MAINTAINER), + (("CMakeLists.txt", STATE, LOCK), "someone-else@example.invalid"), + ): + with self.subTest(files=files, email=email): + self.build() + self.repo.missing.append(beta.Commit("4" * 40, email, files)) + stop = self.stop() + self.assertEqual(stop.stage, "fixes") + self.assertIn("4" * 40, str(stop)) + self.assertNothingDone() + + +class ImageLockTest(SchedulerTestCase): + def setUp(self): + super().setUp() + self.repo.recipes[GREEN] = dict(DRIFTED) + self.repo.recipes[DEVELOP] = dict(DRIFTED) + + def publish_generation(self, run_id, sha, recipes, *, created="2026-10-01T00:00:00Z", attempt=1, + packages=beta.IMAGE_PACKAGES, status="completed"): + generation = f"validated-build-20261001-{run_id}-{attempt}" + for package in packages: + self.packages.tags[package].add(generation) + self.repo.recipes[sha] = dict(recipes) + self.internal.add(run(beta.WARMER, sha=sha, branch="develop", created=created, actor="k1jt", + status=status, run_id=run_id)) + return generation + + def test_unchanged_recipes_keep_the_branch_lock_without_image_lookups(self): + self.repo.recipes[GREEN] = dict(RECIPES) + self.cut() + self.assertEqual(self.repo.written[LOCK], lock()) + self.assertEqual(self.packages.calls, []) + self.assertNotIn(beta.WARMER, self.internal.queries) + self.assertNotIn(beta.PREPARATION, self.internal.queries) + + def test_recipe_drift_prepares_the_newest_generation_built_for_those_recipes(self): + self.publish_generation(702, "a2" * 20, DRIFTED, created="2026-10-01T00:00:00Z") + newest = self.publish_generation(703, "a3" * 20, DRIFTED, created="2026-10-03T00:00:00Z") + rerun = newest.removesuffix("-1") + "-2" + for package in beta.IMAGE_PACKAGES: + self.packages.tags[package].add(rerun) + self.publish_generation(704, "a4" * 20, RECIPES, created="2026-10-04T00:00:00Z") + self.internal.add(preparation("validated-build-20261001-702-1", status="in_progress")) + with self.assertRaisesRegex(beta.Skip, "Dispatched Prepare Release Dependencies"): + self.cut() + self.assertEqual(self.internal.dispatches, [ + (beta.PREPARATION, "develop", {"source_branch": "develop", "generation": rerun}), + ]) + self.assertEqual(self.repo.pushed, []) + + def assertRefreshAlert(self, refresh): + stop = self.stop() + self.assertEqual((stop.stage, stop.link), ("lock", refresh["html_url"])) + self.assertIn("still being refreshed", str(stop)) + self.assertIn("dispatch Scheduled Beta Cut after it does", str(stop)) + self.assertNothingDone() + + def test_recipe_drift_alerts_while_the_image_refresh_runs_because_nothing_resumes_the_cut(self): + self.publish_generation(705, "b1" * 20, RECIPES) + self.repo.recipes["b2" * 20] = dict(DRIFTED) + refresh = run(beta.WARMER, sha="b2" * 20, branch="develop", status="in_progress", actor="k1jt") + self.internal.add(refresh) + self.assertRefreshAlert(refresh) + + def test_only_a_warmer_run_that_refreshes_the_images_holds_the_cut(self): + detect = {"name": "detect", "status": "completed", "conclusion": "success"} + for name, jobs, waits in ( + ("refresh skipped", [detect, {"name": "refresh-linux-images", "status": "completed", + "conclusion": "skipped"}], False), + ("TSan image only", [detect, {"name": "refresh-linux-images / build-normal", "status": "completed", + "conclusion": "skipped"}], False), + ("normal images building", [detect, {"name": "refresh-linux-images / build-normal", + "status": "in_progress", "conclusion": None}], True), + ("built, not yet promoted", [detect, {"name": "refresh-linux-images / build-normal", + "status": "completed", "conclusion": "success"}], True), + ("refresh pending", [detect, {"name": "refresh-linux-images", "status": "queued", + "conclusion": None}], True), + ("not yet decided", [{"name": "detect", "status": "in_progress", "conclusion": None}], True), + ): + with self.subTest(name=name): + self.setUp() + self.publish_generation(720, "c1" * 20, RECIPES) + self.repo.recipes["c2" * 20] = dict(DRIFTED) + warmer = run(beta.WARMER, sha="c2" * 20, branch="develop", status="in_progress", actor="k1jt") + self.internal.add(warmer) + self.internal.job_lists[warmer["id"]] = jobs + if waits: + self.assertRefreshAlert(warmer) + else: + stop = self.stop() + self.assertEqual((stop.stage, stop.link), ("lock", None)) + self.assertIn("No validated Linux image generation", str(stop)) + self.assertNothingDone() + + def test_a_generation_promoted_by_a_run_still_in_progress_is_used(self): + generation = self.publish_generation(722, "c4" * 20, DRIFTED, status="in_progress") + with self.assertRaisesRegex(beta.Skip, "Dispatched"): + self.cut() + self.assertEqual(self.internal.dispatches[0][2]["generation"], generation) + + def test_generations_from_a_direct_image_publication_on_develop_count(self): + generation = "validated-build-20261002-723-1" + for package in beta.IMAGE_PACKAGES: + self.packages.tags[package].add(generation) + self.repo.recipes["c5" * 20] = dict(DRIFTED) + self.internal.add(run(beta.PUBLISHER, sha="c5" * 20, branch="develop", event="workflow_dispatch", + actor="dchristle", run_id=723)) + with self.assertRaisesRegex(beta.Skip, "Dispatched"): + self.cut() + self.assertEqual(self.internal.dispatches[0][2]["generation"], generation) + self.setUp() + building = run(beta.PUBLISHER, sha="c5" * 20, branch="develop", event="workflow_dispatch", + status="in_progress", actor="dchristle") + self.repo.recipes["c5" * 20] = dict(DRIFTED) + self.internal.add(building) + self.internal.job_lists[building["id"]] = [{"name": "build-normal", "status": "in_progress", + "conclusion": None}] + self.assertRefreshAlert(building) + + def test_generation_reruns_are_ordered_by_attempt_number(self): + generation = self.publish_generation(721, "c3" * 20, DRIFTED, attempt=9) + tenth = generation.removesuffix("-9") + "-10" + for package in beta.IMAGE_PACKAGES: + self.packages.tags[package].add(tenth) + with self.assertRaisesRegex(beta.Skip, "Dispatched"): + self.cut() + self.assertEqual(self.internal.dispatches[0][2]["generation"], tenth) + + def test_recipe_drift_without_a_generation_or_refresh_stops(self): + self.publish_generation(706, "b3" * 20, RECIPES) + self.publish_generation(707, "b4" * 20, DRIFTED, packages=beta.IMAGE_PACKAGES[:3]) + self.repo.recipes["b5" * 20] = dict(RECIPES) + self.internal.add(run(beta.WARMER, sha="b5" * 20, branch="develop", status="in_progress", actor="k1jt")) + self.assertEqual(self.stop().stage, "lock") + self.assertNothingDone() + + def test_recipe_drift_waits_for_a_running_preparation(self): + generation = self.publish_generation(708, "b6" * 20, DRIFTED) + self.internal.add(preparation(generation, status="in_progress")) + with self.assertRaisesRegex(beta.Skip, "Prepare Release Dependencies"): + self.cut() + self.assertNothingDone() + + def test_recipe_drift_commits_the_prepared_lock_in_the_cut(self): + generation = self.publish_generation(709, "b7" * 20, DRIFTED) + prepared = preparation(generation, created="2026-10-06T08:00:00Z") + failed_earlier = preparation(generation, created="2026-10-06T07:00:00Z", conclusion="failure") + self.internal.add(prepared, failed_earlier) + self.internal.artifacts[prepared["id"]] = lock(DRIFTED, generation) + self.cut() + self.assertEqual(self.repo.written[LOCK], lock(DRIFTED, generation)) + self.assertIn(generation, self.repo.committed[2]) + self.assertEqual(self.repo.pushed, [(CUT, LINE)]) + self.assertEqual(self.internal.dispatches, []) + + def test_prepared_lock_for_other_recipes_or_generation_is_prepared_again(self): + generation = self.publish_generation(710, "b8" * 20, DRIFTED) + for prepared_lock in (lock(RECIPES, generation), lock(DRIFTED, "validated-build-20261001-1-1"), None): + with self.subTest(prepared_lock=prepared_lock): + self.internal.dispatches.clear() + stale = preparation(generation) + self.internal.add(stale) + self.internal.artifacts[stale["id"]] = prepared_lock + with self.assertRaisesRegex(beta.Skip, "Dispatched"): + self.cut() + self.assertEqual(self.internal.dispatches, [ + (beta.PREPARATION, "develop", {"source_branch": "develop", "generation": generation}), + ]) + + def test_failed_preparation_stops_with_its_run(self): + generation = self.publish_generation(711, "b9" * 20, DRIFTED) + failed = preparation(generation, conclusion="failure") + self.internal.add(failed) + stop = self.stop() + self.assertEqual((stop.stage, stop.link), ("lock", failed["html_url"])) + self.assertNothingDone() + + def test_a_develop_tip_with_other_recipes_alerts_instead_of_preparing_a_lock_that_would_fail(self): + generation = self.publish_generation(724, "c6" * 20, DRIFTED) + self.repo.recipes[DEVELOP] = {key: "9" * 64 for key in beta.images.IMAGES} + stop = self.stop() + self.assertEqual(stop.stage, "lock") + self.assertIn(f"develop's tip {DEVELOP} has other Linux image recipes", str(stop)) + self.assertIn(generation, str(stop)) + self.assertNothingDone() + + def test_a_running_preparation_someone_else_started_alerts(self): + generation = self.publish_generation(725, "c7" * 20, DRIFTED) + running = preparation(generation, status="in_progress", actor="dchristle") + self.internal.add(running) + stop = self.stop() + self.assertEqual((stop.stage, stop.link), ("lock", running["html_url"])) + self.assertNothingDone() + + def test_missing_branch_lock_is_prepared(self): + self.repo.recipes[GREEN] = dict(RECIPES) + self.repo.recipes[DEVELOP] = dict(RECIPES) + del self.repo.files[(TIP, LOCK)] + generation = self.publish_generation(712, "ba" * 20, RECIPES) + with self.assertRaisesRegex(beta.Skip, "Dispatched"): + self.cut() + self.assertEqual(self.internal.dispatches[0][2]["generation"], generation) + + +class MergeTest(SchedulerTestCase): + def test_metadata_conflicts_are_resolved_by_the_bot(self): + self.repo.conflicts = [STATE, LOCK] + self.cut() + self.assertEqual(self.repo.written[STATE], beta.render_state("3.3.0", 3).encode()) + self.assertEqual(self.repo.pushed, [(CUT, LINE)]) + + def test_other_conflicts_stop_without_a_push(self): + self.repo.conflicts = [STATE, "CMakeLists.txt"] + stop = self.stop() + self.assertEqual(stop.stage, "merge") + self.assertIn("CMakeLists.txt", str(stop)) + self.assertIsNone(self.repo.written) + self.assertEqual(self.repo.discarded, [Path("merge-worktree")]) + self.assertNothingDone() + + def test_lock_that_fails_validation_stops_without_a_push(self): + self.repo.validation_error = "Stale recipe for x86_64" + stop = self.stop() + self.assertEqual(stop.stage, "lock") + self.assertIn("Stale recipe", str(stop)) + self.assertIsNone(self.repo.committed) + self.assertNothingDone() + + def test_rejected_push_stops(self): + self.repo.push_error = "non-fast-forward" + self.assertEqual(self.stop().stage, "merge") + self.assertEqual(self.repo.discarded, [Path("merge-worktree")]) + + +class ContinueTest(SchedulerTestCase): + def setUp(self): + super().setUp() + self.repo.files[(TIP, STATE)] = state(number=3) + + def proceed(self, event_run): + return beta.Scheduler(self.repo, self.internal, bot_login=BOT).continue_after(event_run) + + def skipped(self, event_run): + with self.assertRaises(beta.Skip): + self.proceed(event_run) + self.assertEqual(self.internal.dispatches, []) + + def stopped(self, event_run): + with self.assertRaises(beta.Stop) as raised: + self.proceed(event_run) + self.assertEqual(self.internal.dispatches, []) + return raised.exception + + def test_green_cut_ci_dispatches_candidate_creation(self): + self.proceed(run(beta.CI)) + self.assertEqual(self.internal.dispatches, [ + (beta.CANDIDATE, LINE, {"version": "3.3.0-beta3", "expected_sha": TIP, "operation": "create"}), + ]) + self.assertEqual(self.repo.synced, [True]) + + def test_runs_not_started_by_the_release_bot_do_nothing(self): + for actor in ("k1jt", "dependabot[bot]", "github-actions[bot]"): + with self.subTest(actor=actor): + self.skipped(run(beta.CI, actor=actor)) + self.assertEqual(self.repo.synced, []) + + def test_a_person_rerunning_a_release_bot_run_resumes_the_beta(self): + self.proceed(run(beta.CI, triggering_actor="k1jt")) + self.repo.tags["build/v3.3.0-beta3"] = TIP + rerun = candidate("3.3.0-beta3", triggering_actor="dchristle") + self.proceed(rerun) + self.assertEqual([workflow for workflow, _ref, _inputs in self.internal.dispatches], + [beta.CANDIDATE, beta.PROMOTION]) + + def test_green_cut_ci_waits_for_a_candidate_already_running(self): + self.internal.add(candidate("3.3.0-beta3", status="in_progress")) + self.skipped(run(beta.CI)) + + def test_runs_away_from_the_beta_line_tip_do_nothing(self): + for fields in ({"sha": GREEN}, {"branch": "release/3.2", "sha": OLD_LINE_TIP}, {"branch": "release/3.2"}, + {"event": "pull_request"}): + with self.subTest(fields=fields): + self.skipped(run(beta.CI, **fields)) + + def test_failed_cut_ci_alerts(self): + failed = run(beta.CI, conclusion="failure") + stop = self.stopped(failed) + self.assertEqual((stop.stage, stop.link), ("ci", failed["html_url"])) + + def test_existing_candidate_tag_is_not_created_again(self): + self.repo.tags["build/v3.3.0-beta3"] = TIP + self.skipped(run(beta.CI)) + + def test_successful_candidate_dispatches_promotion(self): + self.repo.tags["build/v3.3.0-beta3"] = TIP + done = candidate("3.3.0-beta3") + self.proceed(done) + self.assertEqual(self.internal.dispatches, [(beta.PROMOTION, LINE, { + "version": "3.3.0-beta3", "candidate_run_id": str(done["id"]), "operation": "promote", + })]) + + def test_failed_candidate_alerts_that_a_rerun_resumes_or_the_next_cut_moves_on(self): + self.repo.tags["build/v3.3.0-beta3"] = TIP + failed = candidate("3.3.0-beta3", conclusion="failure") + stop = self.stopped(failed) + self.assertEqual((stop.stage, stop.link), ("candidate", failed["html_url"])) + self.assertIn("Re-run it if the failure is transient", str(stop)) + self.assertIn("moves on to BETA 4", str(stop)) + + def test_candidate_refused_before_its_tag_alerts_that_the_next_cut_retries_the_number(self): + failed = candidate("3.3.0-beta3", conclusion="failure") + stop = self.stopped(failed) + self.assertEqual((stop.stage, stop.link), ("candidate", failed["html_url"])) + self.assertIn("the next scheduled cut retries 3.3.0-beta3", str(stop)) + self.assertNotIn("BETA 4", str(stop)) + + def test_candidate_without_its_tag_at_the_tip_alerts(self): + for tag_sha in (None, GREEN): + with self.subTest(tag_sha=tag_sha): + self.repo.tags["build/v3.3.0-beta3"] = tag_sha + self.assertEqual(self.stopped(candidate("3.3.0-beta3")).stage, "candidate") + + def test_other_candidate_runs_do_nothing(self): + for other in ( + candidate("3.3.0-beta3", "validate"), + candidate("3.3.0-beta2"), + run(beta.CANDIDATE, event="workflow_dispatch", title="Prepare Release Candidate"), + ): + with self.subTest(title=other["display_title"]): + self.repo.tags["build/v3.3.0-beta3"] = TIP + self.skipped(other) + + def test_failed_promotion_alerts_so_a_rerun_can_resume(self): + failed = run(beta.PROMOTION, event="workflow_dispatch", conclusion="failure") + stop = self.stopped(failed) + self.assertEqual((stop.stage, stop.link), ("promotion", failed["html_url"])) + + def test_successful_promotion_leaves_publication_to_the_public_release_run(self): + self.skipped(run(beta.PROMOTION, event="workflow_dispatch")) + + def test_successful_bot_preparation_dispatches_the_beta_cut_on_develop(self): + self.proceed(preparation("validated-build-20261001-714-1")) + self.assertEqual(self.internal.dispatches, [(beta.BETA_CUT, "develop", {})]) + self.assertEqual(self.repo.synced, []) + + def test_other_preparation_and_develop_runs_do_nothing(self): + for other in ( + preparation("validated-build-20261001-714-1", actor="dchristle"), + preparation("validated-build-20261001-714-1", branch=LINE), + preparation("validated-build-20261001-714-1", event="push"), + run(beta.PREPARATION, event="workflow_dispatch", branch="develop", sha=DEVELOP, + title="Prepare Release Dependencies release/3.2 validated-build-20260918-35390550558-1"), + run(beta.PREPARATION, event="workflow_dispatch", branch="develop", sha=DEVELOP, + title="Prepare Release Dependencies"), + run(beta.CI, branch="develop", sha=DEVELOP), + ): + with self.subTest(path=other["path"], title=other["display_title"], branch=other["head_branch"], + event=other["event"], actor=other["actor"]["login"]): + self.skipped(other) + + def test_failed_bot_preparation_alerts(self): + failed = preparation("validated-build-20261001-714-1", conclusion="failure") + stop = self.stopped(failed) + self.assertEqual((stop.stage, stop.link), ("lock", failed["html_url"])) + + +class StepReportTest(unittest.TestCase): + def outcome(self, action): + return beta.run_step("cut", action, ["Beta line: release/3.3."]) + + def test_actions_and_skips_report_without_an_alert(self): + status, summary, alert = self.outcome(lambda: "Dispatched the candidate.") + self.assertEqual((status, alert), (0, None)) + self.assertIn("- Beta line: release/3.3.", summary) + self.assertIn("Dispatched the candidate.", summary) + + def skip(): + raise beta.Skip("develop has not moved") + status, summary, alert = self.outcome(skip) + self.assertEqual((status, alert), (0, None)) + self.assertIn("develop has not moved", summary) + + def test_stops_and_unexpected_errors_alert_and_fail(self): + def stop(): + raise beta.Stop("fixes", "release/3.3 holds a fix.", "https://example.invalid/runs/1") + + def crash(): + raise RuntimeError("API outage") + status, summary, alert = self.outcome(stop) + self.assertEqual((status, alert), (1, ("fixes", "release/3.3 holds a fix.", "https://example.invalid/runs/1"))) + self.assertIn("release/3.3 holds a fix.", summary) + with patch("traceback.print_exc"): + status, summary, alert = self.outcome(crash) + self.assertEqual((status, alert), (1, ("cut", "Unexpected error: API outage", None))) + + +class EntryPointTest(unittest.TestCase): + ENV = {"GITHUB_REPOSITORY": "example/internal", "GITHUB_RUN_ID": "5", "GITHUB_TOKEN": "workflow-token", + "RELEASE_BOT_TOKEN": "bot-token", "RELEASE_BOT_SLUG": "wsjtx-release-bot", + "PUBLIC_READ_TOKEN": "public-token"} + + def test_scheduler_acts_as_the_release_bot(self): + with patch.object(beta.GitHub, "user_id", lambda github, login: 41): + cut = beta.build_scheduler("cut", self.ENV, []) + proceed = beta.build_scheduler("continue", self.ENV, []) + self.assertEqual((cut.bot_login, cut.bot_email), (BOT, BOT_EMAIL)) + self.assertEqual((proceed.bot_login, proceed.bot_email), (BOT, None)) + self.assertEqual(cut.public.repository, beta.PUBLIC_REPOSITORY) + + def main(self, outcome): + posted = [] + with tempfile.TemporaryDirectory() as directory: + output, summary = Path(directory, "output"), Path(directory, "summary") + output.touch() + env = {**self.ENV, "GITHUB_OUTPUT": str(output), "GITHUB_STEP_SUMMARY": str(summary)} + with patch.dict(os.environ, env), \ + patch.object(beta, "build_scheduler", lambda command, environ, notes: SimpleNamespace(cut=outcome)), \ + patch.object(beta.Alerts, "post", lambda alerts, *alert: posted.append(alert)), \ + patch("sys.stdout", io.StringIO()): + status = beta.main(["cut"]) + return status, posted, output.read_text(), summary.read_text() + + def test_a_stop_is_posted_once_and_recorded_so_the_fallback_alert_stays_silent(self): + def stop(): + raise beta.Stop("candidate", "The candidate failed.", "https://example.invalid/runs/2") + status, posted, output, summary = self.main(stop) + self.assertEqual(status, 1) + self.assertEqual(posted, [("candidate", "The candidate failed.", "https://example.invalid/runs/2")]) + self.assertEqual(output, "alerted=true\n") + self.assertIn("The candidate failed.", summary) + + def test_a_skip_posts_nothing(self): + def skip(): + raise beta.Skip("develop has not moved") + status, posted, output, summary = self.main(skip) + self.assertEqual((status, posted, output), (0, [], "")) + self.assertIn("develop has not moved", summary) + + +class FakeIssuesApi: + repository = "example/internal" + + def __init__(self, issues): + self.issues = issues + self.calls = [] + + def call(self, method, path, *, params=None, body=None, missing_ok=False): + self.calls.append((method, path, params, body)) + return self.issues if method == "GET" else {} + + +class AlertsTest(unittest.TestCase): + RUN = "https://example.invalid/runs/1" + + def test_first_alert_opens_the_tracking_issue(self): + api = FakeIssuesApi([ + {"number": 5, "title": beta.ALERT_TITLE + " (old)", "user": {"login": beta.ALERT_CREATOR}}, + {"number": 6, "title": beta.ALERT_TITLE, "user": {"login": "k1jt"}}, + {"number": 7, "title": beta.ALERT_TITLE, "user": {"login": beta.ALERT_CREATOR}, "pull_request": {}}, + ]) + beta.Alerts(api, self.RUN).post("candidate", "The candidate failed.", "https://example.invalid/runs/2") + self.assertEqual(api.calls[0][:3], ("GET", "/repos/example/internal/issues", + {"state": "open", "creator": beta.ALERT_CREATOR, "per_page": 100})) + method, path, _params, body = api.calls[-1] + self.assertEqual((method, path, body["title"]), ("POST", "/repos/example/internal/issues", beta.ALERT_TITLE)) + for text in ("**Stage:** candidate", "**Reason:** The candidate failed.", + "**Run:** https://example.invalid/runs/2", f"**Reported by:** {self.RUN}"): + self.assertIn(text, body["body"]) + + def test_later_alerts_comment_on_the_open_tracking_issue(self): + api = FakeIssuesApi([ + {"number": 12, "title": beta.ALERT_TITLE, "user": {"login": beta.ALERT_CREATOR}}, + {"number": 9, "title": beta.ALERT_TITLE, "user": {"login": beta.ALERT_CREATOR}}, + ]) + beta.Alerts(api, self.RUN).post("lock", "No generation.") + method, path, _params, body = api.calls[-1] + self.assertEqual((method, path), ("POST", "/repos/example/internal/issues/9/comments")) + self.assertIn(f"**Run:** {self.RUN}", body["body"]) + self.assertNotIn("Reported by", body["body"]) + + +class FakeResponse(io.BytesIO): + def __enter__(self): + return self + + def __exit__(self, *exc): + return False + + +class GitHubClientTest(unittest.TestCase): + def test_missing_release_is_unpublished_and_other_errors_raise(self): + github = beta.GitHub("token", "example/public") + + def missing(request, timeout): + raise urllib.error.HTTPError(request.full_url, 404, "Not Found", {}, None) + with patch("urllib.request.urlopen", missing): + self.assertFalse(github.release_published("v3.3.0-beta2")) + with patch("urllib.request.urlopen", lambda request, timeout: FakeResponse(b'{"draft": false}')): + self.assertTrue(github.release_published("v3.3.0-beta2")) + + def denied(request, timeout): + raise urllib.error.HTTPError(request.full_url, 403, "Forbidden", {}, None) + with patch("urllib.request.urlopen", denied), self.assertRaisesRegex(RuntimeError, "HTTP 403"): + github.release_published("v3.3.0-beta2") + + def test_run_and_job_listings_send_their_filters(self): + requests = [] + + def urlopen(request, timeout): + requests.append(request) + return FakeResponse(json.dumps({"workflow_runs": [{"id": 1}], "jobs": [{"id": 2}]}).encode()) + + github = beta.GitHub("token", "example/internal") + with patch("urllib.request.urlopen", urlopen): + self.assertEqual(github.runs(beta.CI, branch="develop", event="push", status="success", + head_sha="ab" * 20), [{"id": 1}]) + self.assertEqual(github.jobs(77), [{"id": 2}]) + runs, jobs = (urllib.parse.urlsplit(request.full_url) for request in requests) + self.assertEqual(runs.path, f"/repos/example/internal/actions/workflows/{beta.CI}/runs") + self.assertEqual(urllib.parse.parse_qs(runs.query), { + "per_page": ["100"], "branch": ["develop"], "event": ["push"], "status": ["success"], + "head_sha": ["ab" * 20], + }) + self.assertEqual((jobs.path, urllib.parse.parse_qs(jobs.query)), + ("/repos/example/internal/actions/runs/77/jobs", {"per_page": ["100"]})) + + def test_artifact_download_follows_the_redirect_without_the_token(self): + bundle = io.BytesIO() + with zipfile.ZipFile(bundle, "w") as archive: + archive.writestr(LOCK, lock()) + requests = [] + + class Opener: + def open(self, request, timeout): + requests.append(request) + location = {"Location": "https://blob.example.invalid/a"} + raise urllib.error.HTTPError(request.full_url, 302, "Found", location, None) + + def urlopen(request, timeout): + requests.append(request) + if isinstance(request, str): + return FakeResponse(bundle.getvalue()) + return FakeResponse(json.dumps({"artifacts": [ + {"id": 9, "name": beta.PREPARED_ARTIFACT, "expired": True}, + {"id": 8, "name": beta.PREPARED_ARTIFACT, "expired": False}, + ]}).encode()) + + github = beta.GitHub("token", "example/internal") + with patch("urllib.request.urlopen", urlopen), patch("urllib.request.build_opener", lambda *handlers: Opener()): + self.assertEqual(github.artifact_file(77, beta.PREPARED_ARTIFACT, LOCK), lock()) + self.assertIn("/actions/runs/77/artifacts?", requests[0].full_url) + self.assertTrue(requests[1].full_url.endswith("/actions/artifacts/8/zip")) + self.assertEqual(requests[1].get_header("Authorization"), "Bearer token") + self.assertEqual(requests[2], "https://blob.example.invalid/a") + + +class RepositoryTest(unittest.TestCase): + """The git layer against a local origin, with no global git identity, as on a runner.""" + + def setUp(self): + directory = tempfile.TemporaryDirectory() + self.addCleanup(directory.cleanup) + self.root = Path(directory.name) + environment = patch.dict(os.environ, {"GIT_CONFIG_GLOBAL": str(self.root / "no-global-config"), + "GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_COUNT": "1", + "GIT_CONFIG_KEY_0": "user.useConfigOnly", + "GIT_CONFIG_VALUE_0": "true"}) + environment.start() + self.addCleanup(environment.stop) + self.origin = self.root / "origin.git" + self.work = self.root / "work" + self.git(self.root, "init", "--bare", "--initial-branch=develop", str(self.origin)) + self.git(self.root, "init", "--initial-branch=develop", str(self.work)) + # Background auto-maintenance would race the directory's removal. + for repository in (self.origin, self.work): + self.git(repository, "config", "maintenance.auto", "false") + (self.work / "app.txt").write_text("one\n") + (self.work / STATE).write_bytes(state("DEVEL", version="9.1.0")) + self.base = self.commit("develop base") + (self.work / STATE).write_bytes(state(number=1, version="9.1.0")) + (self.work / LOCK).write_bytes(lock()) + self.line_start = self.commit("open 9.1 beta line") + self.git(self.work, "push", str(self.origin), f"{self.line_start}:refs/heads/release/9.1") + self.git(self.work, "checkout", "--quiet", "--detach", self.base) + (self.work / "app.txt").write_text("two\n") + self.develop = self.commit("develop work") + self.git(self.work, "push", str(self.origin), f"{self.develop}:refs/heads/develop") + self.checkout = self.root / "checkout" + self.git(self.root, "clone", "--quiet", "--config", "maintenance.auto=false", + str(self.origin), str(self.checkout)) + self.repository = beta.Repository(self.checkout, str(self.origin)) + self.repository.sync() + + def git(self, cwd, *arguments): + return subprocess.run(["git", *arguments], cwd=cwd, check=True, capture_output=True, text=True).stdout.strip() + + def commit(self, message, author=MAINTAINER): + self.git(self.work, "add", "--all") + self.git(self.work, "-c", "user.name=Maintainer", "-c", f"user.email={author}", + "commit", "--quiet", "-m", message) + return self.git(self.work, "rev-parse", "HEAD") + + def origin_git(self, *arguments): + return self.git(self.origin, *arguments) + + def test_reads_refs_files_tags_and_ancestry(self): + self.assertEqual(self.repository.release_heads(), {"release/9.1": self.line_start}) + self.assertEqual(self.repository.develop(), self.develop) + self.assertEqual(self.repository.read(self.line_start, STATE), state(number=1, version="9.1.0")) + self.assertIsNone(self.repository.read(self.base, LOCK)) + self.assertTrue(self.repository.contains(self.develop)) + self.assertFalse(self.repository.contains("0" * 40)) + self.assertTrue(self.repository.is_ancestor(self.base, self.develop)) + self.assertFalse(self.repository.is_ancestor(self.line_start, self.develop)) + self.assertIsNone(self.repository.tag("build/v9.1.0-beta1")) + self.git(self.work, "push", str(self.origin), f"{self.line_start}:refs/tags/build/v9.1.0-beta1") + self.git(self.work, "-c", "user.name=Maintainer", "-c", f"user.email={MAINTAINER}", + "tag", "-a", "-m", "annotated", "annotated", self.base) + self.git(self.work, "push", str(self.origin), "refs/tags/annotated") + self.assertEqual(self.repository.tag("build/v9.1.0-beta1"), self.line_start) + self.assertEqual(self.repository.tag("annotated"), self.base) + + def test_cut_merges_develop_writes_metadata_and_pushes_as_the_bot(self): + self.assertEqual(self.repository.commits_missing_from_develop(self.line_start), + [beta.Commit(self.line_start, MAINTAINER, (LOCK, STATE))]) + worktree, conflicts = self.repository.start_merge(self.line_start, self.develop, BOT, BOT_EMAIL) + self.assertEqual(conflicts, []) + self.repository.write(worktree, {STATE: beta.render_state("9.1.0", 2).encode(), LOCK: lock(DRIFTED)}) + cut = self.repository.commit(worktree, BOT, BOT_EMAIL, "Cut 9.1.0-beta2 from develop\n") + self.repository.push(cut, "release/9.1") + self.repository.discard(worktree) + self.assertFalse(worktree.exists()) + self.assertEqual(self.origin_git("rev-parse", "refs/heads/release/9.1"), cut) + self.assertEqual(self.origin_git("show", "-s", "--format=%P%n%an <%ae>%n%cn <%ce>", cut).splitlines(), [ + f"{self.line_start} {self.develop}", f"{BOT} <{BOT_EMAIL}>", f"{BOT} <{BOT_EMAIL}>", + ]) + self.assertEqual(self.origin_git("show", f"{cut}:app.txt"), "two") + self.assertEqual(self.origin_git("show", f"{cut}:{STATE}") + "\n", beta.render_state("9.1.0", 2)) + self.assertEqual((self.origin_git("show", f"{cut}:{LOCK}") + "\n").encode(), lock(DRIFTED)) + self.repository.sync() + self.assertEqual(self.repository.commits_missing_from_develop(cut), [ + beta.Commit(cut, BOT_EMAIL, ("app.txt", LOCK, STATE)), + beta.Commit(self.line_start, MAINTAINER, (LOCK, STATE)), + ]) + + def test_fix_detection_reads_the_author_not_the_committer(self): + self.git(self.work, "checkout", "--quiet", "--detach", self.line_start) + (self.work / "app.txt").write_text("release fix\n") + self.git(self.work, "add", "--all") + subprocess.run(["git", "-c", "user.name=Maintainer", "-c", f"user.email={MAINTAINER}", + "commit", "--quiet", "-m", "fix committed by the bot"], cwd=self.work, check=True, + env={**os.environ, "GIT_COMMITTER_NAME": BOT, "GIT_COMMITTER_EMAIL": BOT_EMAIL}) + fixed = self.git(self.work, "rev-parse", "HEAD") + self.git(self.work, "push", str(self.origin), f"{fixed}:refs/heads/release/9.1") + self.repository.sync() + self.assertEqual(self.repository.commits_missing_from_develop(fixed)[0], + beta.Commit(fixed, MAINTAINER, ("app.txt",))) + + def test_full_sync_forgets_deleted_release_branches(self): + self.git(self.work, "push", str(self.origin), f"{self.line_start}:refs/heads/release/9.2") + self.repository.sync() + self.assertIn("release/9.2", self.repository.release_heads()) + self.git(self.work, "push", str(self.origin), ":refs/heads/release/9.2") + self.repository.sync() + self.assertEqual(self.repository.release_heads(), {"release/9.1": self.line_start}) + + def test_merge_reports_conflicts_and_push_refuses_to_rewind(self): + self.git(self.work, "checkout", "--quiet", "--detach", self.line_start) + (self.work / "app.txt").write_text("release fix\n") + fixed = self.commit("fix on the release branch") + self.git(self.work, "push", str(self.origin), f"{fixed}:refs/heads/release/9.1") + self.repository.sync() + worktree, conflicts = self.repository.start_merge(fixed, self.develop, BOT, BOT_EMAIL) + self.addCleanup(self.repository.discard, worktree) + self.assertEqual(conflicts, ["app.txt"]) + with self.assertRaisesRegex(RuntimeError, "git push"): + self.repository.push(self.line_start, "release/9.1") + + def test_fingerprints_run_each_commits_own_recipe_scripts(self): + shutil.copytree(ROOT / ".github", self.work / ".github") + recipes = self.commit("add the pipeline") + self.git(self.work, "push", str(self.origin), f"{recipes}:refs/heads/develop") + dockerfile = self.work / ".github/images/linux-ci/Dockerfile.noble" + dockerfile.write_text(dockerfile.read_text() + "# drift\n") + drifted = self.commit("drift the noble recipe") + self.git(self.work, "push", str(self.origin), f"{drifted}:refs/heads/develop") + self.repository.sync() + expected = { + key: subprocess.run(["bash", ".github/scripts/linux-ci-image-fingerprint.sh", spec[1]], cwd=ROOT, + check=True, capture_output=True, text=True).stdout.strip() + for key, spec in beta.images.IMAGES.items() + } + self.assertEqual(self.repository.fingerprints(recipes), expected) + changed = self.repository.fingerprints(drifted) + self.assertNotEqual(changed["x86_64"], expected["x86_64"]) + self.assertEqual(changed["armhf_runtime"], expected["armhf_runtime"]) + self.assertIsNone(self.repository.fingerprints("0" * 40)) + + def test_lock_validation_runs_the_merged_trees_validator(self): + shutil.copytree(ROOT / ".github", self.work / ".github") + (self.work / LOCK).write_text('{"schema": 2}\n') + self.commit("add the pipeline") + with self.assertRaisesRegex(RuntimeError, "Unsupported Linux image selection schema"): + self.repository.validate_lock(self.work) + + +class WorkflowWiringTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.CUT = (ROOT / ".github/workflows/beta-cut.yml").read_text() + cls.CONTINUE = (ROOT / ".github/workflows/beta-continue.yml").read_text() + + @staticmethod + def jobs(workflow): + body = workflow.split("\njobs:\n", 1)[1] + names = re.findall(r"^ ([A-Za-z0-9_-]+):$", body, re.M) + blocks = re.split(r"^ [A-Za-z0-9_-]+:$", body, flags=re.M)[1:] + return dict(zip(names, blocks)) + + def test_candidate_run_name_is_what_the_continuation_parses(self): + helper = (ROOT / ".github/workflows/release-tag-helper.yml").read_text() + run_name = re.search(r"^run-name: (.+)$", helper, re.M).group(1) + rendered = run_name.replace("${{ inputs.version }}", "3.3.0-beta2").replace("${{ inputs.operation }}", "create") + self.assertEqual(beta.candidate_of({"display_title": rendered}), ("3.3.0-beta2", "create")) + + def test_preparation_run_name_is_what_the_scheduler_parses(self): + workflow = (ROOT / ".github/workflows/prepare-release-dependencies.yml").read_text() + run_name = re.search(r"^run-name: (.+)$", workflow, re.M).group(1) + rendered = run_name.replace("${{ inputs.source_branch }}", "develop").replace( + "${{ inputs.generation }}", "validated-build-20261001-1-1") + self.assertEqual(beta.preparation_of({"display_title": rendered}), ("develop", "validated-build-20261001-1-1")) + + def test_beta_workflows_act_only_when_beta_automation_is_exactly_enabled(self): + for workflow in (self.CUT, self.CONTINUE): + jobs = self.jobs(workflow) + gate = jobs["gate"] + self.assertIn("BETA_AUTOMATION: ${{ vars.BETA_AUTOMATION }}", gate) + self.assertRegex( + gate, r'if \[ "\$BETA_AUTOMATION" = enabled \]; then\s+echo "enabled=true" >> "\$GITHUB_OUTPUT"') + self.assertIn('>> "$GITHUB_STEP_SUMMARY"', gate) + # Expression comparisons ignore case, so the variable is compared only in the shell. + self.assertEqual(workflow.count("vars.BETA_AUTOMATION"), 1) + acting = [name for name, block in jobs.items() if "environment: beta-automation" in block] + self.assertEqual(len(acting), 1) + self.assertIn("needs: gate", jobs[acting[0]]) + # Neither a manual dispatch nor always() may bypass the pause. + self.assertRegex(jobs[acting[0]], r"\n if: needs\.gate\.outputs\.enabled == 'true'\n") + + def test_beta_cut_runs_weekly_on_tuesday_at_2000_utc_and_on_dispatch(self): + triggers = re.search(r"^on:\n((?: .*\n)+)", self.CUT, re.M).group(1) + self.assertEqual(triggers, ' schedule:\n - cron: "0 20 * * 2"\n workflow_dispatch:\n') + + def test_cut_and_continuation_act_one_at_a_time(self): + for workflow in (self.CUT, self.CONTINUE): + # A workflow-level group would also hold the gate runs, whose arrival cancels a pending acting run. + self.assertNotRegex(workflow, r"(?m)^concurrency:") + acting = [block for block in self.jobs(workflow).values() if "environment: beta-automation" in block] + self.assertIn(" concurrency:\n group: beta-scheduler\n cancel-in-progress: false\n", acting[0]) + + def test_beta_continue_follows_beta_runs_and_preparations_from_develop(self): + self.assertIn( + 'on:\n workflow_run:\n' + ' workflows: ["CI", "Prepare Release Candidate", "Prepare Release Dependencies", "Promote Release Source"]\n' + ' types: [completed]\n branches: ["release/**", "develop"]\n', self.CONTINUE) + # Every other run on develop, such as a person's push CI, skips the gate and starts no job. + self.assertIn( + " if: >-\n" + " github.event.workflow_run.actor.type == 'Bot' &&\n" + " (github.event.workflow_run.head_branch != 'develop' ||\n" + " github.event.workflow_run.path == '.github/workflows/prepare-release-dependencies.yml')\n", + self.jobs(self.CONTINUE)["gate"]) + + def test_release_bot_token_is_minted_only_in_the_beta_automation_job(self): + for workflow in (self.CUT, self.CONTINUE): + for name, block in self.jobs(workflow).items(): + minted = "actions/create-github-app-token@" in block + self.assertEqual(minted, "environment: beta-automation" in block, name) + if minted: + self.assertRegex(block, r"uses: actions/create-github-app-token@[0-9a-f]{40} # v\d") + self.assertIn("client-id: ${{ vars.RELEASE_BOT_APP_ID }}", block) + self.assertIn("private-key: ${{ secrets.RELEASE_BOT_PRIVATE_KEY }}", block) + self.assertIn("persist-credentials: false", block) + self.assertIn("issues: write", block) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/scripts/tests/test_check_candidate_tag.py b/.github/scripts/tests/test_check_candidate_tag.py index cf44ccf4..9212c4ec 100644 --- a/.github/scripts/tests/test_check_candidate_tag.py +++ b/.github/scripts/tests/test_check_candidate_tag.py @@ -14,6 +14,8 @@ class CheckCandidateTagTest(unittest.TestCase): self.addCleanup(self.directory.cleanup) self.repo = Path(self.directory.name) self.git("init", "-q") + # Background auto-maintenance would race the directory's removal. + self.git("config", "maintenance.auto", "false") self.git( "-c", "user.name=Test", "-c", "user.email=test@example.com", "commit", "--allow-empty", "-qm", "first", diff --git a/.github/scripts/tests/test_ghcr_retention.py b/.github/scripts/tests/test_ghcr_retention.py index 9bffad2d..57232eba 100755 --- a/.github/scripts/tests/test_ghcr_retention.py +++ b/.github/scripts/tests/test_ghcr_retention.py @@ -51,11 +51,22 @@ class RetentionPlanTests(unittest.TestCase): version(1, 100, ("stable", "build-20260101-1-1"), self.now), version(2, 100, ("debug",), self.now), version(3, 100, (), self.now), + version(4, 100, ("buildcache",), self.now), ] plan = self.plan(versions, keep=1) self.assertEqual(plan[1].reason, "stable") self.assertEqual(plan[2].reason, "unknown-or-untagged") self.assertEqual(plan[3].reason, "unknown-or-untagged") + self.assertEqual(plan[4].reason, "unknown-or-untagged") + self.assertFalse(plan[4].delete) + + def test_prepared_release_tags_are_not_disposable_generations(self): + plan = self.plan([ + version(1, 100, ("release-deps-validated-build-20260101-1-1",), self.now), + version(2, 100, ("build-20260101-2-1", "release-deps-validated-build-20260101-2-1"), self.now), + ], keep=0) + self.assertFalse(plan[1].delete) + self.assertFalse(plan[2].delete) def test_exact_sixty_day_boundary_is_kept(self): plan = self.plan([version(1, 60, ("candidate-1-1",), self.now)], keep=1) diff --git a/.github/scripts/tests/test_linux_ccache_policy.py b/.github/scripts/tests/test_linux_ccache_policy.py index 42c97e01..4a6ff3d8 100644 --- a/.github/scripts/tests/test_linux_ccache_policy.py +++ b/.github/scripts/tests/test_linux_ccache_policy.py @@ -1,4 +1,5 @@ import pathlib +import re import unittest @@ -9,6 +10,32 @@ class LinuxCcachePolicyTests(unittest.TestCase): def read(self, relative_path): return (REPOSITORY / relative_path).read_text(encoding="utf-8") + def sanitizer_step(self, name): + action = self.read(".github/actions/build-linux-sanitizers/action.yml") + match = re.search( + rf"^ - name: {re.escape(name)}\n(?P.*?)(?=^ - |\Z)", + action, + re.MULTILINE | re.DOTALL, + ) + self.assertIsNotNone(match, name) + return match.group("body") + + def armhf_job(self, name): + workflow = self.read(".github/workflows/build-linux.yml") + body = workflow.split(f"\n {name}:\n", 1)[1] + following = re.search(r"\n [A-Za-z0-9_-]+:\n", body) + return body[:following.start() + 1] if following else body + + def armhf_step(self, name, job="build-armhf"): + workflow = self.armhf_job(job) + match = re.search( + rf"^ - name: {re.escape(name)}\n(?P.*?)(?=^ - |\Z)", + workflow, + re.MULTILINE | re.DOTALL, + ) + self.assertIsNotNone(match, name) + return match.group("body") + def assert_cache_tiers(self, text, prefix): primary = ( f"{prefix}${{{{ steps.image.outputs.ccache_compatibility_id }}}}-" @@ -42,6 +69,63 @@ class LinuxCcachePolicyTests(unittest.TestCase): action, ) + def test_sanitizer_save_requires_trusted_successful_build(self): + action = self.read(".github/actions/build-linux-sanitizers/action.yml") + save = self.sanitizer_step("Save sanitizer objects") + for condition in ( + "inputs.save_ccache == 'true'", + "github.ref == 'refs/heads/develop'", + "steps.image.outputs.recipe_match == 'true'", + "steps.ccache.outputs.cache-hit != 'true'", + ): + self.assertIn(condition, save) + self.assertNotIn("always()", save) + self.assertNotIn("!cancelled()", save) + self.assertIn("key: ${{ steps.ccache.outputs.cache-primary-key }}", save) + self.assertIn("path: ${{ steps.sanitizer.outputs.ccache_dir }}", save) + self.assertLess( + action.index("- name: Require sanitizer tests to pass"), + action.index("- name: Save sanitizer objects"), + ) + + def test_sanitizer_tests_remain_enabled_by_default(self): + workflow = self.read(".github/workflows/build-linux-sanitizers.yml") + action = self.read(".github/actions/build-linux-sanitizers/action.yml") + self.assertRegex( + workflow, + r" run_tests:\n(?: .*\n)*? type: boolean\n default: true", + ) + self.assertRegex( + action, + r' run_tests:\n(?: .*\n)*? default: "true"', + ) + self.assertIn("run_tests: ${{ inputs.run_tests }}", workflow) + self.assertIn("inputs.sanitizer == 'tsan' && 180 || 60", workflow) + + def test_build_only_sanitizer_keeps_test_targets_and_instrumentation(self): + configure = self.sanitizer_step("Configure sanitizer build") + self.assertIn("-DWSJT_ENABLE_TESTS=ON", configure) + self.assertIn("-DWSJT_ENABLE_GUI_SMOKE_TESTS=ON", configure) + for name in ( + "Configure sanitizer build", + "Build sanitizer targets", + "Verify sanitizer instrumentation", + ): + self.assertNotIn("inputs.run_tests", self.sanitizer_step(name)) + for name in ( + "Prepare test scratch directory", + "Run tests", + "Publish test summary", + "Upload test results", + "Require sanitizer tests to pass", + ): + with self.subTest(step=name): + self.assertIn("inputs.run_tests == 'true'", self.sanitizer_step(name)) + enforce = self.sanitizer_step("Require sanitizer tests to pass") + self.assertIn("always()", enforce) + self.assertIn('steps.ctest.outcome }}" != "success"', enforce) + self.assertIn("exit 1", enforce) + def test_sanitizer_cache_keeps_profile_and_generation(self): action = self.read(".github/actions/build-linux-sanitizers/action.yml") self.assert_cache_tiers( @@ -52,10 +136,6 @@ class LinuxCcachePolicyTests(unittest.TestCase): 'export CCACHE_COMPILERCHECK="${{ steps.image.outputs.ccache_compiler_check }}"', action, ) - self.assertIn( - "if: inputs.save_ccache == 'true' && steps.image.outputs.recipe_match == 'true' && steps.ccache.outputs.cache-hit != 'true'", - action, - ) def test_armhf_verifies_and_forwards_cache_identity(self): workflow = self.read(".github/workflows/build-linux.yml") @@ -72,7 +152,7 @@ class LinuxCcachePolicyTests(unittest.TestCase): workflow.count( "RUNTIME_IMAGE: ${{ needs.resolve-image.outputs.image_reference }}" ), - 2, + 4, ) self.assertIn("build-linux-armhf-cross.sh", workflow) self.assertIn("validate-linux-armhf-runtime.sh", workflow) @@ -83,16 +163,109 @@ class LinuxCcachePolicyTests(unittest.TestCase): self.assertIn("cross_recipe_match", workflow) self.assertIn("runtime_recipe_match", workflow) self.assertIn( - "if: inputs.save_ccache && steps.image.outputs.recipe_match == 'true' && steps.ccache.outputs.cache-hit != 'true'", + "if: inputs.save_ccache && (!inputs.armhf_build_only || github.ref == 'refs/heads/develop') && steps.image.outputs.recipe_match == 'true' && steps.ccache.outputs.cache-hit != 'true'", workflow, ) - def test_release_accepts_separately_promoted_armhf_recipe(self): + def test_armhf_build_only_preserves_compilation_audits_and_pair_verification(self): + workflow = self.read(".github/workflows/build-linux.yml") + self.assertEqual(len(re.findall( + r" armhf_build_only:\n(?: .*\n)*? type: boolean\n default: false", + workflow, + )), 2) + self.assertIn('if [ "$ARMHF_BUILD_ONLY" = true ] && [ "$ARCH" != armhf ]; then', workflow) + for name in ("Inspect ARMHF image pair", "Cross-build ARMHF binaries"): + self.assertNotIn("if:", self.armhf_step(name)) + compile_step = self.armhf_step("Cross-build ARMHF binaries") + self.assertIn("ARMHF_BUILD_ONLY: ${{ inputs.armhf_build_only }}", compile_step) + self.assertIn("-e ARMHF_BUILD_ONLY", compile_step) + script = self.read(".github/scripts/build-linux-armhf-cross.sh") + self.assertIn("-DWSJT_ENABLE_TESTS=ON", script) + skip_install = script.index('if [ "$ARMHF_BUILD_ONLY" = true ]; then', script.index("cmake --build")) + for audit in ("validate_linux_build_executables", ".github/scripts/audit-armhf-cross-build.sh"): + self.assertLess(script.index(audit), skip_install) + self.assertLess(skip_install, script.index("cmake --install")) + self.assertIn("exit 0", script[skip_install:script.index("cmake --install")]) + + def test_armhf_build_only_skips_runtime_and_artifact_steps(self): + test_job = self.armhf_job("test-armhf") + self.assertIn(" if: inputs.arch == 'armhf' && !inputs.armhf_build_only\n", test_job) + for name in ( + "Test and package on native ARMv7", "Publish armhf test summary", + "Upload armhf AppImage startup diagnostics", "Upload .deb", "Upload RPM", + "Upload AppImage", "Upload build artifacts", "Upload test results", + "Upload release tarballs", + ): + with self.subTest(step=name): + self.assertIn(f" - name: {name}\n", test_job) + self.assertNotIn(f" - name: {name}\n", self.armhf_job("build-armhf")) + for name in ("Pack ARMHF build tree", "Upload ARMHF build tree"): + with self.subTest(step=name): + self.assertIn("if: ${{ !inputs.armhf_build_only }}", self.armhf_step(name)) + + def test_armhf_runtime_runs_natively_on_an_arm_runner_from_the_cross_build_tree(self): + build_job = self.armhf_job("build-armhf") + test_job = self.armhf_job("test-armhf") + self.assertIn(" runs-on: ubuntu-24.04\n", build_job) + self.assertIn(" runs-on: ubuntu-24.04-arm\n", test_job) + self.assertIn(" needs: [resolve-image, build-armhf]\n", test_job) + self.assertNotIn("setup-qemu-action", test_job) + self.assertNotIn("validate-linux-armhf-runtime.sh", build_job) + self.assertIn("bash .github/scripts/validate-linux-armhf-runtime.sh", self.armhf_step("Test and package on native ARMv7", "test-armhf")) + pack = self.armhf_step("Pack ARMHF build tree") + self.assertIn( + "sudo tar --create --file armhf-build-tree.tar --exclude='wsjtx-build/*.o' --exclude='wsjtx-build/*.a' wsjtx-build AppDir\n", + pack, + ) + self.assertLess(build_job.index("- name: Save armhf ccache"), build_job.index("- name: Pack ARMHF build tree")) + for step in ("actions/checkout@", "docker/login-action@"): + self.assertIn(step, test_job) + self.assertLess(test_job.index("docker/login-action@"), test_job.index("- name: Require native 32-bit ARM execution")) + self.assertLess(test_job.index("- name: Require native 32-bit ARM execution"), test_job.index("- name: Download ARMHF build tree")) + preflight = self.armhf_step("Require native 32-bit ARM execution", "test-armhf") + self.assertIn("grep -Eq '^CPU op-mode\\(s\\):.*32-bit'", preflight) + self.assertIn("/proc/sys/fs/binfmt_misc/qemu-arm", preflight) + self.assertIn('docker run --rm --platform linux/arm/v7 "$RUNTIME_IMAGE" getconf LONG_BIT', preflight) + runtime_step = self.armhf_step("Test and package on native ARMv7", "test-armhf") + for fragment in ("docker run --rm --platform linux/arm/v7", '-v "${GITHUB_WORKSPACE}:/work"', "-w /work", "-e ARMHF_RUNTIME_PHASE"): + self.assertIn(fragment, runtime_step) + for name in ("Publish armhf test summary", "Upload test results"): + self.assertIn(" if: always()\n", self.armhf_step(name, "test-armhf")) + for name, artifact in ( + ("Upload .deb", "wsjtx-${{ inputs.version }}-linux-armhf-deb"), + ("Upload RPM", "wsjtx-${{ inputs.version }}-linux-armhf-rpm"), + ("Upload AppImage", "wsjtx-${{ inputs.version }}-linux-armhf-AppImage"), + ): + self.assertIn(f" name: {artifact}\n", self.armhf_step(name, "test-armhf")) + self.assertIn("name: armhf-build-tree\n", self.armhf_step("Upload ARMHF build tree")) + self.assertIn("name: armhf-build-tree\n", self.armhf_step("Download ARMHF build tree", "test-armhf")) + self.assertIn("tar --extract --file armhf-build-tree.tar", self.armhf_step("Unpack ARMHF build tree", "test-armhf")) + self.assertLess(test_job.index("- name: Unpack ARMHF build tree"), test_job.index("- name: Test and package on native ARMv7")) + runtime = self.read(".github/scripts/validate-linux-armhf-runtime.sh") + self.assertIn("ctest --parallel 3 --output-on-failure", runtime) + self.assertNotIn("--exclude-regex", runtime) + + def test_armhf_build_only_save_requires_trusted_successful_audits(self): + save = self.armhf_step("Save armhf ccache") + self.assertIn("(!inputs.armhf_build_only || github.ref == 'refs/heads/develop')", save) + self.assertIn("inputs.save_ccache", save) + self.assertIn("steps.image.outputs.recipe_match == 'true'", save) + self.assertIn("steps.ccache.outputs.cache-hit != 'true'", save) + self.assertIn("key: ${{ steps.ccache.outputs.cache-primary-key }}", save) + self.assertNotIn("always()", save) + self.assertNotIn("!cancelled()", save) + build_job = self.armhf_job("build-armhf") + self.assertLess(build_job.index("- name: Cross-build ARMHF binaries"), build_job.index("- name: Save armhf ccache")) + + def test_release_requires_pinned_armhf_pair_without_stale_recipe_fallback(self): workflow = self.read(".github/workflows/release.yml") armhf_job = workflow.split(" linux-armhf:\n", 1)[1].split( "\n windows:\n", 1 )[0] - self.assertIn("allow_stale_image: true", armhf_job) + self.assertNotIn("allow_stale_image: true", armhf_job) + self.assertIn("image_source: public-release", armhf_job) + self.assertIn("image_digest: ${{ needs.prepare.outputs.armhf_digest }}", armhf_job) + self.assertIn("armhf_cross_image_digest: ${{ needs.prepare.outputs.armhf_cross_digest }}", armhf_job) if __name__ == "__main__": diff --git a/.github/scripts/tests/test_linux_image_publication_policy.py b/.github/scripts/tests/test_linux_image_publication_policy.py index cb88ac95..57d0ce1f 100644 --- a/.github/scripts/tests/test_linux_image_publication_policy.py +++ b/.github/scripts/tests/test_linux_image_publication_policy.py @@ -1,5 +1,10 @@ +import fnmatch +import os import pathlib import re +import subprocess +import tempfile +import textwrap import unittest @@ -10,10 +15,10 @@ WARM = (ROOT / ".github/workflows/warm-dependency-caches.yml").read_text() CLASSIFIER = (ROOT / ".github/scripts/is-linux-ci-image-input.sh").read_text() -def job(name: str) -> str: +def job(name: str, workflow: str = PUBLISH) -> str: match = re.search( rf"^ {re.escape(name)}:\n(?P.*?)(?=^ [a-z][a-z0-9-]*:\n|\Z)", - PUBLISH, + workflow, re.MULTILINE | re.DOTALL, ) if not match: @@ -22,6 +27,219 @@ def job(name: str) -> str: class LinuxImagePublicationPolicyTests(unittest.TestCase): + def test_armhf_cross_cache_import_and_export_share_registry_destination(self): + metadata = job("metadata") + for package_root in ("ghcr.io/wsjtx/wsjtx", "ghcr.io/wsjtx/wsjtx-internal"): + self.assertIn( + f"armhf_cross_cache_from=type=registry,ref={package_root}/linux-armhf-cross-bookworm:buildcache", + metadata, + ) + cross = job("build-armhf-cross") + self.assertIn("cache-from: ${{ needs.metadata.outputs.armhf_cross_cache_from }}", cross) + self.assertIn( + "cache-to: type=registry,ref=${{ needs.metadata.outputs.package_root }}/linux-armhf-cross-bookworm:buildcache,mode=max", + cross, + ) + + def select_warmers(self, event, *, target="", schedule="", paths=()): + selector = re.search( + r" run: \|\n(?P.*?)(?=^ refresh-linux-images:)", + WARM, + re.MULTILINE | re.DOTALL, + ).group("body") + git_stub = """ +git() { + case "$1" in + cat-file) return 0 ;; + diff) printf '%s\\n' "$CHANGED_PATHS" ;; + *) return 2 ;; + esac +} +""" + with tempfile.TemporaryDirectory() as directory: + output = pathlib.Path(directory) / "output" + result = subprocess.run( + ["bash", "-c", git_stub + textwrap.dedent(selector)], + cwd=ROOT, + env={ + **os.environ, + "EVENT_NAME": event, + "TARGETS": target, + "SCHEDULE": schedule, + "BEFORE_SHA": "previous", + "CURRENT_SHA": "current", + "CHANGED_PATHS": "\n".join(paths), + "HAMLIB_BRANCH": "4.7.2", + "GITHUB_OUTPUT": str(output), + "GITHUB_STEP_SUMMARY": str(pathlib.Path(directory) / "summary"), + }, + capture_output=True, + text=True, + timeout=10, + ) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + return dict(line.split("=", 1) for line in output.read_text().splitlines()) + + def test_macos_warmer_selection_routes_both_architectures(self): + cases = [ + ({"event": "workflow_dispatch", "target": "macos-x86_64"}, "false", "true"), + ({"event": "workflow_dispatch", "target": "macos-arm64"}, "true", "false"), + ({"event": "workflow_dispatch", "target": "macos"}, "true", "true"), + ({"event": "workflow_dispatch", "target": "all"}, "true", "true"), + ({"event": "workflow_dispatch", "target": "linux"}, "false", "false"), + ({"event": "schedule", "schedule": "23 10 * * 1"}, "true", "true"), + ] + for path in ( + ".github/workflows/build-macos.yml", ".github/actions/warm-macos-deps/action.yml", + ".github/scripts/install-xpack-gfortran-macos.sh", ".github/scripts/build-qt-macos.sh", + ".github/scripts/macos-qt-cache-key.sh", ".github/scripts/verify-macos-static-archives.sh", + ".github/workflows/ci.yml", ".github/workflows/release.yml", + ): + cases.append(({"event": "push", "paths": [path]}, "true", "true")) + for inputs, arm, intel in cases: + with self.subTest(inputs=inputs): + outputs = self.select_warmers(**inputs) + self.assertEqual(outputs["macos_arm64"], arm) + self.assertEqual(outputs["macos_x86_64"], intel) + + def test_asan_warmer_selection(self): + cases = [ + ({"event": "schedule", "schedule": "23 10 * * 1"}, "true", "none"), + ({"event": "workflow_dispatch", "target": "linux-asan-ubsan"}, "true", "none"), + ({"event": "workflow_dispatch", "target": "all"}, "true", "normal"), + ({"event": "workflow_dispatch", "target": "linux-tsan"}, "false", "tsan"), + ({"event": "push", "paths": [".github/scripts/build-hamlib-linux.sh"]}, "false", "normal"), + ({"event": "push", "paths": [".github/scripts/build-qt-tsan-linux.sh"]}, "false", "tsan"), + ({"event": "push", "paths": ["CMakeLists.txt", ".github/scripts/verify-linux-ci-image.sh"]}, "true", "normal-and-tsan"), + ({"event": "push", "paths": ["mainwindow.cpp"]}, "false", "none"), + ] + for arguments, selected, image_set in cases: + with self.subTest(arguments=arguments): + outputs = self.select_warmers(**arguments) + self.assertEqual(outputs["linux_asan_ubsan"], selected) + self.assertEqual(outputs["image_set"], image_set) + + def test_armhf_warmer_selection(self): + cases = [ + ({"event": "schedule", "schedule": "23 10 * * 1"}, "true", "none"), + ({"event": "workflow_dispatch", "target": "linux-armhf"}, "true", "none"), + ({"event": "workflow_dispatch", "target": "all"}, "true", "normal"), + ({"event": "workflow_dispatch", "target": "linux-tsan"}, "false", "tsan"), + ({"event": "push", "paths": [".github/images/linux-ci/Dockerfile.armhf-cross"]}, "false", "normal"), + ({"event": "push", "paths": ["mainwindow.cpp"]}, "false", "none"), + ] + for arguments, selected, image_set in cases: + with self.subTest(arguments=arguments): + outputs = self.select_warmers(**arguments) + self.assertEqual(outputs["linux_armhf"], selected) + self.assertEqual(outputs["image_set"], image_set) + + def test_armhf_build_inputs_select_warming(self): + push_filters = re.findall(r'^ - "([^"]+)"$', WARM.split(" schedule:", 1)[0], re.MULTILINE) + for path in ( + ".github/workflows/build-linux.yml", + ".github/scripts/build-linux-armhf-cross.sh", + ".github/scripts/audit-armhf-cross-build.sh", + ".github/cmake/armhf-toolchain.cmake", + ".github/scripts/linux-artifact-validation.sh", + "CMakeLists.txt", "CMake/Sources.cmake", "tests/unit/CMakeLists.txt", + ): + with self.subTest(path=path): + self.assertTrue(any(fnmatch.fnmatchcase(path, pattern) for pattern in push_filters)) + outputs = self.select_warmers("push", paths=[path]) + self.assertEqual(outputs["linux_armhf"], "true") + self.assertEqual(outputs["image_set"], "none") + + def test_armhf_warmers_share_configuration_and_serialize(self): + standalone = job("warm-linux-armhf-ccache", WARM) + published = job("warm-armhf-ccache") + for warmer in (standalone, published): + for required in ( + "github.ref == 'refs/heads/develop'", + "uses: ./.github/workflows/build-linux.yml", "arch: armhf", + "armhf_build_only: true", "allow_stale_image: false", + "recache: false", "save_ccache: true", + "group: armhf-ccache-develop", "cancel-in-progress: false", + "contents: read", "packages: read", + ): + self.assertIn(required, warmer) + self.assertNotIn("packages: write", warmer) + for condition in ( + "needs.detect.outputs.linux_armhf == 'true'", + "needs.detect.outputs.image_set != 'normal'", + "needs.detect.outputs.image_set != 'normal-and-tsan'", + ): + self.assertIn(condition, standalone) + self.assertIn("- warm-linux-armhf-ccache", job("summary", WARM)) + for condition in ( + "needs.promote.result == 'success'", "inputs.publication_target == 'internal'", + "inputs.mode == 'refresh'", "inputs.promote", "inputs.include_armhf", + "(inputs.image_set == 'normal' || inputs.image_set == 'normal-and-tsan')", + "image_tag: ${{ needs.metadata.outputs.build_tag }}", + ): + self.assertIn(condition, published) + self.assertIn("- metadata", published) + self.assertIn("- promote", published) + self.assertNotIn("warm-armhf-ccache", job("promote")) + + def test_sanitizer_build_inputs_select_warming(self): + push_filters = re.findall( + r'^ - "([^"]+)"$', + WARM.split(" schedule:", 1)[0], + re.MULTILINE, + ) + for path in ( + ".github/workflows/build-linux-sanitizers.yml", + ".github/actions/build-linux-sanitizers/action.yml", + ".github/scripts/verify-sanitizer-instrumentation.py", + "CMakeLists.txt", + "CMake/Sources.cmake", + "tests/CMakeLists.txt", + "tests/unit/CMakeLists.txt", + ): + with self.subTest(path=path): + self.assertTrue(any(fnmatch.fnmatchcase(path, pattern) for pattern in push_filters)) + outputs = self.select_warmers("push", paths=[path]) + self.assertEqual(outputs["linux_asan_ubsan"], "true") + self.assertEqual(outputs["image_set"], "none") + + def test_asan_warmers_share_configuration_and_serialize(self): + standalone = job("warm-linux-asan-ubsan-ccache", WARM) + published = job("warm-asan-ubsan-ccache") + for warmer in (standalone, published): + with self.subTest(warmer=warmer): + for required in ( + "github.ref == 'refs/heads/develop'", + "uses: ./.github/workflows/build-linux-sanitizers.yml", + "sanitizer: asan-ubsan", + "run_tests: false", + "recache: false", + "save_ccache: true", + "allow_stale_image: false", + "group: asan-ubsan-ccache-develop", + "cancel-in-progress: false", + "contents: read", + "packages: read", + ): + self.assertIn(required, warmer) + self.assertNotIn("packages: write", warmer) + self.assertIn("needs.detect.outputs.linux_asan_ubsan == 'true'", standalone) + self.assertIn("needs.detect.outputs.image_set != 'normal'", standalone) + self.assertIn("needs.detect.outputs.image_set != 'normal-and-tsan'", standalone) + self.assertIn("- warm-linux-asan-ubsan-ccache", job("summary", WARM)) + + def test_asan_warming_follows_internal_promotion_without_gating_it(self): + warm = job("warm-asan-ubsan-ccache") + self.assertIn("metadata", warm) + self.assertIn("promote", warm) + self.assertIn("needs.promote.result == 'success'", warm) + self.assertIn("inputs.publication_target == 'internal'", warm) + self.assertIn("inputs.mode == 'refresh'", warm) + self.assertIn("inputs.promote", warm) + self.assertIn("(inputs.image_set == 'normal' || inputs.image_set == 'normal-and-tsan')", warm) + self.assertIn("image_tag: ${{ needs.metadata.outputs.build_tag }}", warm) + self.assertNotIn("warm-asan-ubsan-ccache", job("promote")) + def test_public_release_publication_is_tag_scoped_and_complete(self): validate = job("validate-inputs") self.assertIn('[ "$REQUEST_REPOSITORY" != WSJTX/wsjtx ]', validate) @@ -177,5 +395,35 @@ class LinuxImagePublicationPolicyTests(unittest.TestCase): self.assertIn("stable_packages+=(linux-noble)", rollback) + def test_release_paths_consume_the_same_committed_selection(self): + candidate = (ROOT / ".github/workflows/release.yml").read_text() + public = (ROOT / ".github/workflows/public-release.yml").read_text() + tagging = (ROOT / ".github/workflows/release-tag-helper.yml").read_text() + promotion = (ROOT / ".github/workflows/promote-release.yml").read_text() + for workflow in (candidate, public): + self.assertIn("release-linux-images.py validate release-linux-images.json", workflow) + self.assertIn('--check-remote --github-output "$GITHUB_OUTPUT"', workflow) + self.assertEqual(workflow.count("image_source: public-release"), 3) + for output in ("x86_64_digest", "aarch64_digest", "armhf_digest", "armhf_cross_digest"): + self.assertIn("needs.prepare.outputs." + output, workflow) + self.assertNotIn("allow_stale_image: true", workflow) + self.assertNotIn("resolve-linux-ci-image-tag.py", workflow) + self.assertNotIn("publish-linux-ci-images.yml", public) + self.assertNotIn("packages: write", public) + self.assertIn( + "environment: ${{ needs.prepare.outputs.release_channel == 'BETA' && 'beta-release' || 'public-release' }}", + public, + ) + self.assertIn("linux_images: $linux_images", candidate) + self.assertIn("release-linux-images.py provenance release-linux-images.json", candidate) + self.assertIn("release-linux-images.py verify-provenance", promotion) + self.assertLess(tagging.index("release-linux-images.py validate"), tagging.index("- name: Create candidate tag")) + + def test_prepared_image_consumption_keeps_source_and_recipe_guards(self): + self.assertIn("WSJTX/wsjtx:refs/tags/v*|WSJTX/wsjtx-internal:refs/heads/release/*", BUILD) + self.assertIn('if [ "$ALLOW_STALE_IMAGE" = true ]; then', BUILD) + self.assertIn("Prepared public images require strict recipe verification", BUILD) + + if __name__ == "__main__": unittest.main() diff --git a/.github/scripts/tests/test_native_cache_policy.py b/.github/scripts/tests/test_native_cache_policy.py new file mode 100644 index 00000000..274344c6 --- /dev/null +++ b/.github/scripts/tests/test_native_cache_policy.py @@ -0,0 +1,86 @@ +import importlib.util +import pathlib +import os +import subprocess +import sys +import re +import unittest + +ROOT = pathlib.Path(__file__).resolve().parents[3] +SPEC = importlib.util.spec_from_file_location( + "summary", ROOT / ".github/scripts/summarize-native-caches.py") +summary = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(summary) + + +class NativeCachePolicyTests(unittest.TestCase): + def test_compiler_only_command(self): + result = subprocess.run( + [sys.executable, str(SPEC.origin), "--compiler"], + env={**os.environ, "CACHE_STEPS": "{}", "COLD_BUILD": "true"}, + capture_output=True, text=True, check=True) + self.assertIn("| Compiler objects | bypassed (cold build) | not run |", result.stdout) + + def test_unknown_dependency_is_rejected(self): + result = subprocess.run( + [sys.executable, str(SPEC.origin), "unknown"], + env={**os.environ, "CACHE_STEPS": "{}"}, + capture_output=True, text=True) + self.assertEqual(result.returncode, 2) + self.assertIn("unknown dependency: unknown", result.stderr) + + def test_restore_outcomes(self): + cases = [ + ({}, "not run"), + ({"outcome": "failure"}, "failure"), + ({"outcome": "cancelled"}, "cancelled"), + ({"outcome": "success", "outputs": {"cache-hit": "true"}}, "exact hit"), + ({"outcome": "success", "outputs": {"cache-hit": "false", "cache-matched-key": "older"}}, "fallback restore"), + ({"outcome": "success", "outputs": {"cache-hit": ""}}, "miss"), + ] + for step, expected in cases: + with self.subTest(expected=expected): + self.assertEqual(summary.restore_status(step, False), expected) + self.assertEqual(summary.restore_status({}, True), "bypassed (cold build)") + + def test_failed_rebuild_and_forced_recompilation_are_distinct(self): + report = summary.render({ + "qt-cache": {"outcome": "success"}, + "qt-build": {"outcome": "failure"}, + "ccache": {"outcome": "success", "outputs": {"cache-hit": "true"}}, + "compile": {"outcome": "skipped"}, + }, ["qt"], recache=True, compiler=True) + self.assertIn("| Qt | miss | failure |", report) + self.assertIn("| Compiler objects | exact hit | not run; forced recompilation requested |", report) + + def test_cold_build_blocks_every_workflow_cache_restore_and_save(self): + for platform in ["macos", "windows"]: + text = (ROOT / f".github/workflows/build-{platform}.yml").read_text() + self.assertEqual(len(re.findall(r"^ cold_build:", text, re.M)), 2) + for step in re.split(r"^ - ", text, flags=re.M)[1:]: + if "uses: actions/cache/" in step: + self.assertIn("!inputs.cold_build", step) + self.assertIn("CCACHE_DIR=$(mktemp -d", text) + self.assertIn("id: compile", text) + windows = (ROOT / ".github/workflows/build-windows.yml").read_text() + self.assertIn("cache: ${{ !inputs.cold_build }}", windows) + self.assertIn("cold_build: ${{ inputs.cold_build }}", windows) + action = (ROOT / ".github/actions/build-windows-deps/action.yml").read_text() + for step in re.split(r"^ - ", action, flags=re.M)[1:]: + if "uses: actions/cache/" in step: + self.assertIn("inputs.cold_build != 'true'", step) + + def test_summaries_run_after_failures(self): + paths = [".github/workflows/build-macos.yml", ".github/workflows/build-windows.yml", + ".github/actions/warm-macos-deps/action.yml", ".github/actions/build-windows-deps/action.yml"] + for path in paths: + text = (ROOT / path).read_text() + for step in re.split(r"^\s+- name: ", text, flags=re.M)[1:]: + if step.startswith("Summarize"): + self.assertIn("if: always()", step) + warmer = (ROOT / ".github/workflows/warm-dependency-caches.yml").read_text() + self.assertIn(" summary:\n if: always()", warmer) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/scripts/tests/test_package_cli_tools.py b/.github/scripts/tests/test_package_cli_tools.py new file mode 100644 index 00000000..45e94497 --- /dev/null +++ b/.github/scripts/tests/test_package_cli_tools.py @@ -0,0 +1,745 @@ +import os +import pathlib +import subprocess +import tarfile +import tempfile +import unittest + + +ROOT = pathlib.Path(__file__).resolve().parents[3] +SCRIPT = ROOT / ".github/scripts/package-cli-tools.sh" +SMOKE = ROOT / ".github/scripts/smoke-release-tarballs.sh" +BUILD_MACOS = ROOT / ".github/workflows/build-macos.yml" + + +OTOOL_STUB = """#!/bin/sh +case "$1" in -L) kind=refs ;; -l) kind=load ;; -D) kind=id ;; *) exit 2 ;; esac +echo "$2:" +fixture="$STUB_FIXTURES/otool.$kind.$(basename "$2")" +if [ -f "$fixture" ]; then cat "$fixture"; fi +""" + +OBJDUMP_STUB = """#!/bin/sh +fixture="$STUB_FIXTURES/objdump.$(basename "$2")" +[ -f "$fixture.fail" ] && exit 1 +if [ -f "$fixture" ]; then cat "$fixture"; fi +""" + +READELF_STUB = """#!/bin/sh +case "$1" in -dW) kind=d ;; -VW) kind=V ;; *) exit 2 ;; esac +fixture="$STUB_FIXTURES/readelf.$kind.$(basename "$2")" +if [ -f "$fixture" ]; then cat "$fixture"; fi +""" + +# Copies each --executable into the AppDir, and into usr/lib the libraries +# $STUB_FIXTURES/deploys. names, as linuxdeploy deploys them. +LINUXDEPLOY_STUB = """#!/bin/sh +printf '%s\\n' "$*" "token=${GITHUB_TOKEN-unset}" "extract=${APPIMAGE_EXTRACT_AND_RUN-unset}" >> "$STUB_FIXTURES/linuxdeploy.log" +[ -f "$STUB_FIXTURES/linuxdeploy.fail" ] && exit 1 +appdir="" +while [ "$#" -gt 0 ]; do + case "$1" in + --appdir) appdir="$2"; shift 2 ;; + --executable) + mkdir -p "$appdir/usr/bin" "$appdir/usr/lib" + [ -f "$STUB_FIXTURES/linuxdeploy.skip-programs" ] || cp "$2" "$appdir/usr/bin/" + while read -r library; do cp "$STUB_FIXTURES/appdir-lib/$library" "$appdir/usr/lib/"; done < "$STUB_FIXTURES/deploys.$(basename "$2")" + shift 2 ;; + *) shift ;; + esac +done +mkdir -p "$appdir/usr/share/doc/libqt5core5t64" +echo copyright > "$appdir/usr/share/doc/libqt5core5t64/copyright" +""" + + +def needed(*libraries, runpath=None): + lines = [f" 0x0000000000000001 (NEEDED) Shared library: [{library}]" for library in libraries] + if runpath is not None: + lines.append(f" 0x000000000000001d (RUNPATH) Library runpath: [{runpath}]") + return lines + + +def versions(*names): + return [ + "Version symbols section '.gnu.version' contains 9 entries:", + " 000: 0 (*local*) 2 (GLIBC_9.99)", + "Version needs section '.gnu.version_r' contains 1 entry:", + " 000000: Version: 1 File: libc.so.6 Cnt: 1", + *(f" 0x0010: Name: {name} Flags: none Version: 2" for name in names), + ] + + +def rpath(path): + return ["Load command 12", " cmd LC_RPATH", " cmdsize 32", f" path {path} (offset 12)"] + + +def minos(version): + return ["Load command 9", " cmd LC_BUILD_VERSION", " cmdsize 32", " platform 1", f" minos {version}"] + + +def version_min_macosx(version): + return ["Load command 9", " cmd LC_VERSION_MIN_MACOSX", " cmdsize 16", f" version {version}", " sdk 15.0"] + + +MINOS = minos("11.0") + + +class PackageCliToolsTests(unittest.TestCase): + def setUp(self): + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + self.root = pathlib.Path(temporary.name) + self.bin = self.root / "bin" + self.fixtures = self.root / "fixtures" + self.source = self.root / "build" + self.out = self.root / "out" + for directory in (self.bin, self.fixtures, self.source): + directory.mkdir() + for name, body in ( + ("otool", OTOOL_STUB), ("objdump", OBJDUMP_STUB), ("readelf", READELF_STUB), + ("linuxdeploy", LINUXDEPLOY_STUB), + ): + (self.bin / name).write_text(body, encoding="utf-8") + (self.bin / name).chmod(0o755) + + def fixture(self, name, lines): + (self.fixtures / name).write_text("".join(f"{line}\n" for line in lines), encoding="utf-8") + + def files(self, directory, names): + directory.mkdir(parents=True, exist_ok=True) + for name in names: + (directory / name).write_text(name, encoding="utf-8") + + def package(self, platform, groups, *arguments, newline="\n"): + groups_file = self.root / "release-tarballs.txt" + groups_file.write_bytes(("# comment" + newline + newline.join(groups) + newline).encode()) + return subprocess.run( + [ + "bash", str(SCRIPT), "--platform", platform, "--version", "9.9.9", "--arch", "x86_64", + "--groups", str(groups_file), "--source", str(self.source), "--out", str(self.out), *arguments, + ], + env=dict( + os.environ, PATH=f"{self.bin}:{os.environ['PATH']}", TMPDIR=str(self.root), + STUB_FIXTURES=str(self.fixtures), GITHUB_TOKEN="secret", + ), + text=True, + capture_output=True, + check=False, + ) + + def members(self, name): + with tarfile.open(self.out / f"{name}.tar.gz") as archive: + tops = {member.name.split("/", 1)[0] for member in archive.getmembers()} + self.assertEqual(tops, {name}) + return sorted(member.name.split("/", 1)[1] for member in archive.getmembers() if member.isfile()) + + def text(self, name, member): + with tarfile.open(self.out / f"{name}.tar.gz") as archive: + return archive.extractfile(f"{name}/{member}").read().decode() + + def assert_failed(self, result, *messages): + self.assertEqual(result.returncode, 1, result.stderr) + for message in messages: + self.assertIn(message, result.stderr) + self.assertFalse(self.out.exists() and any(self.out.iterdir())) + + # macOS: the CLI assets directory as deploy-macos-cli-tools.sh leaves it. + # Fixture names differ by more than case: macOS file systems ignore it. + def macos_assets(self): + self.files(self.source, ["jt9", "jt9stream", "wsprd", "encode77"]) + self.files(self.source / "lib", ["QtCore", "libfftw3f.3.dylib", "libfftw3f_threads.3.dylib", "libmystery.dylib"]) + for program in ("jt9", "jt9stream", "encode77"): + self.fixture(f"otool.load.{program}", rpath("@loader_path/lib") + MINOS) + self.fixture("otool.load.wsprd", rpath("@loader_path") + rpath("@loader_path/lib") + MINOS) + for library in ("QtCore", "libfftw3f.3.dylib", "libfftw3f_threads.3.dylib"): + self.fixture(f"otool.load.{library}", MINOS) + self.fixture(f"otool.id.{library}", [f"@rpath/{library}"]) + self.fixture("otool.id.libfftw3f.3.dylib", ["/Users/runner/work/fftw-prefix/lib/libfftw3f.3.dylib"]) + self.fixture("otool.refs.jt9", [ + "\t@rpath/libfftw3f_threads.3.dylib (compatibility version 9.0.0, current version 9.10.0)", + "\t@rpath/QtCore (compatibility version 5.15.0, current version 5.15.18)", + "\t/usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 1900.180.0)", + ]) + self.fixture("otool.refs.jt9stream", ["\t@rpath/libfftw3f_threads.3.dylib (compatibility version 9.0.0)"]) + self.fixture("otool.refs.wsprd", ["\t@rpath/libfftw3f.3.dylib (compatibility version 9.0.0)"]) + self.fixture("otool.refs.encode77", ["\t/usr/lib/libSystem.B.dylib (compatibility version 1.0.0)"]) + self.fixture("otool.refs.QtCore", [ + "\t@rpath/QtCore (compatibility version 5.15.0)", + "\t/System/Library/Frameworks/IOKit.framework/Versions/A/IOKit (compatibility version 1.0.0)", + ]) + self.fixture("otool.refs.libfftw3f_threads.3.dylib", [ + "\t@rpath/libfftw3f_threads.3.dylib (compatibility version 9.0.0)", + "\t@rpath/libfftw3f.3.dylib (compatibility version 9.0.0)", + ]) + self.fixture("otool.refs.libfftw3f.3.dylib", ["\t/Users/runner/work/fftw-prefix/lib/libfftw3f.3.dylib (compatibility version 9.0.0)"]) + + MACOS_GROUPS = ["jt9 jt9", "jt9stream jt9stream", "wsprd wsprd", "utilities encode77"] + + def test_macos_tarballs_hold_each_group_and_the_dylibs_it_reaches(self): + self.macos_assets() + result = self.package("macos", self.MACOS_GROUPS) + self.assertEqual(result.returncode, 0, result.stderr) + documents = ["COPYING", "README.txt", "THIRD-PARTY.txt"] + self.assertEqual( + self.members("wsjtx-9.9.9-x86_64-macOS-jt9"), + sorted([*documents, "jt9", "lib/QtCore", "lib/libfftw3f.3.dylib", "lib/libfftw3f_threads.3.dylib"]), + ) + self.assertEqual( + self.members("wsjtx-9.9.9-x86_64-macOS-jt9stream"), + sorted([*documents, "jt9stream", "lib/libfftw3f.3.dylib", "lib/libfftw3f_threads.3.dylib"]), + ) + self.assertEqual( + self.members("wsjtx-9.9.9-x86_64-macOS-wsprd"), sorted([*documents, "wsprd", "lib/libfftw3f.3.dylib"]) + ) + self.assertEqual(self.members("wsjtx-9.9.9-x86_64-macOS-utilities"), sorted([*documents, "encode77"])) + readme = self.text("wsjtx-9.9.9-x86_64-macOS-jt9", "README.txt") + self.assertIn("They require macOS 11.0 or later.", readme) + self.assertIn("xattr -d com.apple.quarantine", readme) + self.assertIn("wsjtx-9.9.9-src.tar.gz", readme) + self.assertIn("GNU General Public License version 3 (COPYING)", readme) + self.assertIn("are Copyright (C) 2001-", readme) + self.assertIn("Joseph Taylor, K1JT;", readme) + self.assertTrue(readme.rstrip().endswith("other members of the WSJT Development Group."), readme) + self.assertNotIn("_{prog}_", readme) + self.assertIn("jt9stream, in its own tarball, is the same decoder", readme) + self.assertNotIn("mingw-w64", self.text("wsjtx-9.9.9-x86_64-macOS-jt9", "THIRD-PARTY.txt")) + notices = self.text("wsjtx-9.9.9-x86_64-macOS-jt9", "THIRD-PARTY.txt") + self.assertIn("Files: QtCore", notices) + self.assertIn("Files: libfftw3f.3.dylib libfftw3f_threads.3.dylib", notices) + utilities = self.text("wsjtx-9.9.9-x86_64-macOS-utilities", "THIRD-PARTY.txt") + self.assertIn("GCC runtime libraries\n License: GPL-3.0-or-later WITH GCC-exception-3.1\n", utilities) + self.assertIn(" Linked statically into the programs\n", utilities) + self.assertNotIn("Files:", utilities) + self.assertEqual( + self.text("wsjtx-9.9.9-x86_64-macOS-wsprd", "COPYING"), (ROOT / "COPYING").read_text(encoding="utf-8") + ) + + def test_macos_unresolved_rpath_reference_fails_naming_it(self): + self.macos_assets() + with (self.fixtures / "otool.refs.wsprd").open("a", encoding="utf-8") as stream: + stream.write("\t@rpath/libmissing.dylib (compatibility version 1.0.0)\n") + self.assert_failed(self.package("macos", self.MACOS_GROUPS), "@rpath/libmissing.dylib(wsprd)") + + def test_macos_build_tree_reference_fails(self): + self.macos_assets() + self.fixture("otool.refs.encode77", ["\t/opt/homebrew/lib/libgfortran.5.dylib (compatibility version 6.0.0)"]) + self.assert_failed(self.package("macos", self.MACOS_GROUPS), "/opt/homebrew/lib/libgfortran.5.dylib(encode77)") + + def test_macos_absolute_rpath_fails(self): + self.macos_assets() + self.fixture("otool.load.libfftw3f.3.dylib", rpath("/Users/runner/work/fftw-prefix/lib") + MINOS) + self.assert_failed( + self.package("macos", self.MACOS_GROUPS), + "lib/libfftw3f.3.dylib has an absolute LC_RPATH: /Users/runner/work/fftw-prefix/lib", + ) + + def test_macos_program_with_absolute_rpath_fails(self): + self.macos_assets() + self.fixture("otool.load.wsprd", rpath("@loader_path/lib") + rpath("/opt/homebrew/lib") + MINOS) + self.assert_failed(self.package("macos", self.MACOS_GROUPS), "wsprd has an absolute LC_RPATH: /opt/homebrew/lib") + + def test_macos_library_missing_from_notices_table_fails(self): + self.macos_assets() + self.fixture("otool.refs.encode77", ["\t@rpath/libmystery.dylib (compatibility version 1.0.0)"]) + self.assert_failed( + self.package("macos", ["utilities encode77", "jt9 jt9"]), + "bundled libraries missing from third-party-libraries.tsv: libmystery.dylib", + ) + + def test_macos_dylib_outside_lib_fails(self): + self.macos_assets() + self.files(self.source, ["libfftw3f_top.dylib"]) + self.fixture("otool.refs.wsprd", ["\t@rpath/libfftw3f_top.dylib (compatibility version 1.0.0)"]) + self.assert_failed(self.package("macos", self.MACOS_GROUPS), "@rpath/libfftw3f_top.dylib(wsprd)") + + def test_macos_rpath_references_resolve_through_their_own_program(self): + self.macos_assets() + self.files(self.source, ["wsprcode"]) + self.files(self.source / "lib/extra", ["libfftw3f_extra.dylib"]) + self.fixture("otool.load.wsprcode", rpath("@executable_path/lib/extra") + rpath("@loader_path/lib") + MINOS) + self.fixture("otool.load.libfftw3f_extra.dylib", MINOS) + self.fixture("otool.refs.wsprcode", ["\t@rpath/libfftw3f_extra.dylib (compatibility version 1.0.0)"]) + result = self.package("macos", ["utilities wsprcode"]) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("lib/extra/libfftw3f_extra.dylib", self.members("wsjtx-9.9.9-x86_64-macOS-utilities")) + self.out.joinpath("wsjtx-9.9.9-x86_64-macOS-utilities.tar.gz").unlink() + self.fixture("otool.refs.encode77", ["\t@rpath/libfftw3f_extra.dylib (compatibility version 1.0.0)"]) + self.assert_failed(self.package("macos", ["utilities wsprcode encode77"]), "@rpath/libfftw3f_extra.dylib(encode77)") + + def test_macos_loader_path_references_resolve_beside_the_dylib(self): + self.macos_assets() + self.fixture("otool.refs.libfftw3f_threads.3.dylib", ["\t@loader_path/libfftw3f.3.dylib (compatibility version 9.0.0)"]) + result = self.package("macos", self.MACOS_GROUPS) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("lib/libfftw3f.3.dylib", self.members("wsjtx-9.9.9-x86_64-macOS-jt9stream")) + + def test_macos_reference_escaping_the_source_fails(self): + self.macos_assets() + self.files(self.root, ["outside.dylib"]) + self.fixture("otool.refs.libfftw3f_threads.3.dylib", ["\t@loader_path/../../outside.dylib (compatibility version 1.0.0)"]) + self.assert_failed(self.package("macos", self.MACOS_GROUPS), "@loader_path/../../outside.dylib(lib/libfftw3f_threads.3.dylib)") + + def test_macos_program_rpath_outside_its_directory_fails(self): + self.macos_assets() + self.fixture("otool.load.jt9", rpath("@loader_path/../lib") + MINOS) + self.assert_failed(self.package("macos", self.MACOS_GROUPS), "jt9 has an LC_RPATH outside its directory: @loader_path/../lib") + + def test_macos_floor_is_the_highest_minos(self): + self.macos_assets() + self.fixture("otool.load.QtCore", minos("13.0")) + self.fixture("otool.load.libfftw3f.3.dylib", minos("9.5")) + result = self.package("macos", self.MACOS_GROUPS) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("They require macOS 13.0 or later.", self.text("wsjtx-9.9.9-x86_64-macOS-jt9", "README.txt")) + self.assertIn("They require macOS 11.0 or later.", self.text("wsjtx-9.9.9-x86_64-macOS-wsprd", "README.txt")) + + def test_macos_legacy_minimum_version_is_recorded_for_every_tarball(self): + self.macos_assets() + source_version = ["Load command 10", " cmd LC_SOURCE_VERSION", " cmdsize 16", " version 99.0"] + for program in ("jt9", "jt9stream", "wsprd", "encode77"): + self.fixture( + f"otool.load.{program}", + source_version + rpath("@loader_path/lib") + version_min_macosx("10.13") + source_version, + ) + for library in ("QtCore", "libfftw3f.3.dylib", "libfftw3f_threads.3.dylib"): + self.fixture(f"otool.load.{library}", version_min_macosx("10.13") + source_version) + result = self.package("macos", self.MACOS_GROUPS) + self.assertEqual(result.returncode, 0, result.stderr) + for group in ("jt9", "jt9stream", "wsprd", "utilities"): + self.assertIn( + "They require macOS 10.13 or later.", + self.text(f"wsjtx-9.9.9-x86_64-macOS-{group}", "README.txt"), + ) + + def test_macos_floor_is_the_highest_across_both_version_commands(self): + self.macos_assets() + for modern, expected in (("10.12", "10.13"), ("13.0", "13.0")): + with self.subTest(modern=modern): + self.fixture("otool.load.jt9", rpath("@loader_path/lib") + minos(modern)) + self.fixture("otool.load.QtCore", version_min_macosx("10.13")) + for library in ("libfftw3f.3.dylib", "libfftw3f_threads.3.dylib"): + self.fixture(f"otool.load.{library}", minos(modern)) + result = self.package("macos", ["jt9 jt9"]) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn( + f"They require macOS {expected} or later.", + self.text("wsjtx-9.9.9-x86_64-macOS-jt9", "README.txt"), + ) + + def test_macos_minimum_does_not_read_fields_from_other_load_commands(self): + self.macos_assets() + for command in ("LC_BUILD_VERSION", "LC_VERSION_MIN_MACOSX"): + with self.subTest(command=command): + self.fixture("otool.load.encode77", [ + "Load command 9", f" cmd {command}", " cmdsize 16", + "Load command 10", " cmd LC_SOURCE_VERSION", " cmdsize 16", " version 99.0", + ]) + self.assert_failed( + self.package("macos", ["utilities encode77"]), + "no minimum macOS version recorded in wsjtx-9.9.9-x86_64-macOS-utilities", + ) + + def test_macos_without_a_minimum_version_fails(self): + self.macos_assets() + self.fixture("otool.load.encode77", rpath("@loader_path/lib")) + self.assert_failed(self.package("macos", self.MACOS_GROUPS), "no minimum macOS version recorded in wsjtx-9.9.9-x86_64-macOS-utilities") + + def test_tarball_named_twice_fails(self): + self.macos_assets() + self.assert_failed(self.package("macos", ["wsprd wsprd", "jt9 jt9", "wsprd jt9stream"]), "release tarball wsprd is named twice") + + def test_tarball_without_readme_description_fails(self): + self.macos_assets() + self.assert_failed(self.package("macos", ["extra encode77"]), "no README description for release tarball extra") + + def test_missing_program_fails_naming_it(self): + self.macos_assets() + (self.source / "jt9stream").unlink() + self.assert_failed(self.package("macos", self.MACOS_GROUPS), "missing under", "jt9stream") + + def test_group_without_programs_fails(self): + self.macos_assets() + self.assert_failed(self.package("macos", ["jt9 jt9", "utilities"]), "release tarball utilities names no programs") + + # Windows + def windows_build(self, failing=()): + self.files(self.source, ["jt9.exe", "encode77.exe", "wsjtx.exe"]) + self.files(self.root / "dlls", ["libfftw3f-3.dll", "LIBGFORTRAN-5.DLL", "unused.dll"]) + self.files(self.root / "system", ["KERNEL32.dll", "msvcrt.dll"]) + self.fixture("objdump.jt9.exe", ["\tDLL Name: libfftw3f-3.dll", "\tDLL Name: KERNEL32.dll"]) + self.fixture("objdump.libfftw3f-3.dll", ["\tDLL Name: libgfortran-5.dll"]) + self.fixture("objdump.LIBGFORTRAN-5.DLL", ["\tDLL Name: KERNEL32.dll"]) + self.fixture("objdump.encode77.exe", ["\tDLL Name: msvcrt.dll"]) + for name in failing: + self.fixture(f"objdump.{name}.fail", []) + return self.package( + "windows", ["jt9 jt9", "utilities encode77"], + "--dll-dir", str(self.root / "dlls"), "--system-dir", str(self.root / "system"), newline="\r\n", + ) + + def test_windows_tarballs_hold_each_group_and_its_dll_closure(self): + result = self.windows_build() + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual( + self.members("wsjtx-9.9.9-windows-x86_64-jt9"), + ["COPYING", "LIBGFORTRAN-5.DLL", "README.txt", "THIRD-PARTY.txt", "jt9.exe", "libfftw3f-3.dll"], + ) + self.assertEqual( + self.members("wsjtx-9.9.9-windows-x86_64-utilities"), ["COPYING", "README.txt", "THIRD-PARTY.txt", "encode77.exe"] + ) + self.assertIn("no Authenticode signature", self.text("wsjtx-9.9.9-windows-x86_64-jt9", "README.txt")) + notices = self.text("wsjtx-9.9.9-windows-x86_64-jt9", "THIRD-PARTY.txt") + self.assertIn("FFTW 3\n License: GPL-2.0-or-later\n", notices) + self.assertIn("GCC runtime libraries\n License: GPL-3.0-or-later WITH GCC-exception-3.1\n", notices) + self.assertIn(" Files: LIBGFORTRAN-5.DLL\n", notices) + self.assertIn("mingw-w64 runtime\n", notices) + self.assertEqual(notices.count(" Linked statically into the programs"), 1) + self.assertNotIn("libquadmath", notices) + + def test_windows_import_outside_dll_and_system_dirs_fails(self): + (self.root / "system").mkdir() + self.fixture("objdump.encode77.exe", ["\tDLL Name: libmissing.dll"]) + self.files(self.source, ["jt9.exe", "encode77.exe"]) + self.files(self.root / "dlls", []) + self.fixture("objdump.jt9.exe", []) + result = self.package( + "windows", ["jt9 jt9", "utilities encode77"], + "--dll-dir", str(self.root / "dlls"), "--system-dir", str(self.root / "system"), + ) + self.assert_failed(result, "libmissing.dll(encode77.exe)") + + def test_windows_objdump_failure_fails_naming_the_file(self): + self.assert_failed(self.windows_build(failing=["libfftw3f-3.dll"]), "objdump failed on libfftw3f-3.dll") + + # Linux: linuxdeploy and readelf are stubbed; the excludelist is the committed one. + def linux_build(self): + self.files(self.source, ["jt9", "jt9stream", "wsjtx"]) + self.files(self.fixtures / "appdir-lib", ["libQt5Core.so.5", "libicuuc.so.74", "libgfortran.so.5"]) + self.fixture("deploys.jt9", ["libQt5Core.so.5", "libicuuc.so.74", "libgfortran.so.5"]) + self.fixture("deploys.jt9stream", ["libgfortran.so.5"]) + self.fixture("readelf.d.jt9", needed("libQt5Core.so.5", "libgfortran.so.5", "libc.so.6", runpath="$ORIGIN/../lib")) + self.fixture("readelf.V.jt9", versions("GLIBC_2.34", "GLIBC_2.2.5")) + self.fixture("readelf.d.jt9stream", needed("libgfortran.so.5", "libm.so.6", runpath="${ORIGIN}/../lib")) + self.fixture("readelf.V.jt9stream", versions("GLIBC_2.29")) + self.fixture("readelf.d.libQt5Core.so.5", needed("libicuuc.so.74", "libstdc++.so.6", runpath="$ORIGIN")) + self.fixture("readelf.V.libQt5Core.so.5", versions("GLIBC_2.38", "GLIBCXX_3.4.9", "GLIBCXX_3.4.30", "CXXABI_1.3.13")) + self.fixture("readelf.d.libicuuc.so.74", needed("libstdc++.so.6", runpath="${ORIGIN}")) + self.fixture("readelf.d.libgfortran.so.5", needed("libc.so.6", "ld-linux-aarch64.so.1", runpath="$ORIGIN")) + + def linux_package(self, groups=("jt9 jt9", "jt9stream jt9stream")): + return self.package("linux", list(groups), "--linuxdeploy", str(self.bin / "linuxdeploy")) + + def test_linux_tarballs_bundle_deployed_libraries_and_state_host_requirements(self): + self.linux_build() + result = self.linux_package() + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual( + self.members("wsjtx-9.9.9-linux-x86_64-jt9"), + [ + "COPYING", "README.txt", "THIRD-PARTY.txt", "bin/jt9", "lib/libQt5Core.so.5", "lib/libgfortran.so.5", + "lib/libicuuc.so.74", "share/doc/libqt5core5t64/copyright", + ], + ) + readme = self.text("wsjtx-9.9.9-linux-x86_64-jt9", "README.txt") + self.assertIn("glibc 2.38 or later, libstdc++ with GLIBCXX_3.4.30 or later", readme) + self.assertIn("these libraries: ld-linux-aarch64.so.1 libc.so.6 libstdc++.so.6.", readme) + self.assertIn("ICU 74\n", self.text("wsjtx-9.9.9-linux-x86_64-jt9", "THIRD-PARTY.txt")) + self.assertIn("without it", readme) + self.assertIn("glibc 2.29 or later, and these libraries", self.text("wsjtx-9.9.9-linux-x86_64-jt9stream", "README.txt")) + self.assertIn("share/doc/", self.text("wsjtx-9.9.9-linux-x86_64-jt9", "THIRD-PARTY.txt")) + log = (self.fixtures / "linuxdeploy.log").read_text(encoding="utf-8").splitlines() + self.assertTrue(log[0].startswith("--appimage-extract-and-run --appdir "), log[0]) + self.assertTrue(log[0].endswith(f"--executable {self.source}/jt9"), log[0]) + self.assertEqual(log[1:3], ["token=unset", "extract=1"]) + + def test_linux_library_neither_bundled_nor_excluded_fails(self): + self.linux_build() + self.fixture("readelf.d.jt9stream", needed("libfftw3f.so.3", runpath="$ORIGIN/../lib")) + self.assert_failed(self.linux_package(), "libfftw3f.so.3(bin/jt9stream)") + + def test_linux_runpath_is_not_inherited_by_bundled_libraries(self): + self.linux_build() + self.fixture("readelf.d.libQt5Core.so.5", needed("libicuuc.so.74")) + self.assert_failed(self.linux_package(), "libicuuc.so.74(lib/libQt5Core.so.5)") + + def test_linux_runpath_outside_origin_fails(self): + self.linux_build() + self.fixture("readelf.d.jt9", needed("libc.so.6", runpath="$ORIGIN/../lib:/work/wsjtx-build")) + self.assert_failed(self.linux_package(), "bin/jt9 has a RUNPATH entry not relative to $ORIGIN: /work/wsjtx-build") + + def test_linux_empty_runpath_entry_fails(self): + self.linux_build() + self.fixture("readelf.d.jt9", needed("libc.so.6", runpath="$ORIGIN/../lib:")) + self.assert_failed(self.linux_package(), "bin/jt9 has an empty RUNPATH entry: $ORIGIN/../lib:") + + def test_linux_program_linuxdeploy_did_not_deploy_fails(self): + self.linux_build() + self.fixture("linuxdeploy.skip-programs", []) + self.assert_failed(self.linux_package(), "linuxdeploy did not deploy jt9") + + def test_linux_linuxdeploy_failure_fails(self): + self.linux_build() + self.fixture("linuxdeploy.fail", []) + self.assert_failed(self.linux_package(), "linuxdeploy failed for wsjtx-9.9.9-linux-x86_64-jt9") + + def test_linux_requires_linuxdeploy(self): + self.linux_build() + result = self.package("linux", ["jt9 jt9"]) + self.assertEqual(result.returncode, 2) + self.assertIn("--linuxdeploy is required", result.stderr) + + +class LinuxdeployExcludelistTests(unittest.TestCase): + def test_excludelist_belongs_to_the_pinned_linuxdeploy(self): + excludelist = (ROOT / ".github/scripts/linuxdeploy-excludelist.txt").read_text(encoding="utf-8") + tag = excludelist.split("compiled into linuxdeploy ", 1)[1].split(",", 1)[0] + self.assertIn( + f'LINUXDEPLOY_TAG: "{tag}"', (ROOT / ".github/actions/build-linux-payload/action.yml").read_text(encoding="utf-8") + ) + self.assertIn(f"LINUXDEPLOY_TAG={tag}\n", (ROOT / ".github/scripts/package-linux-armhf.sh").read_text(encoding="utf-8")) + names = [line for line in excludelist.splitlines() if line and not line.startswith("#")] + self.assertEqual(len(names), 52) + for name in ("libc.so.6", "libstdc++.so.6", "libgcc_s.so.1", "libz.so.1", "libm.so.6"): + self.assertIn(name, names) + for name in ("libgfortran.so.5", "libgomp.so.1", "libQt5Core.so.5", "libfftw3f.so.3"): + self.assertNotIn(name, names) + + +class SmokeReleaseTarballsTests(unittest.TestCase): + def setUp(self): + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + self.root = pathlib.Path(temporary.name) + self.dir = self.root / "tarballs" + self.bin = self.root / "bin" + self.log = self.root / "smoke.log" + self.dir.mkdir() + self.bin.mkdir() + (self.bin / "timeout").write_text( + f'#!/bin/sh\necho "$1" >> "{self.root}/timeout.log"\nshift\nexec "$@"\n', encoding="utf-8" + ) + (self.bin / "timeout").chmod(0o755) + + def tarball(self, group, programs, layout="bin/", failing=(), libraries=(), target="linux-x86_64", top=None): + name = f"wsjtx-9.9.9-{target}-{group}" + tree = self.root / "trees" / name + for program in programs: + path = tree / f"{layout}{program}" + path.parent.mkdir(parents=True, exist_ok=True) + status = 3 if program in failing else 0 + path.write_text( + f'#!/bin/sh\necho "{program} $* lib=${{LD_LIBRARY_PATH-unset}} cwd=$(pwd)" >> "{self.log}"\nexit {status}\n', + encoding="utf-8", + ) + path.chmod(0o755) + for library in libraries: + (tree / "lib").mkdir(parents=True, exist_ok=True) + (tree / "lib" / library).write_text(library, encoding="utf-8") + with tarfile.open(self.dir / f"{name}.tar.gz", "w:gz") as archive: + archive.add(tree, arcname=top or name) + + def smoke(self, groups, *arguments, platform="linux", target="linux-x86_64", script=SMOKE): + groups_file = self.root / "release-tarballs.txt" + groups_file.write_text("# comment\n" + "".join(f"{line}\n" for line in groups), encoding="utf-8") + return subprocess.run( + [ + "bash", str(script), "--platform", platform, "--version", "9.9.9", "--target", target, + "--groups", str(groups_file), "--dir", str(self.dir), *arguments, + ], + env=dict(os.environ, PATH=f"{self.bin}:{os.environ['PATH']}", TMPDIR=str(self.root), LD_LIBRARY_PATH="/bogus"), + text=True, capture_output=True, check=False, + ) + + def test_every_program_runs_from_its_own_tarball_without_library_path(self): + self.tarball("jt9", ["jt9"]) + self.tarball("wsprd", ["wsprd"]) + self.tarball("utilities", ["encode77", "ft4sim"]) + result = self.smoke(["jt9 jt9", "wsprd wsprd", "utilities encode77 ft4sim"]) + self.assertEqual(result.returncode, 0, result.stderr) + lines = self.log.read_text(encoding="utf-8").splitlines() + self.assertEqual([line.split(" ", 1)[0] for line in lines], ["jt9", "wsprd", "encode77", "ft4sim"]) + self.assertTrue(lines[0].startswith("jt9 --help lib=unset"), lines[0]) + self.assertRegex(lines[1], r"^wsprd -a \S+/run-wsprd \S+/samples/WSPR/150426_0918\.wav lib=unset cwd=\S+/run-wsprd$") + self.assertTrue(lines[2].startswith("encode77 CQ K1ABC FN42 lib=unset"), lines[2]) + self.assertTrue(lines[3].startswith("ft4sim lib=unset"), lines[3]) + self.assertEqual((self.root / "timeout.log").read_text(encoding="utf-8").split(), ["120"] * 4) + + def scripts_copy(self): + scripts = self.root / "repo/.github/scripts" + scripts.mkdir(parents=True) + (scripts / SMOKE.name).write_bytes(SMOKE.read_bytes()) + (scripts / "smoke-launch-windows.sh").write_text( + f'#!/bin/sh\necho "launch $(basename "$1") cwd=$(pwd) args=$*" >> "{self.log}"\n' + 'case "$1" in *ft4sim.exe) exit 1 ;; esac\n', + encoding="utf-8", + ) + (scripts / "smoke-launch-windows.sh").chmod(0o755) + sample = self.root / "repo/samples/WSPR/150426_0918.wav" + sample.parent.mkdir(parents=True) + sample.write_bytes(b"RIFF") + return scripts / SMOKE.name + + def test_windows_programs_launch_through_the_clean_path_launcher(self): + script = self.scripts_copy() + self.tarball("jt9", ["jt9.exe"], layout="", target="windows-x86_64") + self.tarball("utilities", ["encode77.exe"], layout="", target="windows-x86_64") + result = self.smoke(["jt9 jt9", "utilities encode77"], platform="windows", target="windows-x86_64", script=script) + self.assertEqual(result.returncode, 0, result.stderr) + lines = self.log.read_text(encoding="utf-8").splitlines() + self.assertRegex(lines[0], r"^launch jt9\.exe cwd=\S+/run-jt9 args=\S+/wsjtx-9\.9\.9-windows-x86_64-jt9/jt9\.exe --help$") + self.assertRegex(lines[1], r"^launch encode77\.exe cwd=\S+/run-encode77 args=\S+ CQ K1ABC FN42$") + + def test_windows_launch_failure_fails(self): + script = self.scripts_copy() + self.tarball("utilities", ["ft4sim.exe"], layout="", target="windows-x86_64") + result = self.smoke(["utilities ft4sim"], platform="windows", target="windows-x86_64", script=script) + self.assertEqual(result.returncode, 1) + self.assertIn("ft4sim from wsjtx-9.9.9-windows-x86_64-utilities failed", result.stderr) + + def test_macos_programs_run_from_the_top_of_their_tarball(self): + script = self.scripts_copy() + self.tarball("wsprd", ["wsprd"], layout="", target="arm64-macOS") + result = self.smoke(["wsprd wsprd"], platform="macos", target="arm64-macOS", script=script) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertRegex(self.log.read_text(encoding="utf-8"), r"wsprd -a \S+/run-wsprd \S+/repo/\.github/scripts/\.\./\.\./samples/WSPR/150426_0918\.wav ") + self.assertFalse((self.root / "timeout.log").exists()) + + def test_tarball_with_another_top_directory_fails(self): + self.tarball("jt9", ["jt9"], top="jt9") + result = self.smoke(["jt9 jt9"]) + self.assertEqual(result.returncode, 1) + self.assertIn("wsjtx-9.9.9-linux-x86_64-jt9.tar.gz does not extract to wsjtx-9.9.9-linux-x86_64-jt9/", result.stderr) + + def test_failing_program_fails_naming_it(self): + self.tarball("utilities", ["encode77", "ft4sim"], failing=["ft4sim"]) + result = self.smoke(["utilities encode77 ft4sim"]) + self.assertEqual(result.returncode, 1) + self.assertIn("ft4sim from wsjtx-9.9.9-linux-x86_64-utilities failed", result.stderr) + + def test_program_missing_from_its_tarball_fails(self): + self.tarball("jt9", ["jt9stream"]) + result = self.smoke(["jt9 jt9"]) + self.assertEqual(result.returncode, 1) + self.assertIn("jt9 is not in wsjtx-9.9.9-linux-x86_64-jt9", result.stderr) + + def test_program_without_a_smoke_invocation_fails(self): + self.tarball("extra", ["newtool"]) + result = self.smoke(["extra newtool"]) + self.assertEqual(result.returncode, 1) + self.assertIn("no smoke invocation for newtool", result.stderr) + + def ldd_stub(self, resolution, status=0): + (self.bin / "ldd").write_text( + "#!/bin/sh\n" + f'[ "${{LD_LIBRARY_PATH-unset}}" = unset ] || exit 9\n' + 'tree=$(dirname "$(dirname "$1")")\n' + "printf '\\tlinux-vdso.so.1 (0x1)\\n'\n" + f"printf '\\tlibQt5Core.so.5 => %s (0x2)\\n' \"{resolution}\"\n" + "printf '\\tlibc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x3)\\n'\n" + f"exit {status}\n", + encoding="utf-8", + ) + (self.bin / "ldd").chmod(0o755) + + def test_ldd_reports_a_library_not_found(self): + self.tarball("jt9", ["jt9"], libraries=["libQt5Core.so.5"]) + self.ldd_stub("not found") + result = self.smoke(["jt9 jt9"], "--ldd") + self.assertEqual(result.returncode, 1) + self.assertIn("libQt5Core.so.5(bin/jt9): not found", result.stderr) + + def test_ldd_failure_fails(self): + self.tarball("jt9", ["jt9"], libraries=["libQt5Core.so.5"]) + self.ldd_stub("$tree/lib/libQt5Core.so.5", status=1) + result = self.smoke(["jt9 jt9"], "--ldd") + self.assertEqual(result.returncode, 1) + self.assertIn("ldd failed on bin/jt9", result.stderr) + + def test_ldd_accepts_a_library_without_dependencies(self): + # ICU's data library needs nothing; ldd says so and exits 0. + self.tarball("jt9", ["jt9"], libraries=["libicudata.so.74"]) + (self.bin / "ldd").write_text("#!/bin/sh\necho '\tstatically linked'\n", encoding="utf-8") + (self.bin / "ldd").chmod(0o755) + result = self.smoke(["jt9 jt9"], "--ldd") + self.assertEqual(result.returncode, 0, result.stderr) + + def test_ldd_accepts_bundled_copies_through_origin(self): + self.tarball("jt9", ["jt9"], libraries=["libQt5Core.so.5"]) + self.ldd_stub("$tree/bin/../lib/libQt5Core.so.5") + result = self.smoke(["jt9 jt9"], "--ldd") + self.assertEqual(result.returncode, 0, result.stderr) + + def test_ldd_rejects_a_system_copy_of_a_bundled_library(self): + self.tarball("jt9", ["jt9"], libraries=["libQt5Core.so.5"]) + self.ldd_stub("/usr/lib/x86_64-linux-gnu/libQt5Core.so.5") + result = self.smoke(["jt9 jt9"], "--ldd") + self.assertEqual(result.returncode, 1) + self.assertIn("libQt5Core.so.5(bin/jt9): /usr/lib/x86_64-linux-gnu/libQt5Core.so.5", result.stderr) + + +class MacosPostinstallTests(unittest.TestCase): + def setUp(self): + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + self.root = pathlib.Path(temporary.name) / "volume" + self.scripts = pathlib.Path(temporary.name) / "scripts" + self.scripts.mkdir() + lines = BUILD_MACOS.read_text(encoding="utf-8").splitlines() + start = next(i for i, line in enumerate(lines) if line.strip() == 'cat > "${SCRIPTS}/postinstall" << \'SCRIPT\'') + indent = len(lines[start]) - len(lines[start].lstrip()) + end = next(i for i in range(start + 1, len(lines)) if lines[i] == " " * indent + "SCRIPT") + body = [line[indent:] for line in lines[start + 1:end]] + self.assertFalse(any("launchctl" in line or "sysctl" in line for line in body)) + self.assertTrue(any(line.startswith('root="${3%/}"') for line in body)) + for line in body: + for prefix in line.split("/usr/local")[:-1]: + self.assertTrue(prefix.endswith(("$root", '"$root"')), line) + self.postinstall = self.scripts / "postinstall" + self.postinstall.write_text("\n".join(body) + "\n", encoding="utf-8") + (self.scripts / "installed-cli-tools.txt").write_text("jt9\nwsprd\n", encoding="utf-8") + + def executable(self, path): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("#!/bin/sh\n", encoding="utf-8") + path.chmod(0o755) + + def run_postinstall(self): + return subprocess.run( + ["bash", str(self.postinstall), "pkg", "/", str(self.root), "/"], + stdin=subprocess.DEVNULL, text=True, capture_output=True, check=False, + ) + + def test_upgrade_removes_unshipped_programs_and_their_links(self): + programs = self.root / "usr/local/wsjtx" + links = self.root / "usr/local/bin" + for name in ("jt9", "wsprd", "wsprcode"): + self.executable(programs / name) + links.mkdir(parents=True) + (links / "wsprcode").symlink_to(programs / "wsprcode") + result = self.run_postinstall() + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(sorted(path.name for path in programs.iterdir()), ["jt9", "wsprd"]) + self.assertEqual(sorted(path.name for path in links.iterdir()), ["jt9", "wsprd"]) + + def test_symlinked_program_directory_is_not_cleaned(self): + elsewhere = self.root / "Users/someone/bin" + for name in ("jt9", "backup.sh"): + self.executable(elsewhere / name) + (self.root / "usr/local").mkdir(parents=True) + (self.root / "usr/local/wsjtx").symlink_to(elsewhere) + result = self.run_postinstall() + self.assertEqual(result.returncode, 0, result.stderr) + self.assertTrue((elsewhere / "backup.sh").exists()) + + def test_trailing_non_executable_entry_does_not_fail_the_install(self): + programs = self.root / "usr/local/wsjtx" + self.executable(programs / "jt9") + (programs / "zz-notes.txt").write_text("notes", encoding="utf-8") + result = self.run_postinstall() + self.assertEqual(result.returncode, 0, result.stderr) + self.assertTrue((self.root / "usr/local/bin/jt9").is_symlink()) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/scripts/tests/test_release_linux_images.py b/.github/scripts/tests/test_release_linux_images.py new file mode 100644 index 00000000..10a3fd0f --- /dev/null +++ b/.github/scripts/tests/test_release_linux_images.py @@ -0,0 +1,158 @@ +#!/usr/bin/env python3 +"""Release dependency selection and registry-copy regression checks.""" +import hashlib +import importlib.util +import json +from pathlib import Path +import subprocess +import tempfile +import unittest +from unittest.mock import patch + +SPEC = importlib.util.spec_from_file_location("release_linux_images", Path(__file__).parents[1] / "release-linux-images.py") +images = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(images) +GENERATION = "validated-build-20260925-123-1" +DIGEST = "sha256:" + "a" * 64 +RECIPE = "b" * 64 + + +def selection(): + return {"schema": 1, "generation": GENERATION, "images": { + key: {"reference": f"{images.PUBLIC}/{spec[0]}@{DIGEST}", "recipe_sha256": RECIPE} + for key, spec in images.IMAGES.items() + }} + + +def manifests(): + common = {"generation": GENERATION.removeprefix("validated-"), "recipe_sha256": RECIPE, + "toolchain_id": "gcc13-armhf-abc", "runtime_sha256": "c" * 64} + runtime = dict(common) + runtime.update({"cross_" + key: common[key] for key in ("generation", "recipe_sha256", "toolchain_id")}) + return [dict(common), dict(common), dict(common), runtime] + + +class SelectionTests(unittest.TestCase): + def setUp(self): + self.fingerprint = patch.object(images, "fingerprint", return_value=RECIPE) + self.fingerprint.start() + self.addCleanup(self.fingerprint.stop) + + def test_complete_selection_and_anonymous_reads(self): + with patch.object(images, "anonymous_digest", return_value=DIGEST) as remote: + self.assertEqual(images.validate(selection(), True), selection()) + self.assertEqual(remote.call_count, 4) + + def test_missing_malformed_and_untrusted_selection(self): + cases = [] + lock = selection(); del lock["images"]["armhf_cross"]; cases.append(lock) + lock = selection(); lock["images"]["x86_64"] = None; cases.append(lock) + lock = selection(); lock["generation"] = "stable"; cases.append(lock) + lock = selection(); lock["images"]["x86_64"]["reference"] = f"{images.PRIVATE}/linux-noble@{DIGEST}"; cases.append(lock) + lock = selection(); lock["images"]["x86_64"]["reference"] = f"{images.PUBLIC}/linux-noble:stable"; cases.append(lock) + lock = selection(); lock["images"]["aarch64"]["recipe_sha256"] = "c" * 64; cases.append(lock) + for lock in cases: + with self.subTest(lock=lock), self.assertRaises(ValueError): + images.validate(lock) + + def test_remote_digest_mismatch(self): + with patch.object(images, "anonymous_digest", return_value="sha256:" + "c" * 64), self.assertRaisesRegex(ValueError, "digest mismatch"): + images.validate(selection(), True) + + def test_provenance_binds_exact_lock_bytes_and_four_builders(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "lock.json" + path.write_text(json.dumps(selection())) + first = images.provenance(path) + self.assertEqual(first["builders"], dict.fromkeys(images.IMAGES, DIGEST)) + path.write_text(json.dumps(selection(), indent=2)) + self.assertNotEqual(first["lock_sha256"], images.provenance(path)["lock_sha256"]) + + def test_candidate_provenance_mismatch_fails(self): + with tempfile.TemporaryDirectory() as directory: + lock = Path(directory) / "lock.json" + record = Path(directory) / "provenance.json" + lock.write_text(json.dumps(selection())) + expected = images.provenance(lock) + record.write_text(json.dumps({"linux_images": expected})) + with patch("sys.argv", ["helper", "verify-provenance", str(lock), str(record)]): + images.main() + expected["builders"]["armhf_cross"] = "sha256:" + "c" * 64 + record.write_text(json.dumps({"linux_images": expected})) + with self.assertRaisesRegex(ValueError, "provenance does not match"): + images.main() + + def test_existing_output_is_never_reused(self): + with tempfile.TemporaryDirectory() as directory: + with patch("sys.argv", ["helper", "prepare", GENERATION, "--output-directory", directory]), \ + patch.object(images, "prepare") as prepare, \ + self.assertRaisesRegex(ValueError, "must not already exist"): + images.main() + prepare.assert_not_called() + + def prepare(self, existing=None, manifest_values=None): + def inspect(reference, anonymous=False, missing_ok=False): + return existing if missing_ok else DIGEST + with patch.object(images, "inspect", side_effect=inspect), \ + patch.object(images, "image_manifest", side_effect=manifest_values or manifests()), \ + patch.object(images, "anonymous_digest", return_value=DIGEST), \ + patch.object(images, "run") as command: + result = images.prepare(GENERATION) + return result, command.call_args_list + + def test_copy_preserves_all_manifests_and_digest(self): + (lock, _), commands = self.prepare() + self.assertEqual(lock, selection()) + self.assertEqual(len(commands), 4) + for call in commands: + args = call.args[0] + self.assertEqual(args[:4], ["skopeo", "copy", "--all", "--preserve-digests"]) + self.assertIn("@" + DIGEST, args[4]) + self.assertTrue(args[5].endswith(":release-deps-" + GENERATION)) + + def test_identical_rerun_skips_copy(self): + _, commands = self.prepare(existing=DIGEST) + self.assertEqual(commands, []) + + def test_conflicting_retained_tag_fails(self): + with self.assertRaisesRegex(ValueError, "Conflicting retained"): + self.prepare(existing="sha256:" + "c" * 64) + + def test_mixed_armhf_pair_fails_before_copy(self): + for field in ("cross_generation", "cross_recipe_sha256", "cross_toolchain_id", "runtime_sha256"): + values = manifests() + values[-1][field] = "wrong" + with self.subTest(field=field), self.assertRaisesRegex(ValueError, "pair mismatch"): + self.prepare(manifest_values=values) + + def test_partial_copy_failure_emits_no_selection(self): + with tempfile.TemporaryDirectory() as directory: + output = Path(directory) / "output" + with patch("sys.argv", ["helper", "prepare", GENERATION, "--output-directory", str(output)]), \ + patch.object(images, "inspect", side_effect=lambda ref, anonymous=False, missing_ok=False: None if missing_ok else DIGEST), \ + patch.object(images, "image_manifest", side_effect=manifests()), \ + patch.object(images, "run", side_effect=["", subprocess.CalledProcessError(1, "copy", stderr="denied")]), \ + self.assertRaises(subprocess.CalledProcessError): + images.main() + self.assertFalse(output.exists()) + + def test_registry_inspection_hashes_exact_manifest_without_platform_selection(self): + raw = b'{"mediaType":"application/vnd.oci.image.index.v1+json","manifests":[]}\n' + result = subprocess.CompletedProcess([], 0, stdout=raw) + with patch.object(images.subprocess, "run", return_value=result) as command: + digest = images.inspect("ghcr.io/wsjtx/wsjtx/linux-armv7-bookworm:test", anonymous=True) + self.assertEqual(digest, "sha256:" + hashlib.sha256(raw).hexdigest()) + self.assertIn("--raw", command.call_args.args[0]) + self.assertIn("--no-creds", command.call_args.args[0]) + + def test_authentication_error_is_not_missing_tag(self): + with patch.object(images.subprocess, "run", side_effect=subprocess.CalledProcessError(1, "inspect", stderr=b"unauthorized")), self.assertRaises(subprocess.CalledProcessError): + images.inspect("test", missing_ok=True) + + def test_only_manifest_unknown_allows_first_copy(self): + with patch.object(images.subprocess, "run", side_effect=subprocess.CalledProcessError(1, "inspect", stderr=b"manifest unknown")): + self.assertIsNone(images.inspect("test", missing_ok=True)) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/scripts/tests/test_release_policy.py b/.github/scripts/tests/test_release_policy.py index a7929484..7a1c6b1e 100644 --- a/.github/scripts/tests/test_release_policy.py +++ b/.github/scripts/tests/test_release_policy.py @@ -1,5 +1,6 @@ import importlib.util import json +import re import io import shutil import subprocess @@ -19,15 +20,763 @@ SPEC.loader.exec_module(release_policy) class ReleasePolicyTest(unittest.TestCase): - def test_classifies_ga_and_rc(self): - self.assertEqual(release_policy.classify("3.2.0")["channel"], "GA") + def test_candidate_and_public_inventories_require_both_macos_architectures(self): + version = "3.2.0-rc1" + for distribution in (False, True): + mode = "distribution" if distribution else "validation" + suffix = "macOS.pkg" if distribution else "macOS-unsigned.pkg" + required = {f"wsjtx-{version}-{arch}-{suffix}" for arch in ("arm64", "x86_64")} + for inventory in ( + release_policy.expected_assets(version, distribution), + release_policy.public_expected_assets(version, mode), + ): + with self.subTest(mode=mode, inventory=inventory): + self.assertEqual({name for name in inventory if name.endswith(suffix)}, required) + + def test_newest_ga_line_uses_immutable_ga_tags_not_release_order_or_rc_line(self): + refs = { + "refs/tags/v2.7.0": "a" * 40, + "refs/tags/v3.0.2": "b" * 40, + "refs/tags/v3.2.0-rc1": "c" * 40, + } + newest = release_policy.public_release_line_policy("3.2.0", refs) + latest_ga_patch = release_policy.public_release_line_policy("3.0.3", refs) + self.assertEqual(newest["newest_ga_line"], "3.0") + self.assertTrue(newest["ga_line_is_newest"]) + self.assertTrue(newest["legacy_tag_only"]) + self.assertTrue(latest_ga_patch["ga_line_is_newest"]) + + def test_public_release_line_rejects_missing_or_ambiguous_history(self): + with self.assertRaisesRegex(ValueError, "no immutable public vX.Y.Z GA tags"): + release_policy.public_release_line_policy("3.2.0", {}) + with self.assertRaisesRegex(ValueError, "no immutable public vX.Y.Z GA tags"): + release_policy.public_release_line_policy("3.2.0", { + "refs/tags/v3.2.0-rc1": "a" * 40, + "refs/tags/v3.3.0-beta1": "c" * 40, + "refs/heads/release/3.2": "b" * 40, + }) + for refs in ( + {"refs/heads/release/next": "a" * 40}, + {"refs/tags/v3.2.0-beta0": "a" * 40}, + {"refs/tags/v3.2.0-alpha1": "a" * 40}, + ): + with self.subTest(refs=refs), self.assertRaisesRegex(ValueError, "malformed"): + release_policy.public_release_line_policy("3.2.0", refs) + + def test_latest_line_tag_orders_beta_below_rc_below_ga_and_numbers_numerically(self): + for tags, latest in ( + (("v3.3.0-beta9", "v3.3.0-beta10"), "v3.3.0-beta10"), + (("v3.3.0-beta10", "v3.3.0-rc1"), "v3.3.0-rc1"), + (("v3.3.0-rc2", "v3.3.0"), "v3.3.0"), + (("v3.3.0", "v3.3.1-beta1"), "v3.3.1-beta1"), + ): + refs = {"refs/tags/v3.0.2": "a" * 40} + refs.update({f"refs/tags/{tag}": "b" * 40 for tag in tags}) + with self.subTest(tags=tags): + policy = release_policy.public_release_line_policy("3.3.2", refs) + self.assertEqual(policy["latest_public_tag_on_candidate_line"], latest) + + def test_public_ref_listing_resolves_annotated_tags_and_hashes_the_snapshot(self): + refs, digest = release_policy.parse_public_ref_listing( + "".join(( + f"{'a' * 40} refs/heads/master\n", + f"{'b' * 40} refs/tags/v2.7.0\n", + f"{'c' * 40} refs/tags/v2.7.0^{{}}\n", + )) + ) + self.assertEqual(refs["refs/heads/master"], "a" * 40) + self.assertEqual(refs["refs/tags/v2.7.0"], "c" * 40) + line_policy = release_policy.public_release_line_policy("2.7.1", refs) + self.assertEqual(line_policy["latest_public_tag_on_candidate_line"], "v2.7.0") + self.assertEqual(line_policy["latest_public_tag_sha_on_candidate_line"], "c" * 40) + self.assertEqual(len(digest), 64) + + def test_first_public_promotion_creates_release_branch_and_tag_without_master(self): + master = "a" * 40 + candidate = "b" * 40 + plan = release_policy.plan_public_promotion( + "3.2.0-rc1", + candidate, + { + "refs/heads/master": master, + "refs/tags/v3.0.2": master, + }, + lambda ancestor, descendant: ancestor == master and descendant == candidate, + ) + self.assertEqual( + plan["updates"], + ["refs/heads/release/3.2", "refs/tags/v3.2.0-rc1"], + ) + self.assertIsNone(plan["prior_release_branch"]) + self.assertFalse(plan["advance_master"]) + + def test_first_branch_initialization_requires_latest_same_line_tag_ancestry(self): + baseline = "a" * 40 + candidate = "b" * 40 + refs = { + "refs/heads/master": "c" * 40, + "refs/tags/v3.0.2": "c" * 40, + "refs/tags/v3.2.0-rc1": baseline, + } + plan = release_policy.plan_public_promotion( + "3.2.0-rc2", + candidate, + refs, + lambda ancestor, descendant: (ancestor, descendant) == (baseline, candidate), + ) + self.assertEqual(plan["updates"], [ + "refs/heads/release/3.2", "refs/tags/v3.2.0-rc2" + ]) + with self.assertRaisesRegex(ValueError, "disconnected branch initialization"): + release_policy.plan_public_promotion( + "3.2.0-rc2", + candidate, + refs, + lambda ancestor, descendant: False, + ) + + def test_newest_ga_advances_release_branch_tag_and_master(self): + branch = "a" * 40 + master = "b" * 40 + candidate = "c" * 40 + plan = release_policy.plan_public_promotion( + "3.2.0", + candidate, + { + "refs/heads/master": master, + "refs/heads/release/3.2": branch, + "refs/tags/v3.0.2": master, + "refs/tags/v3.2.0-rc1": branch, + }, + lambda ancestor, descendant: (ancestor, descendant) in { + (branch, candidate), + (master, candidate), + }, + ) + self.assertEqual( + plan["updates"], + ["refs/heads/release/3.2", "refs/tags/v3.2.0", "refs/heads/master"], + ) + self.assertTrue(plan["advance_master"]) + + def test_newer_patch_on_current_ga_line_advances_master(self): + current = "a" * 40 + candidate = "b" * 40 + plan = release_policy.plan_public_promotion( + "3.2.2", + candidate, + { + "refs/heads/master": current, + "refs/heads/release/3.2": current, + "refs/tags/v3.0.2": current, + "refs/tags/v3.2.1": current, + }, + lambda ancestor, descendant: ancestor == current and descendant == candidate, + ) + self.assertTrue(plan["ga_release_is_latest"]) + self.assertEqual( + plan["updates"], + ["refs/heads/release/3.2", "refs/tags/v3.2.2", "refs/heads/master"], + ) + + def test_same_sha_public_promotion_skips_existing_tag_and_is_idempotent(self): + candidate = "c" * 40 + plan = release_policy.plan_public_promotion( + "3.2.0", + candidate, + { + "refs/heads/master": candidate, + "refs/heads/release/3.2": candidate, + "refs/tags/v3.2.0": candidate, + "refs/tags/v3.2.0-rc1": "a" * 40, + }, + lambda ancestor, descendant: ancestor == descendant, + ) + self.assertTrue(plan["tag_exists"]) + self.assertEqual( + plan["updates"], + ["refs/heads/release/3.2", "refs/heads/master"], + ) + + def test_public_promotion_rejects_conflicting_tag_and_non_fast_forward_branch(self): + candidate = "c" * 40 + refs = { + "refs/heads/master": "a" * 40, + "refs/tags/v3.0.2": "a" * 40, + "refs/tags/v3.2.0-rc1": "b" * 40, + } + with self.assertRaisesRegex(ValueError, "tags are never moved"): + release_policy.plan_public_promotion( + "3.2.0-rc1", candidate, + {**refs, "refs/tags/v3.2.0-rc1": "d" * 40}, + lambda ancestor, descendant: True, + ) + with self.assertRaisesRegex(ValueError, "non-fast-forward"): + release_policy.plan_public_promotion( + "3.2.0-rc2", candidate, + {**refs, "refs/heads/release/3.2": "d" * 40}, + lambda ancestor, descendant: False, + ) + + def test_older_line_ga_advances_only_its_release_branch(self): + old_branch = "a" * 40 + newest = "b" * 40 + candidate = "c" * 40 + plan = release_policy.plan_public_promotion( + "3.0.3", + candidate, + { + "refs/heads/master": newest, + "refs/heads/release/3.0": old_branch, + "refs/heads/release/3.2": newest, + "refs/tags/v3.0.2": old_branch, + "refs/tags/v3.2.0": newest, + }, + lambda ancestor, descendant: (ancestor, descendant) == (old_branch, candidate), + ) + self.assertEqual( + plan["updates"], + ["refs/heads/release/3.0", "refs/tags/v3.0.3"], + ) + self.assertFalse(plan["advance_master"]) + + def test_newest_ga_requires_master_history_bridge(self): + with self.assertRaisesRegex(ValueError, "history bridge"): + release_policy.plan_public_promotion( + "3.2.0", + "c" * 40, + { + "refs/heads/master": "d" * 40, + "refs/heads/release/3.2": "a" * 40, + "refs/tags/v3.0.2": "d" * 40, + "refs/tags/v3.2.0-rc1": "a" * 40, + }, + lambda ancestor, descendant: (ancestor, descendant) == ("a" * 40, "c" * 40), + ) + + def test_lower_ga_patch_on_current_line_cannot_be_promoted_as_latest(self): + current = "a" * 40 + candidate = "b" * 40 + refs = { + "refs/heads/master": current, + "refs/heads/release/3.2": current, + "refs/tags/v3.0.2": current, + "refs/tags/v3.2.1": current, + } + decision = release_policy.public_release_line_policy("3.2.0", refs) + self.assertFalse(decision["ga_release_is_latest"]) + with self.assertRaisesRegex(ValueError, "lower GA version cannot advance"): + release_policy.plan_public_promotion( + "3.2.0", + candidate, + refs, + lambda ancestor, descendant: ancestor == current, + ) + + def test_lower_ga_patch_on_older_line_cannot_be_promoted(self): + current = "a" * 40 + with self.assertRaisesRegex(ValueError, "lower GA version cannot advance"): + release_policy.plan_public_promotion( + "3.0.1", + "b" * 40, + { + "refs/heads/master": current, + "refs/tags/v3.0.2": current, + "refs/tags/v3.2.0": current, + }, + lambda ancestor, descendant: True, + ) + + def test_first_beta_promotion_creates_line_branch_and_tag_without_master(self): + master = "a" * 40 + plan = release_policy.plan_public_promotion( + "3.3.0-beta1", + "b" * 40, + { + "refs/heads/master": master, + "refs/tags/v3.0.2": master, + "refs/heads/release/3.2": "c" * 40, + "refs/tags/v3.2.0-rc1": "c" * 40, + }, + lambda ancestor, descendant: False, + ) + self.assertEqual(plan["channel"], "BETA") + self.assertEqual(plan["updates"], ["refs/heads/release/3.3", "refs/tags/v3.3.0-beta1"]) + self.assertFalse(plan["advance_master"]) + self.assertFalse(plan["ga_release_is_latest"]) + + def test_beta_on_the_newest_line_never_advances_master(self): + master = "a" * 40 + beta1 = "b" * 40 + candidate = "c" * 40 + plan = release_policy.plan_public_promotion( + "3.3.0-beta2", + candidate, + { + "refs/heads/master": master, + "refs/tags/v3.2.0": master, + "refs/heads/release/3.3": beta1, + "refs/tags/v3.3.0-beta1": beta1, + }, + lambda ancestor, descendant: (ancestor, descendant) in {(beta1, candidate), (master, candidate)}, + ) + self.assertTrue(plan["ga_line_is_newest"]) + self.assertFalse(plan["advance_master"]) + self.assertFalse(plan["ga_release_is_latest"]) + self.assertEqual(plan["updates"], ["refs/heads/release/3.3", "refs/tags/v3.3.0-beta2"]) + + def test_promotion_requires_the_candidate_to_sort_above_the_latest_line_tag(self): + def refs(latest: str) -> dict: + line = latest[1:].rsplit(".", 1)[0] + return { + "refs/heads/master": "c" * 40, + "refs/tags/v3.0.2": "c" * 40, + f"refs/heads/release/{line}": "a" * 40, + f"refs/tags/{latest}": "a" * 40, + } + + for version, latest in ( + ("3.2.0-rc1", "v3.2.0-rc2"), + ("3.2.0-rc3", "v3.2.0"), + ("3.3.0-beta2", "v3.3.0-rc1"), + ("3.3.0-beta9", "v3.3.0-beta10"), + ): + with self.subTest(version=version, latest=latest), self.assertRaisesRegex( + ValueError, f"{latest} is the latest public tag on this line; v{version} must sort above it" + ): + release_policy.plan_public_promotion( + version, "b" * 40, refs(latest), lambda ancestor, descendant: True + ) + for version, latest in ( + ("3.3.0-beta10", "v3.3.0-beta9"), + ("3.3.0-rc1", "v3.3.0-beta5"), + ("3.3.0", "v3.3.0-rc2"), + ("3.3.1-beta1", "v3.3.0"), + ): + with self.subTest(version=version, latest=latest): + plan = release_policy.plan_public_promotion( + version, "b" * 40, refs(latest), lambda ancestor, descendant: True + ) + self.assertIn(f"refs/tags/v{version}", plan["updates"]) + + def test_same_sha_beta_repromotion_is_idempotent(self): + candidate = "c" * 40 + plan = release_policy.plan_public_promotion( + "3.3.0-beta1", + candidate, + { + "refs/heads/master": "a" * 40, + "refs/tags/v3.0.2": "a" * 40, + "refs/heads/release/3.3": candidate, + "refs/tags/v3.3.0-beta1": candidate, + }, + lambda ancestor, descendant: ancestor == descendant, + ) + self.assertTrue(plan["tag_exists"]) + self.assertEqual(plan["updates"], ["refs/heads/release/3.3"]) + + def test_old_line_ga_and_rc_plans_with_public_beta_tags(self): + master = "a" * 40 + rc1 = "b" * 40 + beta1 = "d" * 40 + candidate = "c" * 40 + refs = { + "refs/heads/master": master, + "refs/tags/v3.0.2": master, + "refs/heads/release/3.2": rc1, + "refs/tags/v3.2.0-rc1": rc1, + "refs/heads/release/3.3": beta1, + "refs/tags/v3.3.0-beta1": beta1, + } + ancestry = {(rc1, candidate), (master, candidate)} + + ga = release_policy.plan_public_promotion( + "3.2.0", candidate, refs, lambda ancestor, descendant: (ancestor, descendant) in ancestry + ) + self.assertEqual(ga["newest_ga_line"], "3.0") + self.assertTrue(ga["ga_line_is_newest"]) + self.assertTrue(ga["ga_release_is_latest"]) + self.assertEqual( + ga["updates"], + ["refs/heads/release/3.2", "refs/tags/v3.2.0", "refs/heads/master"], + ) + + rc2 = release_policy.plan_public_promotion( + "3.2.0-rc2", candidate, refs, lambda ancestor, descendant: (ancestor, descendant) in ancestry + ) + self.assertFalse(rc2["advance_master"]) + self.assertEqual(rc2["updates"], ["refs/heads/release/3.2", "refs/tags/v3.2.0-rc2"]) + + self.assertFalse(release_policy.public_release_line_policy("3.2.0-rc2", refs)["ga_release_is_latest"]) + beta2 = release_policy.public_release_line_policy("3.3.0-beta2", refs) + self.assertFalse(beta2["ga_release_is_latest"]) + self.assertEqual(beta2["latest_public_tag_on_candidate_line"], "v3.3.0-beta1") + + def test_older_line_ga_patch_with_newer_line_beta_tags_leaves_master(self): + newest = "a" * 40 + branch = "b" * 40 + candidate = "c" * 40 + plan = release_policy.plan_public_promotion( + "3.2.1", + candidate, + { + "refs/heads/master": newest, + "refs/tags/v3.3.0": newest, + "refs/heads/release/3.2": branch, + "refs/tags/v3.2.0": branch, + "refs/tags/v3.4.0-beta1": "d" * 40, + }, + lambda ancestor, descendant: (ancestor, descendant) == (branch, candidate), + ) + self.assertEqual(plan["newest_ga_line"], "3.3") + self.assertFalse(plan["advance_master"]) + self.assertFalse(plan["ga_release_is_latest"]) + self.assertEqual(plan["updates"], ["refs/heads/release/3.2", "refs/tags/v3.2.1"]) + + def test_public_promotion_fetches_legacy_line_tag_before_branch_bootstrap(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + bare = root / "public.git" + source = root / "source" + legacy = root / "legacy" + subprocess.run(["git", "init", "--bare", bare], check=True, capture_output=True) + # Background auto-maintenance would race the directory's removal. + subprocess.run(["git", "--git-dir", bare, "config", "maintenance.auto", "false"], check=True) + for repository in (source, legacy): + subprocess.run(["git", "init", repository], check=True, capture_output=True) + for key, value in ( + ("user.name", "Release Test"), + ("user.email", "release-test@example.invalid"), + ("maintenance.auto", "false"), + ): + subprocess.run(["git", "-C", repository, "config", key, value], check=True) + (repository / "source.txt").write_text(repository.name, encoding="utf-8") + subprocess.run(["git", "-C", repository, "add", "source.txt"], check=True) + subprocess.run( + ["git", "-C", repository, "commit", "-m", repository.name], + check=True, + capture_output=True, + ) + + def head(repository: Path) -> str: + return subprocess.run( + ["git", "-C", repository, "rev-parse", "HEAD"], + check=True, + capture_output=True, + text=True, + ).stdout.strip() + + source_head = head(source) + legacy_head = head(legacy) + for repository in (source, legacy): + subprocess.run( + ["git", "-C", repository, "remote", "add", "public", bare], + check=True, + ) + subprocess.run( + ["git", "-C", source, "push", "public", f"{source_head}:refs/heads/master"], + check=True, + capture_output=True, + ) + subprocess.run( + ["git", "-C", source, "push", "public", f"{source_head}:refs/tags/v3.0.2"], + check=True, + capture_output=True, + ) + subprocess.run( + ["git", "-C", legacy, "push", "public", f"{legacy_head}:refs/tags/v3.2.0-rc1"], + check=True, + capture_output=True, + ) + + (source / "source.txt").write_text("disconnected", encoding="utf-8") + subprocess.run(["git", "-C", source, "add", "source.txt"], check=True) + subprocess.run( + ["git", "-C", source, "commit", "-m", "disconnected candidate"], + check=True, + capture_output=True, + ) + with self.assertRaisesRegex(ValueError, "disconnected branch initialization"): + release_policy.inspect_public_promotion( + "3.2.0-rc2", head(source), "public", cwd=source + ) + + subprocess.run( + ["git", "-C", source, "checkout", "--detach", legacy_head], + check=True, + capture_output=True, + ) + (source / "source.txt").write_text("descends from public RC", encoding="utf-8") + subprocess.run(["git", "-C", source, "add", "source.txt"], check=True) + subprocess.run( + ["git", "-C", source, "commit", "-m", "connected candidate"], + check=True, + capture_output=True, + ) + plan = release_policy.inspect_public_promotion( + "3.2.0-rc2", head(source), "public", cwd=source + ) + self.assertEqual( + plan["updates"], + ["refs/heads/release/3.2", "refs/tags/v3.2.0-rc2"], + ) + + def test_atomic_public_push_rejects_raced_branch_update_without_creating_tag(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + bare = root / "public.git" + work = root / "source" + subprocess.run(["git", "init", "--bare", bare], check=True, capture_output=True) + subprocess.run(["git", "--git-dir", bare, "config", "maintenance.auto", "false"], check=True) + subprocess.run(["git", "init", work], check=True, capture_output=True) + for key, value in (("user.name", "Release Test"), ("user.email", "release-test@example.invalid"), + ("maintenance.auto", "false")): + subprocess.run(["git", "-C", work, "config", key, value], check=True) + + def commit(parent: str | None, content: str, subject: str) -> str: + if parent: + subprocess.run(["git", "-C", work, "checkout", "--detach", parent], check=True, capture_output=True) + (work / "source.txt").write_text(content, encoding="utf-8") + subprocess.run(["git", "-C", work, "add", "source.txt"], check=True) + subprocess.run(["git", "-C", work, "commit", "-m", subject], check=True, capture_output=True) + return subprocess.run( + ["git", "-C", work, "rev-parse", "HEAD"], + check=True, + capture_output=True, + text=True, + ).stdout.strip() + + initial = commit(None, "initial", "initial") + subprocess.run(["git", "-C", work, "remote", "add", "public", bare], check=True) + subprocess.run(["git", "-C", work, "push", "public", f"{initial}:refs/heads/master"], check=True, capture_output=True) + subprocess.run(["git", "-C", work, "push", "public", f"{initial}:refs/tags/v3.0.2"], check=True, capture_output=True) + + first_candidate = commit(initial, "rc1", "rc1") + first_plan = release_policy.inspect_public_promotion( + "3.2.0-rc1", first_candidate, "public", cwd=work + ) + release_policy.push_public_ref_updates("public", first_plan, cwd=work) + release_policy.push_public_ref_updates( + "public", + release_policy.inspect_public_promotion( + "3.2.0-rc1", first_candidate, "public", cwd=work + ), + cwd=work, + ) + subprocess.run( + ["git", "-C", work, "push", "public", f"{initial}:refs/heads/release/3.4"], + check=True, + capture_output=True, + ) + with self.assertRaisesRegex(ValueError, "changed after validation"): + release_policy.promote_public_source( + "3.2.0-rc1", + first_candidate, + "public", + first_plan["public_refs_digest"], + cwd=work, + ) + + second_candidate = commit(first_candidate, "rc2", "rc2") + second_plan = release_policy.inspect_public_promotion( + "3.2.0-rc2", second_candidate, "public", cwd=work + ) + release_policy.push_public_ref_updates("public", second_plan, cwd=work) + + stale_candidate = commit(second_candidate, "rc3", "rc3") + stale_plan = release_policy.inspect_public_promotion( + "3.2.0-rc3", stale_candidate, "public", cwd=work + ) + concurrent = commit(initial, "concurrent", "concurrent branch update") + subprocess.run(["git", "-C", work, "push", "public", f"{concurrent}:refs/heads/race"], check=True, capture_output=True) + subprocess.run( + ["git", "--git-dir", bare, "update-ref", "refs/heads/release/3.2", concurrent], + check=True, + ) + + with self.assertRaisesRegex(ValueError, "atomic public ref update failed"): + release_policy.push_public_ref_updates("public", stale_plan, cwd=work) + actual_branch = subprocess.run( + ["git", "--git-dir", bare, "rev-parse", "refs/heads/release/3.2"], + check=True, + capture_output=True, + text=True, + ).stdout.strip() + self.assertEqual(actual_branch, concurrent) + missing_tag = subprocess.run( + ["git", "--git-dir", bare, "show-ref", "--verify", "refs/tags/v3.2.0-rc3"], + capture_output=True, + text=True, + ) + self.assertNotEqual(missing_tag.returncode, 0) + + def test_public_promotion_reads_annotated_public_beta_tags(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + bare = root / "public.git" + work = root / "source" + subprocess.run(["git", "init", "--bare", bare], check=True, capture_output=True) + subprocess.run(["git", "--git-dir", bare, "config", "maintenance.auto", "false"], check=True) + subprocess.run(["git", "init", work], check=True, capture_output=True) + for key, value in (("user.name", "Release Test"), ("user.email", "release-test@example.invalid"), + ("maintenance.auto", "false")): + subprocess.run(["git", "-C", work, "config", key, value], check=True) + + def git(*arguments: str) -> str: + return subprocess.run( + ["git", "-C", work, *arguments], check=True, capture_output=True, text=True + ).stdout.strip() + + def commit(parent: str, subject: str) -> str: + if parent: + git("checkout", "--detach", parent) + (work / "source.txt").write_text(subject, encoding="utf-8") + git("add", "source.txt") + git("commit", "-m", subject) + return git("rev-parse", "HEAD") + + initial = commit("", "initial") + rc1 = commit(initial, "rc1") + beta1 = commit(rc1, "beta1") + git("tag", "-a", "v3.3.0-beta1", "-m", "beta1", beta1) + git("remote", "add", "public", str(bare)) + for source, ref in ( + (initial, "refs/heads/master"), + (initial, "refs/tags/v3.0.2"), + (rc1, "refs/heads/release/3.2"), + (rc1, "refs/tags/v3.2.0-rc1"), + (beta1, "refs/heads/release/3.3"), + ("refs/tags/v3.3.0-beta1", "refs/tags/v3.3.0-beta1"), + ): + git("push", "public", f"{source}:{ref}") + + rc2 = commit(rc1, "rc2") + self.assertEqual( + release_policy.inspect_public_promotion("3.2.0-rc2", rc2, "public", cwd=work)["updates"], + ["refs/heads/release/3.2", "refs/tags/v3.2.0-rc2"], + ) + beta2 = commit(beta1, "beta2") + plan = release_policy.inspect_public_promotion("3.3.0-beta2", beta2, "public", cwd=work) + self.assertEqual(plan["latest_public_tag_sha_on_candidate_line"], beta1) + self.assertEqual(plan["updates"], ["refs/heads/release/3.3", "refs/tags/v3.3.0-beta2"]) + + def test_accepts_publication_environment_with_one_or_more_reviewers_and_self_review(self): + release_policy.validate_publication_environment({ + "name": "public-release", + "protection_rules": [{ + "type": "required_reviewers", + "prevent_self_review": False, + "reviewers": [ + {"type": "User", "reviewer": {"id": 42}}, + {"type": "Team", "reviewer": {"id": 7}}, + ], + }], + }) + + def test_rejects_missing_publication_reviewers(self): + with self.assertRaisesRegex(ValueError, "one required-reviewers rule"): + release_policy.validate_publication_environment({ + "name": "public-release", + "protection_rules": [], + }) + + def test_rejects_malformed_or_self_review_blocking_publication_rule(self): + for rule in ( + {"type": "required_reviewers", "reviewers": [{"type": "User", "reviewer": {"id": 42}}]}, + { + "type": "required_reviewers", + "prevent_self_review": True, + "reviewers": [{"type": "User", "reviewer": {"id": 42}}], + }, + { + "type": "required_reviewers", + "prevent_self_review": False, + "reviewers": [{"type": "User", "reviewer": {"id": "42"}}], + }, + ): + with self.subTest(rule=rule), self.assertRaises(ValueError): + release_policy.validate_publication_environment({ + "name": "public-release", + "protection_rules": [rule], + }) + + def test_beta_publication_requires_beta_release_without_reviewers_for_beta_tags_only(self): + environment = { + "name": "beta-release", + "protection_rules": [{"type": "branch_policy"}], + "deployment_branch_policy": {"protected_branches": False, "custom_branch_policies": True}, + } + policies = {"total_count": 1, "branch_policies": [{"id": 3, "name": "v*-beta*", "type": "tag"}]} + release_policy.validate_publication_environment(environment, "BETA", policies) + reviewers = { + "type": "required_reviewers", + "prevent_self_review": False, + "reviewers": [{"type": "Team", "reviewer": {"id": 7}}], + } + protected_only = {"protected_branches": True, "custom_branch_policies": False} + only_beta_tags = "exactly the v\\*-beta\\* tag pattern" + for broken, broken_policies, message in ( + ({**environment, "name": "public-release"}, policies, "beta-release environment response"), + ({**environment, "protection_rules": [reviewers]}, policies, "must not require reviewers"), + ({**environment, "deployment_branch_policy": None}, policies, "custom deployment patterns"), + ({**environment, "deployment_branch_policy": protected_only}, policies, "custom deployment patterns"), + (environment, None, only_beta_tags), + (environment, {"branch_policies": []}, only_beta_tags), + (environment, {"branch_policies": [{"name": "v*", "type": "tag"}]}, only_beta_tags), + (environment, {"branch_policies": [{"name": "v*-beta*", "type": "branch"}]}, only_beta_tags), + ( + environment, + {"branch_policies": [{"name": "v*-beta*", "type": "tag"}, {"name": "v*-rc*", "type": "tag"}]}, + only_beta_tags, + ), + ): + with self.subTest(message=message, environment=broken, policies=broken_policies): + with self.assertRaisesRegex(ValueError, message): + release_policy.validate_publication_environment(broken, "BETA", broken_policies) + + def test_rc_and_ga_publication_keep_the_public_release_reviewer_rule(self): + public = { + "name": "public-release", + "protection_rules": [{ + "type": "required_reviewers", + "prevent_self_review": False, + "reviewers": [{"type": "Team", "reviewer": {"id": 7}}], + }], + } + beta = { + "name": "beta-release", + "protection_rules": [], + "deployment_branch_policy": {"protected_branches": False, "custom_branch_policies": True}, + } + policies = {"branch_policies": [{"name": "v*-beta*", "type": "tag"}]} + for channel in ("RC", "GA"): + with self.subTest(channel=channel): + release_policy.validate_publication_environment(public, channel) + with self.assertRaisesRegex(ValueError, "public-release environment response"): + release_policy.validate_publication_environment(beta, channel, policies) + with self.assertRaisesRegex(ValueError, "one required-reviewers rule"): + release_policy.validate_publication_environment( + {"name": "public-release", "protection_rules": []}, channel + ) + + def test_classifies_ga_beta_and_rc(self): + ga = release_policy.classify("3.2.0") + self.assertEqual((ga["channel"], ga["prerelease_number"]), ("GA", "")) identity = release_policy.classify("3.2.0-rc2") self.assertEqual(identity["channel"], "RC") - self.assertEqual(identity["rc_number"], "2") + self.assertEqual(identity["prerelease_number"], "2") self.assertEqual(identity["release_branch"], "release/3.2") + beta = release_policy.classify("3.3.0-beta10") + self.assertEqual( + (beta["channel"], beta["prerelease_number"], beta["release_branch"]), + ("BETA", "10", "release/3.3"), + ) def test_rejects_non_release_versions(self): - for version in ("v3.2.0", "3.2.0-beta1", "3.2", "3.2.0-rc0"): + for version in ( + "v3.2.0", "3.2", "3.2.0-rc0", "3.2.0-beta0", "3.2.0-beta", "3.2.0-alpha1", + "3.2.0-beta1-rc1", "3.2.0-BETA1", "3.2.0-devel", + ): with self.subTest(version=version), self.assertRaises(ValueError): release_policy.classify(version) @@ -37,7 +786,7 @@ class ReleasePolicyTest(unittest.TestCase): (root / "release-state.txt").write_text( "version=3.2.0\n" "channel=RC\n" - "rc=1\n" + "prerelease=1\n" "revision=$Format:%H$\n" ) identity = release_policy.validate_source(root, "3.2.0-rc1") @@ -46,18 +795,74 @@ class ReleasePolicyTest(unittest.TestCase): with self.assertRaisesRegex(ValueError, "release channel"): release_policy.validate_source(root, "3.2.0") (root / "release-state.txt").write_text( - "version=3.2.0\nchannel=RC\nrc=1\nrevision=" + "a" * 40 + "\n" + "version=3.2.0\nchannel=RC\nprerelease=1\nrevision=" + "a" * 40 + "\n" ) with self.assertRaisesRegex(ValueError, "revision"): release_policy.validate_source(root, "3.2.0-rc1") - def test_read_state_cli_accepts_single_digit_rc(self): + def test_parse_state_prerelease_contract(self): + def state(channel: str, prerelease: str, *extra: str) -> str: + lines = ("version=3.3.0", f"channel={channel}", f"prerelease={prerelease}", "revision=$Format:%H$") + return "\n".join((*lines, *extra)) + "\n" + + beta = release_policy.parse_state(state("BETA", "1", "windows_signing=unsigned")) + self.assertEqual( + (beta["channel"], beta["prerelease"], beta["windows_signing"]), + ("BETA", "1", "unsigned"), + ) + self.assertEqual(release_policy.parse_state(state("RC", "2"))["windows_signing"], "signpath") + self.assertEqual(release_policy.parse_state(state("DEVEL", ""))["prerelease"], "") + for contents, message in ( + (state("BETA", "1"), "BETA release state requires windows_signing=unsigned"), + (state("BETA", "1", "windows_signing=signpath"), "BETA release state requires windows_signing=unsigned"), + (state("BETA", "", "windows_signing=unsigned"), "positive prerelease number"), + (state("BETA", "0", "windows_signing=unsigned"), "positive prerelease number"), + (state("RC", "0"), "positive prerelease number"), + (state("DEVEL", "1"), "empty prerelease number"), + (state("GA", "1"), "empty prerelease number"), + (state("ALPHA", "1"), "channel must be DEVEL, BETA, RC, or GA"), + (state("RC", "1").replace("prerelease=", "rc="), "must define version, channel, prerelease, revision"), + ): + with self.subTest(contents=contents), self.assertRaisesRegex(ValueError, message): + release_policy.parse_state(contents) + + def test_validates_beta_source_and_archive(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + state = ( + "version=3.3.0\nchannel=BETA\nprerelease=1\n" + "revision=$Format:%H$\nwindows_signing=unsigned\n" + ) + (root / "release-state.txt").write_text(state) + identity = release_policy.validate_source(root, "3.3.0-beta1") + self.assertEqual( + (identity["channel"], identity["prerelease_number"], identity["windows_signing"]), + ("BETA", "1", "unsigned"), + ) + for version, message in ( + ("3.3.0-beta2", "prerelease number 1 does not match 2"), + ("3.3.0-rc1", "release channel BETA does not match RC"), + ): + with self.subTest(version=version), self.assertRaisesRegex(ValueError, message): + release_policy.validate_source(root, version) + commit = "e" * 40 + archived_state = state.replace("$Format:%H$", commit).encode() + archive = root / "source.tar.gz" + with tarfile.open(archive, "w:gz") as output: + info = tarfile.TarInfo("wsjtx-3.3.0-beta1/release-state.txt") + info.size = len(archived_state) + output.addfile(info, io.BytesIO(archived_state)) + release_policy.validate_archive(archive, "3.3.0-beta1", commit) + with self.assertRaisesRegex(ValueError, "release identity does not match"): + release_policy.validate_archive(archive, "3.3.0-beta2", commit) + + def test_read_state_cli_accepts_single_digit_prerelease(self): with tempfile.TemporaryDirectory() as directory: root = Path(directory) (root / "release-state.txt").write_text( "version=3.2.0\n" "channel=RC\n" - "rc=1\n" + "prerelease=1\n" "revision=$Format:%H$\n" ) result = subprocess.run( @@ -71,7 +876,7 @@ class ReleasePolicyTest(unittest.TestCase): { "version": "3.2.0", "channel": "RC", - "rc": "1", + "prerelease": "1", "revision": "$Format:%H$", "windows_signing": "signpath", }, @@ -80,7 +885,7 @@ class ReleasePolicyTest(unittest.TestCase): (root / "release-state.txt").write_text( "version=3.2.0\n" "channel=RC\n" - "rc=1beta\n" + "prerelease=1beta\n" "revision=$Format:%H$\n" ) result = subprocess.run( @@ -89,13 +894,13 @@ class ReleasePolicyTest(unittest.TestCase): text=True, ) self.assertNotEqual(result.returncode, 0) - self.assertIn("positive RC number", result.stderr) + self.assertIn("positive prerelease number", result.stderr) def test_source_pins_unsigned_mode_and_rejects_unknown_mode(self): with tempfile.TemporaryDirectory() as directory: root = Path(directory) state = ( - "version=3.2.0\nchannel=RC\nrc=1\n" + "version=3.2.0\nchannel=RC\nprerelease=1\n" "revision=$Format:%H$\nwindows_signing=unsigned\n" ) (root / "release-state.txt").write_text(state) @@ -118,7 +923,7 @@ class ReleasePolicyTest(unittest.TestCase): with tempfile.TemporaryDirectory() as directory: root = Path(directory) commit = "b" * 40 - state = f"version=3.2.0\nchannel=RC\nrc=1\nrevision={commit}\n".encode() + state = f"version=3.2.0\nchannel=RC\nprerelease=1\nrevision={commit}\n".encode() tar_path = root / "source.tar.gz" with tarfile.open(tar_path, "w:gz") as archive: info = tarfile.TarInfo("wsjtx-3.2.0-rc1/release-state.txt") @@ -132,6 +937,43 @@ class ReleasePolicyTest(unittest.TestCase): with self.assertRaisesRegex(ValueError, "revision"): release_policy.validate_archive(tar_path, "3.2.0-rc1", "c" * 40) + def test_candidate_and_public_gates_reject_missing_intel_payloads(self): + version = "3.3.0-beta1" + for distribution in (False, True): + mode = "distribution" if distribution else "validation" + for public in (False, True): + with self.subTest(mode=mode, public=public), tempfile.TemporaryDirectory() as directory: + root = Path(directory) + expected = ( + release_policy.public_expected_assets(version, mode) + if public else release_policy.expected_assets(version, distribution) + ) + for name in expected: + target = root / name + target.mkdir() + suffix = release_policy.asset_suffix(name) + filename = name.replace("-unsigned", "") + if not filename.endswith(suffix): + filename += suffix + (target / filename).write_bytes(name.encode()) + def verify(): + if public: + return release_policy.find_public_asset_files(root, version, mode) + return release_policy.find_asset_files(root, version, distribution) + verify() + suffix = "macOS.pkg" if distribution else "macOS-unsigned.pkg" + required = [f"wsjtx-{version}-x86_64-{suffix}"] + [ + f"wsjtx-{version}-x86_64-macOS-{group}" + for group in ("jt9", "jt9stream", "wsprd", "utilities") + ] + for name in required: + artifact = root / name + held = root / "held" + artifact.rename(held) + with self.subTest(missing=name), self.assertRaisesRegex(ValueError, re.escape(name)): + verify() + held.rename(artifact) + def test_distribution_gate_rejects_unsigned_package(self): with tempfile.TemporaryDirectory() as directory: root = Path(directory) @@ -139,7 +981,7 @@ class ReleasePolicyTest(unittest.TestCase): for name in release_policy.expected_assets(version, True): target = root / name target.mkdir() - suffix = ".pkg" if "macOS" in name else ".AppImage" if "linux" in name else ".exe" + suffix = release_policy.asset_suffix(name) (target / f"artifact{suffix}").write_bytes(b"signed") (root / "extra").mkdir() (root / "extra" / "unexpected-unsigned.pkg").write_bytes(b"unsigned") @@ -153,7 +995,7 @@ class ReleasePolicyTest(unittest.TestCase): for name in release_policy.expected_assets(version, True): target = root / name target.mkdir() - suffix = ".pkg" if "macOS" in name else ".AppImage" if "linux" in name else ".exe" + suffix = release_policy.asset_suffix(name) (target / f"{name}{suffix}" if not name.endswith(suffix) else target / name).write_bytes(name.encode()) for arch in ("x86_64", "aarch64", "armhf"): for package_type in ("deb", "rpm"): @@ -180,21 +1022,82 @@ class ReleasePolicyTest(unittest.TestCase): self.assertEqual(manifest["macos_signing"]["mode"], "distribution") self.assertEqual(manifest["macos_signing"]["replaceable_assets"], []) self.assertEqual(manifest["windows_signing"]["mode"], "signpath") - self.assertEqual(len(manifest["assets"]), 13) + self.assertEqual(len(manifest["assets"]), 37) + self.assertTrue( + {f"{name}.tar.gz" for name in release_policy.release_tarballs(version)} + <= {entry["name"] for entry in manifest["assets"]} + ) def test_manual_macos_assets_keep_release_names_without_immutable_hashes(self): + for version in ("3.2.0", "3.2.0-rc1"): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + for name in release_policy.public_expected_assets(version, "validation"): + target = root / name + target.mkdir() + if name in release_policy.release_tarballs(version): + filename = f"{name}.tar.gz" + elif "macOS" in name: + filename = name.replace("-unsigned", "") + elif "linux" in name: + filename = f"{name}.AppImage" + else: + filename = "wsjtx-win64.exe" + (target / filename).write_bytes(name.encode()) + for arch in ("x86_64", "aarch64", "armhf"): + for package_type in ("deb", "rpm"): + target = root / f"wsjtx-{version}-linux-{arch}-{package_type}" + target.mkdir() + (target / f"wsjtx-{arch}.{package_type}").write_bytes(arch.encode()) + (root / f"wsjtx-{version}-src.tar.gz").write_bytes(b"source") + args = type("Args", (), { + "artifacts": str(root), "version": version, "repository": "WSJTX/wsjtx", + "commit": "a" * 40, "run_id": "123", + "linux_x86_64_digest": "sha256:" + "1" * 64, + "linux_aarch64_digest": "sha256:" + "2" * 64, + "linux_armhf_cross_digest": "sha256:" + "3" * 64, + "linux_armhf_digest": "sha256:" + "4" * 64, + "macos_mode": "validation", + "windows_mode": "signpath", + })() + + release_policy.write_manifest(args) + + manifest = json.loads((root / "release-manifest.json").read_text()) + replaceable = { + f"wsjtx-{version}-arm64-macOS.pkg", + f"wsjtx-{version}-x86_64-macOS.pkg", + } + release_names = {path.name for path in release_policy.release_files(root, version, "validation")} + immutable_names = {entry["name"] for entry in manifest["assets"]} + checksum_names = { + line.split(" ", 1)[1] + for line in (root / "SHA256SUMS").read_text().splitlines() + } + self.assertEqual(manifest["macos_signing"]["mode"], "manual") + self.assertEqual(set(manifest["macos_signing"]["replaceable_assets"]), replaceable) + self.assertTrue(replaceable <= release_names) + self.assertTrue(replaceable.isdisjoint(immutable_names)) + self.assertTrue(replaceable.isdisjoint(checksum_names)) + self.assertIn("wsjtx-win64.exe", immutable_names) + tarballs = {f"{name}.tar.gz" for name in release_policy.release_tarballs(version)} + self.assertTrue(tarballs <= immutable_names & checksum_names) + + def test_unsigned_windows_manifest_selects_and_hashes_installer(self): with tempfile.TemporaryDirectory() as directory: root = Path(directory) - version = "3.2.0" - for name in release_policy.public_expected_assets(version, "validation"): + version = "3.2.0-rc1" + for name in release_policy.public_expected_assets(version, "validation", "unsigned"): target = root / name target.mkdir() - if "macOS" in name: + if name in release_policy.release_tarballs(version): + filename = f"{name}.tar.gz" + elif "macOS" in name: filename = name.replace("-unsigned", "") elif "linux" in name: filename = f"{name}.AppImage" else: - filename = "wsjtx-win64.exe" + filename = f"wsjtx-{version}-win64.exe" (target / filename).write_bytes(name.encode()) for arch in ("x86_64", "aarch64", "armhf"): for package_type in ("deb", "rpm"): @@ -209,38 +1112,147 @@ class ReleasePolicyTest(unittest.TestCase): "linux_aarch64_digest": "sha256:" + "2" * 64, "linux_armhf_cross_digest": "sha256:" + "3" * 64, "linux_armhf_digest": "sha256:" + "4" * 64, - "macos_mode": "validation", - "windows_mode": "signpath", + "macos_mode": "validation", "windows_mode": "unsigned", })() - release_policy.write_manifest(args) - manifest = json.loads((root / "release-manifest.json").read_text()) - replaceable = { - f"wsjtx-{version}-arm64-macOS.pkg", - f"wsjtx-{version}-x86_64-macOS.pkg", - } - release_names = {path.name for path in release_policy.release_files(root, version, "validation")} - immutable_names = {entry["name"] for entry in manifest["assets"]} - checksum_names = { - line.split(" ", 1)[1] - for line in (root / "SHA256SUMS").read_text().splitlines() - } - self.assertEqual(manifest["macos_signing"]["mode"], "manual") - self.assertEqual(set(manifest["macos_signing"]["replaceable_assets"]), replaceable) - self.assertTrue(replaceable <= release_names) - self.assertTrue(replaceable.isdisjoint(immutable_names)) - self.assertTrue(replaceable.isdisjoint(checksum_names)) - self.assertIn("wsjtx-win64.exe", immutable_names) + installer = f"wsjtx-{version}-win64.exe" + self.assertEqual(manifest["windows_signing"]["mode"], "unsigned") + self.assertIn(installer, {entry["name"] for entry in manifest["assets"]}) + for group in ("jt9", "jt9stream", "wsprd", "utilities"): + self.assertIn( + f"wsjtx-{version}-windows-x86_64-{group}.tar.gz", {entry["name"] for entry in manifest["assets"]} + ) + self.assertIn(installer, (root / "SHA256SUMS").read_text()) + installer_path = root / f"wsjtx-{version}-windows-x86_64-installer" / installer + installer_path.rename(installer_path.with_name("unexpected.exe")) + with self.assertRaisesRegex(ValueError, "unexpected unsigned Windows installer"): + release_policy.find_public_asset_files(root, version, "validation", "unsigned") + installer_path.with_name("unexpected.exe").rename(installer_path) + signed_dir = root / f"wsjtx-{version}-windows-x86_64-installer-signed" + signed_dir.mkdir() + with self.assertRaisesRegex(ValueError, "signed Windows installer"): + release_policy.find_public_asset_files(root, version, "validation", "unsigned") - def test_unsigned_windows_manifest_selects_and_hashes_installer(self): + def test_release_tarballs_are_required_by_candidate_and_public_gates(self): + version = "3.2.0-rc1" + tools = release_policy.release_tarballs(version) + self.assertEqual( + tools, + [ + f"wsjtx-{version}-{target}-{group}" + for target in ("arm64-macOS", "x86_64-macOS", "linux-x86_64", "linux-aarch64", "linux-armhf", "windows-x86_64") + for group in ("jt9", "jt9stream", "wsprd", "utilities") + ], + ) + self.assertEqual([release_policy.asset_suffix(name) for name in tools], [".tar.gz"] * 24) + self.assertEqual( + [release_policy.asset_suffix(name) for name in release_policy.expected_assets(version, False)[:6]], + [".pkg", ".pkg", ".AppImage", ".AppImage", ".AppImage", ".exe"], + ) + for distribution in (False, True): + self.assertTrue(set(tools) <= set(release_policy.expected_assets(version, distribution))) + for macos_mode in release_policy.MACOS_MODES: + for windows_mode in release_policy.WINDOWS_MODES: + self.assertTrue( + set(tools) <= set(release_policy.public_expected_assets(version, macos_mode, windows_mode)) + ) with tempfile.TemporaryDirectory() as directory: root = Path(directory) - version = "3.2.0-rc1" + for name in release_policy.expected_assets(version, False): + target = root / name + target.mkdir() + (target / f"{name}{release_policy.asset_suffix(name)}").write_bytes(name.encode()) + files = release_policy.find_asset_files(root, version, False) + self.assertEqual( + sorted(path.name for path in files if path.name.endswith(".tar.gz")), + sorted(f"{name}.tar.gz" for name in tools), + ) + armhf = root / f"wsjtx-{version}-linux-armhf-jt9stream" + (armhf / f"{armhf.name}.tar.gz").unlink() + with self.assertRaisesRegex(ValueError, "linux-armhf-jt9stream must contain exactly one .tar.gz"): + release_policy.find_asset_files(root, version, False) + + def test_release_tarball_uploads_agree_with_the_group_file_and_the_policy(self): + root = SCRIPT.parents[2] + action = (root / ".github/actions/upload-release-tarballs/action.yml").read_text(encoding="utf-8") + prefix = r"wsjtx-\$\{\{ inputs\.version \}\}-\$\{\{ inputs\.target \}\}-" + names = re.findall(rf"\n name: {prefix}(\S+)\n", action) + paths = re.findall(rf"\n path: \$\{{\{{ inputs\.directory \}}\}}/{prefix}(\S+)\.tar\.gz\n", action) + self.assertEqual(names, release_policy.tarball_groups()) + self.assertEqual(paths, names) + self.assertEqual(action.count("if-no-files-found: error"), len(names)) + + version = "3.3.0" + installers = [] + for name in release_policy.public_expected_assets(version, "validation", "unsigned"): + if name not in release_policy.release_tarballs(version): + installers.append(re.sub(r"-(unsigned\.pkg|AppImage|installer)$", "", name.removeprefix(f"wsjtx-{version}-")).removesuffix(".pkg")) + self.assertEqual(installers, list(release_policy.RELEASE_TARGETS)) + macos_arches = [target.removesuffix("-macOS") for target in installers if target.endswith("-macOS")] + linux_arches = [target.removeprefix("linux-") for target in installers if target.startswith("linux-")] + + uploads = [] + for path in ( + ".github/workflows/build-macos.yml", ".github/workflows/build-windows.yml", + ".github/workflows/build-linux.yml", ".github/actions/build-linux-payload/action.yml", + ): + text = (root / path).read_text(encoding="utf-8") + calls = re.findall( + r"uses: \./\.github/actions/upload-release-tarballs\n\s+with:\n\s+version: \$\{\{ inputs\.version \}\}\n" + r"\s+target: (.+)\n\s+directory: release-tarballs\n", + text, + ) + self.assertEqual(len(calls), text.count("upload-release-tarballs"), path) + uploads += [(path, target) for target in calls] + targets = {target for _, target in uploads if "${{" not in target} + for path, target in uploads: + if target == "${{ inputs.arch }}-macOS": + targets |= {f"{arch}-macOS" for arch in macos_arches} + elif target == "linux-${{ inputs.arch }}": + targets |= {f"linux-{arch}" for arch in linux_arches if f"linux-{arch}" not in targets} + self.assertEqual(targets, set(release_policy.RELEASE_TARGETS)) + + def test_tarball_groups_come_from_the_group_file(self): + self.assertEqual(release_policy.tarball_groups(), ["jt9", "jt9stream", "wsprd", "utilities"]) + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "release-tarballs.txt" + path.write_bytes(b"# comment\r\njt9 jt9\r\n\r\nengine jt9stream wsprd\r\n") + self.assertEqual(release_policy.tarball_groups(path), ["jt9", "engine"]) + for contents, message in ( + ("", "must name each release tarball once"), + ("# only a comment\n", "must name each release tarball once"), + ("jt9 jt9\njt9 jt9stream\n", "must name each release tarball once"), + ("jt9 jt9\nutilities\n", "release tarball utilities names no programs"), + ("jt9 jt9\ninstaller wsprd\n", "release tarball name installer cannot name a release asset"), + ("jt9 jt9\nsrc wsprd\n", "release tarball name src cannot name a release asset"), + ("jt9 jt9\nAppImage wsprd\n", "release tarball name AppImage cannot name a release asset"), + ): + with self.subTest(contents=contents): + path.write_text(contents, encoding="utf-8") + with self.assertRaisesRegex(ValueError, message): + release_policy.tarball_groups(path) + + def test_asset_suffix_tells_tarballs_from_installers_on_every_target(self): + version = "3.3.0-beta1" + for name in release_policy.release_tarballs(version): + with self.subTest(name=name): + self.assertEqual(release_policy.asset_suffix(name), ".tar.gz") + self.assertEqual( + [release_policy.asset_suffix(name) for name in release_policy.public_expected_assets(version, "validation", "unsigned")[:6]], + [".pkg", ".pkg", ".AppImage", ".AppImage", ".AppImage", ".exe"], + ) + + def test_beta_manifest_hashes_unsigned_macos_packages_as_immutable_assets(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + version = "3.3.0-beta2" for name in release_policy.public_expected_assets(version, "validation", "unsigned"): target = root / name target.mkdir() - if "macOS" in name: + if name in release_policy.release_tarballs(version): + filename = f"{name}.tar.gz" + elif "macOS" in name: filename = name.replace("-unsigned", "") elif "linux" in name: filename = f"{name}.AppImage" @@ -262,21 +1274,29 @@ class ReleasePolicyTest(unittest.TestCase): "linux_armhf_digest": "sha256:" + "4" * 64, "macos_mode": "validation", "windows_mode": "unsigned", })() + release_policy.write_manifest(args) + manifest = json.loads((root / "release-manifest.json").read_text()) - installer = f"wsjtx-{version}-win64.exe" - self.assertEqual(manifest["windows_signing"]["mode"], "unsigned") - self.assertIn(installer, {entry["name"] for entry in manifest["assets"]}) - self.assertIn(installer, (root / "SHA256SUMS").read_text()) - installer_path = root / f"wsjtx-{version}-windows-x86_64-installer" / installer - installer_path.rename(installer_path.with_name("unexpected.exe")) - with self.assertRaisesRegex(ValueError, "unexpected unsigned Windows installer"): - release_policy.find_public_asset_files(root, version, "validation", "unsigned") - installer_path.with_name("unexpected.exe").rename(installer_path) - signed_dir = root / f"wsjtx-{version}-windows-x86_64-installer-signed" - signed_dir.mkdir() - with self.assertRaisesRegex(ValueError, "signed Windows installer"): - release_policy.find_public_asset_files(root, version, "validation", "unsigned") + beta_assets = {f"wsjtx-{version}-{arch}-macOS.pkg" for arch in ("arm64", "x86_64")} + beta_assets |= {f"{name}.tar.gz" for name in release_policy.release_tarballs(version)} + immutable_names = {entry["name"] for entry in manifest["assets"]} + checksum_names = { + line.split(" ", 1)[1] + for line in (root / "SHA256SUMS").read_text().splitlines() + } + self.assertEqual(manifest["macos_signing"], {"mode": "unsigned", "replaceable_assets": []}) + self.assertTrue(beta_assets <= immutable_names) + self.assertTrue(beta_assets <= checksum_names) + hashes = {entry["name"]: entry["sha256"] for entry in manifest["assets"]} + for arch in ("arm64", "x86_64"): + name = f"wsjtx-{version}-{arch}-macOS.pkg" + package = root / f"wsjtx-{version}-{arch}-macOS-unsigned.pkg" / name + self.assertEqual(hashes[name], release_policy.hash_file(package)) + + args.macos_mode = "distribution" + with self.assertRaisesRegex(ValueError, "BETA releases publish the validated unsigned macOS packages"): + release_policy.write_manifest(args) def test_signing_reports_bind_hashes_and_source(self): with tempfile.TemporaryDirectory() as directory: @@ -316,6 +1336,18 @@ class ReleasePolicyTest(unittest.TestCase): "signer_thumbprint": "5678", "identity_verified": True, })) release_policy.verify_signing_reports(root, version, commit, tag) + intel_report = root / f"macos-signing-report-{version}-x86_64" / "macos-signing-report.json" + contents = intel_report.read_bytes() + intel_report.unlink() + with self.assertRaisesRegex(ValueError, "macos-signing-report.*x86_64"): + release_policy.verify_signing_reports(root, version, commit, tag) + intel_report.write_bytes(contents) + intel_report_data = json.loads(contents) + intel_report_data["sha256"] = "0" * 64 + intel_report.write_text(json.dumps(intel_report_data)) + with self.assertRaisesRegex(ValueError, "macOS x86_64 report hash"): + release_policy.verify_signing_reports(root, version, commit, tag) + intel_report.write_bytes(contents) (verification_dir / "verification.json").write_text("{}") with self.assertRaisesRegex(ValueError, "release ref"): release_policy.verify_signing_reports(root, version, commit, tag) @@ -357,6 +1389,18 @@ class ReleasePolicyTest(unittest.TestCase): })) release_policy.verify_signing_reports(root, version, commit, tag, "validation") + intel_report = root / f"macos-signing-report-{version}-x86_64" / "macos-signing-report.json" + contents = intel_report.read_bytes() + intel_report.unlink() + with self.assertRaisesRegex(ValueError, "macos-signing-report.*x86_64"): + release_policy.verify_signing_reports(root, version, commit, tag, "validation") + intel_report.write_bytes(contents) + intel_report_data = json.loads(contents) + intel_report_data["sha256"] = "0" * 64 + intel_report.write_text(json.dumps(intel_report_data)) + with self.assertRaisesRegex(ValueError, "macOS x86_64 report hash"): + release_policy.verify_signing_reports(root, version, commit, tag, "validation") + intel_report.write_bytes(contents) report = json.loads( (root / f"macos-signing-report-{version}-arm64" / "macos-signing-report.json").read_text() diff --git a/.github/scripts/tests/test_release_workflow_policy.py b/.github/scripts/tests/test_release_workflow_policy.py new file mode 100644 index 00000000..8765cbe1 --- /dev/null +++ b/.github/scripts/tests/test_release_workflow_policy.py @@ -0,0 +1,186 @@ +import pathlib +import re +import unittest + + +ROOT = pathlib.Path(__file__).resolve().parents[3] +PUBLIC = (ROOT / ".github/workflows/public-release.yml").read_text() +SIGN = (ROOT / ".github/workflows/sign-windows-release.yml").read_text() +PREPARE = (ROOT / ".github/workflows/prepare-release-dependencies.yml").read_text() + + +def step(workflow: str, name: str) -> str: + start = workflow.index(f" - name: {name}\n") + following = re.search(r"\n - ", workflow[start + 1:]) + return workflow[start:start + 1 + following.start()] if following else workflow[start:] + + +def job(workflow: str, name: str) -> str: + start = workflow.index(f"\n {name}:\n") + 1 + following = re.search(r"\n [A-Za-z0-9_-]+:\n", workflow[start:]) + return workflow[start:start + following.start() + 1] if following else workflow[start:] + + +class ReleaseWorkflowPolicyTests(unittest.TestCase): + def test_both_macos_jobs_are_required_before_candidate_and_public_assembly(self): + release = (ROOT / ".github/workflows/release.yml").read_text() + for workflow, gate in ((release, "candidate-ready"), (PUBLIC, "assemble")): + self.assertIn("needs: [prepare, macos, macos-intel, linux, linux-arm, linux-armhf, windows]", job(workflow, gate)) + for name, arch, runner, target in ( + ("macos", "arm64", "macos-15", "11.0"), + ("macos-intel", "x86_64", "macos-15-intel", "10.13"), + ): + body = job(workflow, name) + self.assertIn("needs: prepare", body) + self.assertNotIn(" if:", body) + self.assertIn("uses: ./.github/workflows/build-macos.yml", body) + self.assertIn(f"arch: {arch}", body) + self.assertIn(f"runner: {runner}", body) + self.assertIn(f'deployment_target: "{target}"', body) + self.assertNotIn("rc_number:", body) + self.assertNotIn("release_channel:", body) + signing = "validation" if gate == "candidate-ready" else "${{ needs.prepare.outputs.macos_sign_mode }}" + self.assertIn(f"signing_mode: {signing}", body) + + def test_intel_ci_is_opt_in_and_selected_artifacts_include_it(self): + ci = (ROOT / ".github/workflows/ci.yml").read_text() + intel = job(ci, "macos-intel") + self.assertIn("needs: [prepare, linux]", intel) + predicate = intel.split(" if: >-\n", 1)[1].split(" uses:", 1)[0] + self.assertEqual(predicate.strip(), "github.event_name == 'workflow_dispatch' ||\n contains(github.event.pull_request.labels.*.name, 'full-ci')") + selected = (ROOT / ".github/workflows/build-selected-artifacts.yml").read_text() + self.assertIn(" - macos-x64\n", selected) + body = job(selected, "macos-x64") + self.assertIn("(inputs.targets == 'macos-x64' || inputs.targets == 'all')", body) + self.assertIn("needs: [prepare, linux-smoke-x64]", body) + for body in (intel, body): + self.assertIn('arch: "x86_64"', body) + self.assertIn('runner: "macos-15-intel"', body) + self.assertIn('deployment_target: "10.13"', body) + self.assertNotIn("release_channel:", body) + self.assertNotIn("rc_number:", body) + + def test_macos_dispatch_defaults_and_compiler_selection_support_intel(self): + build = (ROOT / ".github/workflows/build-macos.yml").read_text() + runner = "${{ inputs.runner || (inputs.arch == 'x86_64' && 'macos-15-intel' || 'macos-15') }}" + self.assertIn("runs-on: " + runner, job(build, "build")) + self.assertIn("RUNNER: " + runner, job(build, "build")) + self.assertIn("runs-on: " + runner, job(build, "sign_distribution")) + self.assertIn("DEPLOYMENT_TARGET: ${{ inputs.deployment_target || (inputs.arch == 'x86_64' && '10.13' || '11.0') }}", build) + self.assertIn(" - x86_64\n", build) + action = (ROOT / ".github/actions/warm-macos-deps/action.yml").read_text() + for text in (build, action): + self.assertIn("arm64:macos-15:11.0|x86_64:macos-15-intel:10.13)", text) + self.assertIn("if: inputs.arch == 'x86_64'", text) + self.assertIn(".github/scripts/install-xpack-gfortran-macos.sh", text) + self.assertIn('if [ "${{ inputs.arch }}" = "x86_64" ]; then', text) + self.assertIn("steps.controlled-intel-fc.outputs.runtime_archives", text) + + def test_intel_cache_jobs_outputs_and_summary_are_connected(self): + warm = (ROOT / ".github/workflows/warm-dependency-caches.yml").read_text() + self.assertIn(" - macos-x86_64\n", warm) + self.assertIn("macos_x86_64: ${{ steps.detect.outputs.macos_x86_64 }}", job(warm, "detect")) + deps = job(warm, "warm-macos-x86_64-deps") + compiler = job(warm, "warm-macos-x86_64-ccache") + self.assertIn("needs: detect", deps) + self.assertIn("needs: [detect, warm-macos-x86_64-deps]", compiler) + for body in (deps, compiler): + self.assertIn("if: needs.detect.outputs.macos_x86_64 == 'true'", body) + self.assertIn("arch: x86_64", body) + self.assertIn("runner: macos-15-intel", body) + self.assertIn('deployment_target: "10.13"', body) + self.assertIn("runs-on: macos-15-intel", deps) + self.assertIn("save_ccache: true", compiler) + summary = job(warm, "summary") + self.assertIn("- warm-macos-x86_64-deps", summary) + self.assertIn("- warm-macos-x86_64-ccache", summary) + + def test_public_release_marks_every_non_ga_channel_prerelease_and_latest_stays_ga_only(self): + publish = step(PUBLIC, "Publish public GitHub Release") + self.assertRegex(publish, r'if \[ "\$CHANNEL" != GA \]; then\s+EXPECTED_PRERELEASE=true\s+fi') + self.assertRegex(publish, r'if \[ "\$CHANNEL" != GA \]; then\s+FLAGS\+=\(--prerelease\)\s+fi') + self.assertEqual(publish.count("--prerelease"), 1) + self.assertRegex( + publish, + r'LATEST=false\s+if \[ "\$CHANNEL" = GA \] && \[ "\$GA_RELEASE_IS_LATEST" = true \]; then\s+LATEST=true\s+fi', + ) + self.assertEqual(publish.count("LATEST=true"), 1) + self.assertIn('FLAGS+=("--latest=$LATEST")', publish) + + def test_publication_environment_and_its_validation_follow_the_channel(self): + selected = "${{ needs.prepare.outputs.release_channel == 'BETA' && 'beta-release' || 'public-release' }}" + self.assertIn(f" environment: {selected}\n", job(PUBLIC, "publish")) + guard = step(PUBLIC, "Validate final publication environment protection") + self.assertRegex( + guard, + r'ENVIRONMENT=public-release\s+POLICIES=\(\)\s+' + r'if \[ "\$CHANNEL" = BETA \]; then\s+ENVIRONMENT=beta-release', + ) + self.assertIn('"repos/$GITHUB_REPOSITORY/environments/$ENVIRONMENT/deployment-branch-policies"', guard) + self.assertIn('"repos/$GITHUB_REPOSITORY/environments/$ENVIRONMENT"', guard) + self.assertIn('--channel "$CHANNEL" "${POLICIES[@]}"', guard) + self.assertLess(PUBLIC.index(guard), PUBLIC.index("\n macos:\n")) + + def test_betas_publish_validated_macos_packages_with_nothing_replaceable(self): + identity = step(PUBLIC, "Validate public release tag and source identity") + self.assertRegex( + identity, + r'if \[ "\$CHANNEL" = BETA \]; then\s+echo "macos_sign_mode=validation" >> "\$GITHUB_OUTPUT"', + ) + self.assertLess( + identity.index('[ "$CHANNEL" = BETA ]'), + identity.index('[ "$MACOS_DISTRIBUTION_SIGNING_ENABLED" = true ]'), + ) + recheck = step(PUBLIC, "Recheck bundle and immutable public tag") + self.assertRegex(recheck, r'if \[ "\$CHANNEL" = BETA \]; then\s+EXPECTED_MACOS_MODE=unsigned\s+elif') + publish = step(PUBLIC, "Publish public GitHub Release") + self.assertIn(".macos_signing.replaceable_assets[]", publish) + self.assertNotIn("MACOS_MODE", publish) + + def test_a_rerun_compares_every_published_asset_except_the_manifests_replaceable_ones(self): + publish = step(PUBLIC, "Publish public GitHub Release") + self.assertIn("mapfile -t REPLACEABLE_NAMES < <(jq -r '.macos_signing.replaceable_assets[]' " + "release-bundle/release-manifest.json)", publish) + preserve = [ + "if printf '%s\\n' \"${REPLACEABLE_NAMES[@]}\" | grep -Fxq \"$name\"; then", + "if printf '%s\\n' \"${ACTUAL_NAMES[@]}\" | grep -Fxq \"$name\"; then", + "echo \"Preserving manually replaceable macOS asset: $name\"", + ] + self.assertRegex(publish, r"\s+".join(map(re.escape, preserve))) + self.assertEqual(len(re.findall(r"^\s+continue$", publish, re.M)), 1) + self.assertEqual(publish.count('cmp "$file"'), 1) + + def test_windows_signing_guard_admits_only_rc_and_ga(self): + guard = step(SIGN, "Require a public RC or GA invocation") + self.assertIn('test "$(jq -r .channel <<<"$IDENTITY")" = "$CHANNEL"', guard) + self.assertIn('test "$CHANNEL" = RC || test "$CHANNEL" = GA', guard) + self.assertLess(SIGN.index(guard), SIGN.index("uses: signpath/github-action-submit-signing-request")) + + def test_dependency_preparation_fails_unless_develop_and_the_source_branch_are_protected(self): + prepare = job(PREPARE, "prepare") + self.assertIn("github.ref == 'refs/heads/develop'", prepare.split("\n steps:\n", 1)[0]) + self.assertEqual(PREPARE.count("ref_protected"), 1) + self.assertNotIn("continue-on-error", prepare) + guard = step(PREPARE, "Require protected develop") + self.assertNotRegex(guard, r"\n if:") + self.assertIn("REF_PROTECTED: ${{ github.ref_protected }}", guard) + self.assertRegex(guard, r'if \[ "\$REF_PROTECTED" != true \]; then\s+echo "::error::[^"]+"\s+exit 1') + self.assertLess(prepare.index("Require protected develop"), prepare.index("actions/checkout")) + source = step(PREPARE, "Resolve protected source branch to an exact commit") + self.assertRegex( + source, + r'if \[ "\$\(jq -r \'\.protected\' <<< "\$branch"\)" != true \]; then\s+echo "::error::[^"]+"\s+exit 1', + ) + + def test_full_artifact_downloads_drop_the_armhf_build_tree(self): + release = (ROOT / ".github/workflows/release.yml").read_text() + for workflow, job_name, next_step in ((release, "candidate-ready", "Verify all candidate artifacts"), (PUBLIC, "assemble", "Build corresponding source archive")): + body = job(workflow, job_name) + download = body.index("uses: actions/download-artifact@v8\n with:\n path: artifacts\n") + drop = body.index(" - name: Drop the ARMHF build tree\n run: rm -rf artifacts/armhf-build-tree\n") + self.assertLess(download, drop, job_name) + self.assertLess(drop, body.index(f" - name: {next_step}\n"), job_name) + + +if __name__ == "__main__": + unittest.main() -- cgit v1.2.3 From c576a4281ef8c87990ae6399393a827dfaccacd5 Mon Sep 17 00:00:00 2001 From: Christoph Berg Date: Wed, 14 Oct 2026 14:39:20 +0200 Subject: New upstream version 3.3.0~beta2+dfsg --- .github/scripts/build-fftw-macos.sh | 15 + .github/scripts/generate-change-list.py | 154 +++ .github/scripts/generate-quick-downloads.py | 9 +- .github/scripts/tests/test_generate_change_list.py | 263 +++++ .../scripts/tests/test_release_workflow_policy.py | 16 + .github/workflows/public-release.yml | 22 +- CMake/Sources.cmake | 6 +- CMakeLists.txt | 29 +- DecoderEngine.h | 46 +- WavDecodeTestController.cpp | 24 +- WavDecodeTestController.hpp | 2 +- ci-cd/DEPLOYMENT_PLAYBOOK.md | 7 +- ci-cd/DEVELOPMENT_WORKFLOW.md | 2 + lib/decode4.f90 | 112 -- lib/decoder.f90 | 40 +- lib/decoder_callbacks.f90 | 107 +- lib/decoder_engine.f90 | 240 ++++- lib/decoder_engine_types.f90 | 18 +- lib/deep4.f90 | 169 --- lib/extract4.f90 | 18 +- lib/jt4.f90 | 26 +- lib/jt4_decode.f90 | 1071 +++++++++++++++----- lib/jt4_host_support.f90 | 112 ++ lib/jt9.f90 | 3 +- lib/jt9_params_init.f90 | 6 + lib/jt9a.f90 | 5 +- lib/lpf1.f90 | 29 - lib/ps4.f90 | 27 - lib/streaming_apply.f90 | 7 +- lib/streaming_control.f90 | 3 +- lib/streaming_emit.f90 | 27 +- lib/streaming_io.f90 | 5 +- lib/sync4.f90 | 146 --- lib/xcor4.f90 | 30 +- main.cpp | 34 +- map65/commons.cpp | 3 - map65/commons.h | 9 +- map65/libm65/CMakeLists.txt | 5 + map65/libm65/datcom_ptrs_mod.f90 | 79 +- map65/libm65/decode0.f90 | 33 +- map65/libm65/npar_ptrs_mod.f90 | 85 +- map65/libm65/run_m65.f90 | 3 +- map65/mainwindow.cpp | 16 +- release-state.txt | 4 +- .../fixtures/jt4_OK1KIR_141105_175700.expected.txt | 2 +- tests/integration/decoder_engine/run_wav_gui.cmake | 5 +- .../jt9/verify_jt4_12000_read_extent.cmake | 39 +- tests/integration/jt9/verify_jt4_engine.cmake | 19 + tests/unit/decoder_engine/CMakeLists.txt | 56 + tests/unit/decoder_engine/jt4_engine_signal.f90 | 47 + tests/unit/decoder_engine/test_decoder_engine.c | 40 +- .../unit/decoder_engine/test_decoder_engine_jt4.c | 470 +++++++++ .../test_decoder_engine_jt4_host.f90 | 213 ++++ .../test_decoder_engine_jt4_state.f90 | 112 ++ tests/unit/jtty/jtty_cpp_n1mm_smoke.cpp | 37 + tests/unit/jtty/test_jtty_messages.cpp | 48 + tests/unit/jtty/test_jtty_structured_decode.f90 | 29 + tests/unit/map65/test_map65_pass_snapshots.f90 | 100 ++ tests/unit/streaming/CMakeLists.txt | 6 +- tests/unit/streaming/test_streaming_consumers.cpp | 162 ++- widgets/JttyMessages.hpp | 17 + widgets/mainwindow.cpp | 3 +- widgets/mainwindow_jtty.cpp | 73 +- 63 files changed, 3465 insertions(+), 1080 deletions(-) create mode 100644 .github/scripts/generate-change-list.py create mode 100644 .github/scripts/tests/test_generate_change_list.py delete mode 100644 lib/decode4.f90 delete mode 100644 lib/deep4.f90 create mode 100644 lib/jt4_host_support.f90 delete mode 100644 lib/lpf1.f90 delete mode 100644 lib/ps4.f90 delete mode 100644 lib/sync4.f90 create mode 100644 tests/integration/jt9/verify_jt4_engine.cmake create mode 100644 tests/unit/decoder_engine/jt4_engine_signal.f90 create mode 100644 tests/unit/decoder_engine/test_decoder_engine_jt4.c create mode 100644 tests/unit/decoder_engine/test_decoder_engine_jt4_host.f90 create mode 100644 tests/unit/decoder_engine/test_decoder_engine_jt4_state.f90 create mode 100644 tests/unit/map65/test_map65_pass_snapshots.f90 (limited to '.github/scripts/tests') diff --git a/.github/scripts/build-fftw-macos.sh b/.github/scripts/build-fftw-macos.sh index cbaf0291..00c24a40 100755 --- a/.github/scripts/build-fftw-macos.sh +++ b/.github/scripts/build-fftw-macos.sh @@ -10,6 +10,20 @@ version="$1" deployment_target="$2" prefix="$3" +architecture="${ARCH:-$(uname -m)}" +case "$architecture" in + x86_64) + simd_flags=(--enable-sse2 --enable-avx) + ;; + arm64) + simd_flags=(--enable-neon) + ;; + *) + echo "Unsupported macOS architecture: $architecture" >&2 + exit 2 + ;; +esac + curl -L --fail --retry 5 --retry-delay 10 -o fftw.tar.gz "https://www.fftw.org/fftw-${version}.tar.gz" tar -xzf fftw.tar.gz cd "fftw-${version}" @@ -19,6 +33,7 @@ cd "fftw-${version}" --enable-single \ --enable-threads \ --enable-shared --disable-static \ + "${simd_flags[@]}" \ CFLAGS="-O3 -mmacosx-version-min=${deployment_target}" \ LDFLAGS="-mmacosx-version-min=${deployment_target}" make -j"$(sysctl -n hw.ncpu)" diff --git a/.github/scripts/generate-change-list.py b/.github/scripts/generate-change-list.py new file mode 100644 index 00000000..19a73db8 --- /dev/null +++ b/.github/scripts/generate-change-list.py @@ -0,0 +1,154 @@ +#!/usr/bin/env python3 +"""Print a GitHub Release change list from the commit subjects of a public release tag. + +Usage: + generate-change-list.py + +Prints nothing when no earlier release tag exists. +""" +import importlib.util +import re +import subprocess +import sys +from pathlib import Path + + +def load_script(name, filename): + spec = importlib.util.spec_from_file_location(name, Path(__file__).with_name(filename)) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +policy = load_script("release_policy", "release-policy.py") + +SUBJECT_RE = re.compile( + r"^(?P[A-Za-z]+)(?:\((?P[^)]*)\))?(?P!)?:\s*(?P\S.*)$" +) +SECTIONS = (("feat", "New features"), ("fix", "Fixes"), ("perf", "Performance")) +INTERNAL_SCOPES = frozenset(("release", "ci", "test", "tests")) +# Pull request numbers in subjects belong to the private repository; on the public +# release page they would link to unrelated items, and @names would notify people. +TRAILING_PR_RE = re.compile(r"\s*\(#\d+\)$") +REFERENCE_RE = re.compile(r"[\w.-]+/[\w.-]+#\d+|\bGH-\d+\b|(? \n") + return 2 + sys.stdout.write(change_list(argv[1], argv[2])) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv)) diff --git a/.github/scripts/generate-quick-downloads.py b/.github/scripts/generate-quick-downloads.py index 0ba21c36..7a07c6f1 100755 --- a/.github/scripts/generate-quick-downloads.py +++ b/.github/scripts/generate-quick-downloads.py @@ -4,8 +4,7 @@ The release workflow attaches every build artifact to the Release, which makes the assets list long and hard for an end user to navigate (installers sit among the command-line program tarballs, checksums, the manifest, and source). This emits a -short, curated per-platform installer picker to prepend to the auto-generated -release notes. +short, curated per-platform installer picker to put above the change list. It is *asset-driven*: platforms and architectures are derived from the asset filenames passed in, not hard-coded. New build variants (for example an added @@ -13,7 +12,7 @@ Linux architecture such as armhf) therefore appear in Quick Downloads automatically, with no edit to this script. The block is emitted on stdout, ending at the last platform line (no trailing -separator); the caller joins it to the auto-generated notes. +separator); the caller joins it to the change list. Usage: generate-quick-downloads.py ... @@ -108,8 +107,8 @@ def main(argv): if source: out += ["", "### Source", f"- [{source}]({url(source)})"] - # If nothing matched (no installer-grade assets), emit nothing so the - # caller leaves the auto-generated notes untouched. + # If nothing matched (no installer-grade assets), emit nothing; the caller + # then publishes the change list alone. if len(out) == 4: return 0 diff --git a/.github/scripts/tests/test_generate_change_list.py b/.github/scripts/tests/test_generate_change_list.py new file mode 100644 index 00000000..6d2e707c --- /dev/null +++ b/.github/scripts/tests/test_generate_change_list.py @@ -0,0 +1,263 @@ +import os +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + + +SCRIPT = Path(__file__).resolve().parents[1] / "generate-change-list.py" +REPO = "WSJTX/wsjtx" + + +class ChangeListTest(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory() + self.addCleanup(self.directory.cleanup) + self.repo = Path(self.directory.name) + self.env = { + **{key: value for key, value in os.environ.items() if not key.startswith("GIT_")}, + "GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1", + "GIT_AUTHOR_EMAIL": "author@example.com", + "GIT_COMMITTER_NAME": "Committer", "GIT_COMMITTER_EMAIL": "committer@example.com", + } + self.git("init", "-q", "-b", "develop") + # Background auto-maintenance would race the directory's removal. + self.git("config", "maintenance.auto", "false") + self.commit("chore: start") + + def stamp(self, author="Test Author"): + # Distinct dates, so a cherry-pick onto the same parent is a real copy. + self.clock = getattr(self, "clock", 0) + 1 + date = f"@{1_700_000_000 + self.clock} +0000" + return {**self.env, "GIT_AUTHOR_NAME": author, "GIT_AUTHOR_DATE": date, "GIT_COMMITTER_DATE": date} + + def git(self, *args): + return subprocess.run( + ["git", *args], cwd=self.repo, env=self.stamp(), text=True, capture_output=True, check=True, + ).stdout.strip() + + def commit(self, subject, author="Test Author", change=None): + # A distinct change per commit: git treats all empty commits as cherry-picks of each other. + self.changes = getattr(self, "changes", 0) + 1 + change = change or f"change-{self.changes}.txt" + (self.repo / change).write_text(subject + "\n") + self.git("add", change) + subprocess.run( + ["git", "commit", "-qm", subject], + cwd=self.repo, env=self.stamp(author), check=True, capture_output=True, + ) + return self.git("rev-parse", "HEAD") + + def merge(self, ref, subject): + self.git("merge", "--no-ff", "-qm", subject, ref) + + def notes(self, tag): + result = subprocess.run( + [sys.executable, str(SCRIPT), REPO, tag], + cwd=self.repo, env=self.env, text=True, capture_output=True, + ) + self.assertEqual(result.returncode, 0, result.stderr) + return result.stdout + + def test_a_later_beta_lists_the_changes_since_the_previous_beta_in_commit_order(self): + self.git("checkout", "-qb", "release/3.3") + self.commit("feat: old feature") + self.git("tag", "v3.3.0-beta1") + self.commit("feat(decoder): new mode", author="Joe Taylor") + self.commit("fix(wav): keep the dial context", author="David Christle") + self.commit("fix: a later fix") + self.git("tag", "v3.3.0-beta2") + notes = self.notes("v3.3.0-beta2") + self.assertTrue(notes.startswith("## Changes since v3.3.0-beta1\n")) + self.assertIn("### New features\n- decoder: new mode (Joe Taylor)\n", notes) + self.assertIn("### Fixes\n- wav: keep the dial context (David Christle)\n- a later fix (Test Author)\n", notes) + self.assertNotIn("old feature", notes) + self.assertIn(f"[Full comparison](https://github.com/{REPO}/compare/v3.3.0-beta1...v3.3.0-beta2).", notes) + + def test_a_spent_beta_number_falls_back_to_the_newest_published_tag(self): + self.git("checkout", "-qb", "release/3.3") + self.git("tag", "v3.3.0-beta1") + self.commit("fix: carried by the unpublished beta2") + self.commit("fix: new in beta3") + self.git("tag", "v3.3.0-beta3") + notes = self.notes("v3.3.0-beta3") + self.assertTrue(notes.startswith("## Changes since v3.3.0-beta1\n")) + self.assertIn("- carried by the unpublished beta2", notes) + self.assertIn("- new in beta3", notes) + + def test_a_release_candidate_follows_the_last_beta_of_its_line(self): + self.git("checkout", "-qb", "release/3.3") + self.git("tag", "v3.3.0-beta4") + self.commit("fix: freeze-time fix") + self.git("tag", "v3.3.0-rc1") + notes = self.notes("v3.3.0-rc1") + self.assertTrue(notes.startswith("## Changes since v3.3.0-beta4\n")) + self.assertIn("- freeze-time fix", notes) + + def test_a_lines_first_release_leaves_out_what_the_previous_line_shipped(self): + self.commit("feat: in 3.2 already") + self.git("tag", "v3.0.2") + self.git("checkout", "-qb", "release/3.0", "HEAD~1") + self.commit("fix: only on the old line") + self.git("tag", "v3.0.3") + self.git("checkout", "-q", "develop") + self.git("checkout", "-qb", "release/3.2") + self.commit("fix: only on release/3.2") + self.git("checkout", "-q", "develop") + picked = self.commit("fix(gui): picked into 3.2", change="gui.txt") + self.git("checkout", "-q", "release/3.2") + self.git("cherry-pick", picked) + self.git("tag", "v3.2.0-rc1") + self.git("checkout", "-q", "develop") + self.merge("v3.0.3", "Merge 3.0.3 into develop") + self.commit("feat: new on develop") + self.git("checkout", "-qb", "release/3.3") + self.commit("build(release): start 3.3 at BETA 1") + self.git("tag", "v3.3.0-beta1") + notes = self.notes("v3.3.0-beta1") + self.assertTrue(notes.startswith("## Changes since v3.2.0-rc1\n")) + self.assertIn("- new on develop", notes) + for shipped in ("in 3.2 already", "only on release/3.2", "picked into 3.2", "only on the old line"): + self.assertNotIn(shipped, notes) + self.assertIn(f"/compare/v3.2.0-rc1...v3.3.0-beta1", notes) + + def test_a_beta_after_the_previous_ga_is_merged_back_lists_only_new_changes(self): + self.git("checkout", "-qb", "release/3.2") + self.git("tag", "v3.2.0-rc1") + self.git("checkout", "-q", "develop") + original = self.commit("fix(gui): first on develop", change="gui.txt") + self.git("checkout", "-qb", "release/3.3") + self.git("tag", "v3.3.0-beta1") + self.git("checkout", "-q", "release/3.2") + self.git("cherry-pick", original) + self.commit("fix: only on release/3.2") + self.git("tag", "v3.2.0") + self.git("checkout", "-q", "develop") + self.merge("v3.2.0", "Merge 3.2.0 into develop") + self.commit("fix: new on develop") + self.git("checkout", "-q", "release/3.3") + self.merge("develop", "Merge develop into release/3.3") + self.git("tag", "v3.3.0-beta2") + notes = self.notes("v3.3.0-beta2") + self.assertTrue(notes.startswith("## Changes since v3.3.0-beta1\n")) + self.assertIn("### Fixes\n- new on develop (Test Author)\n\n", notes) + self.assertNotIn("first on develop", notes) + self.assertNotIn("only on release/3.2", notes) + + def test_copies_that_a_merged_back_ga_shipped_are_not_listed_again(self): + self.git("checkout", "-qb", "release/3.2") + self.commit("fix: on release/3.2 before the picks") + self.git("tag", "v3.2.0-rc1") + self.git("checkout", "-q", "develop") + self.git("checkout", "-qb", "release/3.3") + self.git("tag", "v3.3.0-beta1") + self.git("checkout", "-q", "develop") + original = self.commit("fix(gui): develop original shipped in 3.2.0", change="gui.txt") + self.git("checkout", "-q", "release/3.2") + self.git("cherry-pick", original) + port = self.commit("fix(cat): made on release/3.2 first", change="cat.txt") + self.git("tag", "v3.2.0") + self.git("checkout", "-q", "develop") + self.git("cherry-pick", port) + self.merge("v3.2.0", "Merge 3.2.0 into develop") + self.commit("fix: new on develop") + self.git("checkout", "-q", "release/3.3") + self.merge("develop", "Merge develop into release/3.3") + self.git("tag", "v3.3.0-beta2") + self.git("tag", "v3.3.0") + for tag in ("v3.3.0-beta2", "v3.3.0"): + notes = self.notes(tag) + self.assertIn("### Fixes\n- new on develop (Test Author)\n\n", notes, tag) + self.assertNotIn("develop original", notes, tag) + self.assertNotIn("made on release/3.2 first", notes, tag) + + def test_a_ga_lists_everything_since_the_previous_ga(self): + self.git("tag", "v3.2.0") + self.git("checkout", "-qb", "release/3.3") + self.commit("feat: from beta1") + self.git("tag", "v3.3.0-beta1") + self.commit("fix: from rc1") + self.git("tag", "v3.3.0-rc1") + self.commit("fix: from GA") + self.git("tag", "v3.3.0") + notes = self.notes("v3.3.0") + self.assertTrue(notes.startswith("## Changes since v3.2.0\n")) + for change in ("from beta1", "from rc1", "from GA"): + self.assertIn(change, notes) + self.commit("fix: patch") + self.git("tag", "v3.3.1-rc1") + self.git("tag", "v3.3.1") + patch = self.notes("v3.3.1") + self.assertTrue(patch.startswith("## Changes since v3.3.0\n")) + self.assertIn("- patch", patch) + self.assertNotIn("from GA", patch) + self.assertEqual(self.notes("v3.3.0"), notes) + + def test_entries_are_grouped_cleaned_and_counted(self): + self.git("tag", "v3.3.0-beta1") + self.commit("feat(jtty)!: change the macro syntax") + self.commit("Fix(gui): uppercase type (#458)") + self.commit("fix: address PR #569 review for @k1jt") + self.commit("perf(fft): use SIMD") + self.commit("fix(gui): uppercase type (#458)") + self.commit("fix(jtty, tests): user-facing despite a test scope") + self.commit("fix(release): pipeline change") + self.commit("feat(ci, tests): pipeline feature") + self.commit("test: cover the decoder") + self.commit("Untyped subject that mentions fix") + self.git("checkout", "-qb", "topic") + self.commit("docs: topic change") + self.git("checkout", "-q", "develop") + self.merge("topic", "Merge pull request #12 from topic") + self.git("tag", "v3.3.0-beta2") + notes = self.notes("v3.3.0-beta2") + self.assertIn("### New features\n- jtty: change the macro syntax (breaking) (Test Author)\n\n", notes) + self.assertIn( + "### Fixes\n" + "- gui: uppercase type (Test Author)\n" + "- address PR `#569` review for `@k1jt` (Test Author)\n" + "- jtty, tests: user-facing despite a test scope (Test Author)\n\n", + notes, + ) + self.assertIn("### Performance\n- fft: use SIMD (Test Author)\n", notes) + self.assertNotIn("pipeline", notes) + self.assertNotIn("Merge pull request", notes) + self.assertIn("Plus 5 other commits: [full comparison]", notes) + + def test_references_are_neutralized_outside_code_spans_only(self): + self.git("tag", "v3.3.0-beta1") + for subject in ( + "fix: mail ops@example.com about C# and see https://example.com/docs/#anchor", + "fix: link WSJTX/wsjtx-internal#569, GH-12 and Hamlib/Hamlib#1940", + "fix: keep `a #12 @b` and literal", + "fix(@team): scope reference", + "fix: handle a lone ` in macros, see #12 and @k1jt", + ): + self.commit(subject) + self.git("tag", "v3.3.0-beta2") + notes = self.notes("v3.3.0-beta2") + self.assertIn("- mail ops@example.com about C# and see https://example.com/docs/#anchor (Test Author)\n", notes) + self.assertIn("- link `WSJTX/wsjtx-internal#569`, `GH-12` and `Hamlib/Hamlib#1940` (Test Author)\n", notes) + self.assertIn("- keep `a #12 @b` and <CR> literal (Test Author)\n", notes) + self.assertIn("- `@team`: scope reference (Test Author)\n", notes) + self.assertIn("- handle a lone ` in macros, see `#12` and `@k1jt` (Test Author)\n", notes) + + def test_a_range_without_listed_changes_says_so(self): + self.git("tag", "v3.3.0-beta1") + self.commit("test: only tests") + self.git("tag", "v3.3.0-beta2") + self.assertIn("\nNo user-facing changes; 1 other commit: [full comparison]", self.notes("v3.3.0-beta2")) + self.git("tag", "v3.3.0-beta3") + notes = self.notes("v3.3.0-beta3") + self.assertTrue(notes.startswith("## Changes since v3.3.0-beta2\n")) + self.assertIn("No source changes since v3.3.0-beta2.", notes) + + def test_no_earlier_release_tag_prints_nothing(self): + for tag in ("not-a-release", "build/v3.2.0-rc1", "v3.2", "v3.2.0-alpha1", "v3.3.0-beta1"): + self.git("tag", tag) + self.assertEqual(self.notes("v3.3.0-beta1"), "") + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/scripts/tests/test_release_workflow_policy.py b/.github/scripts/tests/test_release_workflow_policy.py index 8765cbe1..68e8c23d 100644 --- a/.github/scripts/tests/test_release_workflow_policy.py +++ b/.github/scripts/tests/test_release_workflow_policy.py @@ -150,6 +150,22 @@ class ReleaseWorkflowPolicyTests(unittest.TestCase): self.assertEqual(len(re.findall(r"^\s+continue$", publish, re.M)), 1) self.assertEqual(publish.count('cmp "$file"'), 1) + def test_a_new_release_body_carries_the_change_list_or_keeps_the_generated_notes(self): + self.assertIn("fetch-depth: 0", job(PUBLIC, "publish")) + publish = step(PUBLIC, "Publish public GitHub Release") + self.assertIn("--generate-notes", publish) + notes = publish[publish.index('if [ "$CREATED" = true ]; then'):] + self.assertIn('CHANGES=$(python3 .github/scripts/generate-change-list.py \\\n' + ' "$GITHUB_REPOSITORY" "$GITHUB_REF_NAME" || true)', notes) + self.assertRegex(notes, r'if \[ -z "\$CHANGES" \]; then\s+echo "::warning::[^"]*"\s+' + r'CHANGES=\$\(gh release view "\$GITHUB_REF_NAME" --json body --jq \.body \|\| true\)') + # Notes never fail a publication, and a body without changes never replaces GitHub's notes. + edit = notes.index("gh release edit") + self.assertRegex(notes[:edit], r'if \[ -z "\$CHANGES" \]; then\s+echo "::warning::[^"]*"\s+else\s+NOTES=\$CHANGES\s') + self.assertRegex(notes[edit:], r'^gh release edit "\$GITHUB_REF_NAME" --notes-file "\$RUNNER_TEMP/release-notes.md" \\\n' + r'\s+\|\| echo "::warning::[^"]*"\n\s+fi\n') + self.assertEqual(notes.count("gh release edit"), 1) + def test_windows_signing_guard_admits_only_rc_and_ga(self): guard = step(SIGN, "Require a public RC or GA invocation") self.assertIn('test "$(jq -r .channel <<<"$IDENTITY")" = "$CHANNEL"', guard) diff --git a/.github/workflows/public-release.yml b/.github/workflows/public-release.yml index f515a6fd..2792f7ee 100644 --- a/.github/workflows/public-release.yml +++ b/.github/workflows/public-release.yml @@ -455,11 +455,23 @@ jobs: if [ "$CREATED" = true ]; then QUICK_DOWNLOADS=$(python3 .github/scripts/generate-quick-downloads.py \ "$GITHUB_REPOSITORY" "$GITHUB_REF_NAME" "${FILES[@]}" || true) - if [ -n "$QUICK_DOWNLOADS" ]; then - GENERATED_NOTES=$(gh release view "$GITHUB_REF_NAME" --json body --jq .body) - printf '%s\n\n---\n\n%s\n' "$QUICK_DOWNLOADS" "$GENERATED_NOTES" > "$RUNNER_TEMP/release-notes.md" - gh release edit "$GITHUB_REF_NAME" --notes-file "$RUNNER_TEMP/release-notes.md" + CHANGES=$(python3 .github/scripts/generate-change-list.py \ + "$GITHUB_REPOSITORY" "$GITHUB_REF_NAME" || true) + if [ -z "$CHANGES" ]; then + echo "::warning::No change list was generated; keeping GitHub's generated notes." + CHANGES=$(gh release view "$GITHUB_REF_NAME" --json body --jq .body || true) + fi + if [ -z "$CHANGES" ]; then + echo "::warning::The release notes could not be read; the release body was left unchanged." else - echo "::warning::Quick Downloads picker was empty; generated notes were left unchanged." + NOTES=$CHANGES + if [ -n "$QUICK_DOWNLOADS" ]; then + NOTES=$(printf '%s\n\n---\n\n%s' "$QUICK_DOWNLOADS" "$CHANGES") + else + echo "::warning::Quick Downloads picker was empty." + fi + printf '%s\n' "$NOTES" > "$RUNNER_TEMP/release-notes.md" + gh release edit "$GITHUB_REF_NAME" --notes-file "$RUNNER_TEMP/release-notes.md" \ + || echo "::warning::The release notes could not be updated." fi fi diff --git a/CMake/Sources.cmake b/CMake/Sources.cmake index bd30d0e9..1965bb4d 100644 --- a/CMake/Sources.cmake +++ b/CMake/Sources.cmake @@ -273,6 +273,7 @@ set (wsjt_FSRCS lib/streaming_apply.f90 lib/jt4.f90 lib/jt4_decode.f90 + lib/jt4_host_support.f90 lib/jt65_decode.f90 lib/jt65_host_support.f90 lib/jt65_mod.f90 @@ -356,7 +357,6 @@ set (wsjt_FSRCS lib/ft8/compress.f90 lib/coord.f90 lib/db.f90 - lib/decode4.f90 lib/decode65a.f90 lib/decode65b.f90 lib/decode9w.f90 @@ -369,7 +369,6 @@ set (wsjt_FSRCS lib/decoder_engine.f90 lib/decoder.f90 lib/env_module.f90 - lib/deep4.f90 lib/deg2grid.f90 lib/degrade_snr.f90 lib/demod64a.f90 @@ -461,7 +460,6 @@ set (wsjt_FSRCS lib/libration.f90 lib/lorentzian.f90 lib/fst4/lorentzian_fading.f90 - lib/lpf1.f90 lib/map65_mmdec.f90 lib/mixlpf.f90 lib/makepings.f90 @@ -497,7 +495,6 @@ set (wsjt_FSRCS lib/pltanh.f90 lib/polyfit.f90 lib/prog_args.f90 - lib/ps4.f90 lib/qra/q65/q65_ap.f90 lib/qra/q65/q65_loops.f90 lib/qra/q65/q65_set_list.f90 @@ -529,7 +526,6 @@ set (wsjt_FSRCS lib/symspec.f90 lib/symspec2.f90 lib/symspec65.f90 - lib/sync4.f90 lib/sync65.f90 lib/ft4/getcandidates4.f90 lib/ft4/get_ft4_bitmetrics.f90 diff --git a/CMakeLists.txt b/CMakeLists.txt index 80ce9d86..9b64cbb2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -885,19 +885,6 @@ if (WSJT_ENABLE_TESTS) samples/JT4/JT4F/OK1KIR_141105_175700.WAV test/fixtures/jt4_OK1KIR_141105_175700.expected.txt --jt4 -b F -f 1200 -d 3) - if (TARGET jt4sim) - set (jt4_read_extent_work_dir - "${CMAKE_BINARY_DIR}/Testing/JT4/test_jt4_12000_read_extent") - add_test (NAME test_jt4_12000_read_extent - COMMAND ${CMAKE_COMMAND} - -DJT9=$ - -DJT4SIM=$ - -DWORK_DIR=${jt4_read_extent_work_dir} - -P ${CMAKE_SOURCE_DIR}/tests/integration/jt9/verify_jt4_12000_read_extent.cmake) - set_tests_properties (test_jt4_12000_read_extent PROPERTIES - LABELS "decoder;jt4;integration" - TIMEOUT 120) - endif () # WSPR decodes via the standalone wsprd binary, not jt9. -a isolates its # writable side files (wspr_wisdom.dat, ALL_WSPR.TXT, wspr_spots.txt, @@ -1280,6 +1267,20 @@ if (WSJT_ENABLE_TESTS AND WSJT_ENABLE_GUI_SMOKE_TESTS LABELS "gui;decoder;jt9;integration" PROCESSORS 1 TIMEOUT 90) + add_test ( + NAME test_wsjtx_jt4_wav + COMMAND ${CMAKE_COMMAND} + "-DWSJTX=$" + "-DMODE=JT4" + "-DSAMPLE=${CMAKE_BINARY_DIR}/tests/unit/decoder_engine/jt4-engine.wav" + "-DEXPECTED_MESSAGE=K1ABC W9XYZ FN42" + "-DWORK_DIR=${CMAKE_BINARY_DIR}/Testing/Jt4Wav" + -P ${CMAKE_SOURCE_DIR}/tests/integration/decoder_engine/run_wav_gui.cmake) + set_tests_properties (test_wsjtx_jt4_wav PROPERTIES + FIXTURES_REQUIRED jt4_engine_wav + LABELS "gui;decoder;jt4;integration" + PROCESSORS 1 + TIMEOUT 90) add_test ( NAME test_wsjtx_jt65_wav COMMAND ${CMAKE_COMMAND} @@ -1331,7 +1332,7 @@ if (WSJT_ENABLE_TESTS AND WSJT_ENABLE_GUI_SMOKE_TESTS TIMEOUT 390) endforeach () if (WSJT_ENABLE_TSAN) - set_tests_properties (test_wsjtx_jt9_wav test_wsjtx_jt65_wav test_wsjtx_q65_wav + set_tests_properties (test_wsjtx_jt4_wav test_wsjtx_jt9_wav test_wsjtx_jt65_wav test_wsjtx_q65_wav test_wsjtx_fst4_wav test_wsjtx_fst4w_wav PROPERTIES ENVIRONMENT "TSAN_OPTIONS=${wsjt_tsan_gui_options}") endif () diff --git a/DecoderEngine.h b/DecoderEngine.h index 08c3b7c0..25cfcce3 100644 --- a/DecoderEngine.h +++ b/DecoderEngine.h @@ -6,11 +6,11 @@ extern "C" { #endif typedef void *decoder_engine_handle; -enum { DECODER_ENGINE_ABI = 7, DECODER_MODE_FT4 = 5, DECODER_MODE_FT8 = 8, +enum { DECODER_ENGINE_ABI = 8, DECODER_MODE_JT4 = 4, DECODER_MODE_FT4 = 5, DECODER_MODE_FT8 = 8, DECODER_MODE_JT9 = 9, DECODER_MODE_JT65 = 65, DECODER_MODE_Q65 = 66, DECODER_MODE_FST4 = 240, DECODER_MODE_FST4W = 241 }; enum { DECODER_SUPPORT_FT8 = 1, DECODER_SUPPORT_FT4 = 2, DECODER_SUPPORT_JT9 = 4, - DECODER_SUPPORT_JT65 = 8, DECODER_SUPPORT_Q65 = 16, DECODER_SUPPORT_FST4 = 32, DECODER_SUPPORT_FST4W = 64 }; + DECODER_SUPPORT_JT65 = 8, DECODER_SUPPORT_Q65 = 16, DECODER_SUPPORT_FST4 = 32, DECODER_SUPPORT_FST4W = 64, DECODER_SUPPORT_JT4 = 128 }; enum { DECODER_JT65_SYNC = 0, DECODER_JT65_MESSAGE = 1 }; enum { DECODER_JT65_METHOD_NONE = 0, DECODER_JT65_METHOD_FEC = 1, DECODER_JT65_METHOD_DEEP_SEARCH = 2 }; @@ -102,6 +102,25 @@ typedef struct { char hiscall[12]; } decoder_ft4_options; +/* JT4A-G use one-minute periods. UTC is HHMMSS; submode 0..6 selects A..G. + One signal is searched within receive_frequency_hz +/- tolerance_hz. + minimum_width_profile is 0..submode; depth is effort 1..3. */ +typedef struct { + int32_t utc, submode, receive_frequency_hz, tolerance_hz, depth, min_sync; + int32_t minimum_width_profile, averaging, deep_search; + char mycall[12], hiscall[12], hisgrid[6]; +} decoder_jt4_options; + +enum { DECODER_JT4_NO_SYNC = 0, DECODER_JT4_SYNC = 1, DECODER_JT4_MESSAGE = 2 }; +enum { DECODER_JT4_METHOD_NONE = 0, DECODER_JT4_METHOD_FANO = 1, + DECODER_JT4_METHOD_DEEP_SEARCH = 2 }; +enum { DECODER_JT4_AVERAGE_CAPACITY = 64, DECODER_JT4_CALL_CAPACITY = 6999 }; +typedef struct { char call[12], grid[4]; } decoder_jt4_call; +typedef struct { + int32_t utc, frequency_hz, polarity, used; + float sync, dt_seconds; +} decoder_jt4_average_entry; + /* Slow JT9A-H use one-minute periods; submode 0..7 selects A..H. Decoding spectra are prepared internally, independently of display settings. */ typedef struct { @@ -189,11 +208,14 @@ typedef struct { decoder_jt65_options jt65; decoder_q65_options q65; decoder_fst4_options fst4; + decoder_jt4_options jt4; } decoder_attempt_request; /* Borrowed read-only mono signed PCM. Only sample_count samples are read. All modes accept 12000 Hz. FT8 accepts 1..180000 samples; FT4 accepts 1..72576 samples (its analysis window within a 7.5-second period). + JT4 accepts 11025 or 12000 Hz and 1..sample_rate_hz * 60 samples, + analyzing the first 52 seconds. Its PCM, rate and extent stay fixed until release. Slow JT9 and JT65 accept 1..720000 samples (a one-minute period). JT65 analyzes up to 52 seconds and retains its silence-block rejection; short or gapped input may complete without observations. @@ -250,6 +272,13 @@ typedef struct { float drift_hz_per_minute; } decoder_jt9_result; +/* No-sync and synchronization-only observations have no message. width_profile + is a zero-based profile index, meaningful for decoded messages only. + average_count is zero for individual messages. */ +typedef struct { + int32_t kind, method, average_count, sync_polarity, width_profile; +} decoder_jt4_result; + /* Synchronization-only observations have no message. Width is available only for VHF processing. Drift describes the estimated frequency change across the AFC input span, not a waveform reconstruction parameter. */ @@ -278,6 +307,7 @@ typedef struct { /* dt_seconds retains the mode's operator-facing DT convention. Use the evidence's waveform_start_seconds for reconstruction when available. mode and variant select the result record; inactive records are zero. + JT4 variant is its submode (0..6 for A..G); JT4 has no waveform evidence. JT9 variant is its submode (0..7 for A..H); JT9 has no 77-bit evidence. JT65 variant is its submode (0..2 for A..C); JT65 has no waveform evidence. Q65 variant is its submode (0..5 for A..F); Q65 has no waveform evidence. @@ -296,10 +326,11 @@ typedef struct { decoder_jt65_result jt65; decoder_q65_result q65; decoder_fst4_result fst4; + decoder_jt4_result jt4; } decoder_observation; typedef struct { - /* Includes synchronization-only JT65 observations. */ + /* Includes JT4 no-sync/synchronization-only and JT65 synchronization observations. */ int32_t status, observation_count, retained_count, evidence_dropped; } decoder_attempt_outcome; @@ -314,12 +345,19 @@ int32_t decoder_engine_decode(decoder_engine_handle, const decoder_attempt_reque const decoder_audio_view *, decoder_observation_callback, void *, decoder_attempt_outcome *); /* Released input IDs may be reused for a new reception. - Release retains JT65/Q65 averages and caller knowledge, including FST4W + Release retains JT4/JT65/Q65 averages and caller knowledge, including FST4W call/grid history. Reset clears reception history while retaining reusable capacity and plans. Incompatible mode configuration clears averages. Hosts clear JT65 averages when changing band or operating context. */ int32_t decoder_engine_release_input(decoder_engine_handle, int64_t input_id); int32_t decoder_engine_reset_session(decoder_engine_handle); +/* Replaces the copied JT4 deep-search call/grid list; count zero clears it. */ +int32_t decoder_engine_set_jt4_calls(decoder_engine_handle, const decoder_jt4_call *, int32_t count); +/* Uses the capacity/query convention of decoder_engine_get_jt65_averages. */ +int32_t decoder_engine_get_jt4_averages(decoder_engine_handle, decoder_jt4_average_entry *, + int32_t capacity, int32_t *count); +/* Clear allows the retained reception to contribute again on its next attempt. */ +int32_t decoder_engine_clear_jt4_averages(decoder_engine_handle); /* Replaces the copied deep-search list; count zero clears it. */ int32_t decoder_engine_set_jt65_calls(decoder_engine_handle, const decoder_jt65_call *, int32_t count); /* Returns the total count, copying up to capacity entries. Insufficient nonzero diff --git a/WavDecodeTestController.cpp b/WavDecodeTestController.cpp index 8e25787c..62d33da2 100644 --- a/WavDecodeTestController.cpp +++ b/WavDecodeTestController.cpp @@ -23,7 +23,8 @@ WavDecodeTestController::WavDecodeTestController ( , m_window {window} , m_mode {mode} , m_period {mode == Mode::Fst4 ? 15 : mode == Mode::Fst4w ? 120 : 60} - , m_modeName {mode == Mode::Jt9 ? QStringLiteral ("JT9") + , m_modeName {mode == Mode::Jt4 ? QStringLiteral ("JT4") + : mode == Mode::Jt9 ? QStringLiteral ("JT9") : mode == Mode::Jt65 ? QStringLiteral ("JT65") : mode == Mode::Q65 ? QStringLiteral ("Q65") : mode == Mode::Fst4 ? QStringLiteral ("FST4") : QStringLiteral ("FST4W")} @@ -35,6 +36,8 @@ WavDecodeTestController::WavDecodeTestController ( connect (&m_timeout, &QTimer::timeout, this, [this] { finish (tr ("Timed out waiting for %1 WAV decoding.").arg (m_modeName)); }); + // Windows dispatches coarse timers separately from the mode restore's precise timers. + m_prepareTimer.setTimerType (Qt::PreciseTimer); m_prepareTimer.setSingleShot (true); connect (&m_prepareTimer, &QTimer::timeout, this, &WavDecodeTestController::prepareWhenReady); @@ -72,9 +75,11 @@ WavDecodeTestController::WavDecodeTestController ( finish (tr ("A short silent %1 WAV displayed a stale decode: %2").arg (m_modeName, message)); return; } - if (m_activeGeneration && message.simplified () == m_expectedMessage) + auto const expectedDisplayedMessage = m_mode == Mode::Jt4 + ? m_expectedMessage + QStringLiteral (" f") : m_expectedMessage; + if (m_activeGeneration && message.simplified () == expectedDisplayedMessage) { - if (m_mode != Mode::Jt9 && m_mode != Mode::Jt65) + if (m_mode != Mode::Jt4 && m_mode != Mode::Jt9 && m_mode != Mode::Jt65) { auto * display = m_window->findChild ("decodedTextBrowser"); bool found = false; @@ -125,6 +130,7 @@ void WavDecodeTestController::prepareWhenReady () auto * fast = m_window->findChild ("cbFast9"); auto * cqOnly = m_window->findChild ("cbCQonly"); auto * frequency = m_window->findChild ("RxFreqSpinBox"); + auto const fixtureFrequency = m_mode == Mode::Jt4 ? 1000 : 1500; auto * decode = m_window->findChild ("DecodeButton"); auto * rigStatus = m_window->findChild ("readFreq"); auto * period = m_window->findChild (m_mode == Mode::Fst4w ? "sbTR_FST4W" : "sbTR"); @@ -147,10 +153,9 @@ void WavDecodeTestController::prepareWhenReady () mode->trigger (); quick->trigger (); submode->setValue (0); - if (m_mode != Mode::Jt9 && m_mode != Mode::Jt65) period->setValue (m_period); + if (m_mode != Mode::Jt4 && m_mode != Mode::Jt9 && m_mode != Mode::Jt65) period->setValue (m_period); if (fast->isChecked ()) fast->click (); cqOnly->setChecked (false); - frequency->setValue (1500); if (m_mode == Mode::Fst4 || m_mode == Mode::Fst4w) { auto * blanker = m_window->findChild ("sbNB"); @@ -169,7 +174,7 @@ void WavDecodeTestController::prepareWhenReady () { auto * receive = m_window->findChild ("sbFST4W_RxFreq"); if (!receive) { finish (tr ("The FST4W frequency control was not found.")); return; } - receive->setValue (1500); + receive->setValue (fixtureFrequency); } m_configured = true; m_prepareTimer.start (100); @@ -177,12 +182,13 @@ void WavDecodeTestController::prepareWhenReady () } if (!mode->isChecked () || !quick->isChecked () || submode->value () != 0 || fast->isChecked () - || (m_mode != Mode::Jt9 && m_mode != Mode::Jt65 && period->value () != m_period) + || (m_mode != Mode::Jt4 && m_mode != Mode::Jt9 && m_mode != Mode::Jt65 && period->value () != m_period) || !m_window->configureLiveAudioTestDecodeRange ()) { finish (tr ("Unable to configure ordinary %1A decoding.").arg (m_modeName)); return; } + frequency->setValue (fixtureFrequency); m_started = true; loadShortWav (); } @@ -310,7 +316,7 @@ void WavDecodeTestController::completeCycle (quint64 generation) } if (m_stage == Stage::Repeat) { - m_stage = m_mode == Mode::Jt9 || m_mode == Mode::Jt65 + m_stage = m_mode == Mode::Jt4 || m_mode == Mode::Jt9 || m_mode == Mode::Jt65 ? Stage::ShortReplacement : Stage::ShortBeforeMonitoring; loadShortWav (); return; @@ -328,7 +334,7 @@ void WavDecodeTestController::completeCycle (quint64 generation) finish (); return; } - if (m_mode != Mode::Jt9 && m_mode != Mode::Jt65) + if (m_mode != Mode::Jt4 && m_mode != Mode::Jt9 && m_mode != Mode::Jt65) { auto * period = m_window->findChild (m_mode == Mode::Fst4w ? "sbTR_FST4W" : "sbTR"); period->setValue (m_mode == Mode::Fst4w ? 300 : m_period == 15 ? 30 : 15); diff --git a/WavDecodeTestController.hpp b/WavDecodeTestController.hpp index 39336a59..a23acc15 100644 --- a/WavDecodeTestController.hpp +++ b/WavDecodeTestController.hpp @@ -11,7 +11,7 @@ class MainWindow; class WavDecodeTestController final : public QObject { public: - enum class Mode {Jt9, Jt65, Q65, Fst4, Fst4w}; + enum class Mode {Jt4, Jt9, Jt65, Q65, Fst4, Fst4w}; WavDecodeTestController (MainWindow * window, QString wavPath, QString expectedMessage, Mode mode, QObject * parent = nullptr); diff --git a/ci-cd/DEPLOYMENT_PLAYBOOK.md b/ci-cd/DEPLOYMENT_PLAYBOOK.md index 1e41d2dd..e305ed84 100644 --- a/ci-cd/DEPLOYMENT_PLAYBOOK.md +++ b/ci-cd/DEPLOYMENT_PLAYBOOK.md @@ -252,6 +252,8 @@ Each published public `v*` tag yields, on the public GitHub Release, one install The project-created source tarball is assembled from the public tag. GitHub also generates its own zip and tar.gz source archives for that tag; they contain the tagged tree but may have different compressed hashes. `SHA256SUMS` covers immutable payload assets uploaded by the workflow. For an RC or GA in manual macOS signing mode it excludes each macOS package, which the release manifest identifies as replaceable; a beta's macOS packages are not replaceable, so `SHA256SUMS` covers them. The manifest also records the tag, source commit, workflow run, builder provenance, and both signing modes. Checksums detect changed bytes; platform signatures establish signer identity and must be verified separately. +The release body is a Quick Downloads list of the installers and the source tarball, then the change list that `generate-change-list.py` builds from the promoted commit subjects. It lists features, fixes, and performance changes by their Conventional Commits type, each with its author, except those whose scopes are all among `release`, `ci`, `test`, and `tests`; it counts the other commits and links the full comparison. A beta or RC lists the changes since the newest earlier public tag on its `X.Y` line, or, for a line's first release, since the newest earlier public tag of any line. A GA lists the changes since the newest earlier GA. Commits that an earlier public release already contains are left out, and so are commits whose patch matches one in an earlier release of the same line or the line before it; for a GA, only earlier GAs count. A trailing pull request number in a subject is dropped, and any other `#` or `@` reference is shown as code: the numbers belong to the private repository, and an `@` name would notify that account. If the script fails, or prints nothing because no earlier public tag exists, the publish step warns and keeps GitHub's generated notes, which hold only a comparison link because release commits merge in the private repository. Only the run that creates a release writes its body. + ### All-Platforms-Ready Gate Before publishing, the release workflow requires each platform build to produce its expected installer and release tarball artifacts. This prevents a structurally successful build job from creating a partial release. @@ -915,7 +917,7 @@ Rerun jobs against the immutable tag for transient signing, notarization, or ser ## 10. Scheduled Beta Releases -Betas are unattended weekly prereleases of `develop`, published from the single `release/X.Y` in `BETA` state. The beta scheduler is two workflows. `beta-cut.yml` (Scheduled Beta Cut) applies the [state machine](#state-machine); each of its runs is a cut. `beta-continue.yml` (Scheduled Beta Continue) is the continuation, which chains the runs that follow. A beta's GitHub Release body holds GitHub's generated release notes, preceded by a Quick Downloads list. The channel model is in [Release channels](#release-channels). +Betas are unattended weekly prereleases of `develop`, published from the single `release/X.Y` in `BETA` state. The beta scheduler is two workflows. `beta-cut.yml` (Scheduled Beta Cut) applies the [state machine](#state-machine); each of its runs is a cut. `beta-continue.yml` (Scheduled Beta Continue) is the continuation, which chains the runs that follow. A beta's GitHub Release body is the one [What the Release Produces](#what-the-release-produces) describes. The channel model is in [Release channels](#release-channels). > **Unattended publication.** No person reviews a beta before it is public. Each beta carries the newest green `develop`, including its workflow changes, which the release-bot App merges onto the release line. @@ -999,7 +1001,7 @@ A patch release on an existing line never uses `BETA` state. It uses `RC N` meta ### Starting a release line -Cut `release/X.Y` from a green `develop`. Then land the line-start commit, a reviewed commit that changes only `release-state.txt` and `release-linux-images.json`. The state is `BETA 1` for the line's version (`channel=BETA`, `prerelease=1`, `windows_signing=unsigned`), and the selection is the one prepared as [Prepared Linux release images](#prepared-linux-release-images) describes. For that preparation, choose a `validated-build-YYYYMMDD-RUN-ATTEMPT` generation that all four `ghcr.io/wsjtx/wsjtx-internal/` images carry, from a Refresh Build Caches or Publish Linux CI Images run on `develop` built for the line's recipes. List a package's tags with a token that has the `read:packages` scope: +Cut `release/X.Y` from a green `develop`. Then land the line-start commit, which changes only `release-state.txt` and `release-linux-images.json`. The state is `BETA 1` for the line's version (`channel=BETA`, `prerelease=1`, `windows_signing=unsigned`), and the selection is the one prepared as [Prepared Linux release images](#prepared-linux-release-images) describes. For that preparation, choose a `validated-build-YYYYMMDD-RUN-ATTEMPT` generation that all four `ghcr.io/wsjtx/wsjtx-internal/` images carry, from a Refresh Build Caches or Publish Linux CI Images run on `develop` built for the line's recipes. List a package's tags with a token that has the `read:packages` scope: ```bash # Tags of one internal image package, here linux-noble: @@ -1225,6 +1227,7 @@ gh secret set CROSS_REPO_TOKEN --repo WSJTX/wsjtx-internal --env source-promotio | `.github/scripts/beta-scheduler.py` | Beta scheduler state machine, dispatches, and failure alerts | None | | `.github/scripts/release-linux-images.py` | Linux image selection preparation, validation, and provenance | None | | `.github/scripts/generate-quick-downloads.py` | Quick Downloads list in the GitHub Release body | None | +| `.github/scripts/generate-change-list.py` | Change list in the GitHub Release body | None | ### Secrets Required on `wsjtx-internal` diff --git a/ci-cd/DEVELOPMENT_WORKFLOW.md b/ci-cd/DEVELOPMENT_WORKFLOW.md index 555fb93f..73f07361 100644 --- a/ci-cd/DEVELOPMENT_WORKFLOW.md +++ b/ci-cd/DEVELOPMENT_WORKFLOW.md @@ -244,6 +244,8 @@ git add -A git commit -m "fix: resolve audio dropout on macOS Sequoia" ``` +Commit subjects typed `feat`, `fix`, or `perf` become lines in the public release notes with the author's name, unless their scopes are all among `release`, `ci`, `test`, and `tests`; other subjects are only counted ([What the Release Produces](DEPLOYMENT_PLAYBOOK.md#what-the-release-produces)). + #### 4. Push and open a PR ```bash diff --git a/lib/decode4.f90 b/lib/decode4.f90 deleted file mode 100644 index e0596ed1..00000000 --- a/lib/decode4.f90 +++ /dev/null @@ -1,112 +0,0 @@ -subroutine decode4(dat,npts,dtx,nfreq,flip,mode4,ndepth,neme,minw, & - mycall,hiscall,hisgrid,decoded,nfano,deepbest,qbest,ichbest) - -! Decodes JT4 data, assuming that DT and DF have already been determined. -! Input dat(npts) has already been downsampled by 2: rate = 11025/2. -! ### NB: this initial downsampling should be removed in WSJT-X, since -! it restricts the useful bandwidth to < 2.7 kHz. - - use jt4 - real dat(npts) !Raw data - character decoded*22,deepmsg*22,deepbest*22 - character*12 mycall,hiscall - character*6 hisgrid - real*8 dt,df,phi,f0,dphi,twopi,phi1,dphi1 - complex*16 cz,cz1,c0,c1 - real*4 sym(207) - - twopi=8*atan(1.d0) - dt=2.d0/11025 !Sample interval (2x downsampled data) - df=11025.d0/2520.d0 !Tone separation for JT4A mode - nsym=206 - amp=15.0 - istart=nint((dtx+0.8)/dt) !Start index for synced FFTs - if(istart.lt.0) istart=0 - nchips=0 - qbest=0. - qtop=0. - deepmsg=' ' - ichbest=-1 - c0=0. - k=istart - phi=0.d0 - phi1=0.d0 - - ich1=minw+1 - do ich=1,7 - if(nch(ich).le.mode4) ich2=ich - enddo - - do ich=ich1,ich2 - nchips=min(nch(ich),70) - nspchip=1260/nchips - k=istart - phi=0.d0 - phi1=0.d0 - fac2=1.e-8 * sqrt(float(mode4)) - do j=1,nsym+1 - if(flip.gt.0.0) then - f0=nfreq + (npr(j))*mode4*df - f1=nfreq + (2+npr(j))*mode4*df - else - f0=nfreq + (1-npr(j))*mode4*df - f1=nfreq + (3-npr(j))*mode4*df - endif - dphi=twopi*dt*f0 - dphi1=twopi*dt*f1 - sq0=0. - sq1=0. - do nc=1,nchips - phi=0.d0 - phi1=0.d0 - c0=0. - c1=0. - do i=1,nspchip - k=k+1 - phi=phi+dphi - phi1=phi1+dphi1 - cz=dcmplx(cos(phi),-sin(phi)) - cz1=dcmplx(cos(phi1),-sin(phi1)) - if(k.le.npts) then - c0=c0 + dat(k)*cz - c1=c1 + dat(k)*cz1 - endif - enddo - sq0=sq0 + real(c0)**2 + aimag(c0)**2 - sq1=sq1 + real(c1)**2 + aimag(c1)**2 - enddo - sq0=fac2*sq0 - sq1=fac2*sq1 - rsym=amp*(sq1-sq0) - if(j.ge.1) then - rsymbol(j,ich)=rsym - sym(j)=rsym - endif - enddo - - call extract4(sym,ncount,decoded) !Do the convolutional decode - nfano=0 - if(ncount.ge.0) then - nfano=1 - ichbest=ich - exit - endif - - qual=0. !Now try deep search -! if(ndepth.ge.1) then - if(iand(ndepth,32).eq.32) then - call deep4(sym(2),neme,flip,mycall,hiscall,hisgrid,deepmsg,qual) - if(qual.gt.qbest) then - qbest=qual - deepbest=deepmsg - ichbest=ich - endif - endif - enddo - if(qbest.gt.qtop) then - qtop=qbest - endif - qual=qbest - - return -end subroutine decode4 diff --git a/lib/decoder.f90 b/lib/decoder.f90 index 4bcbe87f..6f6b9075 100644 --- a/lib/decoder.f90 +++ b/lib/decoder.f90 @@ -3,14 +3,12 @@ subroutine multimode_decoder_core(ss,id2,params,nfsample,completion,progress_gen !$ use omp_lib use prog_args use timer_module, only: timer - use jt4_decode use jt65_decode use jt65_host_support, only: load_jt65_calls use jt9_decode use decoder_callbacks, only: decoder_callback_context, & - counting_jt4_decoder, counting_jt65_decoder, counting_jt9_decoder, & - jt4_decoded, & - jt4_average, jt65_decoded, jt9_decoded + counting_jt65_decoder, counting_jt9_decoder, & + jt65_decoded, jt9_decoded use streaming_emit, only: streaming_emit_enabled, & streaming_emit_decode use decode_completion_module, only: decode_completion_result, & @@ -48,15 +46,16 @@ subroutine multimode_decoder_core(ss,id2,params,nfsample,completion,progress_gen character(len=4), allocatable :: jt65_grids(:) data ntr0/-1/ save - type(counting_jt4_decoder) :: my_jt4 type(counting_jt65_decoder) :: my_jt65 type(counting_jt9_decoder) :: my_jt9 - if(params%nmode.eq.8.or.params%nmode.eq.5.or.params%nmode.eq.9.or.params%nmode.eq.65.or. & + if(params%nmode.eq.4.or.params%nmode.eq.8.or.params%nmode.eq.5.or.params%nmode.eq.9.or. & + params%nmode.eq.65.or. & params%nmode.eq.66.or.params%nmode.eq.240.or.params%nmode.eq.241.or.params%nmode.eq.242) then call run_decoder_engine(id2,params,nfsample,completion,progress_generation, & 0_c_int64_t,0_c_int64_t,0_c_int, & - merge(params%kin,0_c_int,params%nmode==5.or.params%nmode==9.or.params%nmode==65.or.params%nmode==66.or. & + merge(params%kin,0_c_int,params%nmode==4.or.params%nmode==5.or.params%nmode==9.or. & + params%nmode==65.or.params%nmode==66.or. & params%nmode==240.or.params%nmode==241.or.params%nmode==242)) return endif @@ -64,7 +63,6 @@ subroutine multimode_decoder_core(ss,id2,params,nfsample,completion,progress_gen call reset_decode_completion(completion) active_progress_generation=progress_generation - my_jt4%decoded = 0 my_jt65%decoded = 0 my_jt9%decoded = 0 nsynced=0 @@ -125,7 +123,6 @@ subroutine multimode_decoder_core(ss,id2,params,nfsample,completion,progress_gen callback_context%bVHF = bVHF callback_context%b_superfox = params%b_superfox callback_context%mycall = mycall - my_jt4%context = callback_context my_jt65%context = callback_context my_jt9%context = callback_context @@ -151,25 +148,6 @@ subroutine multimode_decoder_core(ss,id2,params,nfsample,completion,progress_gen ! id2(1:nz)=0 ! temporarily disabled as it can breaak the JT9 decoder, maybe others endif - if(params%nmode.eq.4) open(14,file=trim(temp_dir)// & - '/avemsg.txt',status='unknown') - - if(params%nmode.eq.4) then - jz=52*nfsample - if(params%newdat) then - if(nfsample.eq.12000) call wav11(id2,jz,dd) - if(nfsample.eq.11025) dd(1:jz)=id2(1:jz) - else - jz=52*11025 - endif - call my_jt4%decode(jt4_decoded,dd,jz,params%nutc,params%nfqso, & - params%ntol,params%emedelay,params%dttol,logical(params%nagain), & - params%ndepth,logical(params%nclearave),params%minsync, & - params%minw,params%nsubmode,mycall,hiscall, & - hisgrid,params%nlist,params%listutc,jt4_average) - go to 800 - endif - npts65=52*12000 if(baddata(id2,npts65)) then nsynced=0 @@ -239,11 +217,10 @@ subroutine multimode_decoder_core(ss,id2,params,nfsample,completion,progress_gen ! JT65 is not yet producing info for nsynced, ndecoded. -800 ndecoded = my_jt4%decoded + my_jt65%decoded + my_jt9%decoded +800 ndecoded = my_jt65%decoded + my_jt9%decoded call set_decode_completion(completion,nsynced,ndecoded,navg0) call write_decode_progress(active_progress_generation) close(13) - if(params%nmode.eq.4) close(14) return end subroutine multimode_decoder_core @@ -265,7 +242,8 @@ subroutine multimode_decoder(ss,id2,params,nfsample) if (.not. completion%available) return if (streaming_emit_enabled()) then - call streaming_emit_decode_finished(params%nutc,params%nmode==66.or.params%nmode==240.or. & + call streaming_emit_decode_finished(params%nutc,params%nmode==4.or.params%nmode==66.or. & + params%nmode==240.or. & params%nmode==241.or.params%nmode==242) else if (.not. lquiet) then call write_decode_completion(completion) diff --git a/lib/decoder_callbacks.f90 b/lib/decoder_callbacks.f90 index 186290c7..3c5821de 100644 --- a/lib/decoder_callbacks.f90 +++ b/lib/decoder_callbacks.f90 @@ -99,69 +99,79 @@ contains logical, intent(in) :: is_average integer, intent(in) :: ave - character*22 decoded - character*3 cflags - integer context_nutc + character(len=22) :: decoded + character(len=3) :: cflags + type(decoder_callback_context) :: context + type(engine_observation) :: observation + integer :: i,display_utc select type (typed_this => this) type is (counting_jt4_decoder) - context_nutc = typed_this%context%nutc + context=typed_this%context class default return end select - if(ich.eq.-99) stop - if (have_sync) then - decoded=decoded0 - cflags=' ' - if(decoded.ne.' ') then - cflags='f ' - if(is_deep) then - cflags='d ' - write(cflags(2:2),'(i1)') min(int(qual),9) - if(qual.ge.10.0) cflags(2:2)='*' - if(qual.lt.3.0) decoded(22:22)='?' + observation=engine_observation() + observation%mode=engine_mode_jt4 + observation%variant=context%submode + observation%snr_db=snr + observation%frequency_hz=real(freq) + observation%dt_seconds=dt + observation%sync=this%sync_strength + observation%quality=qual + if(have_sync) then + observation%jt4%kind=1 + observation%jt4%sync_polarity=merge(-1,1,sync=='#') + if(len_trim(decoded0)>0) then + observation%jt4%kind=2 + observation%jt4%method=merge(2,1,is_deep) + observation%jt4%width_profile=max(0,ich-1) + if(is_average) observation%jt4%average_count=ave + do i=1,len_trim(decoded0) + observation%message(i)=decoded0(i:i) + enddo + endif + endif + if(associated(context%sink)) call context%sink(context%sink_user,observation) + + display_utc=context%nutc + if(context%utc_is_hhmmss) display_utc=display_utc/100 + if(context%render_legacy) then + if(have_sync) then + decoded=decoded0 + cflags=' ' + if(len_trim(decoded)>0) then + cflags='f ' + if(is_deep) then + cflags='d ' + write(cflags(2:2),'(i1)') min(int(qual),9) + if(qual>=10.0) cflags(2:2)='*' + if(qual<3.0) decoded(22:22)='?' + endif + if(is_average) then + write(cflags(3:3),'(i1)') min(ave,9) + if(ave>=10) cflags(3:3)='*' + if(cflags(1:1)=='f') cflags=cflags(1:1)//cflags(3:3)//' ' + endif endif - if(is_average) then - write(cflags(3:3),'(i1)') min(ave,9) - if(ave.ge.10) cflags(3:3)='*' - if(cflags(1:1).eq.'f') cflags=cflags(1:1)//cflags(3:3)//' ' + if(streaming_emit_enabled()) then + call streaming_emit_decode('JT4',context%nutc,snr,dt,freq,decoded,context%utc_is_hhmmss) + else + write(*,1000) display_utc,snr,dt,freq,sync,decoded,cflags endif - endif - if (streaming_emit_enabled()) then - call streaming_emit_decode("JT4", context_nutc, snr, dt, freq, decoded) else - write(*,1000) context_nutc,snr,dt,freq,sync,decoded,cflags - end if - else - if (.not. streaming_emit_enabled()) write(*,1000) context_nutc,snr,dt,freq - end if -1000 format(i4.4,i4,f5.1,i5,1x,'$',a1,1x,a22,1x,a3) + if(.not.streaming_emit_enabled()) write(*,1000) display_utc,snr,dt,freq + endif +1000 format(i4.4,i4,f5.1,i5,1x,'$',a1,1x,a22,1x,a3) + endif select type (typed_this => this) type is (counting_jt4_decoder) - typed_this%decoded = typed_this%decoded + 1 + if(observation%jt4%kind==2) typed_this%decoded=typed_this%decoded+1 end select end subroutine jt4_decoded - subroutine jt4_average (this, used, utc, sync, dt, freq, flip) - implicit none - class(jt4_decoder), intent(inout) :: this - logical, intent(in) :: used - integer, intent(in) :: utc - real, intent(in) :: sync - real, intent(in) :: dt - integer, intent(in) :: freq - logical, intent(in) :: flip - character(len=1) :: cused, csync - - cused = '.' - csync = '*' - if (used) cused = '$' - if (flip) csync = '$' - write(14,1000) cused,utc,sync,dt,freq,csync -1000 format(a1,i5.4,f6.1,f6.2,i6,1x,a1) - end subroutine jt4_average subroutine jt65_decoded(this,sync,snr,dt,freq,drift,nflip,width, & decoded0,ft,qual,nsmo,nsum,minsync) @@ -788,7 +798,8 @@ contains endif if (streaming_emit_enabled()) then - call streaming_emit_decode("FST4", nutc, nsnr, dt, nint(freq), decoded0,context%utc_is_hhmmss) + call streaming_emit_decode(merge('FST4W','FST4 ',context%mode==engine_mode_fst4w), & + nutc, nsnr, dt, nint(freq), decoded0,context%utc_is_hhmmss) else write(*,1005) line end if diff --git a/lib/decoder_engine.f90 b/lib/decoder_engine.f90 index eee39e74..fd49af0d 100644 --- a/lib/decoder_engine.f90 +++ b/lib/decoder_engine.f90 @@ -6,6 +6,7 @@ module decoder_engine use ft8_engine_kernel, only: ft8_kernel_state,params_block,run_ft8_kernel,reset_ft8_kernel,release_ft8_input use decoder_callbacks, only: decoder_callback_context,counting_ft4_decoder,ft4_decoded, & counting_jt9_decoder,jt9_decoded,counting_jt65_decoder,jt65_decoded, & + counting_jt4_decoder,jt4_decoded, & counting_q65_decoder,q65_decoded,counting_fst4_decoder,fst4_decoded use q65_decode, only: q65_options use fst4_decode, only: fst4_options @@ -13,11 +14,15 @@ module decoder_engine use q65_host_support, only: load_q65_history,save_q65_history,write_q65_curves,write_q65_diagnostic use q65_callers, only: Q65_MAX_CALLERS use types, only: q3list + use jt4_decode, only: jt4_options,jt4_call,jt4_average_entry + use jt4_host_support, only: convert_jt4_host_options,load_jt4_calls,write_jt4_averages, & + prepare_jt4_host,write_jt4_diagnostic use jt65_decode, only: jt65_options,jt65_average_entry use jt65_host_support, only: load_jt65_calls,write_jt65_averages use decode_completion_module, only: decode_completion_result,set_decode_completion,write_decode_progress use prog_args, only: temp_dir use timer_module, only: timer + use streaming_emit, only: streaming_emit_enabled implicit none private public :: engine_host_decode @@ -141,6 +146,13 @@ module decoder_engine type, bind(C) :: engine_fst4w_call character(c_char) :: call_grid(20) end type + type, bind(C) :: engine_jt4_call + character(c_char) :: call(12),grid(4) + end type + type, bind(C) :: engine_jt4_average_entry + integer(c_int) :: utc,frequency_hz,polarity,used + real(c_float) :: sync,dt_seconds + end type type, bind(C) :: attempt_request integer(c_int64_t) :: input_id=0,analysis_id=0 integer(c_int) :: attempt_no=0,mode=8,phase=2,source=0 @@ -150,6 +162,7 @@ module decoder_engine type(engine_jt65_options) :: jt65 type(engine_q65_options) :: q65 type(engine_fst4_options) :: fst4 + type(engine_jt4_options) :: jt4 end type type, bind(C) :: audio_view type(c_ptr) :: samples @@ -171,6 +184,7 @@ module decoder_engine type(counting_ft4_decoder) :: ft4 ! GCC 13 can finalize an uninitialized temporary for an embedded finalizable extension. type(counting_jt9_decoder), allocatable :: jt9 + type(counting_jt4_decoder), allocatable :: jt4 type(counting_jt65_decoder), allocatable :: jt65 type(counting_q65_decoder), allocatable :: q65 type(counting_fst4_decoder), allocatable :: fst4 @@ -178,7 +192,7 @@ module decoder_engine type(engine_observation), allocatable :: evidence(:) integer(c_short), allocatable :: audio(:) integer(c_int64_t) :: input_id=0,analysis_id=0 - integer :: input_mode=0,input_sample_count=0 + integer :: input_mode=0,input_sample_count=0,input_sample_rate=0 integer :: last_attempt=0,retained=0,dropped=0,emitted=0 logical :: running=.false.,render_legacy=.false. type(c_funptr) :: callback=c_null_funptr @@ -193,14 +207,17 @@ module decoder_engine contains - pure integer function analysis_extent(mode,period) result(samples) + pure integer function analysis_extent(mode,period,sample_rate) result(samples) integer, intent(in) :: mode - integer, optional, intent(in) :: period + integer, optional, intent(in) :: period,sample_rate select case(mode) case(engine_mode_ft4) samples=72576 case(engine_mode_ft8) samples=180000 + case(engine_mode_jt4) + samples=720000 + if(present(sample_rate)) samples=60*sample_rate case(engine_mode_jt9,engine_mode_jt65) samples=720000 case(engine_mode_q65) @@ -221,6 +238,7 @@ contains subroutine initialize_session(state) type(engine_session), intent(inout) :: state allocate(state%jt9) + allocate(state%jt4) allocate(state%jt65) allocate(state%q65) allocate(state%fst4) @@ -256,7 +274,7 @@ contains caps=engine_capabilities(engine_abi, & ior(ior(engine_support_ft8,engine_support_ft4), & ior(ior(ior(engine_support_jt9,engine_support_jt65),engine_support_q65), & - ior(engine_support_fst4,engine_support_fst4w))), & + ior(ior(engine_support_fst4,engine_support_fst4w),engine_support_jt4))), & 0,0,evidence_capacity) status=invalid if(valid_handle(handle)) status=ok @@ -281,7 +299,8 @@ contains logical, intent(in) :: render integer, intent(in) :: progress integer(c_short), pointer :: samples(:) - integer :: analysis_samples + integer :: analysis_samples,allocation_status + integer(c_short), allocatable :: grown_audio(:) type(params_block) :: params type(decoder_callback_context) :: context outcome=attempt_outcome() @@ -290,21 +309,28 @@ contains status=busy if(session%running) go to 900 status=unsupported - if(request%mode/=engine_mode_ft8.and.request%mode/=engine_mode_ft4.and. & + if(request%mode/=engine_mode_jt4.and.request%mode/=engine_mode_ft8.and.request%mode/=engine_mode_ft4.and. & request%mode/=engine_mode_jt9.and.request%mode/=engine_mode_jt65.and.request%mode/=engine_mode_q65.and. & request%mode/=engine_mode_fst4.and.request%mode/=engine_mode_fst4w) go to 900 - if(audio%sample_rate_hz/=12000) go to 900 + if(request%mode==engine_mode_jt4) then + if(audio%sample_rate_hz/=11025.and.audio%sample_rate_hz/=12000) go to 900 + else + if(audio%sample_rate_hz/=12000) go to 900 + endif status=invalid if(request%input_id<=0.or.request%analysis_id<=0.or.request%attempt_no<=0) go to 900 if(request%phase<1.or.request%phase>3.or.request%source<0.or.request%source>1) go to 900 if(request%mode==engine_mode_fst4.or.request%mode==engine_mode_fst4w) then analysis_samples=analysis_extent(request%mode,request%fst4%period_seconds) else - analysis_samples=analysis_extent(request%mode,request%q65%period_seconds) + analysis_samples=analysis_extent(request%mode,request%q65%period_seconds,audio%sample_rate_hz) endif if(audio%sample_count<1.or.audio%sample_count>analysis_samples) go to 900 if(.not.c_associated(audio%samples)) go to 900 - if(request%mode==engine_mode_ft4) then + if(request%mode==engine_mode_jt4) then + if(request%phase==1) go to 900 + if(.not.valid_jt4_options(request%jt4)) go to 900 + else if(request%mode==engine_mode_ft4) then if(request%phase==1) go to 900 if(request%ft4%search_low_hz<0.or.request%ft4%search_high_hz>6000.or. & request%ft4%search_low_hz>request%ft4%search_high_hz) go to 900 @@ -338,6 +364,9 @@ contains endif if(session%input_id/=0.and.session%input_id/=request%input_id) go to 900 if(session%input_id/=0.and.session%input_mode/=request%mode) go to 900 + if(request%mode==engine_mode_jt4.and.session%input_id/=0) then + if(audio%sample_count/=session%input_sample_count.or.audio%sample_rate_hz/=session%input_sample_rate) go to 900 + endif if(request%mode==engine_mode_q65.and.session%input_id/=0) then if(audio%sample_count/=session%input_sample_count) go to 900 endif @@ -348,14 +377,19 @@ contains if(session%analysis_id==request%analysis_id.and.request%attempt_no<=session%last_attempt) go to 900 if(size(session%audio)collect_superfox context%sink_user=handle context%render_legacy=render - if(request%mode==engine_mode_ft4) then + if(request%mode==engine_mode_jt4) then + call run_jt4_attempt(request%jt4,request%phase,audio%sample_count,audio%sample_rate_hz,context,progress,status) + else if(request%mode==engine_mode_ft4) then call run_ft4_attempt(request%ft4,request%phase,context,progress) else if(request%mode==engine_mode_jt9) then call run_jt9_attempt(request%jt9,request%phase,audio%sample_count,context,progress) @@ -464,6 +500,151 @@ contains call write_decode_progress(progress) end subroutine + pure logical function valid_hhmmss(utc) result(valid) + integer, intent(in) :: utc + valid=utc>=0.and.utc<=235959.and.mod(utc/100,100)<=59.and.mod(utc,100)<=59 + end function + + logical function valid_jt4_options(options) result(valid) + type(engine_jt4_options), intent(in) :: options + valid=.false. + if(.not.valid_hhmmss(options%utc)) return + if(options%submode<0.or.options%submode>6) return + if(options%minimum_width_profile<0.or.options%minimum_width_profile>options%submode) return + if(options%depth<1.or.options%depth>3) return + if(options%receive_frequency_hz<0.or.options%receive_frequency_hz>5000) return + if(options%tolerance_hz<0.or.options%tolerance_hz>5000) return + if(any([options%averaging,options%deep_search]<0).or.any([options%averaging,options%deep_search]>1)) return + valid=.true. + end function + + subroutine run_jt4_attempt(options,phase,sample_count,sample_rate,callback_context,progress,status) + type(engine_jt4_options), intent(in) :: options + integer, intent(in) :: phase,sample_count,sample_rate,progress + type(decoder_callback_context), intent(in) :: callback_context + integer(c_int), intent(out) :: status + type(decoder_callback_context) :: context + type(jt4_options) :: kernel_options + integer :: kernel_status + + context=callback_context + context%nutc=options%utc + context%utc_is_hhmmss=.true. + context%nfqso=options%receive_frequency_hz + context%submode=options%submode + context%ios13=-1 + context%ios14=-1 + if(context%render_legacy) then + call open_legacy_output(phase,context%ios13) + open(14,file=trim(temp_dir)//'/avemsg.txt',status='unknown',iostat=context%ios14) + call prepare_jt4_host(session%jt4) + endif + session%jt4%context=context + session%jt4%decoded=0 + kernel_options%utc=options%utc + kernel_options%submode=options%submode + kernel_options%receive_frequency_hz=options%receive_frequency_hz + kernel_options%tolerance_hz=options%tolerance_hz + kernel_options%depth=options%depth + kernel_options%min_sync=options%min_sync + kernel_options%minimum_width_profile=options%minimum_width_profile + kernel_options%averaging=options%averaging/=0 + kernel_options%deep_search=options%deep_search/=0 + kernel_options%mycall=transfer(options%mycall,kernel_options%mycall) + kernel_options%hiscall=transfer(options%hiscall,kernel_options%hiscall) + kernel_options%hisgrid=transfer(options%hisgrid,kernel_options%hisgrid) + call timer('decjt4 ',0) + if(context%render_legacy) then + call session%jt4%decode_pcm(kernel_options,session%audio(:sample_count),sample_rate,jt4_decoded, & + kernel_status,write_jt4_diagnostic) + else + call session%jt4%decode_pcm(kernel_options,session%audio(:sample_count),sample_rate,jt4_decoded,kernel_status) + endif + call timer('decjt4 ',1) + if(context%ios14==0) then + call write_jt4_averages(session%jt4,14) + close(14) + endif + if(context%ios13==0) close(13) + call set_decode_completion(session%completion,0,session%jt4%decoded,0) + call write_decode_progress(progress) + status=ok + if(kernel_status/=0) status=internal_error + end subroutine + + integer(c_int) function engine_set_jt4_calls(handle,entries,count) & + bind(C,name='decoder_engine_set_jt4_calls') result(status) + type(c_ptr), value :: handle,entries + integer(c_int), value :: count + type(engine_jt4_call), pointer :: records(:) + type(jt4_call), allocatable :: calls(:) + integer :: i,allocation_status,kernel_status + status=invalid + if(.not.valid_handle(handle)) return + status=busy + if(session%running) return + status=invalid + if(count<0.or.count>6999) return + if(count>0.and..not.c_associated(entries)) return + allocate(calls(count),stat=allocation_status) + status=internal_error + if(allocation_status/=0) return + if(count>0) then + call c_f_pointer(entries,records,[count]) + do i=1,count + calls(i)%call=transfer(records(i)%call,calls(i)%call) + calls(i)%grid=transfer(records(i)%grid,calls(i)%grid) + enddo + endif + call session%jt4%set_calls(calls,kernel_status) + if(kernel_status/=0) return + status=ok + end function + + integer(c_int) function engine_get_jt4_averages(handle,entries,entry_capacity,count) & + bind(C,name='decoder_engine_get_jt4_averages') result(status) + type(c_ptr), value :: handle,entries + integer(c_int), value :: entry_capacity + integer(c_int), intent(out) :: count + type(engine_jt4_average_entry), pointer :: records(:) + type(jt4_average_entry) :: averages(64) + integer :: i,n + count=0 + status=invalid + if(.not.valid_handle(handle)) return + status=busy + if(session%running) return + status=invalid + if(entry_capacity<0) return + if(entry_capacity>0.and..not.c_associated(entries)) return + call session%jt4%get_averages(averages,n) + count=n + if(entry_capacity>0) then + call c_f_pointer(entries,records,[entry_capacity]) + do i=1,min(entry_capacity,n) + records(i)%utc=averages(i)%utc + records(i)%frequency_hz=averages(i)%frequency_hz + records(i)%polarity=averages(i)%polarity + records(i)%used=merge(1,0,averages(i)%used) + records(i)%sync=averages(i)%sync + records(i)%dt_seconds=averages(i)%dt_seconds + enddo + endif + status=ok + if(entry_capacity>0.and.entry_capacity3) return @@ -628,10 +808,7 @@ contains if(options%eme_delay_seconds<0.or.options%eme_delay_seconds>real(options%period_seconds)) return if(any([options%single_decode,options%ap_cq_only,options%measure_doppler]<0)) return if(any([options%single_decode,options%ap_cq_only,options%measure_doppler]>1)) return - hours=options%utc/10000 - minutes=mod(options%utc/100,100) - seconds=mod(options%utc,100) - if(options%utc<0.or.hours>23.or.minutes>59.or.seconds>59) return + if(.not.valid_hhmmss(options%utc)) return valid=.true. end function @@ -742,7 +919,6 @@ contains logical function valid_q65_options(options) result(valid) type(engine_q65_options), intent(in) :: options - integer :: hours,minutes,seconds valid=.false. if(.not.any(options%period_seconds==[15,30,60,120,300])) return if(options%submode<0.or.options%submode>5) return @@ -758,10 +934,7 @@ contains options%pileup,options%ap_cq_only]<0)) return if(any([options%averaging,options%auto_clear,options%single_decode,options%extended_eme_search, & options%pileup,options%ap_cq_only]>1)) return - hours=options%utc/10000 - minutes=mod(options%utc/100,100) - seconds=mod(options%utc,100) - if(options%utc<0.or.hours>23.or.minutes>59.or.seconds>59) return + if(.not.valid_hhmmss(options%utc)) return valid=.true. end function @@ -982,11 +1155,13 @@ contains if(input_id<=0.or.session%input_id/=input_id) return call release_ft8_input(session%kernel) call session%jt9%release_input() + call session%jt4%release_input() call session%jt65%release_input() call session%q65%release_input() session%input_id=0 session%input_mode=0 session%input_sample_count=0 + session%input_sample_rate=0 session%analysis_id=0 session%last_attempt=0 session%retained=0 @@ -1003,6 +1178,7 @@ contains call reset_ft8_kernel(session%kernel) call session%ft4%reset() call session%jt9%reset() + call session%jt4%reset() call session%jt65%reset() call session%q65%reset() call session%fst4%reset() @@ -1010,6 +1186,7 @@ contains session%input_id=0 session%input_mode=0 session%input_sample_count=0 + session%input_sample_rate=0 session%analysis_id=0 session%last_attempt=0 session%retained=0 @@ -1105,11 +1282,18 @@ contains type(attempt_outcome) :: outcome type(engine_options) :: options integer(c_int) :: status - integer :: time,history_status,blanker,period_samples + integer :: time,history_status,blanker,period_samples,gate_samples character(len=12), allocatable :: calls(:) character(len=4), allocatable :: grids(:) options%abi_version=engine_abi completion=decode_completion_result(.true.,0,0,0) + if(params%nmode==engine_mode_jt4) then + if(params%nclearave.and.valid_handle(host_handle)) call session%jt4%clear_averages() + gate_samples=min(180000,max(0,valid_samples)) + if(gate_samples>0) then + if(sqrt(sum(real(id2(1:gate_samples))**2)/180000.0)<0.5) return + endif + endif if(params%nmode==engine_mode_ft4) then ! The legacy host's low-signal gate includes its zero-padded 15-second window. if(sqrt(sum(real(id2(1:180000))**2)/180000.0)<0.5) return @@ -1128,7 +1312,7 @@ contains endif if(input_id<=0.or.analysis_id<=0) then if(session%input_id==0.or.params%nutc/=fallback_utc.or.session%input_mode/=request%mode.or. & - ((params%nmode==engine_mode_ft4.or.params%nmode==engine_mode_jt9.or. & + ((params%nmode==engine_mode_jt4.or.params%nmode==engine_mode_ft4.or.params%nmode==engine_mode_jt9.or. & params%nmode==engine_mode_jt65.or.params%nmode==engine_mode_q65.or. & request%mode==engine_mode_fst4.or.request%mode==engine_mode_fst4w).and..not.params%nagain).or. & (params%nzhsym==41.and..not.params%nagain)) then @@ -1153,7 +1337,10 @@ contains if(params%nmode==engine_mode_ft8.and.params%nzhsym<50) request%phase=1 if(params%nagain) request%phase=3 request%source=merge(1,0,params%ndiskdat) - if(request%mode==engine_mode_ft4) then + if(request%mode==engine_mode_jt4) then + call convert_jt4_host_options(params,request%jt4,streaming_emit_enabled()) + if(request%jt4%deep_search/=0) call load_jt4_calls(session%jt4) + else if(request%mode==engine_mode_ft4) then request%ft4%utc=params%nutc request%ft4%qso_progress=params%nQSOProgress request%ft4%receive_frequency_hz=params%nfqso @@ -1304,13 +1491,14 @@ contains request%ft8%hisgrid=params%hisgrid endif audio%samples=c_loc(id2(1)) - period_samples=analysis_extent(request%mode,request%q65%period_seconds) + period_samples=analysis_extent(request%mode,request%q65%period_seconds,nfsample) if(request%mode==engine_mode_fst4.or.request%mode==engine_mode_fst4w) & period_samples=analysis_extent(request%mode,request%fst4%period_seconds) audio%sample_count=min(period_samples,valid_samples) if(valid_samples<=0.and.input_id<=0) then audio%sample_count=period_samples if(request%mode==engine_mode_jt9.or.request%mode==engine_mode_jt65) audio%sample_count=624000 + if(request%mode==engine_mode_jt4) audio%sample_count=52*nfsample endif if(request%mode==engine_mode_ft8) then if(params%lmultift8.and..not.(iand(params%nexp_decode,7)==7.and. & diff --git a/lib/decoder_engine_types.f90 b/lib/decoder_engine_types.f90 index 5c378646..dbf0f2f8 100644 --- a/lib/decoder_engine_types.f90 +++ b/lib/decoder_engine_types.f90 @@ -3,14 +3,14 @@ module decoder_engine_types implicit none private public :: ft8_signal_evidence, ft4_signal_evidence, superfox_evidence, superfox_observation - public :: jt9_result,jt65_result,q65_result,fst4_result + public :: jt9_result,jt65_result,q65_result,fst4_result,jt4_result,engine_jt4_options public :: engine_payload_none,engine_payload_decoded,engine_payload_hypothesis public :: sf_kind_cq,sf_kind_exchange,sf_kind_free_text,sf_kind_verification public :: engine_observation, engine_observation_sink, engine_superfox_sink public :: engine_abi,engine_mode_ft8,engine_mode_ft4,engine_mode_jt9,engine_mode_jt65,engine_mode_q65 public :: engine_support_ft8,engine_support_ft4,engine_support_jt9,engine_support_jt65,engine_support_q65 - integer(c_int), parameter :: engine_abi=7,engine_mode_ft8=8,engine_mode_ft4=5,engine_mode_jt9=9,engine_mode_jt65=65 + integer(c_int), parameter :: engine_abi=8,engine_mode_ft8=8,engine_mode_ft4=5,engine_mode_jt9=9,engine_mode_jt65=65 integer(c_int), parameter :: engine_support_ft8=1,engine_support_ft4=2,engine_support_jt9=4,engine_support_jt65=8 integer(c_int), parameter :: engine_mode_q65=66,engine_support_q65=16 @@ -19,6 +19,19 @@ module decoder_engine_types integer(c_int), parameter :: engine_mode_fst4=240,engine_mode_fst4w=241 integer(c_int), parameter :: engine_support_fst4=32,engine_support_fst4w=64 + public :: engine_mode_jt4,engine_support_jt4 + integer(c_int), parameter :: engine_mode_jt4=4,engine_support_jt4=128 + + type, bind(C) :: engine_jt4_options + integer(c_int) :: utc=0,submode=0,receive_frequency_hz=1500,tolerance_hz=100,depth=1,min_sync=0 + integer(c_int) :: minimum_width_profile=0,averaging=0,deep_search=0 + character(c_char) :: mycall(12)=' ',hiscall(12)=' ',hisgrid(6)=' ' + end type + + type, bind(C) :: jt4_result + integer(c_int) :: kind=0,method=0,average_count=0,sync_polarity=0,width_profile=0 + end type + integer, parameter :: engine_payload_none=0,engine_payload_decoded=1,engine_payload_hypothesis=2 integer, parameter :: sf_kind_cq=1,sf_kind_exchange=2,sf_kind_free_text=3,sf_kind_verification=4 @@ -82,6 +95,7 @@ module decoder_engine_types type(jt65_result) :: jt65 type(q65_result) :: q65 type(fst4_result) :: fst4 + type(jt4_result) :: jt4 end type abstract interface diff --git a/lib/deep4.f90 b/lib/deep4.f90 deleted file mode 100644 index 05f6732d..00000000 --- a/lib/deep4.f90 +++ /dev/null @@ -1,169 +0,0 @@ -subroutine deep4(sym0,neme,flip,mycall,hiscall,hisgrid,decoded,qual) - -! Deep search routine for JT4 - - use prog_args - parameter (MAXCALLS=7000,MAXRPT=63) - real*4 sym0(206),sym(206) - character callsign*12,grid*4,message*22,hisgrid*6,ceme*3 - character*12 mycall,hiscall - character mycall0*12,hiscall0*12,hisgrid0*6 - character*22 decoded - character*22 testmsg(2*MAXCALLS + 2 + MAXRPT) - character*15 callgrid(MAXCALLS) - character*180 line - character*4 rpt(MAXRPT) - integer ncode(206) - real*4 code(206,2*MAXCALLS + 2 + MAXRPT) - real pp(2*MAXCALLS + 2 + MAXRPT) - data neme0/-99/ - data rpt/'-01','-02','-03','-04','-05', & - '-06','-07','-08','-09','-10', & - '-11','-12','-13','-14','-15', & - '-16','-17','-18','-19','-20', & - '-21','-22','-23','-24','-25', & - '-26','-27','-28','-29','-30', & - 'R-01','R-02','R-03','R-04','R-05', & - 'R-06','R-07','R-08','R-09','R-10', & - 'R-11','R-12','R-13','R-14','R-15', & - 'R-16','R-17','R-18','R-19','R-20', & - 'R-21','R-22','R-23','R-24','R-25', & - 'R-26','R-27','R-28','R-29','R-30', & - 'RO','RRR','73'/ - save mycall0,hiscall0,hisgrid0,neme0,ntot,code,testmsg - - sym=sym0 - if(mycall.eq.mycall0 .and. hiscall.eq.hiscall0 .and. & - hisgrid.eq.hisgrid0 .and. neme.eq.neme0) go to 30 - - open(23,file=trim(data_dir)//'/CALL3.TXT',status='unknown') - k=0 - icall=0 - do n=1,MAXCALLS - if(n.eq.1) then - callsign=hiscall - do i=4,12 - if(ichar(callsign(i:i)).eq.0) callsign(i:i)=' ' - enddo - grid=hisgrid(1:4) - if(ichar(grid(3:3)).eq.0) grid(3:3)=' ' - if(ichar(grid(4:4)).eq.0) grid(4:4)=' ' - else - read(23,1002,end=20) line -1002 format (A80) - if(line(1:4).eq.'ZZZZ') go to 20 - if(line(1:2).eq.'//') go to 10 - i1=index(line,',') - if(i1.lt.4) go to 10 - i2=index(line(i1+1:),',') - if(i2.lt.5) go to 10 - i2=i2+i1 - i3=index(line(i2+1:),',') - if(i3.lt.1) i3=index(line(i2+1:),' ') - i3=i2+i3 - callsign=line(1:i1-1) - grid=line(i1+1:i2-1) - ceme=line(i2+1:i3-1) - if(neme.eq.1 .and. ceme.ne.'EME') go to 10 - endif - - icall=icall+1 - j1=index(mycall,' ') - 1 - if(j1.le.-1) j1=12 - if(j1.lt.3) j1=6 - j2=index(callsign,' ') - 1 - if(j2.le.-1) j2=12 - if(j2.lt.3) j2=6 - j3=index(mycall,'/') ! j3>0 means compound mycall - j4=index(callsign,'/') ! j4>0 means compound hiscall - callgrid(icall)=callsign(1:j2) - - mz=1 -! Allow MyCall + HisCall + rpt (?) - if(n.eq.1 .and. j3.lt.1 .and. j4.lt.1 .and. callsign(1:6).ne.' ') & - mz=MAXRPT+1 - do m=1,mz - if(m.gt.1) grid=rpt(m-1) - if(j3.lt.1 .and.j4.lt.1) callgrid(icall)=callsign(1:j2)//' '//grid - message=mycall(1:j1)//' '//callgrid(icall) - k=k+1 - testmsg(k)=message - call encode4(message,ncode) - code(1:206,k)=2*ncode(1:206)-1 - if(n.ge.2) then -! Insert CQ message - if(j4.lt.1) callgrid(icall)=callsign(1:j2)//' '//grid - message='CQ '//callgrid(icall) - k=k+1 - testmsg(k)=message - call encode4(message,ncode) - code(1:206,k)=2*ncode(1:206)-1 - endif - enddo -10 continue - enddo - -20 continue - close(23) - ntot=k - -30 mycall0=mycall - hiscall0=hiscall - hisgrid0=hisgrid - neme0=neme - - sq=0. - do j=1,206 - sq=sq + sym(j)**2 - enddo - rms=sqrt(sq/206.0) - sym=sym/rms - - p1=-1.e30 - p2=-1.e30 - do k=1,ntot - pp(k)=0. -! Should re-instate the following: -! if(k.ge.2 .and. k.le.64 .and. flip.gt.0.0) cycle -! Test all messages if flip=+1; skip the CQ messages if flip=-1. - if(flip.gt.0.0 .or. testmsg(k)(1:3).ne.'CQ ') then - p=0. - do j=1,206 - p=p + code(j,k)*sym(j) - enddo - pp(k)=p - if(p.gt.p1) then - p1=p - ip1=k - endif - endif - enddo - - do i=1,ntot - if(pp(i).gt.p2 .and. testmsg(i).ne.testmsg(ip1)) p2=pp(i) - enddo - - qual=p1-max(1.15*p2,70.0) - -! ### DO NOT REMOVE ### - rewind 77 - if(ip1.ge.1 .and. ip1.le.2*MAXCALLS+2+MAXRPT) write(77,1001) p1,p2,ntot, & - rms,qual,ip1,testmsg(ip1) -1001 format(2f8.2,i8,2f8.2,i6,2x,a22) - call flush(77) - - if(qual.gt.1.0) then - decoded=testmsg(ip1) - else - decoded=' ' - qual=0. - endif - -! Make sure everything is upper case. - do i=1,22 - if(decoded(i:i).ge.'a' .and. decoded(i:i).le.'z') & - decoded(i:i)=char(ichar(decoded(i:i))-32) - enddo - - return -end subroutine deep4 diff --git a/lib/extract4.f90 b/lib/extract4.f90 index ce8fb86a..b10d9da9 100644 --- a/lib/extract4.f90 +++ b/lib/extract4.f90 @@ -14,21 +14,23 @@ subroutine extract4(sym0,ncount,decoded) data first/.true./ save first,mettab,ndelta + ncount=-1 + decoded=' ' + ave0=sum(sym0)/207.0 + sym=sym0-ave0 + sq=dot_product(sym,sym) + rms0=sqrt(sq/206.0) + if(rms0<=tiny(rms0)) return + sym=sym/rms0 + if(first) then call getmet4(mettab,ndelta) first=.false. endif -!### Optimize these params: ... amp=30.0 limit=10000 - ave0=sum(sym0)/207.0 - sym=sym0-ave0 - sq=dot_product(sym,sym) - rms0=sqrt(sq/206.0) - sym=sym/rms0 - do j=1,207 n=nint(amp*sym(j)) if(n.lt.-127) n=-127 @@ -38,8 +40,6 @@ subroutine extract4(sym0,ncount,decoded) nbits=72 ncycles=0 - ncount=-1 - decoded=' ' call interleave4(symbol(2),-1) !Remove the interleaving call fano232(symbol(2),nbits+31,mettab,ndelta,limit,data1, & ncycles,metric,ncount) diff --git a/lib/jt4.f90 b/lib/jt4.f90 index 42a2d16b..b88f0242 100644 --- a/lib/jt4.f90 +++ b/lib/jt4.f90 @@ -1,29 +1,13 @@ module jt4 - parameter (MAXAVE=64) - integer iutc(MAXAVE) - integer nfsave(MAXAVE) - integer listutc(10) - real ppsave(207,7,MAXAVE) !Accumulated data for message averaging - real rsymbol(207,7) - real dtsave(MAXAVE) - real syncsave(MAXAVE) - real flipsave(MAXAVE) - real zz(1260,65,7) - - integer nsave,nlist,ich1,ich2 - integer nch(7) - integer npr(207) - data rsymbol/1449*0.0/ - data nch/1,2,4,9,18,36,72/ - data npr/ & + implicit none + integer, parameter :: MAXAVE=64 + integer, parameter :: nch(7)=[1,2,4,9,18,36,72] + integer, parameter :: npr(207)=[ & 0,0,0,0,1,1,0,0,0,1,1,0,1,1,0,0,1,0,1,0,0,0,0,0,0,0,1,1,0,0, & 0,0,0,0,0,0,0,0,0,0,1,0,1,1,0,1,1,0,1,0,1,1,1,1,1,0,1,0,0,0, & 1,0,0,1,0,0,1,1,1,1,1,0,0,0,1,0,1,0,0,0,1,1,1,1,0,1,1,0,0,1, & 0,0,0,1,1,0,1,0,1,0,1,0,1,0,1,1,1,1,1,0,1,0,1,0,1,1,0,1,0,1, & 0,1,1,1,0,0,1,0,1,1,0,1,1,1,1,0,0,0,0,1,1,0,1,1,0,0,0,1,1,1, & 0,1,1,1,0,1,1,1,0,0,1,0,0,0,1,1,0,1,1,0,0,1,0,0,0,1,1,1,1,1, & - 1,0,0,1,1,0,0,0,0,1,1,0,0,0,1,0,1,1,0,1,1,1,1,0,1,0,1/ - - save ppsave,zz - + 1,0,0,1,1,0,0,0,0,1,1,0,0,0,1,0,1,1,0,1,1,1,1,0,1,0,1 ] end module jt4 diff --git a/lib/jt4_decode.f90 b/lib/jt4_decode.f90 index 8ab48bda..60c2886a 100644 --- a/lib/jt4_decode.f90 +++ b/lib/jt4_decode.f90 @@ -1,13 +1,60 @@ module jt4_decode + use iso_c_binding, only: c_ptr,c_null_ptr,c_associated,c_f_pointer,c_int16_t,c_size_t + use fftw3 + use jt4, only: nch,npr,MAXAVE + + type :: jt4_options + integer :: utc=0,submode=0,receive_frequency_hz=1200,tolerance_hz=100,depth=1 + integer :: min_sync=0,minimum_width_profile=0 + logical :: averaging=.false.,deep_search=.false. + character(len=12) :: mycall='',hiscall='' + character(len=6) :: hisgrid='' + end type + type :: jt4_call + character(len=12) :: call='' + character(len=4) :: grid='' + end type + type :: jt4_average_entry + integer :: utc=0,frequency_hz=0,polarity=1 + logical :: used=.false. + real :: sync=0.,dt_seconds=0. + end type + type, private :: jt4_fft_buffer + type(c_ptr) :: storage=c_null_ptr,forward=c_null_ptr,backward=c_null_ptr + real, pointer :: x(:)=>null() + complex, pointer :: cx(:)=>null() + end type type :: jt4_decoder procedure(jt4_decode_callback), pointer :: decode_callback => null () - procedure(jt4_average_callback), pointer :: average_callback => null () + procedure(jt4_diagnostic_callback), pointer, nopass :: diagnostic_callback => null () + integer :: iutc(MAXAVE)=-1,nfsave(MAXAVE)=0,nsave=0,average_count=0 + real :: dtsave(MAXAVE)=0.,syncsave(MAXAVE)=0.,flipsave(MAXAVE)=0. + logical :: average_used(MAXAVE)=.false. + real, allocatable :: ppsave(:,:,:),rsymbol(:,:) + real, allocatable, private :: dat(:),pcm(:),s2(:,:) + integer, private :: ich1=1,ich2=1,current_submode=-1,current_minimum_profile=-1 + integer, private :: fft_flags=FFTW_ESTIMATE + real :: sync_strength=0. + type(jt4_fft_buffer), private :: transform(4) + type(jt4_call), allocatable :: calls(:) + real, allocatable, private :: code(:,:) + character(len=22), allocatable, private :: testmsg(:) + character(len=12), private :: mycall0='',hiscall0='' + character(len=6), private :: hisgrid0='' + logical, private :: templates_valid=.false.,prepared=.false. + integer, private :: ntot=0,kernel_status=0 contains - procedure :: decode - procedure, private :: wsjt4, avg4 + procedure :: decode_pcm,set_calls,get_averages,clear_averages,release_input,reset,set_fft_flags + procedure :: save_average,select_average + procedure, private :: wsjt4,avg4,decode4,deep4,sync4,lpf1,ps4,getsnr,prepare_workspace,destroy_plans + final :: finalize_jt4 end type jt4_decoder -! Callback function to be called with each decode + abstract interface + subroutine jt4_diagnostic_callback(line) + character(len=*),intent(in) :: line + end subroutine + end interface abstract interface subroutine jt4_decode_callback (this, snr, dt, freq, have_sync, & sync, is_deep, decoded, qual, ich, is_average, ave) @@ -28,136 +75,57 @@ module jt4_decode end subroutine jt4_decode_callback end interface -! Callback function to be called with each average result - abstract interface - subroutine jt4_average_callback (this, used, utc, sync, dt, freq, flip) - import jt4_decoder - implicit none - class(jt4_decoder), intent(inout) :: this - logical, intent(in) :: used - integer, intent(in) :: utc - real, intent(in) :: sync - real, intent(in) :: dt - integer, intent(in) :: freq - logical, intent(in) :: flip - end subroutine jt4_average_callback - end interface contains - subroutine decode(this,decode_callback,dd,jz,nutc,nfqso,ntol0,emedelay, & - dttol,nagain,ndepth,nclearave,minsync,minw,nsubmode,mycall,hiscall, & - hisgrid,nlist0,listutc0,average_callback) + subroutine wsjt4(this,dat,npts,nutc,minsync,ntol,mode4,minw,mycall,hiscall,hisgrid,nfqso,ndepth) - use jt4 - use timer_module, only: timer +! JT4 searches for one signal within the selected frequency tolerance. - class(jt4_decoder), intent(inout) :: this - procedure(jt4_decode_callback) :: decode_callback - integer, intent(in) :: jz,nutc,nfqso,ntol0,ndepth,minsync,minw,nsubmode, & - nlist0,listutc0(10) - real, intent(in) :: dd(jz),emedelay,dttol - logical, intent(in) :: nagain, nclearave - character(len=12), intent(in) :: mycall,hiscall - character(len=6), intent(in) :: hisgrid - procedure(jt4_average_callback), optional :: average_callback - real*4 dat(30*11025) - character*6 cfile6 - save dat - - this%decode_callback => decode_callback - if (present (average_callback)) then - this%average_callback => average_callback - end if - mode4=nch(nsubmode+1) - ntol=ntol0 - neme=0 - lumsg=6 !### temp ? ### - ndiag=1 - nlist=nlist0 - listutc=listutc0 - - ! Lowpass filter and decimate by 2 - call timer('lpf1 ',0) - call lpf1(dd,jz,dat,jz2) - call timer('lpf1 ',1) - - write(cfile6(1:4),1000) nutc -1000 format(i4.4) - cfile6(5:6)=' ' - - call timer('wsjt4 ',0) - call this%wsjt4(dat,jz2,nutc,NClearAve,minsync,ntol,emedelay,dttol,mode4, & - minw,mycall,hiscall,hisgrid,nfqso,NAgain,ndepth,neme) - call timer('wsjt4 ',1) - - return - end subroutine decode - - subroutine wsjt4(this,dat,npts,nutc,NClearAve,minsync,ntol,emedelay,dttol, & - mode4,minw,mycall,hiscall,hisgrid,nfqso,NAgain,ndepth,neme) - -! Orchestrates the process of decoding JT4 messages. Note that JT4 -! always operates as if in "Single Decode" mode; it looks for only one -! decodable signal in the FTol range. - - use jt4 use timer_module, only: timer class(jt4_decoder), intent(inout) :: this integer, intent(in) :: npts,nutc,minsync,ntol,mode4,minw, & - nfqso,ndepth,neme - logical, intent(in) :: NAgain,NClearAve + nfqso,ndepth character(len=12), intent(in) :: mycall,hiscall character(len=6), intent(in) :: hisgrid real, intent(in) :: dat(npts) !Raw data - logical first,prtavg - character decoded*22,special*5 + logical prtavg,have_candidate + character decoded*22 character*22 avemsg,deepmsg,deepave,blank,deepmsg0,deepave1 character csync*1 - data first/.true./,nutc0/-999/,nfreq0/-999999/ - save - - if(first) then - nsave=0 - first=.false. - blank=' ' -! Silence compiler warnings - if(dttol.eq.-99.0 .and. emedelay.eq.-99.0 .and. nagain) stop - endif - zz=0. -! syncmin=3.0 + minsync + blank=' ' + decoded=blank + deepmsg=blank + deepmsg0=blank + deepave1=blank + avemsg=blank + csync=' ' + ich=0 + ich0=-1 + aveich=-1 + nfanoave=0 + ndeepave=0 + dtx0=0. + dtx1=0. + nfreq0=nfqso + nfreq1=nfqso syncmin=1.0+minsync - naggressive=0 - if(iand(ndepth,7).ge.2) naggressive=1 nq1=3 - nq2=6 - if(naggressive.eq.1) nq1=1 - if(NClearAve) then - nsave=0 - iutc=-1 - nfsave=0. - listutc=0 - ppsave=0. - rsymbol=0. - dtsave=0. - syncsave=0. - nfanoave=0 - ndeepave=0 - endif + if(iand(ndepth,7).ge.2) nq1=1 ! Attempt to synchronize: look for sync pattern, get DF and DT. call timer('sync4 ',0) - call sync4(dat,npts,ntol,nfqso,4,mode4,minw+1,dtx,dfx, & - snrx,snrsync,flip,width) + call this%sync4(dat,npts,ntol,nfqso,mode4,minw+1,dtx,dfx,snrsync,flip,have_candidate) sync=snrsync + this%sync_strength=sync dtxz=dtx-0.8 nfreqz=nint(dfx) call timer('sync4 ',1) nsnr=-26 - if(sync.lt.syncmin) then + if(.not.have_candidate.or.sync.lt.syncmin) then if (associated (this%decode_callback)) then call this%decode_callback(nsnr,dtxz,nfreqz,.false.,csync, & .false.,decoded,0.,ich,.false.,0) @@ -169,9 +137,6 @@ contains nsnr=nint(snrsync - 22.9) decoded=blank deepmsg=blank - special=' ' - nsync=sync - nsnrlim=-33 csync='*' if(flip.lt.0.0) csync='#' qbest=0. @@ -185,12 +150,12 @@ contains ! Attempt a single-sequence decode, including deep4 if Fano fails. call timer('decode4 ',0) - call decode4(dat,npts,dtx,nfreq,flip,mode4,ndepth,neme,minw, & + call this%decode4(dat,npts,dtx,nfreq,flip,mode4,ndepth,minw, & mycall,hiscall,hisgrid,decoded,nfano,deepmsg,qual,ich) call timer('decode4 ',1) if(nfano.gt.0) then - call getsnr(dat,npts,mode4,dtx,decoded,nsnr) + call this%getsnr(dat,npts,mode4,dtx,decoded,nsnr) ! Fano succeeded: report the message and return !Fano OK if (associated (this%decode_callback)) then call this%decode_callback(nsnr,dtx,nfreq,.true.,csync, & @@ -213,18 +178,12 @@ contains qave=0. ! If we're doing averaging, call avg4 if(iand(ndepth,16).eq.16 .and. (.not.prtavg)) then - if(nutc.ne.nutc0 .or. abs(nfreq-nfreq0).gt.ntol) then -! This is a new minute or a new frequency, so call avg4. - nutc0=nutc !Try decoding average - nfreq0=nfreq - nsave=nsave+1 - nsave=mod(nsave-1,64)+1 - call timer('avg4 ',0) - call this%avg4(nutc,sync,dtx,flip,nfreq,mode4,ntol,ndepth,neme, & - mycall,hiscall,hisgrid,nfanoave,avemsg,qave,deepave,ich, & - ndeepave) - call timer('avg4 ',1) - endif + call this%save_average(nutc,sync,dtx,flip,nfreq,ntol) + if(this%kernel_status/=0) return + call timer('avg4 ',0) + call this%avg4(nutc,dtx,flip,nfreq,mode4,ntol,ndepth, & + mycall,hiscall,hisgrid,nfanoave,avemsg,qave,deepave,ich,ndeepave) + call timer('avg4 ',1) if(nfanoave.gt.0) then ! Fano succeeded: report the message AVG FANO OK @@ -239,7 +198,7 @@ contains dtx1=dtx nfreq1=nfreq deepave1=deepave - ich1=ich + aveich=ich qabest=qave endif endif @@ -253,7 +212,7 @@ contains qual=qbest if (associated (this%decode_callback)) then - if(qual.gt.0.0) call getsnr(dat,npts,mode4,dtx,deepmsg,nsnr) + if(qual.gt.0.0) call this%getsnr(dat,npts,mode4,dtx,deepmsg,nsnr) if(int(qual).ge.nq1) then call this%decode_callback(nsnr,dtx,nfreqz,.true.,csync,.true., & deepmsg,qual,ich,.false.,0) @@ -266,7 +225,7 @@ contains dtx=dtx1 nfreq=nfreq1 deepave=deepave1 - ich=ich1 + ich=aveich qave=qabest if (associated (this%decode_callback) .and. ndeepave.ge.2) then @@ -279,103 +238,27 @@ contains 990 return end subroutine wsjt4 - subroutine avg4(this,nutc,snrsync,dtxx,flip,nfreq,mode4,ntol,ndepth,neme, & + subroutine avg4(this,nutc,dtxx,flip,nfreq,mode4,ntol,ndepth, & mycall,hiscall,hisgrid,nfanoave,avemsg,qave,deepave,ichbest,ndeepave) ! Decodes averaged JT4 data - use jt4 class(jt4_decoder), intent(inout) :: this character*22 avemsg,deepave,deepbest character mycall*12,hiscall*12,hisgrid*6 - character*1 csync,cused(64) real sym(207,7) - integer iused(64) - logical first - data first/.true./ - save - - if(first) then - iutc=-1 - nfsave=0 - dtdiff=0.2 - first=.false. - nsave=1 ! ### Should this be here? ### - endif - - do i=1,64 - if(nutc.eq.iutc(i) .and. abs(nfreq-nfsave(i)).le.ntol) go to 10 - enddo - -! Save data for message averaging - iutc(nsave)=nutc - syncsave(nsave)=snrsync - dtsave(nsave)=dtxx - nfsave(nsave)=nfreq - flipsave(nsave)=flip - ppsave(1:207,1:7,nsave)=rsymbol(1:207,1:7) - -10 sym=0. - syncsum=0. - dtsum=0. - nfsum=0 - nsum=0 - - do i=1,64 - cused(i)='.' - if(iutc(i).lt.0) cycle - if(mod(iutc(i),2).ne.mod(nutc,2)) cycle !Use only same sequence - if(abs(dtxx-dtsave(i)).gt.dtdiff) cycle !DT must match - if(abs(nfreq-nfsave(i)).gt.ntol) cycle !Freq must match - if(flip.ne.flipsave(i)) cycle !Sync (*/#) must match - sym(1:207,1:7)=sym(1:207,1:7) + ppsave(1:207,1:7,i) - syncsum=syncsum + syncsave(i) - dtsum=dtsum + dtsave(i) - nfsum=nfsum + nfsave(i) - cused(i)='$' - nsum=nsum+1 - iused(nsum)=i - enddo - if(nsum.lt.64) iused(nsum+1)=0 - - syncave=0. - dtave=0. - fave=0. - if(nsum.gt.0) then - sym=sym/nsum - syncave=syncsum/nsum - dtave=dtsum/nsum - fave=float(nfsum)/nsum - endif - - do i=1,nsave - csync='*' - if(flipsave(i).lt.0.0) csync='#' - if (associated (this%average_callback)) then - call this%average_callback(cused(i) .eq. '$',iutc(i), & - syncsave(i),dtsave(i),nfsave(i),flipsave(i).lt.0.) - end if - enddo - - sqt=0. - sqf=0. - do j=1,64 - i=iused(j) - if(i.eq.0) exit - csync='*' - if(flipsave(i).lt.0.0) csync='#' - sqt=sqt + (dtsave(i)-dtave)**2 - sqf=sqf + (nfsave(i)-fave)**2 - enddo - rmst=0. - rmsf=0. - if(nsum.ge.2) then - rmst=sqrt(sqt/(nsum-1)) - rmsf=sqrt(sqf/(nsum-1)) - endif - kbest=ich1 - do k=ich1,ich2 + call this%select_average(nutc,dtxx,flip,nfreq,ntol,sym,nsum) + nfanoave=0 + ndeepave=0 + avemsg=' ' + deepave=' ' + deepbest=' ' + qave=0. + ichbest=-1 + if(nsum==0) return + kbest=this%ich1 + do k=this%ich1,this%ich2 call extract4(sym(1,k),ncount,avemsg) !Do the Fano decode nfanoave=0 if(ncount.ge.0) then @@ -389,12 +272,11 @@ contains deepave=' ' qave=0. -! Possibly should pass nadd=nused, also ? if(iand(ndepth,32).eq.32) then flipx=1.0 !Normal flip not relevant for ave msg qbest=0. - do k=ich1,ich2 - call deep4(sym(2,k),neme,flipx,mycall,hiscall,hisgrid,deepave,qave) + do k=this%ich1,this%ich2 + call this%deep4(sym(2,k),flipx,mycall,hiscall,hisgrid,deepave,qave) if(qave.gt.qbest) then qbest=qave deepbest=deepave @@ -411,35 +293,35 @@ contains 900 return end subroutine avg4 -end module jt4_decode - -subroutine getsnr(dat,npts,mode4,dtx,decoded,nsnr) +subroutine getsnr(this,dat,npts,mode4,dtx,decoded,nsnr) ! Compute SNR using raw data, T, DF, and decoded message. - + + class(jt4_decoder),intent(inout) :: this parameter(NSPS=1260,NH=NSPS/2) real dat(npts) - real x(NSPS) + real,pointer :: x(:) real s(NH),savg(NH) - complex cx(0:NSPS/2) + complex,pointer :: cx(:) integer itone(206) integer ipk(1) character*22 decoded,msgsent - equivalence (x,cx) + x=>this%transform(4)%x + cx=>this%transform(4)%cx call gen4(decoded,0,msgsent,itone,itype) !Get itone values for this message dt=1.0/5512.5 df=5512.5/NSPS istart=(dtx+1.08)/dt - + savg=0. do j=1,206 !Loop over all symbols cx=0. do i=1,NSPS k=(j-1)*NSPS + i + istart if(k.ge.1 .and. k.le.npts) x(i)=dat(k) - enddo - call four2a(cx,NSPS,1,-1,0) !r2c FFT + enddo + call fftwf_execute_dft_r2c(this%transform(4)%forward,x,cx) !r2c FFT do i=1,nh s(i)=real(cx(i))**2 + aimag(cx(i))**2 enddo @@ -449,35 +331,744 @@ subroutine getsnr(dat,npts,mode4,dtx,decoded,nsnr) nskip=mode4/2 call averms(savg,nh,nskip,ave,rms) + if(rms<=tiny(rms)) then + nsnr=-33 + return + endif savg=(savg-ave)/rms do i=1,mode4/4 call smo121(savg,nh) enddo - + ipk=maxloc(savg) psig=0. do i=ipk(1),1,-1 if(savg(i).lt.0) exit psig=psig + savg(i) enddo - i1=i+1 do i=ipk(1),nh if(savg(i).lt.0) exit psig=psig + savg(i) enddo - i2=i-1 pnoise=2500.0*sqrt(206.0)/df snrdb=db(psig/pnoise) nsnr=nint(snrdb) - width=(i2-i1)*df -! rewind(62) -! do i=1,nh -! write(62,1010) i*df,savg(i) -!1010 format(2f10.3) -! enddo -! flush(62) - return end subroutine getsnr + +subroutine decode4(this,dat,npts,dtx,nfreq,flip,mode4,ndepth,minw, & + mycall,hiscall,hisgrid,decoded,nfano,deepbest,qbest,ichbest) + +! Decodes JT4 data, assuming that DT and DF have already been determined. +! Input dat(npts) has already been downsampled by 2: rate = 11025/2. + + class(jt4_decoder),intent(inout) :: this + real dat(npts) !Raw data + character decoded*22,deepmsg*22,deepbest*22 + character*12 mycall,hiscall + character*6 hisgrid + real*8 dt,df,phi,f0,dphi,twopi,phi1,dphi1 + complex*16 cz,cz1,c0,c1 + real*4 sym(207) + + twopi=8*atan(1.d0) + dt=2.d0/11025 !Sample interval (2x downsampled data) + df=11025.d0/2520.d0 !Tone separation for JT4A mode + nsym=206 + amp=15.0 + istart=nint((dtx+0.8)/dt) !Start index for synced FFTs + if(istart.lt.0) istart=0 + nchips=0 + nfano=0 + decoded=' ' + deepbest=' ' + qbest=0. + deepmsg=' ' + ichbest=-1 + c0=0. + k=istart + phi=0.d0 + phi1=0.d0 + + this%ich1=minw+1 + do ich=1,7 + if(nch(ich).le.mode4) this%ich2=ich + enddo + + do ich=this%ich1,this%ich2 + nchips=min(nch(ich),70) + nspchip=1260/nchips + k=istart + phi=0.d0 + phi1=0.d0 + fac2=1.e-8 * sqrt(float(mode4)) + do j=1,nsym+1 + if(flip.gt.0.0) then + f0=nfreq + (npr(j))*mode4*df + f1=nfreq + (2+npr(j))*mode4*df + else + f0=nfreq + (1-npr(j))*mode4*df + f1=nfreq + (3-npr(j))*mode4*df + endif + dphi=twopi*dt*f0 + dphi1=twopi*dt*f1 + sq0=0. + sq1=0. + do nc=1,nchips + phi=0.d0 + phi1=0.d0 + c0=0. + c1=0. + do i=1,nspchip + k=k+1 + phi=phi+dphi + phi1=phi1+dphi1 + cz=dcmplx(cos(phi),-sin(phi)) + cz1=dcmplx(cos(phi1),-sin(phi1)) + if(k.le.npts) then + c0=c0 + dat(k)*cz + c1=c1 + dat(k)*cz1 + endif + enddo + sq0=sq0 + real(c0)**2 + aimag(c0)**2 + sq1=sq1 + real(c1)**2 + aimag(c1)**2 + enddo + sq0=fac2*sq0 + sq1=fac2*sq1 + rsym=amp*(sq1-sq0) + this%rsymbol(j,ich)=rsym + sym(j)=rsym + enddo + + call extract4(sym,ncount,decoded) !Do the convolutional decode + nfano=0 + if(ncount.ge.0) then + nfano=1 + ichbest=ich + exit + endif + + qual=0. !Now try deep search + if(iand(ndepth,32).eq.32) then + call this%deep4(sym(2),flip,mycall,hiscall,hisgrid,deepmsg,qual) + if(qual.gt.qbest) then + qbest=qual + deepbest=deepmsg + ichbest=ich + endif + endif + enddo + +end subroutine decode4 + +subroutine deep4(this,sym0,flip,mycall,hiscall,hisgrid,decoded,qual) + +! Deep search routine for JT4 + + class(jt4_decoder),intent(inout) :: this + parameter (MAXCALLS=7000,MAXRPT=63) + real*4 sym0(206),sym(206) + character callsign*12,grid*4,message*22,hisgrid*6 + character*12 mycall,hiscall + character*22 decoded + character(len=15) :: callgrid + character*180 line + character*4 rpt(MAXRPT) + integer ncode(206) + real :: pp(2*MAXCALLS + 2 + MAXRPT) + integer :: allocation_status + data rpt/'-01','-02','-03','-04','-05', & + '-06','-07','-08','-09','-10', & + '-11','-12','-13','-14','-15', & + '-16','-17','-18','-19','-20', & + '-21','-22','-23','-24','-25', & + '-26','-27','-28','-29','-30', & + 'R-01','R-02','R-03','R-04','R-05', & + 'R-06','R-07','R-08','R-09','R-10', & + 'R-11','R-12','R-13','R-14','R-15', & + 'R-16','R-17','R-18','R-19','R-20', & + 'R-21','R-22','R-23','R-24','R-25', & + 'R-26','R-27','R-28','R-29','R-30', & + 'RO','RRR','73'/ + + sym=sym0 + if(mycall.eq.this%mycall0 .and. hiscall.eq.this%hiscall0 .and. & + hisgrid.eq.this%hisgrid0 .and. this%templates_valid) go to 30 + + if(.not.allocated(this%code)) then + allocate(this%code(206,64+2*size(this%calls)),this%testmsg(64+2*size(this%calls)),stat=allocation_status) + if(allocation_status/=0) then + this%kernel_status=-1 + if(allocated(this%code)) deallocate(this%code) + if(allocated(this%testmsg)) deallocate(this%testmsg) + decoded=' ' + qual=0. + return + endif + endif + k=0 + do n=1,1+size(this%calls) + if(n.eq.1) then + callsign=hiscall + do i=4,12 + if(ichar(callsign(i:i)).eq.0) callsign(i:i)=' ' + enddo + grid=hisgrid(1:4) + if(ichar(grid(3:3)).eq.0) grid(3:3)=' ' + if(ichar(grid(4:4)).eq.0) grid(4:4)=' ' + else + callsign=this%calls(n-1)%call + grid=this%calls(n-1)%grid + endif + + j1=index(mycall,' ') - 1 + if(j1.le.-1) j1=12 + if(j1.lt.3) j1=6 + j2=index(callsign,' ') - 1 + if(j2.le.-1) j2=12 + if(j2.lt.3) j2=6 + j3=index(mycall,'/') ! j3>0 means compound mycall + j4=index(callsign,'/') ! j4>0 means compound hiscall + callgrid=callsign(1:j2) + + mz=1 +! The current contact also supplies report and acknowledgement templates. + if(n.eq.1 .and. j3.lt.1 .and. j4.lt.1 .and. callsign(1:6).ne.' ') & + mz=MAXRPT+1 + do m=1,mz + if(m.gt.1) grid=rpt(m-1) + if(j3.lt.1 .and.j4.lt.1) callgrid=callsign(1:j2)//' '//grid + message=mycall(1:j1)//' '//callgrid + k=k+1 + this%testmsg(k)=message + call encode4(message,ncode) + this%code(1:206,k)=2*ncode(1:206)-1 + if(n.ge.2) then +! Insert CQ message + if(j4.lt.1) callgrid=callsign(1:j2)//' '//grid + message='CQ '//callgrid + k=k+1 + this%testmsg(k)=message + call encode4(message,ncode) + this%code(1:206,k)=2*ncode(1:206)-1 + endif + enddo + enddo + + this%ntot=k + +30 this%mycall0=mycall + this%hiscall0=hiscall + this%hisgrid0=hisgrid + this%templates_valid=.true. + + sq=0. + do j=1,206 + sq=sq + sym(j)**2 + enddo + rms=sqrt(sq/206.0) + decoded=' ' + qual=0. + if(rms<=tiny(rms)) return + sym=sym/rms + ip1=1 + + p1=-1.e30 + p2=-1.e30 + do k=1,this%ntot + pp(k)=0. +! Test all messages if flip=+1; skip the CQ messages if flip=-1. + if(flip.gt.0.0 .or. this%testmsg(k)(1:3).ne.'CQ ') then + p=0. + do j=1,206 + p=p + this%code(j,k)*sym(j) + enddo + pp(k)=p + if(p.gt.p1) then + p1=p + ip1=k + endif + endif + enddo + + do i=1,this%ntot + if(pp(i).gt.p2 .and. this%testmsg(i).ne.this%testmsg(ip1)) p2=pp(i) + enddo + + qual=p1-max(1.15*p2,70.0) + + if(associated(this%diagnostic_callback)) then + write(line,1001) p1,p2,this%ntot,rms,qual,ip1,this%testmsg(ip1) +1001 format(2f8.2,i8,2f8.2,i6,2x,a22) + call this%diagnostic_callback(trim(line)) + endif + + if(qual.gt.1.0) then + decoded=this%testmsg(ip1) + else + decoded=' ' + qual=0. + endif + +! Make sure everything is upper case. + do i=1,22 + if(decoded(i:i).ge.'a' .and. decoded(i:i).le.'z') & + decoded(i:i)=char(ichar(decoded(i:i))-32) + enddo + +end subroutine deep4 + +subroutine sync4(this,dat,jz,ntol,nfqso,mode4,minwidth,dtx,dfx,snrsync,flip,have_candidate) + +! Synchronizes JT4 data, finding the best-fit DT and DF. + + class(jt4_decoder),intent(inout) :: this + parameter (NFFTMAX=2520) !Max length of FFTs + parameter (NHMAX=NFFTMAX/2) !Max length of power spectra + parameter (NSMAX=525) !Max number of half-symbol steps + integer ntol !Range of DF search + real dat(jz) + real ccfblue(-5:540) !CCF with pseudorandom sequence + logical,intent(out) :: have_candidate + +! Do FFTs of twice symbol length, stepped by half symbols. Note that +! we have already downsampled the data by factor of 2. + dtx=0. + dfx=real(nfqso) + snrsync=0. + have_candidate=.false. + flip=1. + nsym=207 + nfft=2520 + nq=nfft/4 + nsteps=jz/nq - 1 + df=0.5*11025.0/nfft + ftop=nfqso + 7*mode4*df + if(ftop.gt.11025.0/4.0) then + go to 900 + endif + + + do j=1,nsteps !Compute spectrum for each step, get average + k=(j-1)*nq + 1 + call this%ps4(dat(k),nfft,this%s2(1,j)) + enddo + +! Set freq and lag ranges + ia=(nfqso-ntol)/df !Index of lowest tone, bottom of search range + ib=(nfqso+ntol)/df !Index of lowest tone, top of search range + iamin=nint(100.0/df) + if(ia.lt.iamin) ia=iamin + ibmax=nint(2700.0/df) - 6*mode4 + if(ib.gt.ibmax) ib=ibmax + + lag1=-5 + lag2=59 + syncbest=-1.e30 + + do ich=minwidth,7 !Find best width + kz=nch(ich)/2 + iaa=ia+kz + ibb=ib-kz + do i=iaa,ibb !Find best frequency channel for CCF + call xcor4(this%s2,i,nsteps,nsym,lag1,lag2,ich,mode4,ccfblue,ccf0, & + lagpk0,flip) + +! Find rms of the CCF, without main peak + call slope(ccfblue(lag1),lag2-lag1+1,lagpk0-lag1+1.0) + sync=abs(ccfblue(lagpk0)) + +! Find best sync value + if(sync.gt.syncbest*1.03) then + ipk=i + ichpk=ich + syncbest=sync + endif + enddo + enddo + if(syncbest<=0.) go to 900 + + dfx=ipk*df + +! Peak up in time, at best whole-channel frequency + call xcor4(this%s2,ipk,nsteps,nsym,lag1,lag2,ichpk,mode4,ccfblue,ccfmax, & + lagpk,flip) + xlag=lagpk + if(lagpk.gt.lag1 .and. lagpk.lt.lag2) then + call peakup(ccfblue(lagpk-1),ccfmax,ccfblue(lagpk+1),dx2) + xlag=lagpk+dx2 + endif + +! Find rms of the CCF, without the main peak + call slope(ccfblue(lag1),lag2-lag1+1,xlag-lag1+1.0) + sq=0. + nsq=0 + do lag=lag1,lag2 + if(abs(lag-xlag).gt.2.0) then + sq=sq+ccfblue(lag)**2 + nsq=nsq+1 + endif + enddo + rms=sqrt(sq/nsq) + if(rms<=tiny(rms)) return + snrsync=max(0.0,db(abs(ccfblue(lagpk)/rms - 1.0)) - 4.5) + dt=2.0/11025.0 + istart=xlag*nq + dtx=istart*dt + have_candidate=.true. + +900 return +end subroutine sync4 + +subroutine lpf1(this,dd,jz,dat,jz2) + + class(jt4_decoder),intent(inout) :: this + parameter (NFFT1=64*11025,NFFT2=32*11025) + real dd(jz) + real dat(jz/2) + real,pointer :: x(:) + complex,pointer :: cx(:) + x=>this%transform(2)%x + cx=>this%transform(2)%cx + + fac=1.0/float(NFFT1) + x(1:jz)=fac*dd(1:jz) + x(jz+1:NFFT1)=0.0 + call fftwf_execute_dft_r2c(this%transform(2)%forward,x,cx) !Forward FFT, r2c + cx(NFFT2/2:)=0.0 + + + call fftwf_execute_dft_c2r(this%transform(2)%backward,cx,x) !Inverse FFT, c2r + jz2=jz/2 + dat(1:jz2)=x(1:jz2) + +end subroutine lpf1 + +subroutine ps4(this,dat,nfft,s) + + class(jt4_decoder),intent(inout) :: this + parameter (NMAX=2520+2) + parameter (NHMAX=NMAX/2-1) + real dat(nfft) + real,pointer :: dat2(:) + real s(NHMAX) + complex,pointer :: c(:) + dat2=>this%transform(3)%x + c=>this%transform(3)%cx + + nh=nfft/2 + do i=1,nh + dat2(i)=dat(i)/128.0 !### Why 128 ?? + enddo + do i=nh+1,nfft + dat2(i)=0. + enddo + + call fftwf_execute_dft_r2c(this%transform(3)%forward,dat2,c) + + fac=1.0/nfft + do i=1,nh + s(i)=fac*(real(c(i))**2 + aimag(c(i))**2) + enddo + +end subroutine ps4 + + subroutine decode_pcm(this,options,input,sample_rate_hz,decode_callback,status,diagnostic_callback) + class(jt4_decoder),intent(inout) :: this + type(jt4_options),intent(in) :: options + integer(c_int16_t),intent(in) :: input(:) + integer,intent(in) :: sample_rate_hz + procedure(jt4_decode_callback) :: decode_callback + integer,intent(out) :: status + procedure(jt4_diagnostic_callback),optional :: diagnostic_callback + integer :: jz,jz2,depth,n + real,pointer :: x(:) + complex,pointer :: cx(:) + + status=-1 + if(sample_rate_hz/=11025.and.sample_rate_hz/=12000) return + if(size(input)<1.or.size(input)>60*sample_rate_hz) return + if(options%submode<0.or.options%submode>6) return + if(options%minimum_width_profile<0.or.options%minimum_width_profile>options%submode) return + call this%prepare_workspace(status,sample_rate_hz==12000) + if(status/=0) return + this%decode_callback=>decode_callback + nullify(this%diagnostic_callback) + if(present(diagnostic_callback)) this%diagnostic_callback=>diagnostic_callback + if(this%current_submode/=options%submode.or.this%current_minimum_profile/=options%minimum_width_profile) & + call this%clear_averages() + this%current_submode=options%submode + this%current_minimum_profile=options%minimum_width_profile + if(.not.this%prepared) then + this%pcm=0. + jz=min(size(input),52*sample_rate_hz) + if(sample_rate_hz==11025) then + this%pcm(1:jz)=real(input(1:jz)) + else + x=>this%transform(1)%x + cx=>this%transform(1)%cx + x=0. + x(1:jz)=real(input(1:jz)) + call fftwf_execute_dft_r2c(this%transform(1)%forward,x,cx) + cx(320000:)=0. + call fftwf_execute_dft_c2r(this%transform(1)%backward,cx,x) + n=int(jz*11025./12000.) + this%pcm(1:n)=1.e-6*x(1:n) + endif + call this%lpf1(this%pcm,52*11025,this%dat,jz2) + this%prepared=.true. + endif + depth=options%depth + if(options%averaging) depth=ior(depth,16) + if(options%deep_search) depth=ior(depth,32) + this%kernel_status=0 + call this%wsjt4(this%dat,26*11025,options%utc,options%min_sync,options%tolerance_hz, & + nch(options%submode+1),options%minimum_width_profile,options%mycall,options%hiscall, & + options%hisgrid,options%receive_frequency_hz,depth) + status=this%kernel_status + nullify(this%decode_callback,this%diagnostic_callback) + end subroutine + + subroutine prepare_workspace(this,status,include_conversion) + class(jt4_decoder),intent(inout) :: this + integer,intent(out) :: status + logical,intent(in),optional :: include_conversion + integer,parameter :: lengths(4)=[64*12000,64*11025,2520,1260] + integer,parameter :: inverse_lengths(4)=[64*11025,32*11025,0,0] + integer :: i,n,allocation_status,first + status=-1 + if(.not.allocated(this%pcm)) then + allocate(this%pcm(52*11025),stat=allocation_status) + if(allocation_status/=0) return + endif + if(.not.allocated(this%dat)) then + allocate(this%dat(30*11025),stat=allocation_status) + if(allocation_status/=0) return + endif + if(.not.allocated(this%s2)) then + allocate(this%s2(1260,525),stat=allocation_status) + if(allocation_status/=0) return + endif + if(.not.allocated(this%ppsave)) then + allocate(this%ppsave(207,7,MAXAVE),stat=allocation_status) + if(allocation_status/=0) return + this%ppsave=0. + endif + if(.not.allocated(this%rsymbol)) then + allocate(this%rsymbol(207,7),stat=allocation_status) + if(allocation_status/=0) return + this%rsymbol=0. + endif + if(.not.allocated(this%calls)) then + allocate(this%calls(0),stat=allocation_status) + if(allocation_status/=0) return + endif + first=2 + if(present(include_conversion)) then + if(include_conversion) first=1 + endif + do i=first,4 + n=lengths(i) + if(.not.c_associated(this%transform(i)%storage)) then + this%transform(i)%storage=fftwf_alloc_complex(int(n/2+1,c_size_t)) + if(.not.c_associated(this%transform(i)%storage)) return + call c_f_pointer(this%transform(i)%storage,this%transform(i)%x,[n+2]) + call c_f_pointer(this%transform(i)%storage,this%transform(i)%cx,[n/2+1]) + this%transform(i)%cx(0:n/2)=>this%transform(i)%cx + endif + if(.not.c_associated(this%transform(i)%forward)) then +!$omp critical(fftw) + this%transform(i)%forward=fftwf_plan_dft_r2c_1d(n,this%transform(i)%x, & + this%transform(i)%cx,this%fft_flags) +!$omp end critical(fftw) + endif + if(.not.c_associated(this%transform(i)%forward)) return + if(inverse_lengths(i)>0.and..not.c_associated(this%transform(i)%backward)) then +!$omp critical(fftw) + this%transform(i)%backward=fftwf_plan_dft_c2r_1d(inverse_lengths(i),this%transform(i)%cx, & + this%transform(i)%x,this%fft_flags) +!$omp end critical(fftw) + endif + if(inverse_lengths(i)>0.and..not.c_associated(this%transform(i)%backward)) return + enddo + status=0 + end subroutine + + subroutine set_fft_flags(this,flags) + class(jt4_decoder),intent(inout) :: this + integer,intent(in) :: flags + if(flags==this%fft_flags) return + call this%destroy_plans() + this%fft_flags=flags + this%prepared=.false. + end subroutine + + subroutine destroy_plans(this) + class(jt4_decoder),intent(inout) :: this + integer :: i +!$omp critical(fftw) + do i=1,4 + if(c_associated(this%transform(i)%forward)) call fftwf_destroy_plan(this%transform(i)%forward) + if(c_associated(this%transform(i)%backward)) call fftwf_destroy_plan(this%transform(i)%backward) + this%transform(i)%forward=c_null_ptr + this%transform(i)%backward=c_null_ptr + enddo +!$omp end critical(fftw) + end subroutine + + subroutine finalize_jt4(this) + type(jt4_decoder),intent(inout) :: this + integer :: i + call this%destroy_plans() + do i=1,4 + if(c_associated(this%transform(i)%storage)) call fftwf_free(this%transform(i)%storage) + this%transform(i)%storage=c_null_ptr + nullify(this%transform(i)%x,this%transform(i)%cx) + enddo + end subroutine + + subroutine release_input(this) + class(jt4_decoder),intent(inout) :: this + this%prepared=.false. + this%sync_strength=0. + nullify(this%decode_callback,this%diagnostic_callback) + end subroutine + + subroutine reset(this) + class(jt4_decoder),intent(inout) :: this + call this%release_input() + call this%clear_averages() + if(allocated(this%calls)) deallocate(this%calls) + if(allocated(this%code)) deallocate(this%code) + if(allocated(this%testmsg)) deallocate(this%testmsg) + this%templates_valid=.false. + this%ntot=0 + this%current_submode=-1 + this%current_minimum_profile=-1 + end subroutine + + subroutine set_calls(this,calls,status) + class(jt4_decoder),intent(inout) :: this + type(jt4_call),intent(in) :: calls(:) + integer,intent(out),optional :: status + type(jt4_call),allocatable :: replacement(:) + integer :: i,count,allocation_status + if(present(status)) status=0 + count=min(size(calls),6999) + if(allocated(this%calls)) then + if(size(this%calls)==count) then + do i=1,count + if(this%calls(i)%call/=calls(i)%call.or.this%calls(i)%grid/=calls(i)%grid) exit + enddo + if(i>count) return + endif + endif + allocate(replacement(count),stat=allocation_status) + if(allocation_status/=0) then + this%kernel_status=-1 + if(present(status)) status=-1 + return + endif + replacement=calls(1:count) + call move_alloc(replacement,this%calls) + if(allocated(this%code)) deallocate(this%code) + if(allocated(this%testmsg)) deallocate(this%testmsg) + this%templates_valid=.false. + end subroutine + + subroutine clear_averages(this) + class(jt4_decoder),intent(inout) :: this + this%iutc=-1 + this%nfsave=0 + this%dtsave=0. + this%syncsave=0. + this%flipsave=0. + this%average_used=.false. + this%nsave=0 + this%average_count=0 + if(allocated(this%ppsave)) this%ppsave=0. + if(allocated(this%rsymbol)) this%rsymbol=0. + end subroutine + + subroutine save_average(this,utc,sync,dt,polarity,freq,tolerance) + class(jt4_decoder),intent(inout) :: this + integer,intent(in) :: utc,freq,tolerance + real,intent(in) :: sync,dt,polarity + integer :: i,allocation_status + if(.not.allocated(this%ppsave)) then + allocate(this%ppsave(207,7,MAXAVE),stat=allocation_status) + if(allocation_status/=0) then + this%kernel_status=-1 + return + endif + this%ppsave=0. + endif + if(.not.allocated(this%rsymbol)) then + allocate(this%rsymbol(207,7),stat=allocation_status) + if(allocation_status/=0) then + this%kernel_status=-1 + return + endif + this%rsymbol=0. + endif + do i=1,MAXAVE + if(this%iutc(i)/100==utc/100.and.this%iutc(i)>=0.and.abs(this%nfsave(i)-freq)<=tolerance) return + enddo + this%nsave=mod(this%nsave,MAXAVE)+1 + this%average_count=min(this%average_count+1,MAXAVE) + i=this%nsave + this%iutc(i)=utc + this%nfsave(i)=freq + this%syncsave(i)=sync + this%dtsave(i)=dt + this%flipsave(i)=polarity + this%ppsave(:,:,i)=this%rsymbol + this%average_used(i)=.false. + end subroutine + + subroutine select_average(this,utc,dt,polarity,freq,tolerance,sym,nsum) + class(jt4_decoder),intent(inout) :: this + integer,intent(in) :: utc,freq,tolerance + real,intent(in) :: dt,polarity + real,intent(out) :: sym(207,7) + integer,intent(out) :: nsum + integer :: i + sym=0. + nsum=0 + this%average_used=.false. + if(.not.allocated(this%ppsave)) return + do i=1,MAXAVE + if(this%iutc(i)<0) cycle + if(mod(this%iutc(i)/100,2)/=mod(utc/100,2)) cycle + if(abs(dt-this%dtsave(i))>0.2) cycle + if(abs(freq-this%nfsave(i))>tolerance) cycle + if(polarity/=this%flipsave(i)) cycle + sym=sym+this%ppsave(:,:,i) + nsum=nsum+1 + this%average_used(i)=.true. + enddo + if(nsum>0) sym=sym/nsum + end subroutine + + subroutine get_averages(this,entries,count) + class(jt4_decoder),intent(in) :: this + type(jt4_average_entry),intent(out) :: entries(:) + integer,intent(out) :: count + integer :: i + count=0 + do i=1,MAXAVE + if(this%iutc(i)<0) cycle + count=count+1 + if(count>size(entries)) cycle + entries(count)%utc=this%iutc(i) + entries(count)%frequency_hz=this%nfsave(i) + entries(count)%polarity=1 + if(this%flipsave(i)<0.) entries(count)%polarity=-1 + entries(count)%used=this%average_used(i) + entries(count)%sync=this%syncsave(i) + entries(count)%dt_seconds=this%dtsave(i) + enddo + end subroutine +end module jt4_decode diff --git a/lib/jt4_host_support.f90 b/lib/jt4_host_support.f90 new file mode 100644 index 00000000..b84e9629 --- /dev/null +++ b/lib/jt4_host_support.f90 @@ -0,0 +1,112 @@ +module jt4_host_support + use jt4_decode, only: jt4_decoder,jt4_call,jt4_average_entry + use decoder_engine_types, only: engine_jt4_options + use prog_args, only: data_dir + use fftw3, only: FFTW_ESTIMATE,FFTW_ESTIMATE_PATIENT,FFTW_MEASURE,FFTW_PATIENT,FFTW_EXHAUSTIVE + include 'jt9com.f90' + private + public :: convert_jt4_host_options,prepare_jt4_host,load_jt4_calls,write_jt4_averages,write_jt4_diagnostic + +contains + + subroutine convert_jt4_host_options(params,options,utc_is_hhmmss) + type(params_block), intent(in) :: params + type(engine_jt4_options), intent(out) :: options + logical, optional, intent(in) :: utc_is_hhmmss + + options=engine_jt4_options() + options%utc=100*params%nutc + if(present(utc_is_hhmmss)) then + if(utc_is_hhmmss) options%utc=params%nutc + endif + options%submode=params%nsubmode + options%receive_frequency_hz=params%nfqso + options%tolerance_hz=params%ntol + options%depth=iand(params%ndepth,7) + options%min_sync=params%minsync + options%minimum_width_profile=params%minw + options%averaging=merge(1_c_int,0_c_int,iand(params%ndepth,16)/=0) + options%deep_search=merge(1_c_int,0_c_int,iand(params%ndepth,32)/=0) + options%mycall=params%mycall + options%hiscall=params%hiscall + options%hisgrid=params%hisgrid + end subroutine convert_jt4_host_options + + subroutine prepare_jt4_host(decoder) + class(jt4_decoder), intent(inout) :: decoder + integer :: flags,npatience,nthreads + common/patience/npatience,nthreads + + flags=FFTW_ESTIMATE + select case(npatience) + case(1) + flags=FFTW_ESTIMATE_PATIENT + case(2) + flags=FFTW_MEASURE + case(3) + flags=FFTW_PATIENT + case(4) + flags=FFTW_EXHAUSTIVE + end select + call decoder%set_fft_flags(flags) + end subroutine prepare_jt4_host + + subroutine load_jt4_calls(decoder) + class(jt4_decoder), intent(inout) :: decoder + type(jt4_call), allocatable :: calls(:) + character(len=180) :: line + integer :: unit,ios,count,i,first,second + + allocate(calls(6999)) + count=0 + open(newunit=unit,file=trim(data_dir)//'/CALL3.TXT',status='old',action='read',iostat=ios) + if(ios==0) then + do i=1,size(calls) + read(unit,'(a80)',iostat=ios) line + if(ios/=0) exit + if(line(:4)=='ZZZZ') exit + if(line(:2)=='//') cycle + first=index(line,',') + if(first<4) cycle + second=index(line(first+1:),',') + if(second<5) cycle + count=count+1 + calls(count)%call=line(:first-1) + calls(count)%grid=line(first+1:first+4) + enddo + close(unit) + endif + call decoder%set_calls(calls(:count)) + end subroutine load_jt4_calls + + subroutine write_jt4_averages(decoder,unit) + class(jt4_decoder), intent(in) :: decoder + integer, intent(in) :: unit + type(jt4_average_entry) :: entries(64) + integer :: count,i + character :: used,polarity + + call decoder%get_averages(entries,count) + rewind(unit) + do i=1,count + used='.' + if(entries(i)%used) used='$' + polarity='*' + if(entries(i)%polarity<0) polarity='$' + write(unit,'(a1,i5.4,f6.1,f6.2,i6,1x,a1)') used,entries(i)%utc/100, & + entries(i)%sync,entries(i)%dt_seconds,entries(i)%frequency_hz,polarity + enddo + endfile(unit) + flush(unit) + end subroutine write_jt4_averages + + subroutine write_jt4_diagnostic(line) + character(len=*), intent(in) :: line + integer :: unit,ios + + open(newunit=unit,file='fort.77',status='replace',iostat=ios) + if(ios/=0) return + write(unit,'(a)') line + close(unit) + end subroutine write_jt4_diagnostic +end module jt4_host_support diff --git a/lib/jt9.f90 b/lib/jt9.f90 index 1e59bd8e..13e0dfb0 100644 --- a/lib/jt9.f90 +++ b/lib/jt9.f90 @@ -394,6 +394,7 @@ program jt9 stop 2 end if call parse_wav_filename_nutc(infile, nutc, wav_utc_has_seconds) + if(mode.eq.4.and.wav_utc_has_seconds) nutc=nutc/100 if((mode.eq.66.or.mode.eq.240.or.mode.eq.241.or.mode.eq.242).and..not.wav_utc_has_seconds) & nutc=100*nutc nsps=6912 @@ -574,7 +575,7 @@ program jt9 endif ! Normal decoding pass - if(mode.eq.8.or.mode.eq.9.or.mode.eq.65.or.mode.eq.66.or. & + if(mode.eq.4.or.mode.eq.8.or.mode.eq.9.or.mode.eq.65.or.mode.eq.66.or. & mode.eq.240.or.mode.eq.241.or.mode.eq.242) then call run_engine_wav(shared_data%id2,engine_valid_samples) else if(mode.eq.5) then diff --git a/lib/jt9_params_init.f90 b/lib/jt9_params_init.f90 index aba14b66..f95c3a58 100644 --- a/lib/jt9_params_init.f90 +++ b/lib/jt9_params_init.f90 @@ -150,6 +150,11 @@ contains ! FST4 60s period uses a larger sample window (jt9.f90:485 in WAV path). if (mode .eq. 240) params%kin = 720000 + if(mode==4) then + params%kin=624000 + params%minw=0 + params%minsync=0 + endif ! JT9 with explicit -S: remap nfa to fsplit (jt9.f90:386, :560). if (mode .eq. 9 .and. args%fsplit .ne. 2700) params%nfa = args%fsplit @@ -185,6 +190,7 @@ contains params%nftx = args%nrxfreq params%minw = 1 + if(params%nmode==4.and.params%nsubmode==0) params%minw=0 params%minsync = 0 params%nlist = 0 params%max_drift = 0 diff --git a/lib/jt9a.f90 b/lib/jt9a.f90 index c1a5a20a..85a02a8e 100644 --- a/lib/jt9a.f90 +++ b/lib/jt9a.f90 @@ -171,11 +171,12 @@ subroutine jt9a() ! MSK144 call decode_msk144_core(shared_memory%payload%id2, local_params, data_dir, & completion) - elseif(local_params%nmode.eq.8.or.local_params%nmode.eq.5.or.local_params%nmode.eq.9.or. & + elseif(local_params%nmode.eq.4.or.local_params%nmode.eq.8.or.local_params%nmode.eq.5.or. & + local_params%nmode.eq.9.or. & local_params%nmode.eq.65.or.local_params%nmode.eq.66.or. & local_params%nmode.eq.240.or.local_params%nmode.eq.241.or.local_params%nmode.eq.242) then pass_valid_samples=min(shared_memory%metadata%valid_samples,180000) - if(local_params%nmode.eq.9.or.local_params%nmode.eq.65) & + if(local_params%nmode.eq.4.or.local_params%nmode.eq.9.or.local_params%nmode.eq.65) & pass_valid_samples=min(shared_memory%metadata%valid_samples,720000) if(local_params%nmode.eq.66.or.local_params%nmode.eq.240.or. & local_params%nmode.eq.241.or.local_params%nmode.eq.242) & diff --git a/lib/lpf1.f90 b/lib/lpf1.f90 deleted file mode 100644 index a620e9a5..00000000 --- a/lib/lpf1.f90 +++ /dev/null @@ -1,29 +0,0 @@ -subroutine lpf1(dd,jz,dat,jz2) - - parameter (NFFT1=64*11025,NFFT2=32*11025) - real dd(jz) - real dat(jz) - real x(NFFT1) - complex cx(0:NFFT1/2) - equivalence (x,cx) - save x,cx - - fac=1.0/float(NFFT1) - x(1:jz)=fac*dd(1:jz) - x(jz+1:NFFT1)=0.0 - call four2a(cx,NFFT1,1,-1,0) !Forwarxd FFT, r2c - cx(NFFT2/2:)=0.0 - -! df=11025.0/NFFT1 -! do i=1,NFFT1/2 -! sx=real(cx(i))**2 + aimag(cx(i))**2 -! write(50,3000) i*df,sx -!3000 format(f15.6,e12.3) -! enddo - - call four2a(cx,NFFT2,1,1,-1) !Inverse FFT, c2r - jz2=jz/2 - dat(1:jz2)=x(1:jz2) - - return -end subroutine lpf1 diff --git a/lib/ps4.f90 b/lib/ps4.f90 deleted file mode 100644 index 782ab50d..00000000 --- a/lib/ps4.f90 +++ /dev/null @@ -1,27 +0,0 @@ -subroutine ps4(dat,nfft,s) - - parameter (NMAX=2520+2) - parameter (NHMAX=NMAX/2-1) - real dat(nfft) - real dat2(NMAX) - real s(NHMAX) - complex c(0:NMAX) - equivalence(dat2,c) - - nh=nfft/2 - do i=1,nh - dat2(i)=dat(i)/128.0 !### Why 128 ?? - enddo - do i=nh+1,nfft - dat2(i)=0. - enddo - - call four2a(c,nfft,1,-1,0) - - fac=1.0/nfft - do i=1,nh - s(i)=fac*(real(c(i))**2 + aimag(c(i))**2) - enddo - - return -end subroutine ps4 diff --git a/lib/streaming_apply.f90 b/lib/streaming_apply.f90 index 0a507481..98573ba4 100644 --- a/lib/streaming_apply.f90 +++ b/lib/streaming_apply.f90 @@ -68,6 +68,9 @@ contains end if if (in_cfg%depth_set) params%ndepth = in_cfg%depth if (in_cfg%submode_set) params%nsubmode = in_cfg%submode + if ((in_cfg%mode_set.or.in_cfg%submode_set).and..not.in_cfg%min_width_set) then + if(params%nmode==4.and.params%nsubmode==0) params%minw=0 + endif if (in_cfg%rxfreq_set) then params%nfqso = in_cfg%rxfreq params%nftx = in_cfg%rxfreq @@ -287,8 +290,8 @@ contains if ((io_mode.eq.240.or.io_mode.eq.241.or.io_mode.eq.242).and.io_TRperiod.ge.60.and. & params%nutc.le.2359) & params%nutc=100*params%nutc - ! Legacy numeric Q65 times may be HHMM. - if (io_mode.eq.66.and.io_TRperiod.ge.60.and.params%nutc.le.2359) & + ! Legacy numeric JT4 and Q65 times may be HHMM. + if ((io_mode.eq.4.or.io_mode.eq.66).and.io_TRperiod.ge.60.and.params%nutc.le.2359) & params%nutc=100*params%nutc endif ! Phase 8 (RFC v1 §6.3/§4.1): utc (ISO "HH:MM:SS") is a SECOND route to nutc, diff --git a/lib/streaming_control.f90 b/lib/streaming_control.f90 index a65915bd..2b02dbac 100644 --- a/lib/streaming_control.f90 +++ b/lib/streaming_control.f90 @@ -61,7 +61,8 @@ module streaming_control integer :: nfa = 0 logical :: nfb_set = .false. integer :: nfb = 0 - ! Per-period UTC as HHMMSS integer. Threaded into + ! Per-period UTC as HHMMSS integer; in periods of a minute or more a + ! value up to 2359 is read as HHMM. Threaded into ! params%nutc so streaming_emit_decode can format the time field ! correctly. Producer should send a fresh nutc in each period's ! configure frame (mirrors WAV-path filename-derived per-invocation diff --git a/lib/streaming_emit.f90 b/lib/streaming_emit.f90 index b3346926..0b6e4590 100644 --- a/lib/streaming_emit.f90 +++ b/lib/streaming_emit.f90 @@ -26,8 +26,11 @@ module streaming_emit private logical, save :: enabled_ = .false. + logical, save :: utc_from_iso_ = .false. + real(8), save :: trperiod_ = 60.d0 public :: streaming_emit_set_enabled + public :: streaming_emit_set_time_form public :: streaming_emit_enabled public :: streaming_emit_ready public :: streaming_emit_decode @@ -44,6 +47,20 @@ contains enabled_ = flag end subroutine streaming_emit_set_enabled + ! Called after each applied configure. An ISO utc is HHMMSS; a numeric nutc + ! is HHMMSS when the period is under a minute or the value exceeds 2359, + ! and HHMM otherwise. + subroutine streaming_emit_set_time_form(utc_set, nutc_set, trperiod) + logical, intent(in) :: utc_set, nutc_set + real(8), intent(in) :: trperiod + if (utc_set) then + utc_from_iso_ = .true. + else if (nutc_set) then + utc_from_iso_ = .false. + end if + trperiod_ = trperiod + end subroutine streaming_emit_set_time_form + pure function streaming_emit_enabled() result(v) logical :: v v = enabled_ @@ -193,15 +210,17 @@ contains logical, optional, intent(in) :: utc_is_hhmmss integer :: hh, mm, ss logical :: full_time - full_time=.false. - if(present(utc_is_hhmmss)) full_time=utc_is_hhmmss + full_time=utc_from_iso_.or.trperiod_.lt.60.d0.or.nutc.gt.2359 + if(present(utc_is_hhmmss)) full_time=full_time.or.utc_is_hhmmss str = '000000' - if (full_time.or.nutc.ge.100000) then + if (nutc .lt. 0) then + return + else if (full_time) then hh = nutc / 10000 mm = mod(nutc/100, 100) ss = mod(nutc, 100) write(str, '(i2.2,i2.2,i2.2)') hh, mm, ss - else if (nutc .ge. 0) then + else hh = nutc / 100 mm = mod(nutc, 100) write(str, '(i2.2,i2.2,a2)') hh, mm, '00' diff --git a/lib/streaming_io.f90 b/lib/streaming_io.f90 index a2c9fa28..ed1ac923 100644 --- a/lib/streaming_io.f90 +++ b/lib/streaming_io.f90 @@ -52,7 +52,7 @@ subroutine jt9_stream(shared_data, mode, TRperiod) use streaming_emit, only: streaming_emit_ready, & streaming_emit_decode_finished, streaming_emit_error, & streaming_emit_error_code, streaming_emit_error_version, & - streaming_emit_error_type + streaming_emit_error_type, streaming_emit_set_time_form use streaming_control, only: parse_control_frame, configure_fields, & control_type_error, CTRL_CONFIGURE, CTRL_HALT, CTRL_PARSE_ERR use streaming_apply, only: apply_configure_fields @@ -327,6 +327,7 @@ subroutine jt9_stream(shared_data, mode, TRperiod) prev_TRperiod = TRperiod call apply_configure_fields(cfg, mode, TRperiod, & shared_data%params, baseline_nfa, baseline_nfb) + call streaming_emit_set_time_form(cfg%utc_set, cfg%nutc_set, TRperiod) ! A configure that changes the applied mode or period starts a ! new period; what was in flight is discarded. Repeating the ! current configuration leaves the period alone. @@ -381,7 +382,7 @@ contains shared_data%params%nzhsym = 181 end if shared_data%params%kin = 64800 - if (mode .eq. 5 .or. mode .eq. 9 .or. mode .eq. 65 .or. mode .eq. 66 .or. & + if (mode .eq. 4 .or. mode .eq. 5 .or. mode .eq. 9 .or. mode .eq. 65 .or. mode .eq. 66 .or. & mode .eq. 240 .or. mode .eq. 241 .or. mode .eq. 242) & shared_data%params%kin = period%k diff --git a/lib/sync4.f90 b/lib/sync4.f90 deleted file mode 100644 index 9f7ceefc..00000000 --- a/lib/sync4.f90 +++ /dev/null @@ -1,146 +0,0 @@ -subroutine sync4(dat,jz,ntol,nfqso,mode,mode4,minwidth,dtx,dfx,snrx, & - snrsync,flip,width) - -! Synchronizes JT4 data, finding the best-fit DT and DF. - - parameter (NFFTMAX=2520) !Max length of FFTs - parameter (NHMAX=NFFTMAX/2) !Max length of power spectra - parameter (NSMAX=525) !Max number of half-symbol steps - integer ntol !Range of DF search - real dat(jz) - real s2(NHMAX,NSMAX) !2d spectrum, stepped by half-symbols - real ccfblue(-5:540) !CCF with pseudorandom sequence - real ccfred(NHMAX) !Peak of ccfblue, as function of freq - real red(NHMAX) !Peak of ccfblue, as function of freq - integer ipk1(1) - integer nch(7) - logical savered - equivalence (ipk1,ipk1a) - data nch/1,2,4,9,18,36,72/ - save - -! Do FFTs of twice symbol length, stepped by half symbols. Note that -! we have already downsampled the data by factor of 2. - nsym=207 - nfft=2520 - nh=nfft/2 - nq=nfft/4 - nsteps=jz/nq - 1 - df=0.5*11025.0/nfft - ftop=nfqso + 7*mode4*df - if(ftop.gt.11025.0/4.0) then - print*,'*** Rx Freq is set too high for this submode ***' - go to 900 - endif - - if(mode.eq.-999) width=0. !Silence compiler warning - - do j=1,nsteps !Compute spectrum for each step, get average - k=(j-1)*nq + 1 - call ps4(dat(k),nfft,s2(1,j)) - enddo - -! Set freq and lag ranges - ia=(nfqso-ntol)/df !Index of lowest tone, bottom of search range - ib=(nfqso+ntol)/df !Index of lowest tone, top of search range - iamin=nint(100.0/df) - if(ia.lt.iamin) ia=iamin - ibmax=nint(2700.0/df) - 6*mode4 - if(ib.gt.ibmax) ib=ibmax - - lag1=-5 - lag2=59 - syncbest=-1.e30 - snrx=-26.0 - ccfred=0. - red=0. - i0=nint(nfqso/df) - - do ich=minwidth,7 !Find best width - kz=nch(ich)/2 - savered=.false. - iaa=ia+kz - ibb=ib-kz - do i=iaa,ibb !Find best frequency channel for CCF - call xcor4(s2,i,nsteps,nsym,lag1,lag2,ich,mode4,ccfblue,ccf0, & - lagpk0,flip) - ccfred(i)=ccf0 - -! Find rms of the CCF, without main peak - call slope(ccfblue(lag1),lag2-lag1+1,lagpk0-lag1+1.0) - sync=abs(ccfblue(lagpk0)) -! write(*,3000) ich,i,i*df,ccf0,sync,syncbest -!3000 format(2i5,4f12.3) - -! Find best sync value - if(sync.gt.syncbest*1.03) then - ipk=i - lagpk=lagpk0 - ichpk=ich - syncbest=sync - savered=.true. - endif - enddo - if(savered) red=ccfred - enddo - if(syncbest.lt.-1.e29) go to 900 - ccfred=red - call pctile(ccfred(iaa:ibb),ibb-iaa+1,45,base) - ccfred=ccfred-base - - dfx=ipk*df - -! Peak up in time, at best whole-channel frequency - call xcor4(s2,ipk,nsteps,nsym,lag1,lag2,ichpk,mode4,ccfblue,ccfmax, & - lagpk,flip) - xlag=lagpk - if(lagpk.gt.lag1 .and. lagpk.lt.lag2) then - call peakup(ccfblue(lagpk-1),ccfmax,ccfblue(lagpk+1),dx2) - xlag=lagpk+dx2 - endif - -! Find rms of the CCF, without the main peak - call slope(ccfblue(lag1),lag2-lag1+1,xlag-lag1+1.0) - sq=0. - nsq=0 - do lag=lag1,lag2 - if(abs(lag-xlag).gt.2.0) then - sq=sq+ccfblue(lag)**2 - nsq=nsq+1 - endif - enddo - rms=sqrt(sq/nsq) - snrsync=max(0.0,db(abs(ccfblue(lagpk)/rms - 1.0)) - 4.5) - dt=2.0/11025.0 - istart=xlag*nq - dtx=istart*dt - - ipk1=maxloc(ccfred) - ccf10=0.5*maxval(ccfred) - do i=ipk1a,ia,-1 - if(ccfred(i).le.ccf10) exit - enddo - i1=i - do i=ipk1a,ib - if(ccfred(i).le.ccf10) exit - enddo - nw=i-i1 - width=nw*df - - sq=0. - ns=0 - iaa=max(ipk1a-10*nw,ia) - ibb=min(ipk1a+10*nw,ib) - jmax=2*mode4/3 - do i=iaa,ibb - j=abs(i-ipk1a) - if(j.gt.nw .and. j.lt.jmax) then - sq=sq + ccfred(j)*ccfred(j) - ns=ns+1 - endif - enddo - rms=sqrt(sq/ns) - snrx=10.0*log10(ccfred(ipk1a)/rms) - 41.2 - -900 return -end subroutine sync4 diff --git a/lib/xcor4.f90 b/lib/xcor4.f90 index fa9c2012..2dc2deb9 100644 --- a/lib/xcor4.f90 +++ b/lib/xcor4.f90 @@ -1,40 +1,22 @@ subroutine xcor4(s2,ipk,nsteps,nsym,lag1,lag2,ich,mode4,ccf,ccf0, & lagpk,flip) -! Computes ccf of the 4_FSK spectral array s2 and the pseudo-random -! array pr2. Returns peak of CCF and the lag at which peak occurs. +! Computes ccf of the 4_FSK spectral array s2 and the pseudo-random +! array pr2. Returns peak of CCF and the lag at which peak occurs. ! The CCF peak may be either positive or negative, with negative ! implying the "OOO" message. + use jt4, only: nch,npr parameter (NHMAX=1260) !Max length of power spectra parameter (NSMAX=525) !Max number of half-symbol steps real s2(NHMAX,NSMAX) !2d spectrum, stepped by half-symbols real a(NSMAX) real ccf(-5:540) - integer nch(7) - integer npr2(207) real pr2(207) - logical first - data lagmin/0/ !Silence compiler warning - data first/.true./ - data npr2/ & - 0,0,0,0,1,1,0,0,0,1,1,0,1,1,0,0,1,0,1,0,0,0,0,0,0,0,1,1,0,0, & - 0,0,0,0,0,0,0,0,0,0,1,0,1,1,0,1,1,0,1,0,1,1,1,1,1,0,1,0,0,0, & - 1,0,0,1,0,0,1,1,1,1,1,0,0,0,1,0,1,0,0,0,1,1,1,1,0,1,1,0,0,1, & - 0,0,0,1,1,0,1,0,1,0,1,0,1,0,1,1,1,1,1,0,1,0,1,0,1,1,0,1,0,1, & - 0,1,1,1,0,0,1,0,1,1,0,1,1,1,1,0,0,0,0,1,1,0,1,1,0,0,0,1,1,1, & - 0,1,1,1,0,1,1,1,0,0,1,0,0,0,1,1,0,1,1,0,0,1,0,0,0,1,1,1,1,1, & - 1,0,0,1,1,0,0,0,0,1,1,0,0,0,1,0,1,1,0,1,1,1,1,0,1,0,1/ - data nch/1,2,4,9,18,36,72/ - save - - if(first) then - do i=1,207 - pr2(i)=2*npr2(i)-1 - enddo - first=.false. - endif + pr2=2*npr-1 + lagpk=lag1 + lagmin=lag1 ccfmax=0. ccfmin=0. nw=nch(min(max(ich,1),7)) diff --git a/main.cpp b/main.cpp index d9546e48..594c851e 100644 --- a/main.cpp +++ b/main.cpp @@ -297,6 +297,7 @@ int main(int argc, char *argv[]) bool jtty_tx_loopback_test {false}; bool ft8_tx_loopback_test {false}; bool receive_handoff_test {false}; + bool jt4_wav_test {false}; bool jt9_wav_test {false}; bool jt65_wav_test {false}; bool q65_wav_test {false}; @@ -400,6 +401,14 @@ int main(int argc, char *argv[]) QStringList {} << "receive-handoff-test", "Backlog two synthetic periods at the MainWindow receive boundary."); parser.addOption (receive_handoff_test_option); + QCommandLineOption jt4_wav_test_option ( + QStringList {} << "jt4-wav-test", + "Decode a JT4 WAV through the application and repeat the decode.", "wav-path"); + parser.addOption (jt4_wav_test_option); + QCommandLineOption jt4_wav_expected_option ( + QStringList {} << "jt4-wav-expected", + "Message that must appear during both JT4 WAV decodes.", "message"); + parser.addOption (jt4_wav_expected_option); QCommandLineOption jt9_wav_test_option ( QStringList {} << "jt9-wav-test", "Decode a JT9 WAV through the application and repeat the decode.", "wav-path"); @@ -472,6 +481,7 @@ int main(int argc, char *argv[]) jtty_tx_loopback_test = parser.isSet (jtty_tx_loopback_test_option); ft8_tx_loopback_test = parser.isSet (ft8_tx_loopback_test_option); receive_handoff_test = parser.isSet (receive_handoff_test_option); + jt4_wav_test = parser.isSet (jt4_wav_test_option); jt9_wav_test = parser.isSet (jt9_wav_test_option); jt65_wav_test = parser.isSet (jt65_wav_test_option); q65_wav_test = parser.isSet (q65_wav_test_option); @@ -501,6 +511,13 @@ int main(int argc, char *argv[]) "must be used together" << std::endl; return EXIT_FAILURE; } + if (jt4_wav_test != parser.isSet (jt4_wav_expected_option) + || (jt4_wav_test && parser.value (jt4_wav_expected_option).trimmed ().isEmpty ())) + { + std::cerr << "--jt4-wav-test and a nonempty --jt4-wav-expected must be used together" + << std::endl; + return EXIT_FAILURE; + } if (jt9_wav_test != parser.isSet (jt9_wav_expected_option) || (jt9_wav_test && parser.value (jt9_wav_expected_option).trimmed ().isEmpty ())) { @@ -540,7 +557,7 @@ int main(int argc, char *argv[]) + (jtty_live_audio_test ? 1 : 0) + (jtty_tx_loopback_test ? 1 : 0) + (ft8_tx_loopback_test ? 1 : 0) - + (receive_handoff_test ? 1 : 0) + (jt9_wav_test ? 1 : 0) + + (receive_handoff_test ? 1 : 0) + (jt4_wav_test ? 1 : 0) + (jt9_wav_test ? 1 : 0) + (jt65_wav_test ? 1 : 0) + (q65_wav_test ? 1 : 0) + (fst4_wav_test ? 1 : 0) + (fst4w_wav_test ? 1 : 0) > 1) { @@ -563,7 +580,7 @@ int main(int argc, char *argv[]) } automated_test = startup_smoke_test || live_audio_test || jtty_live_audio_test || jtty_tx_loopback_test || ft8_tx_loopback_test - || receive_handoff_test || jt9_wav_test || jt65_wav_test || q65_wav_test || fst4_wav_test || fst4w_wav_test; + || receive_handoff_test || jt4_wav_test || jt9_wav_test || jt65_wav_test || q65_wav_test || fst4_wav_test || fst4w_wav_test; #else automated_test = startup_smoke_test; #endif @@ -997,19 +1014,22 @@ int main(int argc, char *argv[]) controller->begin (); }); } - if (jt9_wav_test || jt65_wav_test || q65_wav_test || fst4_wav_test || fst4w_wav_test) + if (jt4_wav_test || jt9_wav_test || jt65_wav_test || q65_wav_test || fst4_wav_test || fst4w_wav_test) { a.setQuitOnLastWindowClosed (false); wav_decode_controller.reset (new WavDecodeTestController { - &w, parser.value (jt9_wav_test ? jt9_wav_test_option + &w, parser.value (jt4_wav_test ? jt4_wav_test_option + : jt9_wav_test ? jt9_wav_test_option : jt65_wav_test ? jt65_wav_test_option : q65_wav_test ? q65_wav_test_option : fst4_wav_test ? fst4_wav_test_option : fst4w_wav_test_option), - parser.value (jt9_wav_test ? jt9_wav_expected_option + parser.value (jt4_wav_test ? jt4_wav_expected_option + : jt9_wav_test ? jt9_wav_expected_option : jt65_wav_test ? jt65_wav_expected_option : q65_wav_test ? q65_wav_expected_option : fst4_wav_test ? fst4_wav_expected_option : fst4w_wav_expected_option), - jt9_wav_test ? WavDecodeTestController::Mode::Jt9 + jt4_wav_test ? WavDecodeTestController::Mode::Jt4 + : jt9_wav_test ? WavDecodeTestController::Mode::Jt9 : jt65_wav_test ? WavDecodeTestController::Mode::Jt65 : q65_wav_test ? WavDecodeTestController::Mode::Q65 : fst4_wav_test ? WavDecodeTestController::Mode::Fst4 @@ -1100,7 +1120,7 @@ int main(int argc, char *argv[]) { result = EXIT_FAILURE; } - if ((jt9_wav_test || jt65_wav_test || q65_wav_test || fst4_wav_test || fst4w_wav_test) + if ((jt4_wav_test || jt9_wav_test || jt65_wav_test || q65_wav_test || fst4_wav_test || fst4w_wav_test) && (!wav_decode_controller || !wav_decode_controller->succeeded ())) { result = EXIT_FAILURE; diff --git a/map65/commons.cpp b/map65/commons.cpp index 74c69b74..bbef8ed0 100644 --- a/map65/commons.cpp +++ b/map65/commons.cpp @@ -4,8 +4,5 @@ extern "C" { float* dd = nullptr; float* ss = nullptr; float* savg = nullptr; - float* dd_old = nullptr; - float* ss_old = nullptr; - float* savg_old = nullptr; } diff --git a/map65/commons.h b/map65/commons.h index 8938348e..b469b4a9 100644 --- a/map65/commons.h +++ b/map65/commons.h @@ -57,9 +57,6 @@ extern struct { //This is "common/datcom/..." in Fortran extern float* dd; extern float* ss; extern float* savg; - extern float* dd_old; - extern float* ss_old; - extern float* savg_old; extern int manualDecodeFlag ; double get_fcenter(); void get_mycall(char*); @@ -100,9 +97,7 @@ extern struct { //This is "common/datcom/..." in Fortran void set_dd_ptr(void* ptr, int dim1, int dim2); void set_ss_ptr(void* ptr, int dim1, int dim2, int dim3); void set_savg_ptr(void* ptr, int dim1, int dim2); - void set_dd_old_ptr(void* ptr, int dim1, int dim2); - void set_ss_old_ptr(void* ptr, int dim1, int dim2, int dim3); - void set_savg_old_ptr(void* ptr, int dim1, int dim2); + void set_snap_ptr(int idx, void* dd_ptr, void* ss_ptr, void* savg_ptr, int ndd, int nfft); void set_fcenter(double); void set_map65RxLog(int); void set_nutc(int); @@ -152,7 +147,7 @@ extern struct { //This is "common/datcom/..." in Fortran int buf_size, intptr_t event_handle); void set_manual_decode_flag(int); - void snapshot_buffers(); + void snapshot_buffers(int idx, int ksamp, int nhsym_snap); } extern QStringList allDecodes2; diff --git a/map65/libm65/CMakeLists.txt b/map65/libm65/CMakeLists.txt index 9ae45c54..3269c2c6 100644 --- a/map65/libm65/CMakeLists.txt +++ b/map65/libm65/CMakeLists.txt @@ -333,6 +333,11 @@ if (WSJT_ENABLE_TESTS) target_link_libraries (test_map65_symspec_contract PRIVATE m65impl) add_test (NAME test_map65_symspec_96 COMMAND test_map65_symspec_contract 96000) add_test (NAME test_map65_symspec_192 COMMAND test_map65_symspec_contract 192000) + add_executable (test_map65_pass_snapshots + ${CMAKE_SOURCE_DIR}/tests/unit/map65/test_map65_pass_snapshots.f90) + target_include_directories (test_map65_pass_snapshots PRIVATE ${CMAKE_CURRENT_BINARY_DIR}) + target_link_libraries (test_map65_pass_snapshots PRIVATE m65impl) + add_test (NAME test_map65_pass_snapshots COMMAND test_map65_pass_snapshots) add_executable (test_map65_q65_handoff ${CMAKE_SOURCE_DIR}/tests/unit/map65/test_map65_q65_handoff.f90) diff --git a/map65/libm65/datcom_ptrs_mod.f90 b/map65/libm65/datcom_ptrs_mod.f90 index a507168e..a4f94b37 100644 --- a/map65/libm65/datcom_ptrs_mod.f90 +++ b/map65/libm65/datcom_ptrs_mod.f90 @@ -1,14 +1,29 @@ module datcom_ptrs_mod use iso_c_binding + use debug_log, only: dbg, itoa + use npar_ptrs_mod, only: snapshot_fill_begin, snapshot_fill_end implicit none ! Fortran pointer targets real(c_float), pointer, contiguous :: dd(:,:) => null() ! [4, 5760000] real(c_float), pointer, contiguous :: ss(:,:,:) => null() ! [4, 322, NFFT] real(c_float), pointer, contiguous :: savg(:,:) => null() ! [4, NFFT] - real(c_float), pointer, contiguous :: dd_old(:,:) => null() ! [4, 5760000] - real(c_float), pointer, contiguous :: ss_old(:,:,:) => null() ! [4, 322, NFFT] - real(c_float), pointer, contiguous :: savg_old(:,:) => null() ! [4, NFFT] + + ! Two decoder snapshot sets, one per automatic pass (1 = early, nhsym1=280; + ! 2 = final, nhsym2=302). Each is filled by snapshot_buffers() at the moment + ! its pass is triggered, before the live buffers can be reset for the next + ! cycle, so a late-starting pass still decodes complete data. + type :: snap_set + real(c_float), pointer, contiguous :: dd(:,:) => null() ! [4, nsmax] + real(c_float), pointer, contiguous :: ss(:,:,:) => null() ! [4, 322, NFFT] + real(c_float), pointer, contiguous :: savg(:,:) => null() ! [4, NFFT] + end type snap_set + type(snap_set), save :: snap(2) + + ! Snapshot selected for the pass now being decoded (set by decode0) + real(c_float), pointer, contiguous :: dd_old(:,:) => null() + real(c_float), pointer, contiguous :: ss_old(:,:,:) => null() + real(c_float), pointer, contiguous :: savg_old(:,:) => null() ! Pointers used by decode0 / narrowband decoder real(c_float), pointer, contiguous :: dd_use(:,:) => null() @@ -21,10 +36,30 @@ module datcom_ptrs_mod contains - subroutine snapshot_buffers() bind(C) - dd_old(:,:) = dd(:,:) - ss_old(:,:,:) = ss(:,:,:) - savg_old(:,:) = savg(:,:) + ! Copy the live buffers into snapshot set idx (1 or 2). Called from dataSink() + ! on the GUI thread, which is also the thread that runs symspec, so ss and + ! savg cannot change during the copy. The sound-in thread writes dd only + ! forward of ksamp, so dd(:,1:ksamp+lookahead) is stable. + subroutine snapshot_buffers(idx, ksamp, nhsym_snap) bind(C, name="snapshot_buffers") + integer(c_int), value :: idx, ksamp, nhsym_snap + integer :: ncopy, ncol + logical :: ok + integer, parameter :: lookahead = 512 ! live_lookahead_samples in symspec + if (idx < 1 .or. idx > 2) return + call snapshot_fill_begin(idx, ok) + if (.not. ok) then + call dbg('snapshot ' // itoa(idx) // ' skipped: slot still in use by the running pass') + return + endif + if (.not. associated(snap(idx)%dd) .or. .not. associated(dd)) return + ncopy = max(0, min(size(dd,2), ksamp + lookahead)) + ncol = max(0, min(size(ss,2), nhsym_snap)) + snap(idx)%dd(:,1:ncopy) = dd(:,1:ncopy) + snap(idx)%dd(:,ncopy+1:) = 0. + snap(idx)%ss(:,1:ncol,:) = ss(:,1:ncol,:) + snap(idx)%ss(:,ncol+1:,:) = 0. + snap(idx)%savg(:,:) = savg(:,:) + call snapshot_fill_end(idx) end subroutine ! Helper subroutine to copy fixed-length Fortran string to C buffer @@ -67,31 +102,15 @@ contains print *, "Fortran: savg pointer associated with dimensions", dim1, dim2 end subroutine - subroutine set_dd_old_ptr(ptr, dim1, dim2) bind(C, name="set_dd_old_ptr") - use iso_c_binding - implicit none - type(c_ptr), value :: ptr - integer(c_int), value :: dim1, dim2 - call c_f_pointer(ptr, dd_old, [dim1, dim2]) - print *, "Fortran: dd_old pointer associated with dimensions", dim1, dim2 - end subroutine - - subroutine set_ss_old_ptr(ptr, dim1, dim2, dim3) bind(C, name="set_ss_old_ptr") + subroutine set_snap_ptr(idx, dd_ptr, ss_ptr, savg_ptr, ndd, nfft_s) bind(C, name="set_snap_ptr") use iso_c_binding implicit none - type(c_ptr), value :: ptr - integer(c_int), value :: dim1, dim2, dim3 - call c_f_pointer(ptr, ss_old, [dim1, dim2, dim3]) - print *, "Fortran: ss_old pointer associated with dimensions", dim1, dim2, dim3 - end subroutine - - subroutine set_savg_old_ptr(ptr, dim1, dim2) bind(C, name="set_savg_old_ptr") - use iso_c_binding - implicit none - type(c_ptr), value :: ptr - integer(c_int), value :: dim1, dim2 - call c_f_pointer(ptr, savg_old, [dim1, dim2]) - print *, "Fortran: savg_old pointer associated with dimensions", dim1, dim2 + integer(c_int), value :: idx, ndd, nfft_s + type(c_ptr), value :: dd_ptr, ss_ptr, savg_ptr + if (idx < 1 .or. idx > 2) return + call c_f_pointer(dd_ptr, snap(idx)%dd, [4, ndd]) + call c_f_pointer(ss_ptr, snap(idx)%ss, [4, 322, nfft_s]) + call c_f_pointer(savg_ptr, snap(idx)%savg, [4, nfft_s]) end subroutine function get_junk1() bind(C, name="get_junk1") diff --git a/map65/libm65/decode0.f90 b/map65/libm65/decode0.f90 index cdb8799b..1e217501 100644 --- a/map65/libm65/decode0.f90 +++ b/map65/libm65/decode0.f90 @@ -7,7 +7,7 @@ contains use iso_c_binding, only: c_int use timer_module, only: timer use npar_ptrs_mod - use datcom_ptrs_mod, only: NFFT, dd, dd_old, dd_use, ss, ss_old, savg, savg_old, ss_use, savg_use + use datcom_ptrs_mod, only: NFFT, dd_old, dd_use, ss_old, savg_old, ss_use, savg_use, snap use debug_log, only: dbg, itoa, rtoa use sec_midn_mod, only: sec_midn use map65a_mod @@ -25,6 +25,7 @@ contains integer nz integer :: nhsym0 integer :: newdat0 + integer :: isnap character(len=128) :: line character mycall0*12, hiscall0*12, hisgrid0*6 logical :: first_mcall3b_check @@ -47,25 +48,29 @@ contains ! newdat is forced to 1 by decode() for every call (manual or ! automatic); it does not by itself mean "the live buffers just - ! finished a fresh accumulation." nagain=1 marks a manual repeat - ! (Decode button / Find Delta Phi), which must not refresh dd_old - ! from a live buffer that may still be mid-fill. - if (newdat0 /= 0 .and. manualDecodeFlag == 0 .and. nagain == 0) then - dd_old = dd - ss_old = ss - savg_old = savg - call dbg('decode0: dd_old REFRESHED from live dd at t=' // rtoa(sec_midn()) // ' nhsym0=' // itoa(nhsym0)) - else - call dbg('decode0: dd_old NOT refreshed (reusing prior snapshot) at t=' // rtoa(sec_midn()) // & - ' nhsym0=' // itoa(nhsym0) // ' nagain=' // itoa(nagain)) - endif + ! finished a fresh accumulation." + ! + ! Each automatic pass decodes its own snapshot, taken by dataSink() at + ! the instant the pass was triggered (snap(1) at nhsym1, snap(2) at + ! nhsym2). decode0 never copies from the live buffers, so a pass that + ! starts late (queued behind a still-running pass) cannot see data the + ! audio thread has already reset for the next cycle. Manual repeats + ! (nagain=1, Decode button / Find Delta Phi) reuse the most recently + ! filled snapshot. + isnap = active_snap_idx ! slot claimed with this request + if (isnap < 1) isnap = 2 + call dbg('decode0: using snapshot ' // itoa(isnap) // ' at t=' // rtoa(sec_midn()) // & + ' nhsym0=' // itoa(nhsym0) // ' nagain=' // itoa(nagain)) + dd_old => snap(isnap)%dd + ss_old => snap(isnap)%ss + savg_old => snap(isnap)%savg nkeep = min(max(ntimeout, 10), 40) call sec0(0, tquick) call timer('decode0 ', 0) - ! Always decode from the snapshot (dd_old/ss_old/savg_old) taken above, + ! Always decode from the snapshot selected above (dd_old/ss_old/savg_old), ! never the live dd/ss/savg. The nhsym2 pass routinely runs past the ! minute boundary (several seconds), and symspec_() on the GUI thread ! resets/overwrites the live buffers for the next cycle unconditionally diff --git a/map65/libm65/npar_ptrs_mod.f90 b/map65/libm65/npar_ptrs_mod.f90 index 10c9b904..99bde665 100644 --- a/map65/libm65/npar_ptrs_mod.f90 +++ b/map65/libm65/npar_ptrs_mod.f90 @@ -60,9 +60,13 @@ module npar_ptrs_mod ! newdat = 1 in that copy) and clears ! draft%manualDecodeFlag ! claim_decode_request() copies the oldest request into active; an - ! automatic live request whose input generation - ! is out of date is marked expired, and run_m65 - ! skips it () + ! automatic request is marked expired, and run_m65 + ! skips it (), when the data + ! snapshot it was published with has been + ! overwritten or never filled (or, for requests + ! without a snapshot, when its input generation + ! is out of date). A request whose snapshot is + ! intact still runs after the minute rolls over. ! initialize_decode_parameters() copies draft into active once, at startup ! The decoder then sees a consistent snapshot for the whole pass, even if ! the GUI changes draft meanwhile. @@ -96,6 +100,8 @@ module npar_ptrs_mod type(decode_parameters) :: parameters integer(c_int64_t) :: id integer(c_int64_t) :: input_generation + integer(c_int) :: snap_idx = 0 ! snapshot slot (1 = nhsym1, 2 = nhsym2); 0 = none + integer(c_int64_t) :: snap_seq = 0 ! fill number of that slot when published type(decode_request), pointer :: next => null() end type type(decode_request), pointer, save :: pending_head => null(), pending_tail => null() @@ -105,6 +111,19 @@ module npar_ptrs_mod integer(c_int64_t), save :: active_input_generation = 0 logical, save :: active_request_expired = .false. + ! Decoder data snapshots (see datcom_ptrs_mod). All of this state is + ! protected by lock_decode_requests(). + ! snap_seq(i) fill number, bumped each time slot i is (re)filled + ! snap_valid_seq(i) fill number whose contents are intact; 0 while a fill + ! is in progress or after a fill was skipped + ! snap_busy(i) slot i is being read by the running decode pass; a fill + ! is skipped rather than overwrite it + integer(c_int64_t), save :: snap_seq(2) = 0 + integer(c_int64_t), save :: snap_valid_seq(2) = 0 + logical, save :: snap_busy(2) = .false. + integer(c_int), save :: snap_latest_idx = 0 ! most recently completed fill + integer(c_int), save :: active_snap_idx = 0 ! slot read by the active pass + real(c_double), pointer :: fcenter => active%fcenter real(c_double), pointer :: ftol_nb => active%ftol_nb integer(c_int), pointer :: nfa => active%nfa @@ -781,6 +800,16 @@ end subroutine request%input_generation = live_input_generation request%parameters = draft request%parameters%newdat = 1 + ! Automatic passes (nhsym1/nhsym2) were just snapshotted by dataSink(); + ! remember which slot and fill they own. Manual repeats use the latest. + if (draft%manualDecodeFlag == 0 .and. draft%nagain == 0 .and. & + (draft%nhsym == 280 .or. draft%nhsym == 302)) then + request%snap_idx = merge(1, 2, draft%nhsym == 280) + request%snap_seq = snap_seq(request%snap_idx) + ! No fill has ever happened for this slot (no snapshot support in the + ! caller): fall back to the input-generation rule. + if (request%snap_seq == 0) request%snap_idx = 0 + endif if (associated(pending_tail)) then pending_tail%next => request else @@ -804,8 +833,26 @@ end subroutine active = request%parameters active_request_id = request%id active_input_generation = request%input_generation - active_request_expired = active%ndiskdat == 0 .and. active%nagain == 0 .and. & - active%manualDecodeFlag == 0 .and. request%input_generation /= live_input_generation + active_snap_idx = 0 + if (request%snap_idx > 0) then + ! Automatic pass: valid while its snapshot is intact, even if the + ! minute has rolled over. A live request more than one generation old + ! (monitoring stopped, period changed) is still dropped. + active_request_expired = snap_valid_seq(request%snap_idx) /= request%snap_seq + if (active%ndiskdat == 0 .and. & + live_input_generation - request%input_generation >= 2) active_request_expired = .true. + if (.not. active_request_expired) then + active_snap_idx = request%snap_idx + snap_busy(active_snap_idx) = .true. + endif + else + active_request_expired = active%ndiskdat == 0 .and. active%nagain == 0 .and. & + active%manualDecodeFlag == 0 .and. request%input_generation /= live_input_generation + if (.not. active_request_expired .and. snap_latest_idx > 0) then + active_snap_idx = snap_latest_idx ! manual repeat: latest snapshot + snap_busy(active_snap_idx) = .true. + endif + endif deallocate(request) endif call unlock_decode_requests() @@ -817,6 +864,34 @@ end subroutine call unlock_decode_requests() end subroutine + ! A snapshot fill starts: invalidate the slot's contents and say whether the + ! copy may proceed (ok = .false. when the running pass is still reading it). + subroutine snapshot_fill_begin(idx, ok) + integer, intent(in) :: idx + logical, intent(out) :: ok + call lock_decode_requests() + snap_seq(idx) = snap_seq(idx) + 1 + snap_valid_seq(idx) = 0 + ok = .not. snap_busy(idx) + call unlock_decode_requests() + end subroutine + + subroutine snapshot_fill_end(idx) + integer, intent(in) :: idx + call lock_decode_requests() + snap_valid_seq(idx) = snap_seq(idx) + snap_latest_idx = idx + call unlock_decode_requests() + end subroutine + + ! The active pass is finished with its snapshot slot. + subroutine snapshot_release() + call lock_decode_requests() + if (active_snap_idx > 0) snap_busy(active_snap_idx) = .false. + active_snap_idx = 0 + call unlock_decode_requests() + end subroutine + subroutine advance_live_input_generation() bind(C) call lock_decode_requests() live_input_generation = live_input_generation + 1 diff --git a/map65/libm65/run_m65.f90 b/map65/libm65/run_m65.f90 index cc0ffe73..14042016 100644 --- a/map65/libm65/run_m65.f90 +++ b/map65/libm65/run_m65.f90 @@ -9,7 +9,7 @@ subroutine run_m65(pol, sample_rate_96000) bind(C, name='run_m65_') use timer_impl, only: init_timer, fini_timer use debug_log use m65a_mod - use npar_ptrs_mod, only: t_start, nhsym, mycall, hiscall, hisgrid, neme, & + use npar_ptrs_mod, only: snapshot_release, t_start, nhsym, mycall, hiscall, hisgrid, neme, & initialize_decode_parameters, claim_decode_request, get_stop_m65, & active_request_id, active_request_expired use stdout_channel_mod, only: write_stdout @@ -88,6 +88,7 @@ subroutine run_m65(pol, sample_rate_96000) bind(C, name='run_m65_') call system_clock(t_start, t_rate) call m65a() call system_clock(t_now) + call snapshot_release() call dbg('run_m65: request completed, elapsed=' // rtoa(real(t_now - t_start)/real(t_rate))) endif endif diff --git a/map65/mainwindow.cpp b/map65/mainwindow.cpp index e9a0e6d6..5e88572e 100644 --- a/map65/mainwindow.cpp +++ b/map65/mainwindow.cpp @@ -157,12 +157,14 @@ MainWindow::MainWindow(QWidget *parent) : std::cout << "ss pointer set to: " << ss << std::endl; set_savg_ptr(savg, 4, active_nfft); std::cout << "savg pointer set to: " << savg << std::endl; - dd_old = new float[ddSize]; - set_dd_old_ptr(dd_old, channels, pairsWorst); - ss_old = new float[4 * 322 * active_nfft]; - savg_old = new float[4 * active_nfft]; - set_ss_old_ptr(ss_old, 4, 322, active_nfft); - set_savg_old_ptr(savg_old, 4, active_nfft); + // Two snapshot sets, one per automatic decode pass (1 = nhsym 280, 2 = nhsym 302). + // They are filled in dataSink() at each trigger; see snapshot_buffers(). + for (int idx = 1; idx <= 2; idx++) { + float* sdd = new float[ddSize](); + float* sss = new float[4 * 322 * active_nfft](); + float* ssavg = new float[4 * active_nfft](); + set_snap_ptr(idx, sdd, sss, ssavg, pairsWorst, active_nfft); + } qDebug() << "MAINWINDOW created dd ss savg "; @@ -1302,6 +1304,7 @@ void MainWindow::dataSink(int k) setNewdat(1); setNagain(0); setNhsym(280); + snapshot_buffers(1, k, 280); //Freeze this pass's data now QDateTime t = QDateTime::currentDateTimeUtc(); m_dateTime=t.toString("yyyy-MMM-dd hh:mm"); decode(); //Start the decoder @@ -1314,6 +1317,7 @@ void MainWindow::dataSink(int k) setNewdat(1); setNagain(0); setNhsym(302); + snapshot_buffers(2, k, 302); //Freeze this pass's data now QDateTime t = QDateTime::currentDateTimeUtc(); m_dateTime=t.toString("yyyy-MMM-dd hh:mm"); decode(); //Start the decoder diff --git a/release-state.txt b/release-state.txt index 327836e0..5519575d 100644 --- a/release-state.txt +++ b/release-state.txt @@ -1,5 +1,5 @@ version=3.3.0 channel=BETA -prerelease=1 -revision=57ba9337fa020065dc0ceee2c4ef85e433ea32d4 +prerelease=2 +revision=9d059511f77e2d1be746ebfeaa7f88e77c1babb7 windows_signing=unsigned diff --git a/test/fixtures/jt4_OK1KIR_141105_175700.expected.txt b/test/fixtures/jt4_OK1KIR_141105_175700.expected.txt index 5add3711..97837102 100644 --- a/test/fixtures/jt4_OK1KIR_141105_175700.expected.txt +++ b/test/fixtures/jt4_OK1KIR_141105_175700.expected.txt @@ -1,2 +1,2 @@ -**** -14 1.8 1199 $# G3WDG OK1KIR RRR f +1757 -14 1.8 1199 $# G3WDG OK1KIR RRR f 0 1 0 diff --git a/tests/integration/decoder_engine/run_wav_gui.cmake b/tests/integration/decoder_engine/run_wav_gui.cmake index 88979815..a4204886 100644 --- a/tests/integration/decoder_engine/run_wav_gui.cmake +++ b/tests/integration/decoder_engine/run_wav_gui.cmake @@ -1,9 +1,10 @@ if (NOT DEFINED MODE) set (MODE JT9) endif () -if (NOT MODE STREQUAL "JT9" AND NOT MODE STREQUAL "JT65" AND NOT MODE STREQUAL "Q65" +if (NOT MODE STREQUAL "JT4" AND NOT MODE STREQUAL "JT9" AND NOT MODE STREQUAL "JT65" + AND NOT MODE STREQUAL "Q65" AND NOT MODE STREQUAL "FST4" AND NOT MODE STREQUAL "FST4W") - message (FATAL_ERROR "MODE must be JT9, JT65, Q65, FST4, or FST4W") + message (FATAL_ERROR "MODE must be JT4, JT9, JT65, Q65, FST4, or FST4W") endif () string (TOLOWER "${MODE}" mode_option) diff --git a/tests/integration/jt9/verify_jt4_12000_read_extent.cmake b/tests/integration/jt9/verify_jt4_12000_read_extent.cmake index 7011cc39..64f6fa33 100644 --- a/tests/integration/jt9/verify_jt4_12000_read_extent.cmake +++ b/tests/integration/jt9/verify_jt4_12000_read_extent.cmake @@ -1,22 +1,32 @@ -foreach (required_variable JT9 JT4SIM WORK_DIR) +foreach (required_variable JT9 WORK_DIR) if (NOT DEFINED ${required_variable} OR "${${required_variable}}" STREQUAL "") message (FATAL_ERROR "${required_variable} is required") endif () endforeach () file (MAKE_DIRECTORY "${WORK_DIR}") -execute_process ( - COMMAND "${JT4SIM}" "G3WDG OK1KIR RRR" F 1 0 0 1 99 - WORKING_DIRECTORY "${WORK_DIR}" - RESULT_VARIABLE simulator_result - OUTPUT_QUIET - ERROR_VARIABLE simulator_stderr) -if (NOT "${simulator_result}" STREQUAL "0") - message (FATAL_ERROR - "jt4sim exited with ${simulator_result}\n${simulator_stderr}") +if (DEFINED JT4_WAV AND NOT "${JT4_WAV}" STREQUAL "") + set (full_wav "${JT4_WAV}") + set (submode A) + set (expected_message "K1ABC W9XYZ FN42") +else () + if (NOT DEFINED JT4SIM OR "${JT4SIM}" STREQUAL "") + message (FATAL_ERROR "JT4_WAV or JT4SIM is required") + endif () + execute_process ( + COMMAND "${JT4SIM}" "G3WDG OK1KIR RRR" F 1 0 0 1 99 + WORKING_DIRECTORY "${WORK_DIR}" + RESULT_VARIABLE simulator_result + OUTPUT_QUIET + ERROR_VARIABLE simulator_stderr) + if (NOT "${simulator_result}" STREQUAL "0") + message (FATAL_ERROR + "jt4sim exited with ${simulator_result}\n${simulator_stderr}") + endif () + set (full_wav "${WORK_DIR}/000000_0001.wav") + set (submode F) + set (expected_message "G3WDG OK1KIR RRR") endif () - -set (full_wav "${WORK_DIR}/000000_0001.wav") set (truncated_wav "${WORK_DIR}/000000_0001_truncated.wav") # Keep enough samples to distinguish a complete JT4 read from premature termination. set (truncate_script [=[ @@ -47,7 +57,7 @@ execute_process ( COMMAND "${JT9}" -a "${WORK_DIR}" -t "${WORK_DIR}" - --jt4 -b F -f 1000 -d 3 + --jt4 -b "${submode}" -f 1000 -d 3 "${truncated_wav}" WORKING_DIRECTORY "${WORK_DIR}" RESULT_VARIABLE decoder_result @@ -59,6 +69,9 @@ if (NOT "${decoder_result}" STREQUAL "0") "stdout:\n${decoder_stdout}\n" "stderr:\n${decoder_stderr}") endif () +if (NOT "${decoder_stdout}" MATCHES "${expected_message}") + message (FATAL_ERROR "Truncated JT4 recording did not decode:\n${decoder_stdout}") +endif () if (NOT "${decoder_stdout}" MATCHES "EOF on input file") message (FATAL_ERROR "jt9 did not read beyond the obsolete 570240-sample cutoff\n" diff --git a/tests/integration/jt9/verify_jt4_engine.cmake b/tests/integration/jt9/verify_jt4_engine.cmake new file mode 100644 index 00000000..45f5226c --- /dev/null +++ b/tests/integration/jt9/verify_jt4_engine.cmake @@ -0,0 +1,19 @@ +if (NOT DEFINED JT9_EXECUTABLE OR NOT DEFINED JT4_WAV OR NOT DEFINED TEST_DIRECTORY) + message (FATAL_ERROR "JT4 engine test requires JT9_EXECUTABLE, JT4_WAV and TEST_DIRECTORY") +endif () +file (MAKE_DIRECTORY "${TEST_DIRECTORY}") +execute_process (COMMAND "${JT9_EXECUTABLE}" --jt4 -b A -f 1000 -d 1 + -a "${TEST_DIRECTORY}" -t "${TEST_DIRECTORY}" "${JT4_WAV}" + WORKING_DIRECTORY "${TEST_DIRECTORY}" + RESULT_VARIABLE status OUTPUT_VARIABLE output ERROR_VARIABLE error TIMEOUT 60) +if (NOT status EQUAL 0) + message (FATAL_ERROR "JT4 CLI failed (${status}): ${error}\n${output}") +endif () +if (NOT output MATCHES "K1ABC W9XYZ FN42") + message (FATAL_ERROR "JT4 CLI did not decode the generated recording:\n${output}\n${error}") +endif () +string (REGEX MATCHALL "K1ABC W9XYZ FN42" messages "${output}") +list (LENGTH messages count) +if (NOT count EQUAL 1 OR NOT output MATCHES "[^\n]*[ ]1[ ]+0") + message (FATAL_ERROR "JT4 CLI produced unexpected messages/completion:\n${output}") +endif () diff --git a/tests/unit/decoder_engine/CMakeLists.txt b/tests/unit/decoder_engine/CMakeLists.txt index c2546109..82965b4b 100644 --- a/tests/unit/decoder_engine/CMakeLists.txt +++ b/tests/unit/decoder_engine/CMakeLists.txt @@ -10,6 +10,9 @@ target_include_directories (test_decoder_engine PRIVATE ${CMAKE_SOURCE_DIR}) target_link_libraries (test_decoder_engine PRIVATE test_decoder_engine_signal) add_test (NAME test_decoder_engine COMMAND test_decoder_engine) set_tests_properties (test_decoder_engine PROPERTIES TIMEOUT 90) +add_test (NAME prepare_ft8_engine_wav COMMAND test_decoder_engine + --write-wav ${CMAKE_CURRENT_BINARY_DIR}/ft8-engine.wav) +set_tests_properties (prepare_ft8_engine_wav PROPERTIES FIXTURES_SETUP ft8_engine_wav TIMEOUT 15) add_executable (test_decoder_engine_ft4 test_decoder_engine_ft4.c) set_target_properties (test_decoder_engine_ft4 PROPERTIES LINKER_LANGUAGE CXX) @@ -220,3 +223,56 @@ if (TARGET wsjt_fort_omp) set_tests_properties (test_decoder_engine_fst4_omp PROPERTIES TIMEOUT 360 PROCESSORS 2 ENVIRONMENT "OMP_DYNAMIC=FALSE;OMP_NUM_THREADS=2;OMP_THREAD_LIMIT=2;OMP_STACKSIZE=1M") endif () + +add_library (test_decoder_engine_jt4_signal STATIC jt4_engine_signal.f90) +wsjt_link_common_fortran (test_decoder_engine_jt4_signal) +add_executable (test_decoder_engine_jt4 test_decoder_engine_jt4.c) +set_target_properties (test_decoder_engine_jt4 PROPERTIES LINKER_LANGUAGE CXX) +target_include_directories (test_decoder_engine_jt4 PRIVATE ${CMAKE_SOURCE_DIR}) +target_link_libraries (test_decoder_engine_jt4 PRIVATE test_decoder_engine_jt4_signal Threads::Threads) +add_test (NAME test_decoder_engine_jt4 COMMAND test_decoder_engine_jt4 --small-stack) +set_tests_properties (test_decoder_engine_jt4 PROPERTIES TIMEOUT 180 + ENVIRONMENT "OMP_DYNAMIC=FALSE;OMP_NUM_THREADS=1;OMP_THREAD_LIMIT=1;OMP_STACKSIZE=1M") +add_executable (test_decoder_engine_jt4_state test_decoder_engine_jt4_state.f90) +set_target_properties (test_decoder_engine_jt4_state PROPERTIES LINKER_LANGUAGE CXX) +wsjt_link_common_fortran (test_decoder_engine_jt4_state) +add_test (NAME test_decoder_engine_jt4_state COMMAND test_decoder_engine_jt4_state) +set_tests_properties (test_decoder_engine_jt4_state PROPERTIES TIMEOUT 30) +add_test (NAME prepare_jt4_engine_wav COMMAND test_decoder_engine_jt4 + --write-wav ${CMAKE_CURRENT_BINARY_DIR}/jt4-engine.wav) +set_tests_properties (prepare_jt4_engine_wav PROPERTIES FIXTURES_SETUP jt4_engine_wav TIMEOUT 15) +if (TARGET wsjt_fort_omp AND TARGET wsjt_fort) + add_library (test_decoder_engine_jt4_signal_omp STATIC jt4_engine_signal.f90) + target_link_libraries (test_decoder_engine_jt4_signal_omp PUBLIC wsjt_fort_omp wsjt_fortran_openmp) + add_executable (test_decoder_engine_jt4_omp test_decoder_engine_jt4.c) + set_target_properties (test_decoder_engine_jt4_omp PROPERTIES LINKER_LANGUAGE CXX) + target_include_directories (test_decoder_engine_jt4_omp PRIVATE ${CMAKE_SOURCE_DIR}) + target_link_libraries (test_decoder_engine_jt4_omp PRIVATE test_decoder_engine_jt4_signal_omp Threads::Threads) + add_test (NAME test_decoder_engine_jt4_omp COMMAND test_decoder_engine_jt4_omp --smoke) + set_tests_properties (test_decoder_engine_jt4_omp PROPERTIES TIMEOUT 90 + ENVIRONMENT "OMP_DYNAMIC=FALSE;OMP_NUM_THREADS=1;OMP_THREAD_LIMIT=1;OMP_STACKSIZE=1M") +endif () + +add_test (NAME test_jt4_engine_cli COMMAND ${CMAKE_COMMAND} + "-DJT9_EXECUTABLE=$" + "-DJT4_WAV=${CMAKE_CURRENT_BINARY_DIR}/jt4-engine.wav" + "-DTEST_DIRECTORY=${CMAKE_CURRENT_BINARY_DIR}/jt4-cli" + -P ${CMAKE_SOURCE_DIR}/tests/integration/jt9/verify_jt4_engine.cmake) +set_tests_properties (test_jt4_engine_cli PROPERTIES FIXTURES_REQUIRED jt4_engine_wav TIMEOUT 60) + +add_executable (test_decoder_engine_jt4_host test_decoder_engine_jt4_host.f90) +set_target_properties (test_decoder_engine_jt4_host PROPERTIES LINKER_LANGUAGE CXX) +target_link_libraries (test_decoder_engine_jt4_host PRIVATE test_decoder_engine_jt4_signal) +wsjt_link_common_fortran (test_decoder_engine_jt4_host) +file (MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/jt4-host) +add_test (NAME test_decoder_engine_jt4_host COMMAND test_decoder_engine_jt4_host) +set_tests_properties (test_decoder_engine_jt4_host PROPERTIES + WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/jt4-host TIMEOUT 90) + +add_test (NAME test_jt4_12000_read_extent COMMAND ${CMAKE_COMMAND} + "-DJT9=$" + "-DJT4_WAV=${CMAKE_CURRENT_BINARY_DIR}/jt4-engine.wav" + "-DWORK_DIR=${CMAKE_CURRENT_BINARY_DIR}/jt4-read-extent" + -P ${CMAKE_SOURCE_DIR}/tests/integration/jt9/verify_jt4_12000_read_extent.cmake) +set_tests_properties (test_jt4_12000_read_extent PROPERTIES + FIXTURES_REQUIRED jt4_engine_wav LABELS "decoder;jt4;integration" TIMEOUT 60) diff --git a/tests/unit/decoder_engine/jt4_engine_signal.f90 b/tests/unit/decoder_engine/jt4_engine_signal.f90 new file mode 100644 index 00000000..0599b7d5 --- /dev/null +++ b/tests/unit/decoder_engine/jt4_engine_signal.f90 @@ -0,0 +1,47 @@ +subroutine decoder_engine_test_jt4_signal(rate,submode,seed,amplitude,noise,frequency,samples) bind(C) + use iso_c_binding, only: c_int,c_int16_t,c_float + implicit none + integer(c_int), value :: rate,submode,seed + real(c_float), value :: amplitude,noise,frequency + integer(c_int16_t), intent(out) :: samples(60*rate) + call jt4_engine_make_signal('K1ABC W9XYZ FN42',rate,submode,seed,amplitude,noise,frequency,samples) +end subroutine + +subroutine jt4_engine_make_signal(message,rate,submode,seed,amplitude,noise,frequency,samples) + use iso_c_binding, only: c_int,c_int16_t,c_float + use iso_fortran_env, only: int64,real64 + use jt4, only: nch + implicit none + character(len=*), intent(in) :: message + integer(c_int), intent(in) :: rate,submode,seed + real(c_float), intent(in) :: amplitude,noise,frequency + integer(c_int16_t), intent(out) :: samples(60*rate) + real(real64), parameter :: twopi=6.283185307179586476925286766559_real64 + integer(int64) :: state + integer :: tones(206),i,symbol,itype + real(real64) :: phase,value,u1,u2,freq + character(len=22) :: encoded,sent + + if(submode<0.or.submode>6) error stop 'invalid JT4 fixture submode' + if(rate/=11025.and.rate/=12000) error stop 'invalid JT4 fixture sample rate' + encoded=message + call gen4(encoded,0,sent,tones,itype) + state=104729_int64+int(seed,int64) + phase=0.0_real64 + do i=1,size(samples) + state=modulo(16807_int64*state,2147483647_int64) + u1=max(real(state,real64)/2147483647.0_real64,tiny(1.0_real64)) + state=modulo(16807_int64*state,2147483647_int64) + u2=real(state,real64)/2147483647.0_real64 + value=noise*sqrt(-2.0_real64*log(u1))*cos(twopi*u2) + if(i>rate) then + symbol=int(real(i-rate-1,real64)*4.375_real64/rate)+1 + if(symbol<=206) then + freq=frequency+tones(symbol)*4.375_real64*nch(submode+1) + phase=modulo(phase+twopi*freq/rate,twopi) + value=value+amplitude*sin(phase) + endif + endif + samples(i)=int(nint(max(-32768.0_real64,min(32767.0_real64,value))),c_int16_t) + enddo +end subroutine diff --git a/tests/unit/decoder_engine/test_decoder_engine.c b/tests/unit/decoder_engine/test_decoder_engine.c index 218688b3..71d9e3be 100644 --- a/tests/unit/decoder_engine/test_decoder_engine.c +++ b/tests/unit/decoder_engine/test_decoder_engine.c @@ -270,8 +270,44 @@ static void check_mtd_lifecycle(callback_context *context, decoder_attempt_reque free(saved); } -int main(void) +static void write_le(FILE *file, uint32_t value, unsigned bytes) { + for (unsigned i = 0; i < bytes; ++i) CHECK(fputc((value >> (8 * i)) & 255, file) != EOF); +} + +static void write_wav(const char *path) +{ + const int count = 180000; + int16_t *samples = malloc(count * sizeof *samples); + int8_t payload[77], tones[79]; + CHECK(samples); + decoder_engine_test_signal(samples, payload, tones, 6000); + FILE *file = fopen(path, "wb"); + CHECK(file); + CHECK(fwrite("RIFF", 1, 4, file) == 4); + write_le(file, 36 + count * 2, 4); + CHECK(fwrite("WAVEfmt ", 1, 8, file) == 8); + write_le(file, 16, 4); + write_le(file, 1, 2); + write_le(file, 1, 2); + write_le(file, 12000, 4); + write_le(file, 24000, 4); + write_le(file, 2, 2); + write_le(file, 16, 2); + CHECK(fwrite("data", 1, 4, file) == 4); + write_le(file, count * 2, 4); + for (int i = 0; i < count; ++i) write_le(file, (uint16_t)samples[i], 2); + CHECK(fclose(file) == 0); + free(samples); +} + +int main(int argc, char **argv) +{ + if (argc == 3 && !strcmp(argv[1], "--write-wav")) { + write_wav(argv[2]); + return 0; + } + CHECK(argc == 1); decoder_engine_options options = {DECODER_ENGINE_ABI}; decoder_engine_handle engine = NULL, second = NULL; decoder_engine_capabilities capabilities; @@ -293,7 +329,7 @@ int main(void) CHECK(decoder_engine_create(&options, &second) == DECODER_BUSY); CHECK(decoder_engine_get_capabilities(engine, &capabilities) == DECODER_OK); CHECK(capabilities.abi_version == DECODER_ENGINE_ABI); - CHECK(capabilities.supported_modes == (DECODER_SUPPORT_FT8 | DECODER_SUPPORT_FT4 | DECODER_SUPPORT_JT9 | DECODER_SUPPORT_JT65 | DECODER_SUPPORT_Q65 | DECODER_SUPPORT_FST4 | DECODER_SUPPORT_FST4W)); + CHECK(capabilities.supported_modes == (DECODER_SUPPORT_FT8 | DECODER_SUPPORT_FT4 | DECODER_SUPPORT_JT9 | DECODER_SUPPORT_JT65 | DECODER_SUPPORT_Q65 | DECODER_SUPPORT_FST4 | DECODER_SUPPORT_FST4W | DECODER_SUPPORT_JT4)); CHECK(capabilities.cancellation == 0); CHECK(capabilities.concurrent_sessions == 0); CHECK(capabilities.evidence_capacity == 1024); diff --git a/tests/unit/decoder_engine/test_decoder_engine_jt4.c b/tests/unit/decoder_engine/test_decoder_engine_jt4.c new file mode 100644 index 00000000..3b1d9e7d --- /dev/null +++ b/tests/unit/decoder_engine/test_decoder_engine_jt4.c @@ -0,0 +1,470 @@ +#if defined(__linux__) && !defined(_GNU_SOURCE) +#define _GNU_SOURCE +#endif +#include "DecoderEngine.h" +#include +#include +#include +#include +#ifdef _WIN32 +#include +#else +#include +#endif +#ifdef __linux__ +#include +#endif + +#define CHECK(condition) do { \ + if (!(condition)) { \ + fprintf(stderr, "%s:%d: %s\n", __FILE__, __LINE__, #condition); \ + exit(EXIT_FAILURE); \ + } \ +} while (0) + +enum { SAMPLE_CAPACITY = 60 * 12000 }; +extern void decoder_engine_test_jt4_signal(int, int, int, float, float, float, int16_t *); + +typedef struct { + decoder_engine_handle engine; + decoder_attempt_request request; + decoder_audio_view audio; + int16_t *samples, *before; + int observations, messages, method, average_count, kind; + float sync; +} fixture; + +static void observe(const decoder_observation *record, void *opaque) +{ + fixture *f = opaque; + CHECK(record->input_id == f->request.input_id); + CHECK(record->analysis_id == f->request.analysis_id); + CHECK(record->attempt_no == f->request.attempt_no); + CHECK(record->mode == DECODER_MODE_JT4); + CHECK(record->variant == f->request.jt4.submode); + CHECK(isfinite(record->sync) && isfinite(record->frequency_hz)); + CHECK(isfinite(record->dt_seconds) && isfinite(record->quality)); + CHECK(record->ap_type == 0); + CHECK(record->ft8.payload_origin == DECODER_PAYLOAD_NONE); + CHECK(record->ft4.payload_origin == DECODER_PAYLOAD_NONE); + CHECK(record->jt4.kind >= DECODER_JT4_NO_SYNC && record->jt4.kind <= DECODER_JT4_MESSAGE); + ++f->observations; + f->kind = record->jt4.kind; + f->sync = record->sync; + if (record->jt4.kind == DECODER_JT4_MESSAGE) { + CHECK(!strcmp(record->message, "K1ABC W9XYZ FN42")); + CHECK(record->jt4.method == DECODER_JT4_METHOD_FANO || + record->jt4.method == DECODER_JT4_METHOD_DEEP_SEARCH); + CHECK(record->jt4.average_count >= 0 && record->jt4.average_count <= 64); + CHECK(record->jt4.width_profile >= 0 && record->jt4.width_profile <= f->request.jt4.submode); + CHECK(record->jt4.sync_polarity == 1); + CHECK(fabsf(record->frequency_hz - 1000) < 10); + CHECK(fabsf(record->dt_seconds) < 0.4f); + ++f->messages; + f->method = record->jt4.method; + f->average_count = record->jt4.average_count; + } else { + CHECK(!record->message[0]); + CHECK(record->jt4.method == DECODER_JT4_METHOD_NONE); + } + CHECK(decoder_engine_release_input(f->engine, record->input_id) == DECODER_BUSY); + CHECK(decoder_engine_clear_jt4_averages(f->engine) == DECODER_BUSY); + CHECK(decoder_engine_set_jt4_calls(f->engine, NULL, 0) == DECODER_BUSY); +} + +static void create(fixture *f) +{ + decoder_engine_options options = {DECODER_ENGINE_ABI}; + decoder_engine_capabilities capabilities; + f->samples = malloc(SAMPLE_CAPACITY * sizeof *f->samples); + f->before = malloc(SAMPLE_CAPACITY * sizeof *f->before); + CHECK(f->samples && f->before); + f->audio.samples = f->samples; + CHECK(decoder_engine_create(&options, &f->engine) == DECODER_OK); + CHECK(decoder_engine_get_capabilities(f->engine, &capabilities) == DECODER_OK); + CHECK(capabilities.supported_modes & DECODER_SUPPORT_JT4); +} + +static void prepare(fixture *f, int rate, int submode, int utc) +{ + static int64_t next_id = 100; + memset(&f->request, 0, sizeof f->request); + f->request.input_id = ++next_id; + f->request.analysis_id = next_id; + f->request.attempt_no = 1; + f->request.mode = DECODER_MODE_JT4; + f->request.phase = DECODER_PHASE_NORMAL; + f->request.source = DECODER_SOURCE_FILE; + f->request.jt4.utc = utc; + f->request.jt4.submode = submode; + f->request.jt4.receive_frequency_hz = 1000; + f->request.jt4.tolerance_hz = 50; + f->request.jt4.depth = 1; + memset(f->request.jt4.mycall, ' ', sizeof f->request.jt4.mycall); + memset(f->request.jt4.hiscall, ' ', sizeof f->request.jt4.hiscall); + memset(f->request.jt4.hisgrid, ' ', sizeof f->request.jt4.hisgrid); + f->audio.sample_count = 60 * rate; + f->audio.sample_rate_hz = rate; + decoder_engine_test_jt4_signal(rate, submode, utc + 1, 300, 100, 1000, f->samples); +} + +static void decode(fixture *f, int expected) +{ + decoder_attempt_outcome outcome; + decoder_attempt_request before_request = f->request; + size_t bytes = f->audio.sample_count * sizeof *f->samples; + memcpy(f->before, f->samples, bytes); + f->observations = f->messages = f->average_count = 0; + f->method = DECODER_JT4_METHOD_NONE; + f->kind = -1; + f->sync = NAN; + CHECK(decoder_engine_decode(f->engine, &f->request, &f->audio, observe, f, &outcome) == DECODER_OK); + CHECK(outcome.status == DECODER_OK && outcome.observation_count == f->observations); + CHECK(outcome.evidence_dropped == 0); + CHECK(!memcmp(&before_request, &f->request, sizeof before_request)); + CHECK(!memcmp(f->before, f->samples, bytes)); + if (expected >= 0) { + if (!!f->messages != !!expected) + fprintf(stderr, "JT4%c %d Hz UTC %06d: got %d messages, expected %d\n", + 'A' + f->request.jt4.submode, f->audio.sample_rate_hz, + f->request.jt4.utc, f->messages, expected); + CHECK(!!f->messages == !!expected); + } +} + +static void release(fixture *f) +{ + CHECK(decoder_engine_release_input(f->engine, f->request.input_id) == DECODER_OK); +} + +static void repeat(fixture *f) +{ + f->request.phase = DECODER_PHASE_REPEAT; + ++f->request.analysis_id; + ++f->request.attempt_no; +} + +static void destroy(fixture *f) +{ + CHECK(decoder_engine_destroy(f->engine) == DECODER_OK); + free(f->before); + free(f->samples); +} + +static void invalid(fixture *f) +{ + decoder_attempt_outcome outcome; + f->observations = 0; + CHECK(decoder_engine_decode(f->engine, &f->request, &f->audio, observe, f, &outcome) == DECODER_INVALID); + CHECK(f->observations == 0); +} + +static void lifecycle(fixture *f) +{ + prepare(f, 11025, 0, 120000); + decode(f, 1); + CHECK(f->method == DECODER_JT4_METHOD_FANO && !f->average_count); + repeat(f); + --f->audio.sample_count; + invalid(f); + ++f->audio.sample_count; + f->audio.sample_rate_hz = 12000; + invalid(f); + f->audio.sample_rate_hz = 11025; + f->request.jt4.receive_frequency_hz = 1500; + decode(f, 0); + repeat(f); + f->request.jt4.receive_frequency_hz = 1000; + decode(f, 1); + release(f); + + prepare(f, 12000, 0, 120100); + decode(f, 1); + release(f); + CHECK(decoder_engine_reset_session(f->engine) == DECODER_OK); + prepare(f, 11025, 0, 120200); + f->audio.sample_count = 1; + f->samples[0] = 0; + decode(f, 0); + CHECK(f->observations == 1); + release(f); + prepare(f, 11025, 0, 120300); + decode(f, 1); + release(f); + prepare(f, 11025, 0, 120400); + memset(f->samples, 0, f->audio.sample_count * sizeof *f->samples); + decode(f, 0); + CHECK(f->observations == 1); + release(f); +} + +static void averages(fixture *f, int expected) +{ + decoder_jt4_average_entry entries[DECODER_JT4_AVERAGE_CAPACITY]; + int32_t count; + CHECK(decoder_engine_get_jt4_averages(f->engine, NULL, 0, &count) == DECODER_OK); + CHECK(count == expected); + CHECK(decoder_engine_get_jt4_averages(f->engine, entries, DECODER_JT4_AVERAGE_CAPACITY, &count) == DECODER_OK); + CHECK(count == expected); + for (int i = 0; i < count; ++i) { + CHECK(entries[i].utc == 120000 + i * 200); + CHECK(entries[i].polarity == 1 && entries[i].used == 1); + CHECK(abs(entries[i].frequency_hz - 1000) < 10); + CHECK(isfinite(entries[i].sync) && isfinite(entries[i].dt_seconds)); + } + if (count > 1) { + CHECK(decoder_engine_get_jt4_averages(f->engine, entries, 1, &count) == DECODER_CAPACITY); + CHECK(count == expected); + } +} + +static void weak_averaging(fixture *f) +{ + CHECK(decoder_engine_reset_session(f->engine) == DECODER_OK); + for (int i = 0; i < 2; ++i) { + prepare(f, 11025, 0, 120000 + i * 200); + f->request.jt4.depth = 3; + f->request.jt4.averaging = 1; + decoder_engine_test_jt4_signal(11025, 0, 5 + i, 5.0f, 100, 1000, f->samples); + decode(f, i == 1); + averages(f, i + 1); + if (i == 0) release(f); + } + CHECK(f->messages == 1 && f->method == DECODER_JT4_METHOD_FANO && f->average_count == 2); + repeat(f); + decode(f, 1); + CHECK(f->average_count == 2); + averages(f, 2); + CHECK(decoder_engine_clear_jt4_averages(f->engine) == DECODER_OK); + averages(f, 0); + repeat(f); + decode(f, 0); + int32_t count; + decoder_jt4_average_entry entry; + CHECK(decoder_engine_get_jt4_averages(f->engine, &entry, 1, &count) == DECODER_OK); + CHECK(count == 1 && entry.utc == 120200); + release(f); + prepare(f, 11025, 1, 120400); + decode(f, 1); + averages(f, 0); + release(f); +} + +static void forced_decode(fixture *f) +{ + CHECK(decoder_engine_reset_session(f->engine) == DECODER_OK); + prepare(f, 11025, 0, 120000); + f->request.jt4.tolerance_hz = 0; + f->request.jt4.averaging = 1; + decoder_engine_test_jt4_signal(11025, 0, 1, 0, 100, 1000, f->samples); + decode(f, 0); + CHECK(f->kind == DECODER_JT4_NO_SYNC && f->sync == 0); + int32_t count; + CHECK(decoder_engine_get_jt4_averages(f->engine, NULL, 0, &count) == DECODER_OK && count == 0); + repeat(f); + f->request.jt4.min_sync = -1; + decode(f, 0); + CHECK(f->kind == DECODER_JT4_SYNC && f->sync == 0); + CHECK(decoder_engine_get_jt4_averages(f->engine, NULL, 0, &count) == DECODER_OK && count == 1); + release(f); + + CHECK(decoder_engine_reset_session(f->engine) == DECODER_OK); + prepare(f, 11025, 0, 120200); + f->request.jt4.min_sync = -1; + f->request.jt4.averaging = 1; + memset(f->samples, 0, f->audio.sample_count * sizeof *f->samples); + decode(f, 0); + CHECK(f->kind == DECODER_JT4_NO_SYNC && f->sync == 0); + CHECK(decoder_engine_get_jt4_averages(f->engine, NULL, 0, &count) == DECODER_OK && count == 0); + release(f); +} + +static void deep_search(fixture *f) +{ + decoder_jt4_call call = {"W9XYZ ", "FN42"}; + CHECK(decoder_engine_reset_session(f->engine) == DECODER_OK); + prepare(f, 11025, 0, 120000); + f->request.jt4.depth = 3; + memcpy(f->request.jt4.mycall, "K1ABC ", 12); + decoder_engine_test_jt4_signal(11025, 0, 1, 5.0f, 100, 1000, f->samples); + decode(f, 0); + CHECK(decoder_engine_set_jt4_calls(f->engine, &call, 1) == DECODER_OK); + memset(&call, 0, sizeof call); + repeat(f); + f->request.jt4.deep_search = 1; + decode(f, 1); + CHECK(f->method == DECODER_JT4_METHOD_DEEP_SEARCH && !f->average_count); + memcpy(call.call, "N0CALL ", 12); + memcpy(call.grid, "EM00", 4); + CHECK(decoder_engine_set_jt4_calls(f->engine, &call, 1) == DECODER_OK); + repeat(f); + decode(f, 0); + CHECK(decoder_engine_set_jt4_calls(f->engine, NULL, 0) == DECODER_OK); + memcpy(f->request.jt4.hiscall, "W9XYZ ", 12); + memcpy(f->request.jt4.hisgrid, "FN42 ", 6); + repeat(f); + decode(f, 1); + CHECK(f->method == DECODER_JT4_METHOD_DEEP_SEARCH); + memcpy(f->request.jt4.hiscall, "N0CALL ", 12); + memcpy(f->request.jt4.hisgrid, "EM00 ", 6); + repeat(f); + decode(f, 0); + release(f); + memcpy(call.call, "W9XYZ ", 12); + memcpy(call.grid, "FN42", 4); + CHECK(decoder_engine_set_jt4_calls(f->engine, &call, 1) == DECODER_OK); + CHECK(decoder_engine_reset_session(f->engine) == DECODER_OK); + prepare(f, 11025, 0, 120200); + f->request.jt4.depth = 3; + f->request.jt4.deep_search = 1; + memcpy(f->request.jt4.mycall, "K1ABC ", 12); + decoder_engine_test_jt4_signal(11025, 0, 1, 5.0f, 100, 1000, f->samples); + decode(f, 0); + release(f); +} + +static void run_tests(int smoke) +{ + fixture f = {0}; + create(&f); + for (int submode = 0; submode < (smoke ? 1 : 7); ++submode) { + prepare(&f, submode == 5 ? 12000 : 11025, submode, 0); + decode(&f, 1); + CHECK(f.method == DECODER_JT4_METHOD_FANO && !f.average_count); + release(&f); + } + if (!smoke) { + decoder_jt4_call call = {"W9XYZ ", "FN42"}; + CHECK(decoder_engine_set_jt4_calls(f.engine, &call, 1) == DECODER_OK); + memset(&call, 0, sizeof call); + CHECK(decoder_engine_set_jt4_calls(f.engine, NULL, 1) == DECODER_INVALID); + CHECK(decoder_engine_set_jt4_calls(f.engine, NULL, DECODER_JT4_CALL_CAPACITY + 1) == DECODER_INVALID); + CHECK(decoder_engine_set_jt4_calls(f.engine, NULL, 0) == DECODER_OK); + int32_t count = -1; + CHECK(decoder_engine_get_jt4_averages(f.engine, NULL, 0, &count) == DECODER_OK && count == 0); + prepare(&f, 11025, 0, 0); + f.request.phase = DECODER_PHASE_EARLY; + invalid(&f); + f.request.phase = DECODER_PHASE_NORMAL; + f.request.jt4.minimum_width_profile = 1; + invalid(&f); + f.request.jt4.minimum_width_profile = 0; + f.request.jt4.utc = 126000; + invalid(&f); + f.request.jt4.utc = 0; + f.request.jt4.submode = 7; + invalid(&f); + f.request.jt4.submode = 0; + f.audio.sample_rate_hz = 8000; + decoder_attempt_outcome outcome; + f.observations = 0; + CHECK(decoder_engine_decode(f.engine, &f.request, &f.audio, observe, &f, &outcome) == DECODER_UNSUPPORTED); + CHECK(f.observations == 0); + f.audio.sample_rate_hz = 11025; + ++f.audio.sample_count; + invalid(&f); + --f.audio.sample_count; + f.request.jt4.averaging = 2; + invalid(&f); + } + lifecycle(&f); + if (!smoke) { + weak_averaging(&f); + forced_decode(&f); + deep_search(&f); + } + CHECK(decoder_engine_destroy(f.engine) == DECODER_OK); + decoder_engine_options options = {DECODER_ENGINE_ABI}; + CHECK(decoder_engine_create(&options, &f.engine) == DECODER_OK); + prepare(&f, 11025, 0, 130000); + decode(&f, 1); + destroy(&f); +} + +static void write_le(FILE *file, uint32_t value, unsigned bytes) +{ + for (unsigned i = 0; i < bytes; ++i) CHECK(fputc((value >> (8 * i)) & 255, file) != EOF); +} + +static void write_wav(const char *path) +{ + int16_t *samples = malloc(SAMPLE_CAPACITY * sizeof *samples); + CHECK(samples); + decoder_engine_test_jt4_signal(12000, 0, 1, 300, 100, 1000, samples); + FILE *file = fopen(path, "wb"); + CHECK(file); + CHECK(fwrite("RIFF", 1, 4, file) == 4); + write_le(file, 36 + SAMPLE_CAPACITY * 2, 4); + CHECK(fwrite("WAVEfmt ", 1, 8, file) == 8); + write_le(file, 16, 4); + write_le(file, 1, 2); + write_le(file, 1, 2); + write_le(file, 12000, 4); + write_le(file, 24000, 4); + write_le(file, 2, 2); + write_le(file, 16, 2); + CHECK(fwrite("data", 1, 4, file) == 4); + write_le(file, SAMPLE_CAPACITY * 2, 4); + for (int i = 0; i < SAMPLE_CAPACITY; ++i) write_le(file, (uint16_t)samples[i], 2); + CHECK(fclose(file) == 0); + free(samples); +} + +#ifdef _WIN32 +static DWORD WINAPI run_on_small_stack(LPVOID unused) +#else +static void *run_on_small_stack(void *unused) +#endif +{ + (void)unused; + run_tests(0); + return 0; +} + +#ifdef __linux__ +static int add_tls_size(struct dl_phdr_info *info, size_t size, void *opaque) +{ + (void)size; + size_t *stack_size = opaque; + for (int i = 0; i < info->dlpi_phnum; ++i) { + const ElfW(Phdr) *header = &info->dlpi_phdr[i]; + if (header->p_type == PT_TLS) *stack_size += header->p_memsz + header->p_align; + } + return 0; +} +#endif + +int main(int argc, char **argv) +{ + if (argc == 3 && !strcmp(argv[1], "--write-wav")) write_wav(argv[2]); + else if (argc == 2 && !strcmp(argv[1], "--smoke")) run_tests(1); + else if (argc == 1) run_tests(0); + else { + CHECK(argc == 2 && !strcmp(argv[1], "--small-stack")); +#ifdef _WIN32 + HANDLE thread = CreateThread(NULL, 1024 * 1024, run_on_small_stack, NULL, + STACK_SIZE_PARAM_IS_A_RESERVATION, NULL); + CHECK(thread != NULL); + CHECK(WaitForSingleObject(thread, INFINITE) == WAIT_OBJECT_0); + DWORD status; + CHECK(GetExitCodeThread(thread, &status) && status == 0); + CHECK(CloseHandle(thread)); +#else + pthread_attr_t attributes; + pthread_t thread; + size_t stack_size = 1024 * 1024; +#ifdef __linux__ + /* Linux puts static TLS in the stack mapping; reserve 1 MiB for calls. */ + dl_iterate_phdr(add_tls_size, &stack_size); +#endif + CHECK(pthread_attr_init(&attributes) == 0); + CHECK(pthread_attr_setstacksize(&attributes, stack_size) == 0); + int error = pthread_create(&thread, &attributes, run_on_small_stack, NULL); + if (error) fprintf(stderr, "pthread_create with %zu bytes: %s\n", stack_size, strerror(error)); + CHECK(error == 0); + CHECK(pthread_attr_destroy(&attributes) == 0); + CHECK(pthread_join(thread, NULL) == 0); +#endif + } + return EXIT_SUCCESS; +} diff --git a/tests/unit/decoder_engine/test_decoder_engine_jt4_host.f90 b/tests/unit/decoder_engine/test_decoder_engine_jt4_host.f90 new file mode 100644 index 00000000..2b228894 --- /dev/null +++ b/tests/unit/decoder_engine/test_decoder_engine_jt4_host.f90 @@ -0,0 +1,213 @@ +program test_decoder_engine_jt4_host + use iso_c_binding, only: c_int,c_int8_t,c_int16_t,c_int64_t,c_float,c_sizeof + use decoder_engine, only: engine_host_decode + use decoder_engine_types, only: engine_jt4_options + use ft8_engine_kernel, only: params_block + use jt4_decode, only: jt4_decoder + use jt4_host_support, only: convert_jt4_host_options,load_jt4_calls,write_jt4_averages + use decode_completion_module, only: decode_completion_result + use prog_args, only: data_dir,temp_dir + implicit none + type(params_block) :: params,before_params + type(engine_jt4_options) :: options + type(jt4_decoder), allocatable :: decoder + type(decode_completion_result) :: completion + integer(c_int8_t) :: zeros(c_sizeof(params)) + integer(c_int16_t), allocatable, target :: samples(:) + integer(c_int16_t), allocatable :: before(:) + integer(c_int64_t) :: input_id=700,analysis_id=700 + integer :: npatience,nthreads,unit,ios,attempt=1 + character(len=100) :: line + logical :: exists + common/patience/npatience,nthreads + interface + subroutine signal(rate,submode,seed,amplitude,noise,frequency,samples) bind(C,name='decoder_engine_test_jt4_signal') + import c_int,c_int16_t,c_float + integer(c_int), value :: rate,submode,seed + real(c_float), value :: amplitude,noise,frequency + integer(c_int16_t), intent(out) :: samples(*) + end subroutine + end interface + + data_dir='.' + temp_dir='.' + zeros=0 + params=transfer(zeros,params) + params%nmode=4 + params%ntr=60 + params%nutc=1234 + params%nfqso=1000 + params%ntol=50 + params%ndepth=3+16+32+128 + params%mycall=transfer('K1ABC ',params%mycall) + params%hiscall=transfer('W9XYZ ',params%hiscall) + params%hisgrid=transfer('FN42 ',params%hisgrid) + before_params=params + call convert_jt4_host_options(params,options) + call require(options%utc==123400,'legacy HHMM converts to HHMMSS') + call require(options%depth==3.and.options%averaging==1.and.options%deep_search==1,'packed effort separates feature flags') + call require(all(transfer(params,zeros)==transfer(before_params,zeros)),'conversion does not mutate legacy parameters') + + allocate(decoder) + npatience=0 + call remove_file('CALL3.TXT') + call load_jt4_calls(decoder) + inquire(file='CALL3.TXT',exist=exists) + call require(.not.exists,'missing call list is not created by loading') + call require(size(decoder%calls)==0,'missing call list clears template knowledge') + open(newunit=unit,file='CALL3.TXT',status='replace') + write(unit,'(a)') '// ignored comment','invalid','W9XYZ,FN42,,','K9XYZ,EN50,,','ZZZZ,AA00,,','N0CALL,EM00,,' + close(unit) + call load_jt4_calls(decoder) + call require(size(decoder%calls)==2,'CALL3 terminator stops parsing') + call require(decoder%calls(1)%call=='W9XYZ'.and.decoder%calls(2)%call=='K9XYZ','CALL3 ordering is preserved') + call require(decoder%calls(1)%grid=='FN42','CALL3 grid survives loading') + open(newunit=unit,file='CALL3.TXT',status='replace') + write(unit,'(a)') 'N0CALL,EM00,,' + close(unit) + call load_jt4_calls(decoder) + call require(size(decoder%calls)==1.and.decoder%calls(1)%call=='N0CALL','changed call list replaces host knowledge') + + call decoder%save_average(123400,5.0,0.1,1.0,1000,50) + call decoder%save_average(123600,6.0,0.1,-1.0,1000,50) + decoder%average_used(1)=.true. + open(newunit=unit,file='avemsg.txt',status='replace') + call write_jt4_averages(decoder,unit) + rewind(unit) + read(unit,'(a)') line + call require(line(1:1)=='$'.and.line(3:6)=='1234'.and.index(line,'*')>0,'legacy average row UTC and selection') + read(unit,'(a)') line + call require(line(1:1)=='.'.and.index(line(2:),'$')>0,'legacy inverted-polarity average marker') + call decoder%clear_averages() + call write_jt4_averages(decoder,unit) + rewind(unit) + read(unit,'(a)',iostat=ios) line + call require(ios<0,'clear truncates old average output') + close(unit) + deallocate(decoder) + + allocate(samples(60*11025),before(60*11025)) + params%ndepth=1 + params%newdat=.true. + params%ndiskdat=.true. + params%nclearave=.true. + samples=0 + before=samples + call run(0) + params%nclearave=.false. + call signal(11025,0,1,300.0,100.0,1000.0,samples) + before=samples + call run(1) + call require(output_contains('K1ABC W9XYZ FN42'),'legacy host prints recovered message') + call require(output_contains('1234'),'legacy host retains HHMM output') + params%newdat=.false. + params%nagain=.true. + attempt=2 + analysis_id=analysis_id+1 + call run(1) + call require(output_contains('K1ABC W9XYZ FN42'),'manual repeat decodes retained input') + input_id=input_id+1 + analysis_id=analysis_id+1 + attempt=1 + params%newdat=.true. + params%nagain=.false. + samples=0 + before=0 + call run(0) + call require(.not.output_contains('K1ABC'),'no-sync output cannot reuse prior message') + call new_period(1234) + params%ndepth=3+16 + call signal(11025,0,5,5.0,100.0,1000.0,samples) + before=samples + call run(0) + call require(average_rows()==1,'weak synchronized reception enters average history') + call require(.not.output_contains('K1ABC'),'sync-only observation is not a recovered message') + + params%minsync=100 + params%nagain=.true. + params%newdat=.false. + attempt=2 + analysis_id=analysis_id+1 + call run(0) + call require(output_contains('1234'),'no-sync observation remains visible without counting as decoded') + params%minsync=0 + + call new_period(1235) + params%nclearave=.true. + samples=0 + before=samples + call run(0) + params%nclearave=.false. + + call new_period(1236) + call signal(11025,0,6,5.0,100.0,1000.0,samples) + before=samples + call run(0) + call require(average_rows()==1,'quiet clear prevents reuse of the preceding weak reception') + deallocate(samples,before) + +contains + subroutine require(condition,message) + logical, intent(in) :: condition + character(len=*), intent(in) :: message + if(.not.condition) then + print *, 'JT4 host: ',message + error stop 1 + endif + end subroutine + + subroutine run(expected) + integer, intent(in) :: expected + before_params=params + open(unit=6,file='host-output.txt',status='replace') + call engine_host_decode(samples,params,11025,completion,0,input_id,analysis_id,attempt,size(samples)) + close(6) + call require(completion%available.and.completion%decoded==expected,'host completion counts only recovered messages') + call require(all(before==samples),'host leaves supplied PCM unchanged') + call require(all(transfer(params,zeros)==transfer(before_params,zeros)),'host leaves packed parameters unchanged') + end subroutine + + subroutine new_period(utc) + integer, intent(in) :: utc + params%nutc=utc + params%newdat=.true. + params%nagain=.false. + input_id=input_id+1 + analysis_id=analysis_id+1 + attempt=1 + end subroutine + + integer function average_rows() result(count) + integer :: file_unit,status + character(len=100) :: row + count=0 + open(newunit=file_unit,file='avemsg.txt',status='old') + do + read(file_unit,'(a)',iostat=status) row + if(status/=0) exit + count=count+1 + enddo + close(file_unit) + end function + + logical function output_contains(text) result(found) + character(len=*), intent(in) :: text + integer :: file_unit,status + character(len=256) :: row + found=.false. + open(newunit=file_unit,file='host-output.txt',status='old') + do + read(file_unit,'(a)',iostat=status) row + if(status/=0) exit + if(index(row,text)>0) found=.true. + enddo + close(file_unit) + end function + + subroutine remove_file(path) + character(len=*), intent(in) :: path + integer :: file_unit,status + open(newunit=file_unit,file=path,status='old',iostat=status) + if(status==0) close(file_unit,status='delete') + end subroutine +end program diff --git a/tests/unit/decoder_engine/test_decoder_engine_jt4_state.f90 b/tests/unit/decoder_engine/test_decoder_engine_jt4_state.f90 new file mode 100644 index 00000000..947750ce --- /dev/null +++ b/tests/unit/decoder_engine/test_decoder_engine_jt4_state.f90 @@ -0,0 +1,112 @@ +program test_decoder_engine_jt4_state + use iso_c_binding, only: c_int16_t + use jt4_decode, only: jt4_decoder,jt4_options,jt4_average_entry + implicit none + type(jt4_decoder), allocatable :: decoder,other + type(jt4_average_entry) :: entries(64) + type(jt4_options) :: options + integer(c_int16_t) :: silence(1)=0 + real :: sym(207,7),symbols(207) + integer :: nsum,i,slot,entry_count,ncount,status + character(len=22) :: decoded + interface + subroutine ignore_result(this,snr,dt,freq,have_sync,sync,is_deep,decoded,qual,ich,is_average,ave) + import jt4_decoder + class(jt4_decoder),intent(inout) :: this + integer,intent(in) :: snr,freq,ich,ave + real,intent(in) :: dt,qual + logical,intent(in) :: have_sync,is_deep,is_average + character,intent(in) :: sync + character(len=22),intent(in) :: decoded + end subroutine + end interface + + allocate(decoder,other) + allocate(decoder%rsymbol(207,7),decoder%ppsave(207,7,64)) + decoder%rsymbol=2.0 + call decoder%save_average(120000,4.0,0.0,1.0,1000,20) + call check(decoder%average_count==1,'first reception') + decoder%rsymbol=4.0 + call decoder%save_average(120000,6.0,0.01,1.0,1010,20) + call check(decoder%average_count==1,'same minute and nearby frequency deduplicate') + call decoder%save_average(120200,6.0,0.1,1.0,1010,20) + call decoder%select_average(120200,0.0,1.0,1000,20,sym,nsum) + call check(nsum==2.and.all(abs(sym-3.0)<1.e-6),'matching receptions average symbols') + call check(count(decoder%average_used)==2,'selected reception flags') + + call decoder%save_average(120100,8.0,0.0,1.0,1000,20) + call decoder%save_average(120400,8.0,0.5,1.0,1000,20) + call decoder%save_average(120600,8.0,0.0,-1.0,1000,20) + call decoder%save_average(120800,8.0,0.0,1.0,1100,20) + call decoder%select_average(120200,0.0,1.0,1000,20,sym,nsum) + call check(nsum==2,'parity, DT, polarity and frequency exclude incompatible receptions') + call check(decoder%average_count==6,'excluded receptions remain in history') + call check(other%average_count==0,'decoder instances do not share history') + + call decoder%clear_averages() + call check(decoder%average_count==0.and.all(decoder%iutc<0),'clear removes all entries') + call check(.not.any(decoder%average_used),'clear removes selection flags') + decoder%rsymbol=1.0 + call decoder%save_average(120000,4.0,0.0,1.0,1000,20) + call check(decoder%average_count==1,'cleared reception can be inserted again') + + call decoder%clear_averages() + do i=0,64 + decoder%rsymbol=real(i) + call decoder%save_average((i/60)*10000+mod(i,60)*100,4.0,0.0,1.0,1000,20) + enddo + call check(decoder%average_count==64,'history capacity after ring wrap') + call check(count(decoder%iutc>=0)==64,'all slots remain visible after ring wrap') + call check(.not.any(decoder%iutc==0),'oldest reception evicted') + call check(any(decoder%iutc==10400),'newest reception retained') + call decoder%get_averages(entries,entry_count) + call check(entry_count==64,'snapshot reports all entries after ring wrap') + call check(entries(1)%utc==10400,'snapshot preserves physical slot order') + call decoder%select_average(10400,0.0,1.0,1000,20,sym,nsum) + call check(nsum==32,'parity selection remains correct across hour and ring wrap') + call check(all(abs(sym-33.0)<1.e-6),'wrapped average contains precisely retained even minutes') + slot=decoder%nsave + call decoder%save_average(10400,9.0,0.0,1.0,1001,20) + call check(decoder%nsave==slot.and.decoder%average_count==64,'duplicate does not advance ring') + + options%submode=1 + call decoder%decode_pcm(options,silence,11025,ignore_result,status) + call check(status==0,'prepare changed submode') + decoder%rsymbol=1.0 + call decoder%save_average(120000,4.0,0.0,1.0,1000,20) + call decoder%decode_pcm(options,silence,11025,ignore_result,status) + call check(status==0.and.decoder%average_count==1,'same width profile retains compatible history') + options%minimum_width_profile=1 + call decoder%decode_pcm(options,silence,11025,ignore_result,status) + call check(status==0.and.decoder%average_count==0,'changed width profile clears incompatible history') + deallocate(decoder,other) + + do i=0,1 + symbols=real(i) + decoded='stale decoded message' + ncount=42 + call extract4(symbols,ncount,decoded) + call check(ncount<0.and.len_trim(decoded)==0,'zero-variance symbols fail without stale message') + enddo + +contains + subroutine check(condition,message) + logical, intent(in) :: condition + character(len=*), intent(in) :: message + if(.not.condition) then + print *, 'JT4 average state: ',message + stop 1 + endif + end subroutine +end program + +subroutine ignore_result(this,snr,dt,freq,have_sync,sync,is_deep,decoded,qual,ich,is_average,ave) + use jt4_decode, only: jt4_decoder + implicit none + class(jt4_decoder),intent(inout) :: this + integer,intent(in) :: snr,freq,ich,ave + real,intent(in) :: dt,qual + logical,intent(in) :: have_sync,is_deep,is_average + character,intent(in) :: sync + character(len=22),intent(in) :: decoded +end subroutine diff --git a/tests/unit/jtty/jtty_cpp_n1mm_smoke.cpp b/tests/unit/jtty/jtty_cpp_n1mm_smoke.cpp index c2b3b45b..25fa54b0 100644 --- a/tests/unit/jtty/jtty_cpp_n1mm_smoke.cpp +++ b/tests/unit/jtty/jtty_cpp_n1mm_smoke.cpp @@ -80,3 +80,40 @@ extern "C" int jtty_cpp_rtty_smoke (int tones[], int* nsym) } return status; } + +extern "C" int jtty_cpp_rtty_line_refused () +{ + // 80 characters; RTTY Roundup writes the serial as 005, which makes it 81. + QString const line = QString (73, QLatin1Char {'A'}) + QStringLiteral (" 599 05"); + auto encodesWith = [] (Jtty::NativeExchangeProfile exchange) { + return [profile = static_cast (exchange)] (QString const& text) { + auto frame = Jtty::transmitFrame (text).toLatin1 (); + std::array tones {}; + std::array frameStarts {}; + int symbols {}; + int const isFinal = 0; + genjtty_profile_ (frame.data (), &profile, tones.data (), &symbols, + frameStarts.data (), &isFinal, frame.size ()); + return symbols > 0; + }; + }; + auto const rtty = Jtty::encodeTransmitLine (line, encodesWith (Jtty::NativeExchangeProfile::RttyRoundup)); + auto const none = Jtty::encodeTransmitLine (line, encodesWith (Jtty::NativeExchangeProfile::None)); + return !rtty && none && none->size () == 1; +} + +extern "C" int jtty_cpp_rtty_line_tones (int tones[], int* nsym) +{ + // 79 characters; with the serial written as 005 it is exactly 80. + QString const line = QString (72, QLatin1Char {'A'}) + QStringLiteral (" 599 05"); + int const profile = static_cast (Jtty::NativeExchangeProfile::RttyRoundup); + auto encode = [&] (QString const& text, int isFinal) { + auto frame = Jtty::transmitFrame (text).toLatin1 (); + std::array frameStarts {}; + *nsym = 0; + genjtty_profile_ (frame.data (), &profile, tones, nsym, frameStarts.data (), &isFinal, frame.size ()); + return *nsym > 0; + }; + auto const segments = Jtty::encodeTransmitLine (line, [&] (QString const& text) { return encode (text, 0); }); + return segments && segments->size () == 1 && encode (segments->front ().text, 1); +} diff --git a/tests/unit/jtty/test_jtty_messages.cpp b/tests/unit/jtty/test_jtty_messages.cpp index 033966e4..f877e1a0 100644 --- a/tests/unit/jtty/test_jtty_messages.cpp +++ b/tests/unit/jtty/test_jtty_messages.cpp @@ -2,6 +2,16 @@ #include "widgets/JttyMessages.hpp" +namespace +{ + // 121 characters: two transmit segments. + QString longLine () + { + return QStringLiteral ("THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG AND KEEPS RUNNING ACROSS THE FIELD" + " UNTIL IT REACHES THE OLD BARN BY THE RIVER"); + } +} + class TestJttyMessages final : public QObject { @@ -690,6 +700,44 @@ private slots: Jtty::maxTransmitLength); } + void encodeTransmitLineRefusesRatherThanShortens () + { + QString const line = QString (73, QLatin1Char {'A'}) + QStringLiteral (" 599 05"); + QStringList attempts; + auto const encoded = Jtty::encodeTransmitLine (line, [&] (QString const& text) { + attempts << text; + return text.size () < line.size (); + }); + QVERIFY (!encoded); + QCOMPARE (attempts, QStringList {line}); + + QStringList cuts; + auto const laterSegmentFails = Jtty::encodeTransmitLine (longLine (), [&] (QString const& text) { + cuts << text; + return cuts.size () < 2; + }); + QVERIFY (!laterSegmentFails); + QCOMPARE (cuts.size (), 2); + QCOMPARE (cuts.join (QString {}), longLine ()); + } + + void encodeTransmitLineKeepsTheSegmentCuts () + { + QString const line = longLine (); + QStringList attempts; + auto const encoded = Jtty::encodeTransmitLine (line, [&] (QString const& text) { + attempts << text; + return true; + }); + QVERIFY (encoded); + QCOMPARE (encoded->size (), 2); + QCOMPARE (attempts, (QStringList {encoded->at (0).text, encoded->at (1).text})); + QCOMPARE (encoded->at (0).text + encoded->at (1).text, line); + auto const blank = Jtty::encodeTransmitLine (QString (5, QLatin1Char {' '}), + [] (QString const&) { return false; }); + QVERIFY (blank && blank->isEmpty ()); + } + void wavCaptureValid_data () { QTest::addColumn ("k0"); diff --git a/tests/unit/jtty/test_jtty_structured_decode.f90 b/tests/unit/jtty/test_jtty_structured_decode.f90 index 6a55a816..56f9256a 100644 --- a/tests/unit/jtty/test_jtty_structured_decode.f90 +++ b/tests/unit/jtty/test_jtty_structured_decode.f90 @@ -37,6 +37,15 @@ program test_jtty_structured_decode integer(c_int), intent(out) :: tones(*),nsym integer(c_int) :: status end function jtty_cpp_rtty_smoke + function jtty_cpp_rtty_line_refused() result(refused) bind(C) + import :: c_int + integer(c_int) :: refused + end function jtty_cpp_rtty_line_refused + function jtty_cpp_rtty_line_tones(tones,nsym) result(planned) bind(C) + import :: c_int + integer(c_int), intent(out) :: tones(*),nsym + integer(c_int) :: planned + end function jtty_cpp_rtty_line_tones subroutine genjtty_atoms(atoms,natoms,itone,nsym) use jtty_mod, only: jtty_source_atom type(jtty_source_atom), intent(in) :: atoms(:) @@ -63,6 +72,9 @@ program test_jtty_structured_decode call decode_cpp_compiled_n1mm(failures) call decode_compact_text(failures) call decode_profile_text(failures) + call expect(jtty_cpp_rtty_line_refused().eq.1, & + 'an RTTY line whose serial does not fit is refused, not split',failures) + call decode_accepted_rtty_line(failures) if(failures.ne.0) then write(*,'(a,i0)') 'test_jtty_structured_decode: failures=',failures @@ -351,6 +363,23 @@ contains deallocate(pcm,wave,complex_wave) end subroutine decode_waveform + subroutine decode_accepted_rtty_line(count) + integer, intent(inout) :: count + integer(c_int) :: tones(MAX_FRAMES*frame_symbols),nsymbols + character(len=80) :: expected + + expected=repeat('A',72)//' 599 005' + call expect(jtty_cpp_rtty_line_tones(tones,nsymbols).eq.1, & + 'the longest RTTY line that fits is one segment',count) + if(nsymbols.le.0) return + call decode_waveform(tones,int(nsymbols)) + call expect(npending.ge.1,'the accepted RTTY line produces updates',count) + if(npending.lt.1) return + call expect(trim(normalized(pending_updates(npending)%decoded)).eq.trim(expected) .and. & + pending_updates(npending)%complete .and. nactive.eq.0, & + 'the accepted RTTY line arrives whole, serial included',count) + end subroutine decode_accepted_rtty_line + function normalized(value) result(result_value) character(len=*), intent(in) :: value character(len=80) :: result_value diff --git a/tests/unit/map65/test_map65_pass_snapshots.f90 b/tests/unit/map65/test_map65_pass_snapshots.f90 new file mode 100644 index 00000000..cfbd12b7 --- /dev/null +++ b/tests/unit/map65/test_map65_pass_snapshots.f90 @@ -0,0 +1,100 @@ +program test_map65_pass_snapshots + ! Each automatic decode pass must decode data frozen at the moment it was + ! triggered. Simulates the new minute resetting the live buffers while the + ! 302-symbol pass is still queued behind the running 280-symbol pass. + use iso_c_binding, only: c_float + use datcom_ptrs_mod, only: dd, ss, savg, snap, snapshot_buffers + use npar_ptrs_mod, only: snap_latest_idx, set_nhsym, set_nagain, set_ndiskdat, & + publish_decode_request, claim_decode_request, active_request_expired, & + active_snap_idx, snapshot_release, advance_live_input_generation + implicit none + + integer, parameter :: nsmax = 4000, ncol = 12, nfft = 16 + integer(8) :: rid + + allocate(dd(4,nsmax), ss(4,ncol,nfft), savg(4,nfft)) + allocate(snap(1)%dd(4,nsmax), snap(1)%ss(4,ncol,nfft), snap(1)%savg(4,nfft)) + allocate(snap(2)%dd(4,nsmax), snap(2)%ss(4,ncol,nfft), snap(2)%savg(4,nfft)) + snap(1)%dd = -1.0; snap(1)%ss = -1.0; snap(1)%savg = -1.0 + snap(2)%dd = -1.0; snap(2)%ss = -1.0; snap(2)%savg = -1.0 + + ! Early pass (nhsym 280 stand-in): live buffers hold cycle A up to sample 3000 + dd = 0.0; dd(:,1:3000) = 1.0 + ss = 0.0; ss(:,1:10,:) = 1.0 + savg = 10.0 + call snapshot_buffers(1, 3000, 10) + call require(snap_latest_idx == 1, 'latest snapshot is the early one') + + ! Later: live buffers keep filling, then the new minute resets them + dd(:,3001:3800) = 2.0 + ss(:,11:12,:) = 2.0 + savg = 20.0 + call snapshot_buffers(2, 3800, 12) + call require(snap_latest_idx == 2, 'latest snapshot is the final one') + + dd = 7.0; ss = 7.0; savg = 0.0 !Next cycle overwrites / resets live + + call require(all(snap(1)%dd(:,1:3000) == 1.0), 'early dd frozen') + call require(all(snap(1)%dd(:,3513:) == 0.0), 'early dd past lookahead is zero') + call require(all(snap(1)%ss(:,1:10,:) == 1.0), 'early ss frozen') + call require(all(snap(1)%ss(:,11:,:) == 0.0), 'early ss past nhsym is zero') + call require(all(snap(1)%savg == 10.0), 'early savg frozen') + + call require(all(snap(2)%dd(:,1:3000) == 1.0), 'final dd has early part') + call require(all(snap(2)%dd(:,3001:3800) == 2.0), 'final dd has later part') + call require(all(snap(2)%ss(:,11:12,:) == 2.0), 'final ss frozen') + call require(all(snap(2)%savg == 20.0), 'final savg frozen') + + ! ---- request expiry follows the snapshot, not the minute boundary ---- + call set_nagain(0); call set_ndiskdat(0) + + ! 1. A final-pass request claimed after the minute rolled over still runs + ! (its snapshot is intact), and holds its slot while running. + dd = 3.0; ss = 3.0; savg = 3.0 + call set_nhsym(302) + call snapshot_buffers(2, 3800, 12) + rid = publish_decode_request() + call advance_live_input_generation() !new minute begins + call require(claim_decode_request(), 'request claimed') + call require(.not. active_request_expired, 'late request with intact snapshot runs') + call require(active_snap_idx == 2, 'late request reads its own slot') + + ! 2. While that pass is running, the next cycle's fill must not overwrite + ! the slot; the request published for it is then dropped, not mis-decoded. + dd = 4.0 + call snapshot_buffers(2, 3800, 12) + call require(all(snap(2)%dd(:,1:3800) == 3.0), 'busy slot not overwritten') + rid = publish_decode_request() + call snapshot_release() + call require(claim_decode_request(), 'second request claimed') + call require(active_request_expired, 'request whose fill was skipped is dropped') + + ! 3. A queued request whose slot is refilled before it is claimed is dropped. + dd = 5.0 + call snapshot_buffers(2, 3800, 12) + rid = publish_decode_request() + dd = 6.0 + call snapshot_buffers(2, 3800, 12) + call require(claim_decode_request(), 'third request claimed') + call require(active_request_expired, 'overwritten snapshot request is dropped') + + ! 4. More than one generation old (monitoring stopped etc.) is dropped. + call snapshot_buffers(2, 3800, 12) + rid = publish_decode_request() + call advance_live_input_generation() + call advance_live_input_generation() + call require(claim_decode_request(), 'fourth request claimed') + call require(active_request_expired, 'request two generations old is dropped') + print *, 'test_map65_pass_snapshots: PASS' + +contains + + subroutine require(ok, what) + logical, intent(in) :: ok + character(*), intent(in) :: what + if (.not. ok) then + print *, 'FAIL: ', what + error stop 1 + end if + end subroutine require +end program test_map65_pass_snapshots diff --git a/tests/unit/streaming/CMakeLists.txt b/tests/unit/streaming/CMakeLists.txt index 4db80617..6aae5282 100644 --- a/tests/unit/streaming/CMakeLists.txt +++ b/tests/unit/streaming/CMakeLists.txt @@ -1,11 +1,13 @@ add_executable (test_streaming_consumers test_streaming_consumers.cpp) -add_dependencies (test_streaming_consumers test_decoder_engine_q65 test_decoder_engine_fst4) +add_dependencies (test_streaming_consumers test_decoder_engine test_decoder_engine_q65 test_decoder_engine_fst4 test_decoder_engine_jt4) target_link_libraries (test_streaming_consumers Qt5::Test) target_compile_definitions (test_streaming_consumers PRIVATE + JT4_ENGINE_WAV="${CMAKE_BINARY_DIR}/tests/unit/decoder_engine/jt4-engine.wav" JT9_EXECUTABLE="$" WSPRD_EXECUTABLE="$" FST4_ENGINE_WAV="${CMAKE_BINARY_DIR}/tests/unit/decoder_engine/fst4-engine.wav" FST4W_ENGINE_WAV="${CMAKE_BINARY_DIR}/tests/unit/decoder_engine/fst4w-engine.wav" + FT8_ENGINE_WAV="${CMAKE_BINARY_DIR}/tests/unit/decoder_engine/ft8-engine.wav" Q65_ENGINE_WAV="${CMAKE_BINARY_DIR}/tests/unit/decoder_engine/q65-engine.wav" ) @@ -13,7 +15,7 @@ add_test (NAME test_streaming_consumers COMMAND test_streaming_consumers) set_tests_properties (test_streaming_consumers PROPERTIES LABELS "streaming;runtime" TIMEOUT 360 - FIXTURES_REQUIRED "q65_engine_wav;fst4_engine_wav;fst4w_engine_wav" + FIXTURES_REQUIRED "ft8_engine_wav;jt4_engine_wav;q65_engine_wav;fst4_engine_wav;fst4w_engine_wav" ) if (WSJT_ENABLE_TSAN) set_tests_properties (test_streaming_consumers PROPERTIES diff --git a/tests/unit/streaming/test_streaming_consumers.cpp b/tests/unit/streaming/test_streaming_consumers.cpp index 91ed0e2e..3d9caf46 100644 --- a/tests/unit/streaming/test_streaming_consumers.cpp +++ b/tests/unit/streaming/test_streaming_consumers.cpp @@ -238,6 +238,52 @@ class TestStreamingConsumers final : public QObject Q_OBJECT private slots: + void jt4DecodesWaveform_data () + { + QTest::addColumn ("timeFields"); + QTest::addColumn ("expected"); + QTest::newRow ("afternoon") << QJsonObject {{"utc", "12:34:00"}} << QString {"123400"}; + QTest::newRow ("legacy-numeric") << QJsonObject {{"nutc", 1234}} << QString {"123400"}; + QTest::newRow ("early-hour-iso-precedence") + << QJsonObject {{"nutc", 1234}, {"utc", "00:12:34"}} << QString {"001234"}; + } + + void jt4DecodesWaveform () + { + QFETCH (QJsonObject, timeFields); + QFETCH (QString, expected); + QFile recording {QString::fromUtf8 (JT4_ENGINE_WAV)}; + QVERIFY2 (recording.open (QIODevice::ReadOnly), qPrintable (recording.errorString ())); + auto const wav = recording.readAll (); + QCOMPARE (wav.size (), 44 + 60 * 12000 * 2); + QCOMPARE (wav.left (4), QByteArray {"RIFF"}); + QCOMPARE (wav.mid (36, 4), QByteArray {"data"}); + QTemporaryDir directory; + QVERIFY (directory.isValid ()); + QJsonObject configuration {{"t", "configure"}, {"mode", "JT4"}, {"trperiod", 60}, + {"submode", 0}, {"depth_level", 1}, {"rxfreq", 1000}, {"ntol", 50}}; + for (auto it = timeFields.constBegin (); it != timeFields.constEnd (); ++it) + { + configuration.insert (it.key (), it.value ()); + } + auto const input = sessionHeader () + controlFrame ( + QJsonDocument {configuration}.toJson (QJsonDocument::Compact)) + + frame (0x01u, wav.mid (44)) + controlFrame (R"({"t":"halt"})"); + auto const result = runProcess (QString::fromUtf8 (JT9_EXECUTABLE), + {"-a", directory.path (), "-t", directory.path (), "--stream"}, input, directory.path ()); + verifyCompleted (result, 0); + auto const events = verifyEvents (result); + QCOMPARE (eventsMatching (events.values, "error").size (), 0); + auto const decodes = eventsMatching (events.values, "decode"); + QCOMPARE (decodes.size (), 1); + QCOMPARE (decodes.first ().value ("mode").toString (), QString {"JT4"}); + QCOMPARE (decodes.first ().value ("time").toString (), expected); + QCOMPARE (decodes.first ().value ("message").toString ().trimmed (), QString {"K1ABC W9XYZ FN42"}); + auto const completions = eventsMatching (events.values, "decode_finished"); + QCOMPARE (completions.size (), 1); + QCOMPARE (completions.first ().value ("period_end").toString (), expected); + } + void fst4DecodesWaveform_data () { QTest::addColumn ("mode"); @@ -277,7 +323,7 @@ private slots: bool found = false; for (auto const& decode : eventsMatching (events.values, "decode")) { - QCOMPARE (decode.value ("mode").toString (), QString {"FST4"}); + QCOMPARE (decode.value ("mode").toString (), mode); found |= decode.value ("message").toString ().trimmed () == message; } QVERIFY2 (found, result.standardOutput.constData ()); @@ -475,6 +521,120 @@ private slots: QCOMPARE (eventsMatching (events.values, "decode_finished").size (), 2); } + // A period's label is the producer's UTC, whichever key and frame carried it. + void jt9LabelsPeriodsWithTheProducersUtc_data () + { + QTest::addColumn ("configure"); + QTest::addColumn ("samples"); + QTest::addColumn ("periodEnd"); + QTest::newRow ("FT8 05:11:15") + << controlFrame (R"({"t":"configure","mode":"FT8","utc":"05:11:15"})") << 15 * 12000 << QString {"051115"}; + QTest::newRow ("FT8 00:45:15") + << controlFrame (R"({"t":"configure","mode":"FT8","utc":"00:45:15"})") << 15 * 12000 << QString {"004515"}; + QTest::newRow ("JT9, utc, then FT8") + << controlFrame (R"({"t":"configure","mode":"JT9"})") + controlFrame (R"({"t":"configure","utc":"05:11:15"})") + + controlFrame (R"({"t":"configure","mode":"FT8"})") + << 15 * 12000 << QString {"051115"}; + QTest::newRow ("FT8 nutc") + << controlFrame (R"({"t":"configure","mode":"FT8","nutc":51115})") << 15 * 12000 << QString {"051115"}; + QTest::newRow ("JT9, nutc 1530, then FT8") + << controlFrame (R"({"t":"configure","mode":"JT9"})") + controlFrame (R"({"t":"configure","nutc":1530})") + + controlFrame (R"({"t":"configure","mode":"FT8"})") + << 15 * 12000 << QString {"001530"}; + QTest::newRow ("FT8 negative nutc") + << controlFrame (R"({"t":"configure","mode":"FT8","nutc":-1})") << 15 * 12000 << QString {"000000"}; + QTest::newRow ("FT4 05:11:15") + << controlFrame (R"({"t":"configure","mode":"FT4","utc":"05:11:15"})") << Ft4PeriodSamples << QString {"051115"}; + QTest::newRow ("MSK144 05:11:15") + << controlFrame (R"({"t":"configure","mode":"MSK144","trperiod":15,"utc":"05:11:15"})") << 15 * 12000 + << QString {"051115"}; + QTest::newRow ("FST4-15 05:11:15") + << controlFrame (R"({"t":"configure","mode":"FST4","trperiod":15,"utc":"05:11:15"})") << 15 * 12000 + << QString {"051115"}; + QTest::newRow ("JT9 05:11:00") + << controlFrame (R"({"t":"configure","mode":"JT9","utc":"05:11:00"})") << 60 * 12000 << QString {"051100"}; + QTest::newRow ("JT9 nutc HHMM") + << controlFrame (R"({"t":"configure","mode":"JT9","nutc":511})") << 60 * 12000 << QString {"051100"}; + QTest::newRow ("JT9 nutc HHMMSS") + << controlFrame (R"({"t":"configure","mode":"JT9","nutc":51100})") << 60 * 12000 << QString {"051100"}; + QTest::newRow ("JT9 nutc 4515") + << controlFrame (R"({"t":"configure","mode":"JT9","nutc":4515})") << 60 * 12000 << QString {"004515"}; + QTest::newRow ("JT9 utc and nutc in one frame") + << controlFrame (R"({"t":"configure","mode":"JT9","utc":"00:15:00","nutc":1530})") << 60 * 12000 + << QString {"001500"}; + QTest::newRow ("utc 00:15:00, then JT9") + << controlFrame (R"({"t":"configure","utc":"00:15:00"})") + controlFrame (R"({"t":"configure","mode":"JT9"})") + << 60 * 12000 << QString {"001500"}; + QTest::newRow ("nutc HHMM, then JT9") + << controlFrame (R"({"t":"configure","nutc":511})") + controlFrame (R"({"t":"configure","mode":"JT9"})") + << 60 * 12000 << QString {"051100"}; + QTest::newRow ("JT9 utc, then nutc") + << controlFrame (R"({"t":"configure","mode":"JT9","utc":"05:11:00"})") + + controlFrame (R"({"t":"configure","nutc":512})") + << 60 * 12000 << QString {"051200"}; + QTest::newRow ("JT65 05:11:00") + << controlFrame (R"({"t":"configure","mode":"JT65","utc":"05:11:00"})") << 60 * 12000 << QString {"051100"}; + QTest::newRow ("JT4 05:11:00") + << controlFrame (R"({"t":"configure","mode":"JT4","utc":"05:11:00"})") << 60 * 12000 << QString {"051100"}; + QTest::newRow ("FST4-60 05:11:00") + << controlFrame (R"({"t":"configure","mode":"FST4","trperiod":60,"utc":"05:11:00"})") << 60 * 12000 + << QString {"051100"}; + QTest::newRow ("FST4W-120 05:12:00") + << controlFrame (R"({"t":"configure","mode":"FST4W","trperiod":120,"utc":"05:12:00"})") << 120 * 12000 + << QString {"051200"}; + QTest::newRow ("Q65-60 05:11:00") + << controlFrame (R"({"t":"configure","mode":"Q65","trperiod":60,"utc":"05:11:00"})") << 60 * 12000 + << QString {"051100"}; + } + + void jt9LabelsPeriodsWithTheProducersUtc () + { + QFETCH (QByteArray, configure); + QFETCH (int, samples); + QFETCH (QString, periodEnd); + auto const result = runJt9 (sessionHeader () + configure + silentAudioFrame (samples)); + verifyCompleted (result, 0); + auto const events = verifyEvents (result); + QCOMPARE (eventsMatching (events.values, "error").size (), 0); + auto const completions = eventsMatching (events.values, "decode_finished"); + QCOMPARE (completions.size (), 1); + QCOMPARE (completions.first ().value ("period_end").toString (), periodEnd); + } + + void ft8DecodeCarriesTheProducersUtc_data () + { + QTest::addColumn ("utc"); + QTest::addColumn ("label"); + QTest::newRow ("05:11:15") << QString {"05:11:15"} << QString {"051115"}; + QTest::newRow ("00:45:15") << QString {"00:45:15"} << QString {"004515"}; + } + + void ft8DecodeCarriesTheProducersUtc () + { + QFETCH (QString, utc); + QFETCH (QString, label); + QFile recording {QString::fromUtf8 (FT8_ENGINE_WAV)}; + QVERIFY2 (recording.open (QIODevice::ReadOnly), qPrintable (recording.errorString ())); + auto const wav = recording.readAll (); + QCOMPARE (wav.size (), 44 + 15 * 12000 * 2); + QJsonObject configuration {{"t", "configure"}, {"mode", "FT8"}, {"utc", utc}}; + auto const result = runJt9 (sessionHeader () + controlFrame ( + QJsonDocument {configuration}.toJson (QJsonDocument::Compact)) + frame (0x01u, wav.mid (44))); + verifyCompleted (result, 0); + auto const events = verifyEvents (result); + QCOMPARE (eventsMatching (events.values, "error").size (), 0); + bool found = false; + for (auto const& decode : eventsMatching (events.values, "decode")) + { + QCOMPARE (decode.value ("time").toString (), label); + found |= decode.value ("message").toString ().trimmed () == "CQ K1JT FN20"; + } + QVERIFY2 (found, result.standardOutput.constData ()); + auto const completions = eventsMatching (events.values, "decode_finished"); + QCOMPARE (completions.size (), 1); + QCOMPARE (completions.first ().value ("period_end").toString (), label); + } + void wsprdRejectsOversizedFrames_data () { QTest::addColumn ("declaredLength"); diff --git a/widgets/JttyMessages.hpp b/widgets/JttyMessages.hpp index b25a1cf9..9f51a6a0 100644 --- a/widgets/JttyMessages.hpp +++ b/widgets/JttyMessages.hpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include @@ -262,6 +263,22 @@ namespace Jtty return {offset, length, message.mid (offset, length)}; } + // A segment that does not encode refuses the line rather than being cut shorter: the rest would continue the receiver's 80-column message. + template + std::optional> encodeTransmitLine (QString const& line, Encode&& encode) + { + QVector segments; + for (int offset = 0; offset < line.size ();) { + auto const source = nextTransmitTextSegment (line, offset); + if (!source.text.trimmed ().isEmpty ()) { + if (!encode (source.text)) return std::nullopt; + segments.append (source); + } + offset += source.length; + } + return segments; + } + // An empty result rejects oversized text before it reaches the fixed-width codec. inline QString transmitFrame (QString const& message) { diff --git a/widgets/mainwindow.cpp b/widgets/mainwindow.cpp index 9c9031fb..41f25835 100644 --- a/widgets/mainwindow.cpp +++ b/widgets/mainwindow.cpp @@ -5630,7 +5630,8 @@ void MainWindow::decode (Ft8MtdDecodeCoordinator::Stage ft8Stage, #if defined (WSJT_ENABLE_LIVE_AUDIO_TEST) bool MainWindow::startWavDecodeTest (QString const& path) { - auto const fixtureMode = ((m_mode == QStringLiteral ("JT9") + auto const fixtureMode = ((m_mode == QStringLiteral ("JT4") + || m_mode == QStringLiteral ("JT9") || m_mode == QStringLiteral ("JT65") || m_mode == QStringLiteral ("Q65")) && m_TRperiod == 60.0) || (m_mode == QStringLiteral ("FST4") && m_TRperiod == 15.0) diff --git a/widgets/mainwindow_jtty.cpp b/widgets/mainwindow_jtty.cpp index 2ad9b573..bd19b584 100644 --- a/widgets/mainwindow_jtty.cpp +++ b/widgets/mainwindow_jtty.cpp @@ -341,29 +341,18 @@ int MainWindow::countJttyTransmitFrames(QString const& preparedMessage) const int totalFrames = 0; auto const lines = preparedMessage.split (QLatin1Char ('\n')); for (auto const& line : lines) { - for (int offset = 0; offset < line.size ();) { - auto source = Jtty::nextTransmitTextSegment (line, offset); - if (source.text.trimmed ().isEmpty ()) { - offset += source.length; - continue; - } - for (;;) { - auto frame = Jtty::transmitFrame (source.text).toLatin1 (); - QVector tones (944); - int nsym = 0; - int frameStarts[kMaxJttyFrames] = {}; - int const finalFlag = 1; // irrelevant to frame count, which EOM doesn't affect - genjtty_profile_ (frame.data (), &exchangeProfile, tones.data (), - &nsym, frameStarts, &finalFlag, (FCL)80); - if (nsym > 0) { - totalFrames += nsym / 59; - break; - } - if (source.length <= 1) return totalFrames; - source = Jtty::nextTransmitTextSegment (line, offset, source.length - 1); - } - offset += source.length; - } + auto const encoded = Jtty::encodeTransmitLine (line, [&] (QString const& text) { + auto frame = Jtty::transmitFrame (text).toLatin1 (); + QVector tones (944); + int nsym = 0; + int frameStarts[kMaxJttyFrames] = {}; + int const finalFlag = 1; // irrelevant to frame count, which EOM doesn't affect + genjtty_profile_ (frame.data (), &exchangeProfile, tones.data (), + &nsym, frameStarts, &finalFlag, (FCL)80); + totalFrames += nsym / 59; + return nsym > 0; + }); + if (!encoded) return 0; } return totalFrames; } @@ -475,7 +464,7 @@ void MainWindow::execute_jtty_tx(qint64 requestId, QString message, bool isFinal } int const exchangeProfile = static_cast(jttyExchangeProfile(m_config)); - // One-shot encode of text already known to fit (no retry): used for the initial non-final pass and to re-bake a line's true last segment once its real EOM status is known. + // One-shot encode; empty tones mean the text did not encode. Used for the initial non-final pass and to re-bake a line's true last segment once its real EOM status is known. auto encodeOnce = [&] (QString const& text, bool segmentIsFinal) { Jtty::TransmitSegment segment; auto frame = Jtty::transmitFrame(text).toLatin1(); @@ -494,9 +483,15 @@ void MainWindow::execute_jtty_tx(qint64 requestId, QString message, bool isFinal // Fortran gives 1-indexed columns; store 0-indexed offsets. segment.frameCharStarts.append(frameStarts[i] - 1); } + } else { + segment.tones.clear(); } return segment; }; + auto refuseUnencodable = [&] { + showStatusMessage(tr("JTTY text not sent: a line does not fit in one message once encoded; shorten it and send again")); + Q_EMIT jttyTextRejected(requestId, JttyTxRejectReason::EncodingFailed); + }; QVector segments; // Newlines force a new segment; split them out before nextTransmitTextSegment (space-only breaks). @@ -504,32 +499,26 @@ void MainWindow::execute_jtty_tx(qint64 requestId, QString message, bool isFinal for (int lineIndex = 0; lineIndex < lines.size(); ++lineIndex) { auto const& line = lines[lineIndex]; int const lineStart = segments.size(); - for (int offset = 0; offset < line.size();) { - auto source = Jtty::nextTransmitTextSegment(line, offset); - if (source.text.trimmed().isEmpty()) { - offset += source.length; - continue; - } - Jtty::TransmitSegment segment; - for (;;) { - segment = encodeOnce(source.text, /*segmentIsFinal=*/false); - if (!segment.tones.isEmpty()) break; - if (source.length <= 1) { - Q_EMIT jttyTextRejected(requestId, JttyTxRejectReason::EncodingFailed); - return; - } - source = Jtty::nextTransmitTextSegment(line, offset, source.length - 1); - } + auto const encoded = Jtty::encodeTransmitLine(line, [&] (QString const& text) { + auto segment = encodeOnce(text, /*segmentIsFinal=*/false); + if (segment.tones.isEmpty()) return false; segment.frequency = ui->TxFreqSpinBox_2->value(); segments.append(std::move(segment)); - offset += source.length; + return true; + }); + if (!encoded) { + refuseUnencodable(); + return; } if (segments.size() == lineStart) continue; bool const lineIsFinal = lineIndex + 1 < lines.size() || isFinal; if (!lineIsFinal) continue; auto& last = segments.last(); auto final_ = encodeOnce(last.text, /*segmentIsFinal=*/true); - Q_ASSERT (!final_.tones.isEmpty()); // same text that just succeeded above + if (final_.tones.isEmpty()) { + refuseUnencodable(); + return; + } final_.frequency = last.frequency; last = std::move(final_); } -- cgit v1.2.3