blob: 3da683c70450fbc2dc78e6f688f526f1ef6aeea3 [file]
# Copyright 2026 The Fuchsia Authors
#
# Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0
# <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT
# license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
# This file may not be copied, modified, or distributed except according to
# those terms.
"""Unit tests for `ci/check_unstable_registry.py`."""
from __future__ import annotations
import json
from pathlib import Path
import sys
import tempfile
import unittest
sys.path.insert(0, str(Path(__file__).resolve().parent))
import check_unstable_registry as cur
LICENSE_HASH = (
"# Copyright 2026 The Fuchsia Authors\n"
"# Licensed under a BSD-style license <LICENSE-BSD>, Apache License, "
"Version 2.0\n"
)
LICENSE_MD = (
"<!--\n"
"Copyright 2026 The Fuchsia Authors\n"
"Licensed under a BSD-style license <LICENSE-BSD>, Apache License, "
"Version 2.0\n"
"-->\n"
)
def _write(path: Path, text: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text, encoding="utf-8")
def _add_feature(root: Path, fid: str = "mir_alloc") -> None:
gate = f"tests/gates/{fid}.rs"
_write(root / gate, "// gate test\n")
_write(
root / f"docs/unstable/{fid}.toml",
LICENSE_HASH
+ 'owners = ["@joshlf"]\n'
+ 'tracking_issue = "https://github.com/google/anneal/issues/42"\n'
+ 'review_by = "2027-03-01"\n'
+ f'gate_test = "{gate}"\n',
)
_write(
root / f"docs/unstable/{fid}.md",
LICENSE_MD
+ f"\n# `{fid}`\n\n"
+ "> [!NOTE]\n> Experimental opt-in on `main`.\n\n"
+ "Tracking: https://github.com/google/anneal/issues/42\n\n"
+ "## Limitations\n\nExplicitly logged assumptions.\n\n"
+ "## Graduation checklist\n\n- Correspondence and zerocopy targets.\n",
)
class CheckUnstableRegistryTests(unittest.TestCase):
def test_empty_registry_and_paired_feature_pass(self):
with tempfile.TemporaryDirectory(prefix="anneal-unstable-ok-") as tmp:
root = Path(tmp)
_write(root / "docs/unstable/README.md", LICENSE_MD + "# Unstable\n")
self.assertEqual(cur.check_repo(root), [])
_add_feature(root, "mir_alloc")
_write(
root / "trusted/cargo-anneal/src/unstable.rs",
'pub const UNSTABLE_FEATURES: &[&str] = &["mir_alloc"];\n',
)
self.assertEqual(cur.check_repo(root), [])
def test_orphaned_registry_and_unregistered_code_sites_rejected(self):
with tempfile.TemporaryDirectory(prefix="anneal-unstable-orphan-") as tmp:
root = Path(tmp)
_add_feature(root, "mir_alloc")
errs = cur.check_repo(root)
self.assertTrue(any("orphaned registry entry" in e for e in errs), errs)
_write(
root / "trusted/locks/cartridges.lock.json",
json.dumps({
"schema_version": 1,
"reference_lean_id": "v4.34.1",
"cartridges": [
{
"id": "C-Cpp",
"namespace_prefix": "Trusted.CppSemantics",
"stability": "candidate:cpp",
"parents": [],
"stage_l_required": False,
}
],
}),
)
_write(root / "theory/Anneal/Unstable/fast_tactic/Main.lean", "-- ok\n")
errs2 = cur.check_repo(root)
joined = "\n".join(errs2)
self.assertIn("`cpp` has no registry entry", joined)
self.assertIn("`fast_tactic` has no registry entry", joined)
def test_graduated_redirect_stub_allowed_and_internal_patterns_rejected(self):
with tempfile.TemporaryDirectory(prefix="anneal-unstable-stub-") as tmp:
root = Path(tmp)
_write(
root / "docs/unstable/old_feat.md",
LICENSE_MD
+ "\n# `old_feat`\n\nThis feature has graduated to `docs/guide/`.\n",
)
self.assertEqual(cur.check_repo(root), [])
_add_feature(root, "bad_sink")
_write(
root / "trusted/cargo-anneal/src/unstable.rs",
'pub const UNSTABLE_FEATURES: &[&str] = &["bad_sink"];\n',
)
_write(
root / "docs/unstable/bad_sink.md",
(root / "docs/unstable/bad_sink.md").read_text(encoding="utf-8")
+ "\nSee https://host.internal/private.\n",
)
errs = cur.check_repo(root)
self.assertTrue(any("private corporate hostname" in e for e in errs), errs)
def test_rust_const_extraction_hardening_and_fail_closed_sites(self):
# 1. Invalid IDs (`mir-alloc`, `MirAlloc`, ``) must surface, not drop.
with tempfile.TemporaryDirectory(prefix="anneal-unstable-badid-") as tmp:
root = Path(tmp)
_write(
root / "trusted/cargo-anneal/src/unstable.rs",
'const UNSTABLE_FEATURES: [&str; 3] = ["mir-alloc", "MirAlloc", ""];\n',
)
errs = cur.check_repo(root)
joined = "\n".join(errs)
self.assertIn("invalid unstable feature ID `mir-alloc`", joined)
self.assertIn("invalid unstable feature ID `MirAlloc`", joined)
self.assertIn("invalid unstable feature ID ``", joined)
# 2. Preceding comments with decoy `const` do not shadow real const,
# and `pub(super)` + struct arrays with nested `[...]` work.
with tempfile.TemporaryDirectory(prefix="anneal-unstable-comment-") as tmp:
root = Path(tmp)
_add_feature(root, "real_feat")
_write(
root / "trusted/cargo-anneal/src/unstable.rs",
"// Example: pub const UNSTABLE_FEATURES: &[&str] = &[];\n"
"/* Block decoy: pub const UNSTABLE_FEATURES: &[&str] = &[\"fake\"]; */\n"
"pub(super) const UNSTABLE_FEATURES: [Feat; 1] = [\n"
' Feat { id: "real_feat", tags: &["a", "b"] },\n'
"];\n",
)
self.assertEqual(cur.check_repo(root), [])
# 3. Unparseable `const UNSTABLE_FEATURES` fails closed.
with tempfile.TemporaryDirectory(prefix="anneal-unstable-shape-") as tmp:
root = Path(tmp)
_write(
root / "trusted/cargo-anneal/src/unstable.rs",
"pub const UNSTABLE_FEATURES: &[&str] = make_features();\n",
)
errs = cur.check_repo(root)
self.assertTrue(any("array or slice literal" in e for e in errs), errs)
# 4. Corrupt `cartridges.lock.json` fails closed (not as `{}`).
with tempfile.TemporaryDirectory(prefix="anneal-unstable-corrupt-") as tmp:
root = Path(tmp)
_write(root / "trusted/locks/cartridges.lock.json", "{not valid json\n")
errs = cur.check_repo(root)
self.assertTrue(any("cannot parse JSON" in e for e in errs), errs)
# 5. Symlinks at any monitored code site fail closed.
with tempfile.TemporaryDirectory(prefix="anneal-unstable-sym-") as tmp:
root = Path(tmp)
(root / "trusted/locks").mkdir(parents=True)
(root / "trusted/locks/cartridges.lock.json").symlink_to(root / "missing.json")
(root / "theory/Anneal").mkdir(parents=True)
(root / "theory/Anneal/Unstable").symlink_to(root / "missing_dir")
(root / "Specs").mkdir(parents=True)
(root / "Specs/Unstable").symlink_to(root / "missing_specs")
(root / "trusted/cargo-anneal/src").mkdir(parents=True)
(root / "trusted/cargo-anneal/src/unstable.rs").symlink_to(root / "missing.rs")
errs = cur.check_repo(root)
joined = "\n".join(errs)
self.assertIn("trusted/locks/cartridges.lock.json: symlinks are forbidden", joined)
self.assertIn("theory/Anneal/Unstable: symlinks are forbidden", joined)
self.assertIn("Specs/Unstable: symlinks are forbidden", joined)
self.assertIn("trusted/cargo-anneal/src/unstable.rs: symlinks are forbidden", joined)
def test_rust_const_parser_rejects_mixed_elements_and_handles_chars_and_strings(self):
# 1. Mixed plain slice with non-literal const must fail closed.
with tempfile.TemporaryDirectory(prefix="anneal-unstable-mix1-") as tmp:
root = Path(tmp)
_add_feature(root, "real_feat")
_write(
root / "trusted/cargo-anneal/src/unstable.rs",
'pub const UNSTABLE_FEATURES: &[&str] = &["real_feat", UNREGISTERED];\n',
)
errs = cur.check_repo(root)
self.assertTrue(any("UNSTABLE_FEATURES" in e for e in errs), errs)
# 2. Mixed struct array with constructor call must fail closed.
with tempfile.TemporaryDirectory(prefix="anneal-unstable-mix2-") as tmp:
root = Path(tmp)
_add_feature(root, "real_feat")
_write(
root / "trusted/cargo-anneal/src/unstable.rs",
"pub const UNSTABLE_FEATURES: &[Feat] = &[\n"
' Feat { id: "real_feat" },\n'
' Feat::new("sneaky"),\n'
"];\n",
)
errs = cur.check_repo(root)
self.assertTrue(any("UNSTABLE_FEATURES`[1]" in e for e in errs), errs)
# 3. Tuple slice fails closed instead of reading description as ID.
with tempfile.TemporaryDirectory(prefix="anneal-unstable-tup-") as tmp:
root = Path(tmp)
_add_feature(root, "real_feat")
_write(
root / "trusted/cargo-anneal/src/unstable.rs",
'pub const UNSTABLE_FEATURES: &[(&str, &str)] = &[("real_feat", "desc")];\n',
)
errs = cur.check_repo(root)
self.assertTrue(any("UNSTABLE_FEATURES`[0]" in e for e in errs), errs)
# 4. `']'` / `'"'` / `'\''` char literals (including `'\''|'"'` quote
# parity traps), `id:` inside help strings, `r#` raw identifiers,
# `static` tables, and raw string test fixtures work cleanly.
with tempfile.TemporaryDirectory(prefix="anneal-unstable-lex-") as tmp:
root = Path(tmp)
_add_feature(root, "feat_a")
_add_feature(root, "feat_b")
_write(
root / "trusted/cargo-anneal/src/unstable.rs",
"fn quote_trap(ch: char) -> bool {\n"
" matches!(ch, '\\''|'\"') || ['\\'','\"'].contains(&ch)\n"
"}\n"
"pub const UNSTABLE_FEATURES: &[Feat] = &[\n"
" Feat { id: \"feat_a\", sep: ']', q: '\"', desc: \"Feature id: mir_alloc\" },\n"
" Feat { r#id: \"feat_b\", sep: '[', q: '\\'', desc: \"id: other\" },\n"
"];\n"
"const TEST_FIXTURE: &str = r#\"pub const UNSTABLE_FEATURES: &[&str] = &[\"fake\"];\"#;\n",
)
self.assertEqual(cur.check_repo(root), [])
# 5. Raw `const r#UNSTABLE_FEATURES` and `static mut` are scanned.
with tempfile.TemporaryDirectory(prefix="anneal-unstable-raw-") as tmp:
root = Path(tmp)
_write(
root / "trusted/cargo-anneal/src/unstable.rs",
'pub const r#UNSTABLE_FEATURES: &[&str] = &["sneaky_raw"];\n',
)
_write(
root / "tools/anneal-spec/lower/src/parse.rs",
"fn quote_trap(ch: char) -> bool { matches!(ch, '\\''|'\"') }\n"
'pub static mut PREVIEW_UNSTABLE_FEATURES: &[&str] = &["sneaky_static"];\n',
)
errs = cur.check_repo(root)
joined = "\n".join(errs)
self.assertIn("`sneaky_raw` has no registry entry", joined)
self.assertIn("`sneaky_static` has no registry entry", joined)
# 6. Intermediate directory symlink in `gate_test` fails closed.
with tempfile.TemporaryDirectory(prefix="anneal-unstable-psym-") as tmp:
root = Path(tmp)
_add_feature(root, "sym_gate")
_write(
root / "trusted/cargo-anneal/src/unstable.rs",
'pub const UNSTABLE_FEATURES: &[&str] = &["sym_gate"];\n',
)
outside = Path(tmp) / "outside_dir"
outside.mkdir()
(outside / "sym_gate.rs").write_text("// outside\n", encoding="utf-8")
(root / "tests/gates/sym_gate.rs").unlink()
(root / "tests/gates").rmdir()
(root / "tests/gates").symlink_to(outside)
errs = cur.check_repo(root)
self.assertTrue(any("gate_test" in e for e in errs), errs)
# 7. Hidden dotfile symlink inside `Unstable/` fails closed.
with tempfile.TemporaryDirectory(prefix="anneal-unstable-dotsym-") as tmp:
root = Path(tmp)
unstable_dir = root / "theory/Anneal/Unstable"
unstable_dir.mkdir(parents=True)
(unstable_dir / ".hidden_link.lean").symlink_to(root / "missing.lean")
errs = cur.check_repo(root)
self.assertTrue(
any(".hidden_link.lean: symlinks are forbidden" in e for e in errs),
errs,
)
def test_checks_toml_anneal_ci_tests_covers_all_monitored_code_sites(self):
import fnmatch
import tomllib
checks_toml = Path(__file__).resolve().parent / "checks.toml"
data = tomllib.loads(checks_toml.read_text(encoding="utf-8"))
ci_tests = next(c for c in data["checks"] if c["id"] == "anneal-ci-tests")
globs = [
pat
for inp in ci_tests["inputs"]
if inp.get("kind") == "glob"
for pat in inp.get("include", [])
]
monitored = [
"docs/unstable/foo.toml",
"trusted/locks/cartridges.lock.json",
"theory/Anneal/Unstable/foo/Main.lean",
"Specs/Unstable/foo/Main.lean",
"specs/Specs/Unstable/foo/Main.lean",
"trusted/cargo-anneal/src/unstable.rs",
"tools/cargo-anneal/cargo-anneal/src/unstable.rs",
"tools/cargo-anneal/src/unstable.rs",
"trusted/rustc-capture/src/lib.rs",
"trusted/mir-dump/src/lib.rs",
"trusted/anneal-lower/src/lib.rs",
"tools/anneal-spec/lower/src/parse.rs",
"tools/anneal-spec/lower/src/lib.rs",
]
for rel in monitored:
matched = any(
fnmatch.fnmatch(rel, g)
or (g.endswith("/**") and rel.startswith(g[:-2]))
for g in globs
)
self.assertTrue(matched, f"anneal-ci-tests inputs missing {rel}")
if __name__ == "__main__":
unittest.main()