diff --git a/.github/release/check_release_body.py b/.github/release/check_release_body.py new file mode 100644 index 0000000000..777c261dab --- /dev/null +++ b/.github/release/check_release_body.py @@ -0,0 +1,238 @@ +#!/usr/bin/env python3 +"""Read-only preflight for a decoded cargo-dist announcement or final notes file. + +Exit 0: pass/warning; 1: a size policy fails; 2: input/configuration error. +GitHub reports a 125,000-character maximum, without documenting its Unicode +unit. Code points are this check's explicit character-counting policy. The +optional UTF-8 budget is a conservative project policy, not an API byte limit. +No text is trimmed, normalized, truncated, published, or written by this tool. +Configuration checks require Python 3.11+; --check-dist-config prints the audited +version instead of a body report, for use by the installer step. +""" + +import argparse +import hashlib +import json +import os +from pathlib import Path +import sys + +GITHUB_MAX_CHARS = 125_000 +DEFAULT_WARN_AT = 120_000 +# Audit notes-file transport and release-job ordering before changing this pin. +AUDITED_DIST_VERSION = "0.31.0" +ENV_OVERHEAD = len(b"ANNOUNCEMENT_BODY=") + 1 # Include the terminating NUL. + + +def diagnostic(level, message): + if os.environ.get("GITHUB_ACTIONS") == "true": + # Keep untrusted paths/JSON diagnostics inside one workflow command. + message = message.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A") + print(f"::{level}::{message}", file=sys.stderr) + else: + print(f"{level.upper()}: {message}", file=sys.stderr) + + +class PreflightParser(argparse.ArgumentParser): + def error(self, message): + self.print_usage(sys.stderr) + diagnostic("error", message) + self.exit(2) + + +def audited_dist_version(path): + try: + import tomllib + except ImportError as exc: + raise ValueError("cargo-dist configuration checks require Python 3.11+") from exc + config = tomllib.loads(path.read_bytes().decode("utf-8", errors="strict")) + dist = config.get("dist") + if not isinstance(dist, dict) or dist.get("cargo-dist-version") != AUDITED_DIST_VERSION: + raise ValueError("configured cargo-dist version must match audited version " + + AUDITED_DIST_VERSION + + "; review the notes transport before upgrading the audit pin") + return AUDITED_DIST_VERSION + + +def unique_object(pairs): + result = {} + for key, value in pairs: + if key in result: + raise ValueError("duplicate JSON key: " + json.dumps(key)) + result[key] = value + return result + + +def reject_constant(value): + raise ValueError("non-standard JSON constant: " + value) + + +def read_input(args): + source = args.manifest or args.notes_file + # read_text() would translate CRLF and could undercount a notes file. + raw = source.read_bytes().decode("utf-8", errors="strict") + metadata = {} + if args.manifest: + doc = json.loads(raw, object_pairs_hook=unique_object, + parse_constant=reject_constant) + if not isinstance(doc, dict): + raise ValueError("manifest must be a JSON object") + body = doc.get("announcement_github_body") + if args.require_changelog: + changelog = doc.get("announcement_changelog") + if not isinstance(changelog, str) or not changelog.strip(): + raise ValueError("manifest must contain a nonempty changelog") + for key, expected in (("announcement_tag", args.expected_tag), + ("dist_version", args.expected_dist_version)): + if expected is not None and doc.get(key) != expected: + raise ValueError(key + " does not match the expected value") + if key in doc: + if not isinstance(doc[key], str) or not doc[key]: + raise ValueError(key + " must be a nonempty string") + metadata[key] = doc[key] + else: + body = raw + if not isinstance(body, str) or not body.strip(): + raise ValueError("release body must be a nonempty, non-whitespace string") + if "\x00" in body: + raise ValueError("release body contains NUL, unsupported by the transport") + # json.loads permits lone escaped surrogates; valid UTF-8 does not. + body.encode("utf-8", errors="strict") + return body, metadata + + +def check(body, args, metadata): + submitted = body + ("\n" if args.append_final_lf else "") + encoded = submitted.encode("utf-8") + counts = { + "announcement_code_points": len(body), + "submitted_code_points": len(submitted), + "submitted_utf8_bytes": len(encoded), + "submitted_utf16_units": len(submitted.encode("utf-16-le")) // 2, + "submitted_sha256": hashlib.sha256(encoded).hexdigest(), + "headroom_code_points": args.max_chars - len(submitted), + } + if args.manifest: + counts["announcement_env_entry_bytes"] = ( + len(body.encode("utf-8")) + ENV_OVERHEAD + ) + errors = [] + warnings = [] + if len(submitted) > args.max_chars: + errors.append(f"Submitted body has {len(submitted):,} code points; " + f"maximum {args.max_chars:,}; remove at least " + f"{len(submitted) - args.max_chars:,} code points.") + if args.max_utf8_bytes is not None and len(encoded) > args.max_utf8_bytes: + errors.append(f"Submitted body has {len(encoded):,} UTF-8 bytes; " + f"project byte budget {args.max_utf8_bytes:,}.") + if args.max_env_bytes is not None: + env_size = counts["announcement_env_entry_bytes"] + if env_size > args.max_env_bytes: + errors.append(f"ANNOUNCEMENT_BODY environment entry is {env_size:,} " + f"bytes including name and NUL; transport maximum " + f"{args.max_env_bytes:,}.") + if not errors: + if len(submitted) >= args.warn_at: + warnings.append(f"Submitted body reached warning threshold " + f"{args.warn_at:,} code points; " + f"{counts['headroom_code_points']:,} remain.") + if (args.max_utf8_bytes is not None and len(encoded) >= args.warn_at): + warnings.append(f"Submitted body reached {args.warn_at:,} UTF-8 " + f"bytes; project byte-budget headroom is " + f"{args.max_utf8_bytes - len(encoded):,} bytes.") + return { + "status": "fail" if errors else "warn" if warnings else "pass", + "metadata": metadata, + "measurements": counts, + "policy": { + "max_code_points": args.max_chars, + "warn_at": args.warn_at, + "max_utf8_bytes": args.max_utf8_bytes, + "max_env_bytes": args.max_env_bytes, + "append_final_lf": args.append_final_lf, + }, + "errors": errors, + "warnings": warnings, + } + + +def main(argv=None): + parser = PreflightParser(description=__doc__) + source = parser.add_mutually_exclusive_group(required=True) + source.add_argument("--manifest", type=Path) + source.add_argument("--notes-file", type=Path) + source.add_argument("--check-dist-config", type=Path, + help="validate TOML against the audit pin and print its version") + parser.add_argument("--expected-tag") + parser.add_argument("--expected-dist-version") + parser.add_argument("--audited-dist-config", type=Path, + help="validate TOML and manifest against the shared audit pin") + parser.add_argument("--require-changelog", action="store_true", + help="reject an announcement containing only downloads") + parser.add_argument("--append-final-lf", action="store_true", + help="model the LF added by cargo-dist's audited echo transport") + parser.add_argument("--max-chars", type=int, + help="character ceiling (default: 125000)") + parser.add_argument("--warn-at", type=int, + help="warning threshold (default: min(120000, --max-chars))") + parser.add_argument("--max-utf8-bytes", type=int, + help="optional conservative project byte budget") + parser.add_argument("--max-env-bytes", type=int, + help="target Linux per-env-string cap, including NUL") + args = parser.parse_args(argv) + if args.check_dist_config: + if (args.expected_tag is not None or args.expected_dist_version is not None + or args.audited_dist_config is not None or args.require_changelog + or args.append_final_lf or args.max_chars is not None + or args.warn_at is not None or args.max_utf8_bytes is not None + or args.max_env_bytes is not None): + parser.error("--check-dist-config must be used without body-check options") + try: + print(audited_dist_version(args.check_dist_config)) + except (OSError, ValueError, UnicodeError) as exc: + diagnostic("error", "release-body preflight input error: " + str(exc)) + return 2 + return 0 + if args.max_chars is None: + args.max_chars = GITHUB_MAX_CHARS + if not 0 < args.max_chars <= GITHUB_MAX_CHARS: + parser.error("--max-chars must be between 1 and 125000") + if args.warn_at is None: + args.warn_at = min(DEFAULT_WARN_AT, args.max_chars) + if not 0 < args.warn_at <= args.max_chars: + parser.error("--warn-at must be positive and no greater than --max-chars") + for value in (args.max_utf8_bytes, args.max_env_bytes): + if value is not None and value <= 0: + parser.error("byte budgets must be positive") + if args.notes_file and (args.expected_tag is not None + or args.expected_dist_version is not None + or args.audited_dist_config is not None + or args.require_changelog + or args.append_final_lf + or args.max_env_bytes is not None): + parser.error("metadata, LF and environment options require --manifest") + if args.audited_dist_config is not None and args.expected_dist_version is not None: + parser.error("choose --audited-dist-config or --expected-dist-version, not both") + try: + if args.audited_dist_config is not None: + args.expected_dist_version = audited_dist_version(args.audited_dist_config) + body, metadata = read_input(args) + report = check(body, args, metadata) + except (OSError, ValueError, UnicodeError) as exc: + diagnostic("error", "release-body preflight input error: " + str(exc)) + return 2 + print(json.dumps(report, indent=2, ensure_ascii=True)) + counts = report["measurements"] + print(f"release-body preflight {report['status']}: " + f"{counts['submitted_code_points']:,}/{args.max_chars:,} code points, " + f"{counts['submitted_utf8_bytes']:,} UTF-8 bytes, " + f"{counts['headroom_code_points']:,} code-point headroom", file=sys.stderr) + for message in report["errors"]: + diagnostic("error", message) + for message in report["warnings"]: + diagnostic("warning", message) + return 1 if report["errors"] else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.github/release/test_release_body.py b/.github/release/test_release_body.py new file mode 100644 index 0000000000..0a41e7be1f --- /dev/null +++ b/.github/release/test_release_body.py @@ -0,0 +1,414 @@ +#!/usr/bin/env python3 +"""CLI contract tests for the release-body preflight (no network).""" + +import hashlib +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + + +CHECKER = Path(__file__).with_name("check_release_body.py") + + +class ReleaseBodyTests(unittest.TestCase): + def invoke(self, raw, *, mode="manifest", args=(), expected=0, env_overrides=None): + """Run a real CLI process and verify that it never edits its input.""" + with tempfile.TemporaryDirectory(prefix="release-body-test-") as tmp: + root = Path(tmp) + path = root / ("input.json" if mode == "manifest" else "notes.md") + path.write_bytes(raw) + argv = [sys.executable, str(CHECKER)] + if mode is not None: + argv.extend(["--" + mode, str(path)]) + argv.extend(str(path) if arg == "{input}" else arg for arg in args) + env = dict(os.environ, PYTHONDONTWRITEBYTECODE="1", PYTHONUTF8="1", + GITHUB_ACTIONS="false") + for key, value in (env_overrides or {}).items(): + if value is None: + env.pop(key, None) + else: + env[key] = value + result = subprocess.run( + argv, cwd=root, env=env, capture_output=True, timeout=10, + check=False, + ) + stdout = result.stdout.decode("utf-8") + stderr = result.stderr.decode("utf-8") + self.assertEqual(result.returncode, expected, (stdout, stderr)) + self.assertEqual(path.read_bytes(), raw, "Preflight modified its input") + self.assertEqual( + sorted(p.name for p in root.iterdir()), [path.name], + "Preflight created an unexpected file", + ) + if expected == 2: + self.assertTrue(stderr.strip(), "Invalid input needs a diagnostic") + return None, stdout, stderr + report = json.loads(stdout) + self.assertIsInstance(report, dict) + self.assertIn(report["status"], ("pass", "warn", "fail")) + self.assertIsInstance(report["errors"], list) + self.assertIsInstance(report["warnings"], list) + self.assertIsInstance(report["measurements"], dict) + if expected == 1: + self.assertEqual(report["status"], "fail") + self.assertTrue(report["errors"]) + else: + self.assertNotEqual(report["status"], "fail") + self.assertFalse(report["errors"]) + if report["status"] == "warn": + self.assertTrue(report["warnings"]) + return report, stdout, stderr + + @staticmethod + def manifest(body, **overrides): + value = { + "announcement_github_body": body, + "announcement_tag": "v3.0.0-alpha.1", + "dist_version": "0.31.0", + } + value.update(overrides) + return json.dumps(value, ensure_ascii=True).encode("utf-8") + + def check_counts(self, report, submitted, *, announcement=None, limit=125_000): + counts = report["measurements"] + self.assertEqual(counts["submitted_code_points"], len(submitted)) + self.assertEqual(counts["submitted_utf8_bytes"], len(submitted.encode("utf-8"))) + self.assertEqual( + counts["submitted_utf16_units"], len(submitted.encode("utf-16-le")) // 2, + ) + self.assertEqual( + counts["submitted_sha256"], hashlib.sha256(submitted.encode("utf-8")).hexdigest(), + ) + self.assertEqual(counts["headroom_code_points"], limit - len(submitted)) + if announcement is not None: + self.assertEqual(counts["announcement_code_points"], len(announcement)) + self.assertEqual( + counts["announcement_env_entry_bytes"], + len(b"ANNOUNCEMENT_BODY=") + len(announcement.encode("utf-8")) + 1, + ) + + def test_ascii_notes_boundaries(self): + for length, code in ((124_999, 0), (125_000, 0), (125_001, 1)): + with self.subTest(length=length): + body = "a" * length + report, _, _ = self.invoke(body.encode(), mode="notes-file", expected=code) + self.check_counts(report, body) + + def test_manifest_without_append_preserves_exact_limit(self): + body = "a" * 125_000 + report, _, _ = self.invoke(self.manifest(body)) + self.check_counts(report, body, announcement=body) + + def test_manifest_appended_lf_boundary(self): + for length, code in ((124_999, 0), (125_000, 1)): + with self.subTest(length=length): + body = "a" * length + report, _, _ = self.invoke( + self.manifest(body), args=["--append-final-lf"], expected=code, + ) + self.check_counts(report, body + "\n", announcement=body) + + def test_existing_trailing_newlines_are_not_stripped(self): + body = "release\n\n" + report, _, _ = self.invoke(self.manifest(body), args=["--append-final-lf"]) + self.check_counts(report, body + "\n", announcement=body) + report, _, _ = self.invoke(body.encode(), mode="notes-file") + self.check_counts(report, body) + + def test_notes_crlf_is_not_normalized(self): + body = "first\r\nsecond\r\n" + report, _, _ = self.invoke(body.encode(), mode="notes-file") + self.check_counts(report, body) + + def test_unicode_codepoints_bytes_and_utf16_are_distinct(self): + body = "รฉ๐Ÿ˜€e\u0301" + self.assertEqual((len(body), len(body.encode("utf-8"))), (4, 9)) + report, _, _ = self.invoke(self.manifest(body)) + self.check_counts(report, body, announcement=body) + + def test_json_escapes_are_decoded_before_counting(self): + value = {"announcement_github_body": "รฉ๐Ÿ˜€\r\nquoted: \"ok\"\\"} + reports = [] + for ensure_ascii in (True, False): + with self.subTest(ensure_ascii=ensure_ascii): + raw = json.dumps(value, ensure_ascii=ensure_ascii).encode("utf-8") + report, _, _ = self.invoke(raw) + self.check_counts(report, value["announcement_github_body"], + announcement=value["announcement_github_body"]) + reports.append(report["measurements"]) + for key in ("submitted_code_points", "submitted_utf8_bytes", "submitted_sha256"): + self.assertEqual(reports[0][key], reports[1][key]) + + def test_default_does_not_impose_a_125000_byte_limit(self): + for body in ("รฉ" * 62_501, "๐Ÿ˜€" * 31_251): + with self.subTest(character=body[0]): + self.assertGreater(len(body.encode("utf-8")), 125_000) + report, _, _ = self.invoke(body.encode("utf-8"), mode="notes-file") + self.check_counts(report, body) + + def test_optional_utf8_budget_boundary(self): + for suffix, code in (("", 0), ("a", 1)): + with self.subTest(suffix=suffix): + body = "รฉ" * 62_500 + suffix + report, _, _ = self.invoke( + body.encode("utf-8"), mode="notes-file", + args=["--max-utf8-bytes", "125000"], expected=code, + ) + self.check_counts(report, body) + + def test_optional_byte_budget_counts_appended_lf(self): + for length, code in ((9, 0), (10, 1)): + with self.subTest(length=length): + body = "a" * length + report, _, _ = self.invoke( + self.manifest(body), + args=["--append-final-lf", "--max-utf8-bytes", "10"], expected=code, + ) + self.check_counts(report, body + "\n", announcement=body) + + def test_env_boundary_includes_name_equals_and_nul(self): + for suffix, code in (("a", 0), ("aa", 1)): + with self.subTest(suffix=suffix): + body = "รฉ" * 65_526 + suffix + report, _, _ = self.invoke( + self.manifest(body), args=["--max-env-bytes", "131072"], expected=code, + ) + self.check_counts(report, body, announcement=body) + + def test_env_boundary_excludes_lf_added_to_notes_file(self): + body = "รฉ" * 65_526 + "a" + report, _, _ = self.invoke( + self.manifest(body), args=["--max-env-bytes", "131072", "--append-final-lf"], + ) + self.check_counts(report, body + "\n", announcement=body) + + def test_warning_threshold(self): + for length, status in ((119_999, "pass"), (120_000, "warn")): + with self.subTest(length=length): + report, _, _ = self.invoke(("a" * length).encode(), mode="notes-file") + self.assertEqual(report["status"], status) + + def test_smaller_project_character_budget(self): + for length, code in ((10, 0), (11, 1)): + with self.subTest(length=length): + body = "a" * length + report, _, _ = self.invoke( + body.encode(), mode="notes-file", + args=["--max-chars", "10", "--warn-at", "8"], expected=code, + ) + self.check_counts(report, body, limit=10) + + def test_max_chars_alone_derives_warning_threshold(self): + for length, code, status in ((99_999, 0, "pass"), (100_000, 0, "warn"), + (100_001, 1, "fail")): + with self.subTest(length=length): + body = "a" * length + report, _, _ = self.invoke( + body.encode(), mode="notes-file", args=["--max-chars", "100000"], + expected=code, + ) + self.assertEqual(report["status"], status) + self.check_counts(report, body, limit=100_000) + + def assert_annotation(self, stderr, severity): + annotations = [line for line in stderr.splitlines() + if line.startswith(("::warning::", "::error::"))] + self.assertEqual(len(annotations), 1, stderr) + self.assertTrue(annotations[0].startswith("::" + severity + "::"), stderr) + self.assertNotIn("\r", stderr) + return annotations[0] + + def test_actions_warning_annotation(self): + report, stdout, stderr = self.invoke( + b"a" * 120_000, mode="notes-file", env_overrides={"GITHUB_ACTIONS": "true"}, + ) + self.assertEqual(report["status"], "warn") + self.assert_annotation(stderr, "warning") + self.assertNotIn("::warning::", stdout) + + def test_actions_size_failure_annotation(self): + report, stdout, stderr = self.invoke( + b"a" * 125_001, mode="notes-file", expected=1, + env_overrides={"GITHUB_ACTIONS": "true"}, + ) + self.assertEqual(report["status"], "fail") + self.assert_annotation(stderr, "error") + self.assertNotIn("::error::", stdout) + + def test_actions_input_failure_annotation(self): + _, stdout, stderr = self.invoke( + b"{", expected=2, env_overrides={"GITHUB_ACTIONS": "true"}, + ) + self.assert_annotation(stderr, "error") + self.assertNotIn("::error::", stdout) + + def test_plain_diagnostics_outside_github_actions(self): + for value in (None, "false", "TRUE"): + for raw, code, label in ((b"a" * 120_000, 0, "WARNING:"), + (b"a" * 125_001, 1, "ERROR:")): + with self.subTest(github_actions=value, expected=code): + _, _, stderr = self.invoke( + raw, mode="notes-file", expected=code, + env_overrides={"GITHUB_ACTIONS": value}, + ) + self.assertIn(label, stderr) + self.assertNotIn("::warning::", stderr) + self.assertNotIn("::error::", stderr) + + def test_actions_duplicate_key_cannot_inject_a_workflow_command(self): + key = json.dumps("duplicate%0A\r\n::warning::INJECTED_KEY") + raw = ('{"announcement_github_body":"valid",' + key + ':1,' + key + ':2}').encode() + _, _, stderr = self.invoke( + raw, expected=2, env_overrides={"GITHUB_ACTIONS": "true"}, + ) + annotation = self.assert_annotation(stderr, "error") + self.assertIn("%250A", annotation) + self.assertFalse(any(line.startswith("::warning::") for line in stderr.splitlines())) + + def test_actions_missing_path_cannot_inject_a_workflow_command(self): + path = "missing%0D\r\n::warning::INJECTED_PATH.json" + _, _, stderr = self.invoke( + b"unused", mode=None, args=["--manifest", path], expected=2, + env_overrides={"GITHUB_ACTIONS": "true"}, + ) + annotation = self.assert_annotation(stderr, "error") + self.assertIn("%250D", annotation) + self.assertFalse(any(line.startswith("::warning::") for line in stderr.splitlines())) + + def test_actions_parser_error_escapes_percent_cr_and_lf(self): + argument = "--unknown%0A\r\n::warning::INJECTED_ARGUMENT" + _, _, stderr = self.invoke( + self.manifest("release"), args=[argument], expected=2, + env_overrides={"GITHUB_ACTIONS": "true"}, + ) + annotation = self.assert_annotation(stderr, "error") + self.assertIn("--unknown%250A%0D%0A::warning::INJECTED_ARGUMENT", annotation) + self.assertFalse(any(line.startswith("::warning::") for line in stderr.splitlines())) + + def test_matching_tag_and_dist_version(self): + report, _, _ = self.invoke( + self.manifest("release"), + args=["--expected-tag", "v3.0.0-alpha.1", "--expected-dist-version", "0.31.0"], + ) + self.check_counts(report, "release", announcement="release") + + def test_mismatching_tag_or_dist_version(self): + for flag, expected in (("--expected-tag", "v9.0.0"), + ("--expected-dist-version", "0.0.1")): + with self.subTest(flag=flag): + self.invoke(self.manifest("release"), args=[flag, expected], expected=2) + + def test_missing_or_invalid_expected_metadata(self): + for key, flag in (("announcement_tag", "--expected-tag"), + ("dist_version", "--expected-dist-version")): + for value in (None, 31, "missing"): + with self.subTest(key=key, value=value): + data = {"announcement_github_body": "release"} + if value != "missing": + data[key] = value + self.invoke(json.dumps(data).encode(), args=[flag, "expected"], expected=2) + + def test_malformed_json(self): + for raw in (b"{", b"not-json", b'{"announcement_github_body":"ok"} garbage'): + with self.subTest(raw=raw): + self.invoke(raw, expected=2) + + def test_require_changelog_accepts_nonempty_notes(self): + report, _, _ = self.invoke( + self.manifest("generated body", announcement_changelog="Release changes"), + args=["--require-changelog"], + ) + self.assertEqual(report["status"], "pass") + + def test_require_changelog_rejects_missing_or_invalid_notes(self): + self.invoke(self.manifest("downloads only"), args=["--require-changelog"], expected=2) + for changelog in (None, "", " \r\n", 1, []): + with self.subTest(changelog=changelog): + self.invoke( + self.manifest("downloads only", announcement_changelog=changelog), + args=["--require-changelog"], expected=2, + ) + + def test_invalid_manifest_shapes_and_body_types(self): + values = [None, [], "release", {}, {"unrelated": "text"}] + values.extend({"announcement_github_body": value} + for value in (None, 0, False, [], {})) + for value in values: + with self.subTest(value=value): + self.invoke(json.dumps(value).encode(), expected=2) + + def test_empty_or_whitespace_only_body(self): + for body in ("", " \t\r\n", "\u2003\u00a0"): + for mode in ("manifest", "notes-file"): + with self.subTest(body=repr(body), mode=mode): + raw = self.manifest(body) if mode == "manifest" else body.encode("utf-8") + self.invoke(raw, mode=mode, expected=2) + + def test_invalid_utf8(self): + for mode, raw in (("manifest", b'{"announcement_github_body":"\xff"}'), + ("notes-file", b"release\xff"), + ("notes-file", b"\xed\xa0\x80")): + with self.subTest(mode=mode, raw=raw): + self.invoke(raw, mode=mode, expected=2) + + def test_escaped_lone_surrogates(self): + for body in ("\ud800", "\udfff", "prefix\ud800suffix"): + with self.subTest(body=repr(body)): + self.invoke(self.manifest(body), expected=2) + + def test_embedded_nul_is_rejected(self): + self.invoke(self.manifest("a\0b"), expected=2) + self.invoke(b"a\0b", mode="notes-file", expected=2) + + def test_duplicate_json_keys_are_rejected(self): + for raw in ( + b'{"announcement_github_body":"first","announcement_github_body":"second"}', + b'{"announcement_github_body":"ok","dist_version":"1","dist_version":"1"}', + b'{"announcement_github_body":"ok","other":{"x":1,"x":2}}', + ): + with self.subTest(raw=raw): + self.invoke(raw, expected=2) + + def test_input_selector_and_missing_file_errors(self): + self.invoke(b"unused", mode=None, expected=2) + self.invoke(self.manifest("ok"), args=["--notes-file", "{input}"], expected=2) + self.invoke(b"unused", mode=None, args=["--manifest", "missing.json"], expected=2) + + def test_manifest_only_options_rejected_for_notes_file(self): + for args in (["--append-final-lf"], ["--expected-tag", "v1"], + ["--expected-dist-version", "0.31.0"], ["--max-env-bytes", "131072"], + ["--require-changelog"]): + with self.subTest(args=args): + self.invoke(b"release", mode="notes-file", args=args, expected=2) + + def test_invalid_numeric_configuration(self): + cases = [ + ["--max-chars", "0"], ["--max-chars", "-1"], + ["--max-chars", "125001"], ["--max-chars", "abc"], + ["--warn-at", "0"], ["--warn-at", "-1"], ["--warn-at", "125001"], + ["--max-chars", "100", "--warn-at", "101"], + ["--max-utf8-bytes", "0"], ["--max-utf8-bytes", "-1"], + ["--max-env-bytes", "0"], ["--max-env-bytes", "-1"], + ] + for args in cases: + with self.subTest(args=args): + self.invoke(self.manifest("release"), args=args, expected=2) + + def test_report_and_diagnostics_do_not_expose_the_body(self): + sentinel = "PRIVATE_RELEASE_BODY_CONTENT_DO_NOT_PRINT_5a71f0" + for mode in ("manifest", "notes-file"): + for excess, code in ((0, 0), (125_001, 1)): + with self.subTest(mode=mode, excess=excess): + body = sentinel + "a" * excess + raw = self.manifest(body) if mode == "manifest" else body.encode() + _, stdout, stderr = self.invoke(raw, mode=mode, expected=code) + self.assertNotIn(sentinel, stdout) + self.assertNotIn(sentinel, stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/release/test_release_body_config.py b/.github/release/test_release_body_config.py new file mode 100644 index 0000000000..4c0ad934b6 --- /dev/null +++ b/.github/release/test_release_body_config.py @@ -0,0 +1,187 @@ +#!/usr/bin/env python3 +"""CLI tests for the shared cargo-dist transport audit (no network).""" + +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + + +CHECKER = Path(__file__).with_name("check_release_body.py") +# These fixtures describe the reviewed transport, not a second production pin. +AUDITED_VERSION = "0.31.0" +UNAUDITED_VERSION = "0.32.0" +CONFIG = "dist-workspace.toml" +MANIFEST = "manifest.json" + + +class ReleaseBodyConfigTests(unittest.TestCase): + def invoke(self, args, files, *, expected=0): + """Exercise the real CLI and require every supplied file to stay intact.""" + with tempfile.TemporaryDirectory(prefix="release-body-config-test-") as tmp: + root = Path(tmp) + for name, content in files.items(): + (root / name).write_bytes(content) + env = dict(os.environ, PYTHONDONTWRITEBYTECODE="1", PYTHONUTF8="1") + result = subprocess.run( + [sys.executable, "-B", str(CHECKER), *args], + cwd=root, env=env, capture_output=True, timeout=10, check=False, + ) + stdout = result.stdout.decode("utf-8") + stderr = result.stderr.decode("utf-8") + self.assertEqual(result.returncode, expected, (stdout, stderr)) + self.assertEqual( + sorted(p.name for p in root.iterdir()), sorted(files), + "Configuration validation created an unexpected file", + ) + for name, content in files.items(): + self.assertEqual((root / name).read_bytes(), content, + "Configuration validation changed " + name) + if expected == 2: + self.assertEqual(stdout, "", "An invalid config must not yield a usable version") + self.assertTrue(stderr.strip(), "Invalid input needs a diagnostic") + return stdout, stderr + + @staticmethod + def config(version=AUDITED_VERSION): + return ( + '[workspace]\nmembers = ["cargo:."]\n\n' + '[dist]\n# Version whose notes transport was audited.\n' + f'cargo-dist-version = "{version}"\nci = "github"\n' + ).encode("utf-8") + + @staticmethod + def manifest(version=AUDITED_VERSION, *, omit_version=False): + doc = { + "announcement_github_body": "Release body\n", + "announcement_changelog": "Release changes", + "announcement_tag": "v3.0.0-alpha", + } + if not omit_version: + doc["dist_version"] = version + return json.dumps(doc).encode("utf-8") + + def test_config_only_prints_exact_validated_version(self): + stdout, stderr = self.invoke( + ["--check-dist-config", CONFIG], {CONFIG: self.config()}, + ) + self.assertEqual(stdout, AUDITED_VERSION + "\n") + self.assertEqual(stderr, "") + + def test_config_upgrade_is_rejected_before_providing_installer_version(self): + self.invoke( + ["--check-dist-config", CONFIG], + {CONFIG: self.config(UNAUDITED_VERSION)}, expected=2, + ) + + def test_missing_config_file_is_rejected(self): + self.invoke(["--check-dist-config", CONFIG], {}, expected=2) + + def test_malformed_or_invalid_utf8_config_is_rejected(self): + for config in (b'[dist\ncargo-dist-version = "0.31.0"\n', + b'[dist]\ncargo-dist-version = "\xff"\n'): + with self.subTest(config=config): + self.invoke(["--check-dist-config", CONFIG], {CONFIG: config}, expected=2) + + def test_missing_config_version_or_dist_table_is_rejected(self): + for config in (b"", b"[dist]\nci = 'github'\n", + b"[other]\ncargo-dist-version = '0.31.0'\n", + b"dist = 'not a table'\n"): + with self.subTest(config=config): + self.invoke(["--check-dist-config", CONFIG], {CONFIG: config}, expected=2) + + def test_nonstring_config_versions_are_rejected(self): + for value in ("31", "31.0", "true", '["0.31.0"]', '{value = "0.31.0"}'): + with self.subTest(value=value): + config = f"[dist]\ncargo-dist-version = {value}\n".encode("utf-8") + self.invoke(["--check-dist-config", CONFIG], {CONFIG: config}, expected=2) + + def test_empty_or_semver_range_config_is_not_an_audited_exact_version(self): + for version in ("", "^0.31.0", ">=0.31.0", "0.31", "v0.31.0"): + with self.subTest(version=version): + self.invoke( + ["--check-dist-config", CONFIG], + {CONFIG: self.config(version)}, expected=2, + ) + + def test_audited_manifest_uses_shared_version_policy(self): + stdout, _ = self.invoke( + ["--manifest", MANIFEST, "--audited-dist-config", CONFIG, + "--expected-tag", "v3.0.0-alpha", "--require-changelog", "--append-final-lf"], + {CONFIG: self.config(), MANIFEST: self.manifest()}, + ) + report = json.loads(stdout) + self.assertEqual(report["status"], "pass") + self.assertEqual(report["metadata"]["dist_version"], AUDITED_VERSION) + self.assertEqual(report["measurements"]["submitted_code_points"], + len("Release body\n\n")) + + def test_stale_or_unaudited_manifest_version_is_rejected(self): + for version in ("0.30.0", UNAUDITED_VERSION): + with self.subTest(version=version): + self.invoke( + ["--manifest", MANIFEST, "--audited-dist-config", CONFIG], + {CONFIG: self.config(), MANIFEST: self.manifest(version)}, expected=2, + ) + + def test_synchronized_config_and_manifest_upgrade_still_needs_transport_audit(self): + self.invoke( + ["--manifest", MANIFEST, "--audited-dist-config", CONFIG], + {CONFIG: self.config(UNAUDITED_VERSION), + MANIFEST: self.manifest(UNAUDITED_VERSION)}, expected=2, + ) + + def test_missing_or_invalid_manifest_version_is_rejected(self): + manifests = [self.manifest(omit_version=True)] + manifests.extend(self.manifest(value) for value in (None, "", 31, True, [], {})) + for manifest in manifests: + with self.subTest(manifest=manifest): + self.invoke( + ["--manifest", MANIFEST, "--audited-dist-config", CONFIG], + {CONFIG: self.config(), MANIFEST: manifest}, expected=2, + ) + + def test_manifest_audit_also_requires_config_to_exist_and_match(self): + for files in ({MANIFEST: self.manifest()}, + {CONFIG: self.config(UNAUDITED_VERSION), MANIFEST: self.manifest()}): + with self.subTest(files=files): + self.invoke( + ["--manifest", MANIFEST, "--audited-dist-config", CONFIG], + files, expected=2, + ) + + def test_explicit_version_cannot_override_or_duplicate_audit_policy(self): + for version in (AUDITED_VERSION, UNAUDITED_VERSION): + with self.subTest(version=version): + self.invoke( + ["--manifest", MANIFEST, "--audited-dist-config", CONFIG, + "--expected-dist-version", version], + {CONFIG: self.config(), MANIFEST: self.manifest()}, expected=2, + ) + + def test_audit_config_requires_a_manifest(self): + self.invoke( + ["--notes-file", "notes.md", "--audited-dist-config", CONFIG], + {CONFIG: self.config(), "notes.md": b"Release body\n"}, expected=2, + ) + + def test_config_only_rejects_body_and_manifest_options(self): + files = {CONFIG: self.config(), MANIFEST: self.manifest(), "notes.md": b"Release body\n"} + body_options = ( + ["--manifest", MANIFEST], ["--notes-file", "notes.md"], + ["--audited-dist-config", CONFIG], ["--expected-tag", "v3.0.0-alpha"], + ["--expected-dist-version", AUDITED_VERSION], ["--require-changelog"], + ["--append-final-lf"], ["--max-chars", "125000"], + ["--warn-at", "120000"], ["--max-utf8-bytes", "125000"], + ["--max-env-bytes", "131072"], + ) + for options in body_options: + with self.subTest(options=options): + self.invoke(["--check-dist-config", CONFIG, *options], files, expected=2) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/workflows/release-body.yml b/.github/workflows/release-body.yml new file mode 100644 index 0000000000..b90b7c3394 --- /dev/null +++ b/.github/workflows/release-body.yml @@ -0,0 +1,74 @@ +name: Release Body Preflight + +# The generated release workflow is tag-only (pr-run-mode = "skip"). +# This independent check measures the version declared by the checked-out crate. +# Repeat after staging the final changelog and version bump. +# A PR stacked onto release/* is intentionally excluded. Its parent PR to main +# must pass this workflow after the changes are integrated, before tagging. +on: + pull_request: + branches: ["main", "v[0-9]*"] + push: + branches: ["main", "v[0-9]*"] + +permissions: + contents: read + +jobs: + check: + name: Generated release body + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + submodules: recursive + - name: Test the preflight checker + run: python3 -B -m unittest discover -s .github/release -p 'test_release_body*.py' -v + - name: Verify the audited cargo-dist configuration + id: dist-version + shell: bash + run: | + version=$(python3 -B .github/release/check_release_body.py \ + --check-dist-config dist-workspace.toml) + printf 'version=%s\n' "$version" >> "$GITHUB_OUTPUT" + - name: Install the pinned cargo-dist + shell: bash + env: + AUDITED_DIST_VERSION: ${{ steps.dist-version.outputs.version }} + run: | + curl --proto '=https' --tlsv1.2 -LsSf \ + "https://github.com/axodotdev/cargo-dist/releases/download/v${AUDITED_DIST_VERSION}/cargo-dist-installer.sh" | sh + "$HOME/.cargo/bin/dist" --version + - name: Determine the prospective release tag + id: version + shell: bash + run: | + cargo metadata --format-version=1 --no-deps > "$RUNNER_TEMP/release-body-cargo-metadata.json" + tag=$(jq -er '. as $workspace | .packages[] | + select(.manifest_path == ($workspace.workspace_root + "/Cargo.toml")) | + "v" + .version' "$RUNNER_TEMP/release-body-cargo-metadata.json") + printf 'tag=%s\n' "$tag" >> "$GITHUB_OUTPUT" + - name: Check generated workflow freshness + run: | + "$HOME/.cargo/bin/dist" generate --mode ci --check + - name: Plan and check the release body + shell: bash + env: + RELEASE_TAG: ${{ steps.version.outputs.tag }} + run: | + # Run in the checkout; only output files go to RUNNER_TEMP. + # Planning performs no builds, hosting, release creation or publishing. + "$HOME/.cargo/bin/dist" plan --tag="$RELEASE_TAG" --output-format=json \ + > "$RUNNER_TEMP/release-body-plan.json" + # The UTF-8 budget is project policy; GitHub reports a character limit. + # The environment cap is a backstop if that byte budget is raised. + python3 -B .github/release/check_release_body.py \ + --manifest "$RUNNER_TEMP/release-body-plan.json" \ + --expected-tag "$RELEASE_TAG" \ + --audited-dist-config dist-workspace.toml \ + --require-changelog \ + --append-final-lf \ + --max-utf8-bytes 125000 \ + --max-env-bytes 131072 diff --git a/.github/workflows/release-gate.yml b/.github/workflows/release-gate.yml index 9d0ef213fb..ddb785a486 100644 --- a/.github/workflows/release-gate.yml +++ b/.github/workflows/release-gate.yml @@ -22,6 +22,25 @@ jobs: persist-credentials: false - name: Test release validation run: python3 -B -m unittest discover -s .github/release -v + - name: Download the generated release plan + uses: actions/download-artifact@v7 + with: + name: artifacts-plan-dist-manifest + path: ${{ runner.temp }}/release-body-preflight + - name: Check the generated release body + shell: bash + run: | + # Use the same audited version/configuration policy as the PR check. + # The UTF-8 budget is project policy; GitHub reports a character limit. + # The environment cap is a backstop if that byte budget is raised. + python3 -B .github/release/check_release_body.py \ + --manifest "$RUNNER_TEMP/release-body-preflight/plan-dist-manifest.json" \ + --expected-tag "$GITHUB_REF_NAME" \ + --audited-dist-config dist-workspace.toml \ + --require-changelog \ + --append-final-lf \ + --max-utf8-bytes 125000 \ + --max-env-bytes 131072 - name: Require successful CI on the tagged commit env: GH_TOKEN: ${{ github.token }} diff --git a/CHANGELOG.md b/CHANGELOG.md index 718a369df8..debcb220a7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] -Minigraf v3 introduces format v8 with crash-atomic checkpoints, a streaming query engine, bounded-memory large transactions, and expanded query and binding APIs. This is the release-notes preview for 3.0.0-alpha. +## v3.0.0-alpha โ€” 2026-12-XX + +Minigraf v3 introduces format v8 with crash-atomic checkpoints, a streaming query engine, bounded-memory large transactions, and expanded query and binding APIs. This is the first v3 prerelease; v2.x users should stay on v2.x until 3.0.0 final. **Upgrading from v2.x.** Back up the `.graph` file and any `.wal` before opening it with v3. The first read-write open re-indexes a v7 file into v8 automatically and replays a v2.x WAL after migration. Migration appends the new pages and a backup meta page before committing page 0; an interrupted migration is repeated or recovered from that backup meta on the next open. The backup meta is crash recovery machinery, not a rollback copy. Read-only open loads v7 facts into memory without migrating or writing the file (memory grows with the file). Formats v1โ€“v6 are refused with STG-028: open them with v2.x first to migrate to v7. Migration is one-way; v2.x refuses v8 with STG-006, so retain the v7 backup for rollback and run `verify()` after upgrading. See [the migration and rollback procedure](docs/DURABILITY.md#upgrading). Results are bags, as in v2.0.12; add `:distinct` for set results and review the semantic changes below. The [v3 upgrade guide](https://project-minigraf.github.io/minigraf-docs/v3.0.0/upgrading-to-v3/) is on the v3 preview; `/latest/` stays on v2 until v3.0.0 final. @@ -19,6 +21,8 @@ Known issues for v2.x are in [#421](https://github.com/project-minigraf/minigraf - **`Value` is `#[non_exhaustive]` and has a `Set` variant** (#316). A `match` on `Value` outside the crate needs a wildcard arm, so later value kinds are not breaking changes. +- **`IndexedDbBackend::write_pages` takes the pages to delete** (Rust, `browser` feature). Its new second parameter, `deletes: Vec`, lists page ids removed in the same IndexedDB transaction. Pass `Vec::new()` when there is nothing to delete. The JavaScript API is not affected. + - **Kotlin package rename (JVM and Android).** Generated classes now live in `io.github.project_minigraf.minigraf` instead of `uniffi.minigraf_ffi`. Update Kotlin and Java imports, fully qualified names and any reflection lookups to the new package. - **Result multiplicity when upgrading** (#493). Queries return bags: different bindings can produce repeated `:find` tuples. This was already the default in v2.0.12; v3 adds the explicit `:distinct` option described under Added. If your application needs set results, add `:distinct` rather than relying on projection to remove duplicates, and check counts and pagination against that choice. @@ -289,63 +293,7 @@ Known issues for v2.x are in [#421](https://github.com/project-minigraf/minigraf ### Testing -- **JVM/WASI nightly lanes** (#858): 14 JVM and 3 WASI routes, pinned runtimes, measured-core/artifact provenance, strict raw-sample reporting and independent histories, live on both branches with the adapter merged in `minigraf-java`. The iOS simulator and Android emulator were qualified against matched Device Farm physical runs and rejected for every case, so no mobile lane is enabled ([report](docs/benchmarks/858-mobile-qualification/REPORT.md)). No runtime, file-format or Rust test inventory change. See [the adapter contract](docs/BINDING_BENCHMARKS.md). - -- **Heavy WAL entry replay test** (#865): a nightly acceptance test writes one WAL entry of 1,000,000 facts, reopens without a checkpoint and checks every replayed fact through entity, attribute and attribute-value lookups, then checkpoints, verifies and reopens. It passes; no production change. - -- **Owned and browser transaction tests** (#824): `tests/owned_tx_test.rs` checks that an owned transaction leaves the database as a borrowed one given the same statements and options (commit, rollback, drop; small and large; file and in-memory, after reopening), the threads rules and the begin refusals; the fault matrix runs its large-transaction and mixed-sync-mode cases through the owned transaction too. `src/browser/tx_tests.rs` (`wasm-bindgen`) checks the browser transaction against the native one over fixed statement sequences, its IndexedDB commit, rollback, drop and failed-flush paths, and the `[INT-001]`/`[API-018]` rules. - -- **Acceptance execution gaps** (#837): nonlinear and multistratum recursive - scaling, custom transaction chunk/clamp bounds, mandatory Linux RSS assertions, - and exact named-test/output verification in the nightly smoke route. The storage - bound now compares exact bytes rather than a truncated ratio. No engine, public - API or format change. See [bounds and validation](docs/benchmarks/837-acceptance-gaps.md). - -- **Deterministic storage schedule tests (#760).** Three separately enabled native tests explore transaction append, snapshot cutoffs and checkpoint publication with Shuttle, using the real storage methods and immutable committed-reader fixtures. Deliberate fault patches validate failure detection and schedule replay. Focused PR checks cover Linux, macOS, Windows and Linux MSRV; nightly/manual runs explore more schedules and retain replay inputs. [Findings and reproduction](docs/testing/deterministic-schedules.md) describe the limits; ordinary tests and production builds retain `std` synchronization. - -- **Format-v8 scalar key decoders are model checked (#693).** Pure inner decoders let Kani prove round trips for signed and unsigned integers, descending transaction counts, valid-to times, floats and six tagged scalar value kinds, plus no panic and bounded cursor consumption on short malformed inputs. The `Reader` still returns the same INT-049 messages and cursor positions; a test-only copy of its old code checks those against exhaustive 0โ€“2 byte and seeded longer inputs. Strings, sets, packed pages and WAL retain fuzz and property coverage. No key bytes or file format change. - -- **Statement bases and large write transactions (#550).** A `WriteTransaction` whose statements repeat, change, retract and re-assert each other's facts across chunks gives every statement the same outcome, and stores the same records, at chunk sizes 1 to 4 as with one chunk; queries after each statement return what a commit of the statements so far would hold; failed and rolled-back statements and transactions leave the file passing `verify`. The fault matrix covers a large `WriteTransaction` at every write and sync, and with `test-hooks` the crash-kill test runs every third transaction of its large variant as one. - -- **Golden-file compatibility corpus (#391).** `tests/golden/` holds v7 files written by minigraf 2.0.3, each with a JSON manifest of its CRC32, `tx_count` and expected query results. They cover one checkpoint, several checkpoints, indexes rebuilt on open, a WAL left by a crash, a WAL whose entries were already checkpointed, and same-transaction multi-values (#371). `tests/golden_corpus_test.rs` opens a copy of each file and checks its manifest after open, after a checkpoint and reopen, and after one more write. Golden files are never regenerated, only added; a new `golden-corpus` job in `policy.yml` fails a pull request that changes one. The generator is a standalone crate pinned to `minigraf = "=2.0.3"` (`tests/golden/gen/v7/`). On `v3`, each v7 file must also carry a v8 meta page after its first open, and seven v8 files are frozen alongside them, written by the `v3` branch at `23aa57c` (`tests/golden/gen/v8/`): one checkpoint, seven copy-on-write checkpoints, a crash-left v2 WAL, an already-checkpointed v2 WAL, same-transaction multi-values, a v7 file migrated in place, and long values (a 4,068-byte string stored twice, the 64/65-byte inline boundary, a 1,000-byte attribute and keyword). All #371 queries now pass. - -- **Model-based storage test (#385).** `tests/model_based_test.rs` runs random sequences of `transact` (multi-valued batches, transaction- and fact-level valid-time windows, a triple repeated with another window), `retract`, write transactions (committed or rolled back, retracting their own assertions), checkpoints, reopens (default, a 4-page cache, auto-checkpoint every 2 writes) and simulated crashes (a copy of the `.graph` file and WAL taken while the handle is open, so the WAL is replayed) against a file in a temp dir. After every step, `current_tx_count`, `verify`, full rows with windows and tx counts, and entity-, entity+attribute-, attribute-, attribute+value-, value-bound and full-scan queries, under `:as-of N` and `:valid-at T`, must match a plain reference model (one valid-time window per triple, #435; API-011 for two windows of one triple in one statement and API-019 for an empty or inverted window, from `execute` and `tx.execute`, #436; the last statement that writes a triple decides it at commit, #477). Reads inside a write transaction are checked against what its commit holds. Normal CI runs 24 cases; the nightly property-test workflow runs 30,000. - -- **SIGKILL crash test checks committed data (#384).** `tests/crash_kill_test.rs` used to check only that the file reopened and one attribute query ran, so it missed #370 and could not reach #371. The child now runs a seeded workload (multi-valued batches, batched retracts, re-assertions) and logs each transaction after `execute` returns; it checkpoints after every transaction, every third, never (WAL replay), automatically every 2 writes, or every third with `SyncMode::Normal`. After a `SIGKILL` at a random point, the reopened file must hold exactly the model after the last logged transaction or the one in flight, through a full scan, attribute (AEVT), attribute+value (AVET) and entity-bound (EAVT) queries and `:as-of`, with `verify` clean. The checks run again after a second reopen and after a checkpoint plus reopen. Per-PR CI runs 5 rounds (one per mode); the nightly crash-kill workflow runs 100 per OS. `MINIGRAF_CRASH_KILL_SEED` replays a failure. - -- **Fuzzing reaches the v8 decoders, and the corpus is kept between runs (#387, #375).** On `v3`, the `btree_page` and `fact_page` targets still wrote the pre-release single-header layout and stopped at `STG-032` on every input, and `file_header` rarely got past the meta CRC. The page targets now start from a real v8 file built through the public API (rewritten with `LogWriter` at fixed tx times so its bytes are the same in every process). They overwrite one page with the input and recompute that page's checksum. `btree_page` fuzzes any leaf or internal node of the five trees, `file_header` fuzzes either meta slot (with or without a matching CRC, with or without the other slot), and `fact_page` fuzzes the fact page of a v7 golden file through migration and the read-only load. Each run executes one input-chosen probe query or `verify()`. The nightly fuzz workflow now runs every target in its own parallel job, on `main` and `v3` on alternating crons, and keeps each target's corpus in the Actions cache. A new weekly workflow (`fuzz-corpus.yml`) minimizes the cached corpus with `cargo fuzz cmin`, keeps every committed `seed_*` file, and proposes the result as a pull request. - -- **Two fuzz targets check results, not just crashes (#387).** `ops_sequence` decodes the input into up to 32 storage operations (transact, retract, a write transaction that commits or rolls back, checkpoint, reopen, and a crash that opens a copy of the file and WAL) and, after each one, compares the full rows now and at an input-chosen `:as-of`, plus one input-chosen query shape, with the reference model of the model-based test. It uses that test's driver and checks, now in `tests/reference_model`, so the proptest test and the fuzzer share one oracle. `corrupt_file` damages a file written over three checkpoints with up to 16 byte flips and an optional truncation, without fixing any checksum, and requires every query to fail or to return exactly the answers of the last checkpoint or the one before it, all from the same one. Its first run found that a file cut to under one page opened as a new, empty database (#506). After that fix, the target checks short files too: a successful open must be empty under the torn-initial-write rules. - -- **Weekly soak test at scale (#392).** `tests/soak_test.rs` grows a file-backed database to 10M live facts in batches of 1โ€“2,000 facts (multi-valued tags and shard values in one transaction, strings over 64 bytes, refs), then churns it for the rest of a 5-hour budget at 50 transactions a second: retracts and re-asserts of random facts, and long retract/assert histories on 32 hot entities. It checkpoints every 20โ€“200 transactions and reopens every 2โ€“10 minutes, half from a checkpointed file and half replaying the WAL. Every 10 minutes, after every reopen, and between churn writes it checks samples against a reference that derives each entity's facts from its number and keeps only what was retracted: EAVT per entity, entity and attribute on the tags, AVET by unique name, AEVT over a sparse attribute, `:as-of` on hot entities, and the transaction counter; a full scan runs in a child process at 2M facts (so its memory does not hide a leak), and `verify()` at the end. It fails if RSS after a reopen grows past 1.25ร— the baseline plus 256 MiB. Metrics (file size, open and checkpoint time, RSS and peak RSS, p50/p99 per query path) go to a JSON-lines file that `.github/workflows/soak.yml` uploads weekly, alternating `main` and `v3`. `soak_short` runs the same driver at 20K facts in the per-PR suite. Found #518: attribute-and-value patterns scan the whole attribute. - -- **Coverage gates that gate (#396).** The per-module gate in `coverage-gates.yml` had never checked anything: the instrumented test run failed (the lock tests could not find `pid_ns_helper`), the report it grepped was empty, and every module was skipped with a warning, so the job passed. It also read `cargo llvm-cov --text`, which has no per-file percentages, and named `btree_v6`, which v3 no longer has. The job now runs the whole suite with branch coverage on a pinned nightly, fails if any test fails, and checks each file's line and branch percentage against `coverage-thresholds.toml` with `scripts/coverage_gates.py`; a file missing from the report, or without branch data, fails. The thresholds file covers the WAL, `db.rs`, the fact log and log writer, every storage file, and the evaluator, executor and stratification, with floors at the measured values less one point. It also lists the paths left uncovered on purpose (invariant checks, browser-only and Windows-only paths). New tests cover the WAL's fact-size and fact-count limits (the old fact-size test changed bytes inside the fact and never reached the limit), a WAL opened in a missing directory, a failed cut of a torn WAL tail, short v7 pages and slots past the count, backup meta pages of another generation or length, a torn first meta with data in page 1, `save` with nothing pending, `into_backend` with pending facts, `rebuild_indexes` with nothing checkpointed, unsorted or repeated B+tree input, a stored key inserted with another value, a tree pointer to a page of another type, the read-only `MutexStorageBackend`, and two threads missing the same page in the page cache (before, only a lucky race reached that path). Branch coverage of `wal.rs` went from 83% to 95%, `packed_pages.rs` from 86% to 100%, `persistent_facts.rs` from 82% to 88%, and `btree.rs` from 85% to 85.5%. A follow-up brought the storage files the issue named to 90% branch coverage or more: `btree.rs` to 95.7%, `persistent_facts.rs` to 91.7% and `index.rs` to 100%, with floors raised to match. New tests cover a leaf packing retried around one large entry, an entry larger than a page, separators over the fill target, an insert into a tree whose root points to itself, auto-save on drop, a torn first meta with a blank page 1, and an unreadable page past the meta's page count. Splitting internal nodes is now one pass: the old retry loop could not run, because the balanced cut always leaves each node within the fill target. The workflow pins cargo-llvm-cov 0.9.1, since 0.8.x missed the library's unit tests under the pinned nightly and reported much lower numbers. - -- **Performance envelope at 100Kโ€“10M facts (#394).** `examples/perf_envelope.rs` builds and caches fixtures of 100K, 1M and 10M facts (six attributes per entity, a ref tree, two valid-time windows, an entity with 1,000 versions). It reports open and checkpoint times, RSS, and p50/p99 latency for twelve query shapes, each shape in its own process. It builds with a new `envelope` Cargo profile (`release` at opt-level 3, as an application compiles the library; `release` itself is opt-level "z"). `docs/BENCHMARKS.md` and the README publish the results: point lookups and single-entity time travel stay flat (12โ€“14 ยตs at 10M facts). Scans, aggregations and joins grow linearly with the attributes they touch. Rule queries are supported to 100K facts only. A Python FFI round trip (`bench/envelope.py` in minigraf-python) adds about 70 ยตs per query. `.github/workflows/envelope.yml` runs 100K and 1M on demand, and a 10K smoke pass on PRs that change the harness. The nightly Criterion `query/*` groups gain 100K and 1M scales. Profiling at 1M facts found #528, #529, #530, #531 and #532. - -- **Pseudo-attribute sources (#594).** `tests/pseudo_source_test.rs` covers the source rule (nearest earlier pattern in the text, two pseudo-attributes sharing one, every fact through `[?e ?a _]`, constants by entity id, `$slot`s by name), `PRS-081` for each shape with no source, reading the outer fact from `not`, `not-join` (listed and unlisted variable), `or` (never a sibling branch) and `or-join`, closed rule bodies, and `:db/valid-at`. Parser, optimizer and matcher unit tests cover the hidden variables, their placement and the join variables a crossed `not-join` gains. The plan-independence matrix gains the pseudo-attribute shapes. - -- **Answers that depend on the plan fail the tests (#596).** A test-only switch (`minigraf::__reorder`, `test-hooks` feature) turns off every place the native build reorders: the pattern selectivity sort, the `not`/`not-join` and `or`/`or-join` cost sorts and the `or` short-circuits (#250), and the engine's `HashJoin` build side. `tests/plan_independence_test.rs` runs a matrix of queries (joins, expressions, rules, `or`/`or-join`, `not`/`not-join`, keyword and ref, floats, long strings, aggregates, time travel), in memory and on file, through `execute` and a cursor, with the switch on and off, and requires the same rows. Under `test-hooks` the model-based (#385) and property (#386) tests also run every generated query with the switch off. - -- **Rule queries on the engine (#548).** `tests/recursive_engine_test.rs` (10 tests) runs rule queries in memory, on a file with pending facts and after a checkpoint, checked against the executor until #551 and against its recorded answers since: transitive closure (linear and non-linear), mutual recursion, strata whose `not` and `or` rules recurse, rules that read their stratum outside a top-level invocation, derived facts seen by every pattern, the identity of derived facts, `nil` metadata, heads, both `INT-020` limits, and rule queries with aggregates, `not-join`, `or` and windows. Every existing rule suite (`recursive_rules_test`, `negation_test`, `disjunction_test`, `magic_sets_test`, the model-based and property tests) now runs its rule queries on the engine with the oracle. Engine unit tests cover routing and derived rows read across batches. - -- **Recursive rules at 5M derived facts (#473 acceptance, #548).** `tests/recursive_acceptance_test.rs` (ignored; the nightly smoke workflow runs it) derives 4,882,500 `reach` facts in 62 rounds over a layered graph of 155,000 edges and checks that every one is returned and that the query's peak RSS stays under 256 bytes per derived fact (169 measured); the default `max_derived_facts` then stops the same rule with `INT-020`. The #394 envelope has a `recursive` shape: the whole transitive closure of `:manager`, with no constant, so no magic sets. - -- **Query memory at 1M groups and on the #575 product (#549).** `tests/memory_limit_acceptance_test.rs` (ignored; the nightly smoke workflow runs it) returns 1M aggregate groups, or `QRY-012` naming `Aggregate` under a 32 MiB limit, and streams the 1.6M rows of 13 patterns sharing no variable over the fuzz harness's 3 facts in under 64 MiB of peak RSS (the executor held more than 5.7 GB), or `QRY-012` naming `HashJoin` under a 64-byte limit. An ignored engine test prints the meter's peak against the peak RSS: 435 MiB against about 545 MiB for the groups (`docs/BENCHMARKS.md`). Measuring it found `Aggregate`'s sorted map of groups uncharged while its hash table was still held; the map is now charged and the table freed first, which lowered the real peak from 651 MiB. - -- **Negation bodies in both forms (#546).** A second test-only switch (`minigraf::__subplans`, `test-hooks` feature) forces the engine's `not` / `not-join` bodies to run hashed or correlated. `tests/plan_independence_test.rs` runs every query with the body forms chosen, forced hashed and forced correlated, each with reordering on and off; its matrix gains negations over floats near zero, `0.0` and `-0.0`, keywords and refs of one entity, long strings, bodies reading an imported variable they do not bind, variable-free bodies and `:db/valid-at`. `tests/negation_equality_test.rs` checks the changed answers on every executor path, in memory and after a checkpoint. The property test's rerun also forces hashed bodies. Engine unit tests cover the form the planner picks, routing, multiplicity, failing expressions in bodies, and that a hashed body is read once and a correlated one probes once per row. - -- **Disjunctions (#546).** `tests/or_equality_test.rs` checks the changed `or` / `or-join` answers through `execute` and a cursor, in memory and after a checkpoint. `tests/plan_independence_test.rs` gains disjunctions (keywords meeting refs, floats near zero, long strings as keys, branches naming different outer variables or no join variable, a branch with `not`, an `or` with nothing before it, a cross product, `:db/valid-at` in a branch), run with branches chosen, forced hashed and forced correlated. The property test generates `or` and `or-join` over bound variables, with a reference evaluator that deduplicates the rows they keep. Engine unit tests run every disjunction shape with each branch form forced against the executor, and cover routing, the form the planner picks, `Distinct`, and that a hashed branch is read once. - -- **Aggregates and windows (#547).** `src/query/datalog/aggregate.rs` unit tests check every accumulator over every order of small inputs (exact float sums against hand-computed values, cancellation, subnormals, signed zeros, infinities and NaN, integer saturation, errors decided at the end) and that the value order is total. `tests/aggregate_window_rules_test.rs` checks the changed answers; `tests/plan_independence_test.rs` gains aggregate, window and mixed queries over ties, keywords and refs, and floats. - -- `tests/snapshot_atomicity_test.rs` races a writer against a reader: a query must see each transaction whole, whether written with `execute` or a `WriteTransaction` (#554), and must read one state for all its patterns (#555), in memory and on file. It also runs the v2.x checkpoint race from #558, which never failed on v3: copy-on-write checkpoints do not overwrite pages a published reader uses. - -- **The `datalog_eval` fuzz guard counts partial bindings** (#597). The guard skipped inputs whose patterns join to more than 50,000 rows, counting only the rows after the last pattern. At the time, a `not-join` body ran on the executor pattern by pattern in text order, so a 120-pattern body built hundreds of thousands of partial bindings before its last pattern matched nothing, and ran past the 60-second timeout. The guard now counts the bindings after every pattern. On the `v3` corpus (4,783 inputs) coverage drops by 7 of 9,719 edges. The input is added as a seed, as is the `btree_page` input of the cursor fix above. - -- **Kani proofs of the key and value encoders (#627).** `src/storage/keys/verification.rs` and `src/storage/index/verification.rs` hold 12 Kani encoder harnesses, compiled only under `cfg(kani)`. They prove for every input that the v8 key encoders (`put_int`, `put_uint`, `put_tx_desc`, `put_valid_to`, `float_bits`) and `encode_value` keep the order the indexes rely on, that every NaN encodes to one value, and that `float_bits` round-trips. `.github/workflows/kani.yml` runs them on pull requests that touch the keys and nightly on `main` and `v3`. The original #627 scope left decoders out; #693 above adds scalar decoder proofs. Strings, sets, packed pages, WAL and `Reader`'s error mapping remain under fuzz, property and differential tests. Test-only; `Cargo.toml` declares the `kani` cfg so normal builds do not warn. - -- **Parser vs grammar verifier (#643).** `src/query/datalog/parser/verifier.rs` checks, for every generated input, that the parser rejects what `tests/grammar/grammar.pest` rejects, and accepts what it accepts unless the error code is semantic (a listed code with a witness pest accepts). It runs every string of 1 to 3 characters over 102 characters (ASCII, `\t \n \r`, four non-ASCII stand-ins) through `parse_edn`, and every bracket-balanced sequence of up to `MINIGRAF_GRAMMAR_BOUND` (default 3) of 42 tokens in 17 command templates through `parse_datalog_command`, also with no separators up to 3 tokens. The initial 32-token, 15-template version took about 20 s by default and 3.5 min at bound 4 on a 16-thread machine. `KNOWN_DRIFT` is now empty: comments and non-ASCII identifiers are documented (#650); empty sections, ignored keywords, rule and call heads, a lone `:` and unterminated strings are checked (#651); excess fact elements are rejected (#649). Each fix removed its drift entry; a lone `-` remains the subtraction operator. `grammar.pest` now says what the parser means: a fact is exactly `[e a v]` plus an optional valid-time map and a retracted fact exactly `[e a v]`; `not`, `not-join`, `or`, `or-join` (and `and` inside an `or`) are never rule names; literal keywords end at a word boundary (`:find?x` is one keyword). +- New fault-injection, crash, model-based, golden-file, fuzz, Kani, grammar-verifier, plan-independence, soak and acceptance tests are listed in [Testing changes in v3.0.0-alpha](docs/testing/3.0.0-alpha-testing.md). ### Documentation diff --git a/CLAUDE.md b/CLAUDE.md index b5c7740a34..9498a5144e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -262,7 +262,7 @@ On v3, ordinary `avg` skips nil/nonnumeric values and divides the exact rounded ## Current Maintainer Context -**The latest release is v2.0.12; v3.0.0-alpha is in preparation on `main`** (the 3.x line; `v3` until the #937 branch move). The feature and correctness work is complete; the remaining milestone items are release tasks and documentation. +**The latest release is v3.0.0-alpha** (2026-12-XX), the first prerelease of the 3.x line on `main` (`v3` until the #937 branch move); the latest stable release is v2.0.12, on `v2.x`. The v8 format is frozen from the alpha. Known issues for the prereleases are the open issues in the v3.0.0 milestones. On `v3`, ordinary sum/sum-distinct skip nonnumbers and min/max compare all non-nil types by the window total order (#789). Empty-query conventions and all-nil min/max group dropping are preserved; INT-041/043/044 are deprecated for these paths. #781 expands Ordered Aggregate to sum/avg, fixed-scalar extrema and Integer/nil sum-distinct, with safe effective tuples and retained Sort for :with. Ordinary avg shipped in #777. @@ -273,7 +273,7 @@ On `v3`, expression `=` / `!=` resolves literal keywords once per operator (#774 Current plan (see `ROADMAP.md` and the milestones): - **In-memory ancestors (#723)**: eligible positive three-pattern delta runs retain an entity-first alternative with the same `Old`/`Delta`/`Full` ranges and separately planned head slots. Each round can select it when the committed dictionary is empty, the source relation has at most 128 rows and no stored records, and a capped AEVT count favors entity probes over building an uncached pending value map. Populated committed generations keep AVET probes. No additional write-time index. - **v2.x** (`v2.x` branch, format v7; `main` until #937) gets all bug fixes, including data-integrity and security fixes, as patch releases, but no new features, until 12 months after v3.0.0 final ships (not a prerelease). -- **v3.0.0** (format v8 and data integrity, plus `:limit` #306, optional `:distinct` output #493, `lag`/`lead` #182, sliding row frames #183, set membership predicates #316 and prepared queries in every binding #181, UDF registration in every binding #180; [v3.0.0 milestone](https://github.com/project-minigraf/minigraf/milestone/1)) is implemented on `main` for the alpha. The #937 branch move renamed `main` to `v2.x` and `v3` to `main` before the alpha was tagged: 3.x PRs target `main`, and 2.x fixes land on `main` first, then a backport PR to `v2.x`. Do not merge `v2.x` into `main`. Scheduled workflows run only from `main`'s copy and alternate `main` and `v2.x` by cron string; dispatch a check of either line from `main` with its ref. Shared CI changes that affect PR or push runs on `v2.x` (its own workflow copies) need a separate `v2.x` PR. The pre-release `main` โ†’ `v3` merge was done in #930. +- **v3.0.0** (format v8 and data integrity, plus `:limit` #306, optional `:distinct` output #493, `lag`/`lead` #182, sliding row frames #183, set membership predicates #316 and prepared queries in every binding #181, UDF registration in every binding #180; [v3.0.0 milestone](https://github.com/project-minigraf/minigraf/milestone/1)) is implemented on `main` and shipped in v3.0.0-alpha. The #937 branch move renamed `main` to `v2.x` and `v3` to `main` before the alpha was tagged: 3.x PRs target `main`, and 2.x fixes land on `main` first, then a backport PR to `v2.x`. Do not merge `v2.x` into `main`. Scheduled workflows run only from `main`'s copy and alternate `main` and `v2.x` by cron string; dispatch a check of either line from `main` with its ref. Shared CI changes that affect PR or push runs on `v2.x` (its own workflow copies) need a separate `v2.x` PR. The pre-release `main` โ†’ `v3` merge was done in #930. - **Input order (#641)** is complete on `v3`: committed scalar Sort omission, one-group count/count-distinct and partition-at-a-time windows. The reviewed design, fallback scope and acceptance gates are in `docs/superpowers/specs/2026-10-28-641-input-order-design.md`. - **Scalar key decoder proofs (#693)** are complete on `v3`. The pure decoder refactor preserves key bytes and INT-049 behavior; Kani covers round trips and bounded malformed inputs. The approved design and CI limits are in `docs/superpowers/specs/2026-10-29-693-decoder-proofs.md`. - **v3.next** (the release after v3.0.0) holds the query profiler (#185) and rule persistence (#241). OPFS `BrowserDb` (#441) is implemented on `v3` and is Tier 2 in the 3.0.0 release; its benchmark is an explicit exclusion carried to v3.next (#844). diff --git a/Cargo.toml b/Cargo.toml index dc427afb03..f8f4d2de12 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,7 +5,7 @@ resolver = "2" [package] name = "minigraf" -version = "2.0.5" +version = "3.0.0-alpha" edition = "2024" rust-version = "1.89" description = "Zero-config, single-file, embedded graph database with bi-temporal Datalog queries" diff --git a/ROADMAP.md b/ROADMAP.md index ff8feebefc..91b544e6d3 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -4,7 +4,7 @@ Minigraf runs inside agent processes, mobile apps and browsers. The project prioritizes embedded deployment and reliable storage. -For the unreleased v3.0.0, `main` implements ordinary `avg` with the same numeric inputs as window `avg` (#777). Ordinary `sum` and `sum-distinct` skip nil and nonnumeric values, and ordinary `min` and `max` compare non-nil values in the same order as the window functions (#789). Existing empty-group results are unchanged. These changes were not backported to v2.x. See the [changelog](CHANGELOG.md) for details. +From v3.0.0-alpha, `main` implements ordinary `avg` with the same numeric inputs as window `avg` (#777). Ordinary `sum` and `sum-distinct` skip nil and nonnumeric values, and ordinary `min` and `max` compare non-nil values in the same order as the window functions (#789). Existing empty-group results are unchanged. These changes were not backported to v2.x. See the [changelog](CHANGELOG.md) for details. Completed releases and their implementation details live in the [CHANGELOG](CHANGELOG.md). This roadmap lists planned work and research. @@ -158,9 +158,9 @@ v2.x gets all bug fixes, including data-integrity and security fixes, but no new --- -## v3.0.0 โ€” File Format v8 and Data Integrity (alpha in preparation) +## v3.0.0 โ€” File Format v8 and Data Integrity (3.0.0-alpha released 2026-12-XX) -The feature and correctness work below is complete for **3.0.0-alpha** (developed on `v3`, which became `main` in the #937 branch move); it is not yet released. The open milestone items are release preparation: version bump (#929), branch move (#937), performance-envelope refresh or exception (#942), nightly routing (#940), release pipeline (#938, #939), and documentation (#931โ€“#933). +The feature and correctness work below shipped in **3.0.0-alpha** (developed on `v3`, which became `main` in the #937 branch move). Issues open before 3.0.0 final are in the [v3.0.0 milestone](https://github.com/project-minigraf/minigraf/milestone/1). - Bounded typed incoming references (#924): core Rust transaction APIs implemented, with separate link/record limits, exact scalar Ref matching and target-local access in every storage layer. The JVM bindings and docs-site deliverables are merged. The measurement report shows no median regression above 5% on any of 65 IDs in either round; see [acceptance evidence](docs/testing/924-incoming-refs.md). - Incoming-reference binding parity (#925; done): `BrowserWriteTransaction.incomingRefs` implements exact JS budgets, typed complete/exhausted outcomes and callback reentry guards. The remaining native bindings, binding template, WASM package and docs-site PRs are merged. The WASI package remains a REPL without transaction handles. @@ -326,7 +326,7 @@ When evaluating features, ask: ## Current Focus - v2.x maintenance on `v2.x`: all bug fixes, including data-integrity and security fixes, but no new features, until 12 months after v3.0.0 final ships (not a prerelease) -- v3.0.0-alpha release preparation on `main`: the feature and correctness work is complete; remaining release tasks are tracked in the [v3.0.0 milestone](https://github.com/project-minigraf/minigraf/milestone/1) +- v3.0.0 prereleases on `main`, towards 3.0.0 final: fixes for issues in the [v3.0.0 milestone](https://github.com/project-minigraf/minigraf/milestone/1) arrive in the next prerelease - v3.next features after v3.0.0 - Ecosystem work tracked in [`minigraf-examples`](https://github.com/project-minigraf/minigraf-examples) - Developer tools tracked in `minigraf-inspector` and `minigraf-visualizer` @@ -335,4 +335,4 @@ See [GitHub Issues](https://github.com/project-minigraf/minigraf/issues) for spe --- -**Last updated**: November 2026 โ€” v3.0.0-alpha in preparation. +**Last updated**: December 2026 โ€” v3.0.0-alpha, the first v3 prerelease, is the current release; v2.0.12 is the latest stable release. diff --git a/docs/TEST_COVERAGE.md b/docs/TEST_COVERAGE.md index 88ccd6a816..9476a237f7 100644 --- a/docs/TEST_COVERAGE.md +++ b/docs/TEST_COVERAGE.md @@ -276,7 +276,7 @@ Not counted above: the browser tests and the WASI run (see [Browser and WASI](#b Also outside those counts: three native unit tests in the separate #760 `minigraf_shuttle` build. The [bounded suite and findings](testing/deterministic-schedules.md) record 90,000 passing schedule executions and three deliberately injected faults, each replayed 10/10 times. The suite checks real storage synchronization with immutable committed-reader fixtures; it does not simulate file durability. `deterministic-schedules.yml` runs relevant v3 PRs on three native OSes plus Linux MSRV, with larger nightly/manual searches and replay artifacts. Default-feature test counts are unchanged. -**Scope**: the unreleased file-format-v8 work (#287, #371): the index-key value-collision fix, the v7โ†’v8 migration, and the drop of formats v1โ€“v6. Otherwise the public database API, the Datalog engine, storage and recovery paths, v2.0.0's locking and structured-error-code changes, and v2.0.1's regression test for rebuilding indexes on open after several checkpoints (#370). Tests merged from the v2.x line are marked *(v2.x)*. +**Scope**: the v3.0.0 file-format-v8 work (#287, #371): the index-key value-collision fix, the v7โ†’v8 migration, and the drop of formats v1โ€“v6. Otherwise the public database API, the Datalog engine, storage and recovery paths, v2.0.0's locking and structured-error-code changes, and v2.0.1's regression test for rebuilding indexes on open after several checkpoints (#370). Tests merged from the v2.x line are marked *(v2.x)*. **#789 verification (2026-10-29)**: the change adds 12 default-feature tests and one additional `test-hooks` test. Before the runtime edits, all seven new diff --git a/docs/testing/3.0.0-alpha-testing.md b/docs/testing/3.0.0-alpha-testing.md new file mode 100644 index 0000000000..5a71f56812 --- /dev/null +++ b/docs/testing/3.0.0-alpha-testing.md @@ -0,0 +1,61 @@ +# Testing changes in v3.0.0-alpha + +The full Testing section of the [v3.0.0-alpha changelog](../../CHANGELOG.md#v300-alpha--2026-12-xx). It is a separate file because GitHub limits a release body to 125,000 characters and cargo-dist copies the whole changelog section into it. + +- **JVM/WASI nightly lanes** (#858): 14 JVM and 3 WASI routes, pinned runtimes, measured-core/artifact provenance, strict raw-sample reporting and independent histories, live on both branches with the adapter merged in `minigraf-java`. The iOS simulator and Android emulator were qualified against matched Device Farm physical runs and rejected for every case, so no mobile lane is enabled ([report](../benchmarks/858-mobile-qualification/REPORT.md)). No runtime, file-format or Rust test inventory change. See [the adapter contract](../BINDING_BENCHMARKS.md). + +- **Heavy WAL entry replay test** (#865): a nightly acceptance test writes one WAL entry of 1,000,000 facts, reopens without a checkpoint and checks every replayed fact through entity, attribute and attribute-value lookups, then checkpoints, verifies and reopens. It passes; no production change. + +- **Owned and browser transaction tests** (#824): `tests/owned_tx_test.rs` checks that an owned transaction leaves the database as a borrowed one given the same statements and options (commit, rollback, drop; small and large; file and in-memory, after reopening), the threads rules and the begin refusals; the fault matrix runs its large-transaction and mixed-sync-mode cases through the owned transaction too. `src/browser/tx_tests.rs` (`wasm-bindgen`) checks the browser transaction against the native one over fixed statement sequences, its IndexedDB commit, rollback, drop and failed-flush paths, and the `[INT-001]`/`[API-018]` rules. + +- **Acceptance execution gaps** (#837): nonlinear and multistratum recursive + scaling, custom transaction chunk/clamp bounds, mandatory Linux RSS assertions, + and exact named-test/output verification in the nightly smoke route. The storage + bound now compares exact bytes rather than a truncated ratio. No engine, public + API or format change. See [bounds and validation](../benchmarks/837-acceptance-gaps.md). + +- **Deterministic storage schedule tests (#760).** Three separately enabled native tests explore transaction append, snapshot cutoffs and checkpoint publication with Shuttle, using the real storage methods and immutable committed-reader fixtures. Deliberate fault patches validate failure detection and schedule replay. Focused PR checks cover Linux, macOS, Windows and Linux MSRV; nightly/manual runs explore more schedules and retain replay inputs. [Findings and reproduction](deterministic-schedules.md) describe the limits; ordinary tests and production builds retain `std` synchronization. + +- **Format-v8 scalar key decoders are model checked (#693).** Pure inner decoders let Kani prove round trips for signed and unsigned integers, descending transaction counts, valid-to times, floats and six tagged scalar value kinds, plus no panic and bounded cursor consumption on short malformed inputs. The `Reader` still returns the same INT-049 messages and cursor positions; a test-only copy of its old code checks those against exhaustive 0โ€“2 byte and seeded longer inputs. Strings, sets, packed pages and WAL retain fuzz and property coverage. No key bytes or file format change. + +- **Statement bases and large write transactions (#550).** A `WriteTransaction` whose statements repeat, change, retract and re-assert each other's facts across chunks gives every statement the same outcome, and stores the same records, at chunk sizes 1 to 4 as with one chunk; queries after each statement return what a commit of the statements so far would hold; failed and rolled-back statements and transactions leave the file passing `verify`. The fault matrix covers a large `WriteTransaction` at every write and sync, and with `test-hooks` the crash-kill test runs every third transaction of its large variant as one. + +- **Golden-file compatibility corpus (#391).** `tests/golden/` holds v7 files written by minigraf 2.0.3, each with a JSON manifest of its CRC32, `tx_count` and expected query results. They cover one checkpoint, several checkpoints, indexes rebuilt on open, a WAL left by a crash, a WAL whose entries were already checkpointed, and same-transaction multi-values (#371). `tests/golden_corpus_test.rs` opens a copy of each file and checks its manifest after open, after a checkpoint and reopen, and after one more write. Golden files are never regenerated, only added; a new `golden-corpus` job in `policy.yml` fails a pull request that changes one. The generator is a standalone crate pinned to `minigraf = "=2.0.3"` (`tests/golden/gen/v7/`). On `v3`, each v7 file must also carry a v8 meta page after its first open, and seven v8 files are frozen alongside them, written by the `v3` branch at `23aa57c` (`tests/golden/gen/v8/`): one checkpoint, seven copy-on-write checkpoints, a crash-left v2 WAL, an already-checkpointed v2 WAL, same-transaction multi-values, a v7 file migrated in place, and long values (a 4,068-byte string stored twice, the 64/65-byte inline boundary, a 1,000-byte attribute and keyword). All #371 queries now pass. + +- **Model-based storage test (#385).** `tests/model_based_test.rs` runs random sequences of `transact` (multi-valued batches, transaction- and fact-level valid-time windows, a triple repeated with another window), `retract`, write transactions (committed or rolled back, retracting their own assertions), checkpoints, reopens (default, a 4-page cache, auto-checkpoint every 2 writes) and simulated crashes (a copy of the `.graph` file and WAL taken while the handle is open, so the WAL is replayed) against a file in a temp dir. After every step, `current_tx_count`, `verify`, full rows with windows and tx counts, and entity-, entity+attribute-, attribute-, attribute+value-, value-bound and full-scan queries, under `:as-of N` and `:valid-at T`, must match a plain reference model (one valid-time window per triple, #435; API-011 for two windows of one triple in one statement and API-019 for an empty or inverted window, from `execute` and `tx.execute`, #436; the last statement that writes a triple decides it at commit, #477). Reads inside a write transaction are checked against what its commit holds. Normal CI runs 24 cases; the nightly property-test workflow runs 30,000. + +- **SIGKILL crash test checks committed data (#384).** `tests/crash_kill_test.rs` used to check only that the file reopened and one attribute query ran, so it missed #370 and could not reach #371. The child now runs a seeded workload (multi-valued batches, batched retracts, re-assertions) and logs each transaction after `execute` returns; it checkpoints after every transaction, every third, never (WAL replay), automatically every 2 writes, or every third with `SyncMode::Normal`. After a `SIGKILL` at a random point, the reopened file must hold exactly the model after the last logged transaction or the one in flight, through a full scan, attribute (AEVT), attribute+value (AVET) and entity-bound (EAVT) queries and `:as-of`, with `verify` clean. The checks run again after a second reopen and after a checkpoint plus reopen. Per-PR CI runs 5 rounds (one per mode); the nightly crash-kill workflow runs 100 per OS. `MINIGRAF_CRASH_KILL_SEED` replays a failure. + +- **Fuzzing reaches the v8 decoders, and the corpus is kept between runs (#387, #375).** On `v3`, the `btree_page` and `fact_page` targets still wrote the pre-release single-header layout and stopped at `STG-032` on every input, and `file_header` rarely got past the meta CRC. The page targets now start from a real v8 file built through the public API (rewritten with `LogWriter` at fixed tx times so its bytes are the same in every process). They overwrite one page with the input and recompute that page's checksum. `btree_page` fuzzes any leaf or internal node of the five trees, `file_header` fuzzes either meta slot (with or without a matching CRC, with or without the other slot), and `fact_page` fuzzes the fact page of a v7 golden file through migration and the read-only load. Each run executes one input-chosen probe query or `verify()`. The nightly fuzz workflow now runs every target in its own parallel job, on `main` and `v3` on alternating crons, and keeps each target's corpus in the Actions cache. A new weekly workflow (`fuzz-corpus.yml`) minimizes the cached corpus with `cargo fuzz cmin`, keeps every committed `seed_*` file, and proposes the result as a pull request. + +- **Two fuzz targets check results, not just crashes (#387).** `ops_sequence` decodes the input into up to 32 storage operations (transact, retract, a write transaction that commits or rolls back, checkpoint, reopen, and a crash that opens a copy of the file and WAL) and, after each one, compares the full rows now and at an input-chosen `:as-of`, plus one input-chosen query shape, with the reference model of the model-based test. It uses that test's driver and checks, now in `tests/reference_model`, so the proptest test and the fuzzer share one oracle. `corrupt_file` damages a file written over three checkpoints with up to 16 byte flips and an optional truncation, without fixing any checksum, and requires every query to fail or to return exactly the answers of the last checkpoint or the one before it, all from the same one. Its first run found that a file cut to under one page opened as a new, empty database (#506). After that fix, the target checks short files too: a successful open must be empty under the torn-initial-write rules. + +- **Weekly soak test at scale (#392).** `tests/soak_test.rs` grows a file-backed database to 10M live facts in batches of 1โ€“2,000 facts (multi-valued tags and shard values in one transaction, strings over 64 bytes, refs), then churns it for the rest of a 5-hour budget at 50 transactions a second: retracts and re-asserts of random facts, and long retract/assert histories on 32 hot entities. It checkpoints every 20โ€“200 transactions and reopens every 2โ€“10 minutes, half from a checkpointed file and half replaying the WAL. Every 10 minutes, after every reopen, and between churn writes it checks samples against a reference that derives each entity's facts from its number and keeps only what was retracted: EAVT per entity, entity and attribute on the tags, AVET by unique name, AEVT over a sparse attribute, `:as-of` on hot entities, and the transaction counter; a full scan runs in a child process at 2M facts (so its memory does not hide a leak), and `verify()` at the end. It fails if RSS after a reopen grows past 1.25ร— the baseline plus 256 MiB. Metrics (file size, open and checkpoint time, RSS and peak RSS, p50/p99 per query path) go to a JSON-lines file that `.github/workflows/soak.yml` uploads weekly, alternating `main` and `v3`. `soak_short` runs the same driver at 20K facts in the per-PR suite. Found #518: attribute-and-value patterns scan the whole attribute. + +- **Coverage gates that gate (#396).** The per-module gate in `coverage-gates.yml` had never checked anything: the instrumented test run failed (the lock tests could not find `pid_ns_helper`), the report it grepped was empty, and every module was skipped with a warning, so the job passed. It also read `cargo llvm-cov --text`, which has no per-file percentages, and named `btree_v6`, which v3 no longer has. The job now runs the whole suite with branch coverage on a pinned nightly, fails if any test fails, and checks each file's line and branch percentage against `coverage-thresholds.toml` with `scripts/coverage_gates.py`; a file missing from the report, or without branch data, fails. The thresholds file covers the WAL, `db.rs`, the fact log and log writer, every storage file, and the evaluator, executor and stratification, with floors at the measured values less one point. It also lists the paths left uncovered on purpose (invariant checks, browser-only and Windows-only paths). New tests cover the WAL's fact-size and fact-count limits (the old fact-size test changed bytes inside the fact and never reached the limit), a WAL opened in a missing directory, a failed cut of a torn WAL tail, short v7 pages and slots past the count, backup meta pages of another generation or length, a torn first meta with data in page 1, `save` with nothing pending, `into_backend` with pending facts, `rebuild_indexes` with nothing checkpointed, unsorted or repeated B+tree input, a stored key inserted with another value, a tree pointer to a page of another type, the read-only `MutexStorageBackend`, and two threads missing the same page in the page cache (before, only a lucky race reached that path). Branch coverage of `wal.rs` went from 83% to 95%, `packed_pages.rs` from 86% to 100%, `persistent_facts.rs` from 82% to 88%, and `btree.rs` from 85% to 85.5%. A follow-up brought the storage files the issue named to 90% branch coverage or more: `btree.rs` to 95.7%, `persistent_facts.rs` to 91.7% and `index.rs` to 100%, with floors raised to match. New tests cover a leaf packing retried around one large entry, an entry larger than a page, separators over the fill target, an insert into a tree whose root points to itself, auto-save on drop, a torn first meta with a blank page 1, and an unreadable page past the meta's page count. Splitting internal nodes is now one pass: the old retry loop could not run, because the balanced cut always leaves each node within the fill target. The workflow pins cargo-llvm-cov 0.9.1, since 0.8.x missed the library's unit tests under the pinned nightly and reported much lower numbers. + +- **Performance envelope at 100Kโ€“10M facts (#394).** `examples/perf_envelope.rs` builds and caches fixtures of 100K, 1M and 10M facts (six attributes per entity, a ref tree, two valid-time windows, an entity with 1,000 versions). It reports open and checkpoint times, RSS, and p50/p99 latency for twelve query shapes, each shape in its own process. It builds with a new `envelope` Cargo profile (`release` at opt-level 3, as an application compiles the library; `release` itself is opt-level "z"). `docs/BENCHMARKS.md` and the README publish the results: point lookups and single-entity time travel stay flat (12โ€“14 ยตs at 10M facts). Scans, aggregations and joins grow linearly with the attributes they touch. Rule queries are supported to 100K facts only. A Python FFI round trip (`bench/envelope.py` in minigraf-python) adds about 70 ยตs per query. `.github/workflows/envelope.yml` runs 100K and 1M on demand, and a 10K smoke pass on PRs that change the harness. The nightly Criterion `query/*` groups gain 100K and 1M scales. Profiling at 1M facts found #528, #529, #530, #531 and #532. + +- **Pseudo-attribute sources (#594).** `tests/pseudo_source_test.rs` covers the source rule (nearest earlier pattern in the text, two pseudo-attributes sharing one, every fact through `[?e ?a _]`, constants by entity id, `$slot`s by name), `PRS-081` for each shape with no source, reading the outer fact from `not`, `not-join` (listed and unlisted variable), `or` (never a sibling branch) and `or-join`, closed rule bodies, and `:db/valid-at`. Parser, optimizer and matcher unit tests cover the hidden variables, their placement and the join variables a crossed `not-join` gains. The plan-independence matrix gains the pseudo-attribute shapes. + +- **Answers that depend on the plan fail the tests (#596).** A test-only switch (`minigraf::__reorder`, `test-hooks` feature) turns off every place the native build reorders: the pattern selectivity sort, the `not`/`not-join` and `or`/`or-join` cost sorts and the `or` short-circuits (#250), and the engine's `HashJoin` build side. `tests/plan_independence_test.rs` runs a matrix of queries (joins, expressions, rules, `or`/`or-join`, `not`/`not-join`, keyword and ref, floats, long strings, aggregates, time travel), in memory and on file, through `execute` and a cursor, with the switch on and off, and requires the same rows. Under `test-hooks` the model-based (#385) and property (#386) tests also run every generated query with the switch off. + +- **Rule queries on the engine (#548).** `tests/recursive_engine_test.rs` (10 tests) runs rule queries in memory, on a file with pending facts and after a checkpoint, checked against the executor until #551 and against its recorded answers since: transitive closure (linear and non-linear), mutual recursion, strata whose `not` and `or` rules recurse, rules that read their stratum outside a top-level invocation, derived facts seen by every pattern, the identity of derived facts, `nil` metadata, heads, both `INT-020` limits, and rule queries with aggregates, `not-join`, `or` and windows. Every existing rule suite (`recursive_rules_test`, `negation_test`, `disjunction_test`, `magic_sets_test`, the model-based and property tests) now runs its rule queries on the engine with the oracle. Engine unit tests cover routing and derived rows read across batches. + +- **Recursive rules at 5M derived facts (#473 acceptance, #548).** `tests/recursive_acceptance_test.rs` (ignored; the nightly smoke workflow runs it) derives 4,882,500 `reach` facts in 62 rounds over a layered graph of 155,000 edges and checks that every one is returned and that the query's peak RSS stays under 256 bytes per derived fact (169 measured); the default `max_derived_facts` then stops the same rule with `INT-020`. The #394 envelope has a `recursive` shape: the whole transitive closure of `:manager`, with no constant, so no magic sets. + +- **Query memory at 1M groups and on the #575 product (#549).** `tests/memory_limit_acceptance_test.rs` (ignored; the nightly smoke workflow runs it) returns 1M aggregate groups, or `QRY-012` naming `Aggregate` under a 32 MiB limit, and streams the 1.6M rows of 13 patterns sharing no variable over the fuzz harness's 3 facts in under 64 MiB of peak RSS (the executor held more than 5.7 GB), or `QRY-012` naming `HashJoin` under a 64-byte limit. An ignored engine test prints the meter's peak against the peak RSS: 435 MiB against about 545 MiB for the groups (`docs/BENCHMARKS.md`). Measuring it found `Aggregate`'s sorted map of groups uncharged while its hash table was still held; the map is now charged and the table freed first, which lowered the real peak from 651 MiB. + +- **Negation bodies in both forms (#546).** A second test-only switch (`minigraf::__subplans`, `test-hooks` feature) forces the engine's `not` / `not-join` bodies to run hashed or correlated. `tests/plan_independence_test.rs` runs every query with the body forms chosen, forced hashed and forced correlated, each with reordering on and off; its matrix gains negations over floats near zero, `0.0` and `-0.0`, keywords and refs of one entity, long strings, bodies reading an imported variable they do not bind, variable-free bodies and `:db/valid-at`. `tests/negation_equality_test.rs` checks the changed answers on every executor path, in memory and after a checkpoint. The property test's rerun also forces hashed bodies. Engine unit tests cover the form the planner picks, routing, multiplicity, failing expressions in bodies, and that a hashed body is read once and a correlated one probes once per row. + +- **Disjunctions (#546).** `tests/or_equality_test.rs` checks the changed `or` / `or-join` answers through `execute` and a cursor, in memory and after a checkpoint. `tests/plan_independence_test.rs` gains disjunctions (keywords meeting refs, floats near zero, long strings as keys, branches naming different outer variables or no join variable, a branch with `not`, an `or` with nothing before it, a cross product, `:db/valid-at` in a branch), run with branches chosen, forced hashed and forced correlated. The property test generates `or` and `or-join` over bound variables, with a reference evaluator that deduplicates the rows they keep. Engine unit tests run every disjunction shape with each branch form forced against the executor, and cover routing, the form the planner picks, `Distinct`, and that a hashed branch is read once. + +- **Aggregates and windows (#547).** `src/query/datalog/aggregate.rs` unit tests check every accumulator over every order of small inputs (exact float sums against hand-computed values, cancellation, subnormals, signed zeros, infinities and NaN, integer saturation, errors decided at the end) and that the value order is total. `tests/aggregate_window_rules_test.rs` checks the changed answers; `tests/plan_independence_test.rs` gains aggregate, window and mixed queries over ties, keywords and refs, and floats. + +- `tests/snapshot_atomicity_test.rs` races a writer against a reader: a query must see each transaction whole, whether written with `execute` or a `WriteTransaction` (#554), and must read one state for all its patterns (#555), in memory and on file. It also runs the v2.x checkpoint race from #558, which never failed on v3: copy-on-write checkpoints do not overwrite pages a published reader uses. + +- **The `datalog_eval` fuzz guard counts partial bindings** (#597). The guard skipped inputs whose patterns join to more than 50,000 rows, counting only the rows after the last pattern. At the time, a `not-join` body ran on the executor pattern by pattern in text order, so a 120-pattern body built hundreds of thousands of partial bindings before its last pattern matched nothing, and ran past the 60-second timeout. The guard now counts the bindings after every pattern. On the `v3` corpus (4,783 inputs) coverage drops by 7 of 9,719 edges. The input is added as a seed, as is the `btree_page` input of the cursor fix above. + +- **Kani proofs of the key and value encoders (#627).** `src/storage/keys/verification.rs` and `src/storage/index/verification.rs` hold 12 Kani encoder harnesses, compiled only under `cfg(kani)`. They prove for every input that the v8 key encoders (`put_int`, `put_uint`, `put_tx_desc`, `put_valid_to`, `float_bits`) and `encode_value` keep the order the indexes rely on, that every NaN encodes to one value, and that `float_bits` round-trips. `.github/workflows/kani.yml` runs them on pull requests that touch the keys and nightly on `main` and `v3`. The original #627 scope left decoders out; #693 above adds scalar decoder proofs. Strings, sets, packed pages, WAL and `Reader`'s error mapping remain under fuzz, property and differential tests. Test-only; `Cargo.toml` declares the `kani` cfg so normal builds do not warn. + +- **Parser vs grammar verifier (#643).** `src/query/datalog/parser/verifier.rs` checks, for every generated input, that the parser rejects what `tests/grammar/grammar.pest` rejects, and accepts what it accepts unless the error code is semantic (a listed code with a witness pest accepts). It runs every string of 1 to 3 characters over 102 characters (ASCII, `\t \n \r`, four non-ASCII stand-ins) through `parse_edn`, and every bracket-balanced sequence of up to `MINIGRAF_GRAMMAR_BOUND` (default 3) of 42 tokens in 17 command templates through `parse_datalog_command`, also with no separators up to 3 tokens. The initial 32-token, 15-template version took about 20 s by default and 3.5 min at bound 4 on a 16-thread machine. `KNOWN_DRIFT` is now empty: comments and non-ASCII identifiers are documented (#650); empty sections, ignored keywords, rule and call heads, a lone `:` and unterminated strings are checked (#651); excess fact elements are rejected (#649). Each fix removed its drift entry; a lone `-` remains the subtraction operator. `grammar.pest` now says what the parser means: a fact is exactly `[e a v]` plus an optional valid-time map and a retracted fact exactly `[e a v]`; `not`, `not-join`, `or`, `or-join` (and `and` inside an `or`) are never rule names; literal keywords end at a word boundary (`:find?x` is one keyword).