test_code_harmony_plugin.py
python
sha256:81ae324db5ad375fbfe4834c6fcb378312cafad3cc92dec5d3e5c427306621a2
fix: remove commit_exists filter from have anchors — server…
Sonnet 4.6
patch
21 days ago
| 1 | """Tests for muse/core/plugins/code_harmony.py. |
| 2 | |
| 3 | ``CodePlugin`` — HarmonyPlugin implementation for code-domain conflicts. |
| 4 | ``code_fingerprint(source)`` — normalized token-bag fingerprint for a code snippet. |
| 5 | |
| 6 | The fingerprint encodes a sorted space-separated list of normalized tokens: |
| 7 | - Python keywords preserved as-is (``def``, ``return``, ``class``, …) |
| 8 | - Identifiers → ``ID`` |
| 9 | - String literals → ``STR`` |
| 10 | - Number literals → ``NUM`` |
| 11 | - Operators/punctuation → preserved (``(``, ``)`` , ``:``, ``+``, …) |
| 12 | - Comments → stripped |
| 13 | - Whitespace/indentation → irrelevant (sorting makes order-independent) |
| 14 | |
| 15 | Similarity is Tanimoto coefficient on the token multisets: |
| 16 | sim = |min(A, B)| / |max(A, B)| |
| 17 | |
| 18 | Also covers the relaxed ``--semantic-fingerprint`` CLI validation that allows |
| 19 | non-hex64 fingerprints (required for code plugin fingerprints). |
| 20 | |
| 21 | Coverage tiers |
| 22 | -------------- |
| 23 | I Unit — code_fingerprint output shape, normalization rules |
| 24 | II Integration — CodePlugin.similarity on real code snippets |
| 25 | III End-to-end — harmony store + engine finds code semantic matches |
| 26 | IV Stress — 500-line file fingerprint; large similarity batches |
| 27 | V Data integrity — symmetry, bounds [0,1], determinism, Protocol conformance |
| 28 | VI Security — malformed Python, very large input, null bytes, empty |
| 29 | VII Performance — fingerprint <10ms/function; similarity <1ms; engine <100ms |
| 30 | """ |
| 31 | from __future__ import annotations |
| 32 | |
| 33 | import datetime |
| 34 | import pathlib |
| 35 | import time |
| 36 | |
| 37 | import pytest |
| 38 | |
| 39 | from muse.core.paths import config_toml_path, muse_dir |
| 40 | from muse.core.types import fake_id |
| 41 | from muse.core.harmony import ( |
| 42 | AgentProvenance, |
| 43 | ConflictPattern, |
| 44 | blob_fingerprint, |
| 45 | compute_pattern_id, |
| 46 | best_resolution, |
| 47 | record_pattern, |
| 48 | save_resolution, |
| 49 | Resolution, |
| 50 | ResolutionStrategy, |
| 51 | ) |
| 52 | from muse.core.harmony.engine import EngineConfig, find_similar |
| 53 | from muse.core.plugins.code_harmony import CodePlugin, code_fingerprint |
| 54 | |
| 55 | |
| 56 | # --------------------------------------------------------------------------- |
| 57 | # Shared helpers |
| 58 | # --------------------------------------------------------------------------- |
| 59 | |
| 60 | |
| 61 | |
| 62 | def _utc_now() -> datetime.datetime: |
| 63 | return datetime.datetime.now(datetime.timezone.utc) |
| 64 | |
| 65 | |
| 66 | @pytest.fixture() |
| 67 | def repo(tmp_path: pathlib.Path) -> pathlib.Path: |
| 68 | muse_dir(tmp_path).mkdir() |
| 69 | return tmp_path |
| 70 | |
| 71 | |
| 72 | def _make_pattern( |
| 73 | path: str, |
| 74 | semantic_fp: str, |
| 75 | ours: str = "ours", |
| 76 | theirs: str = "theirs", |
| 77 | ) -> ConflictPattern: |
| 78 | ours_id = fake_id(ours) |
| 79 | theirs_id = fake_id(theirs) |
| 80 | blob_fp = blob_fingerprint(ours_id, theirs_id) |
| 81 | pid = compute_pattern_id(path, blob_fp, semantic_fp) |
| 82 | return ConflictPattern( |
| 83 | pattern_id=pid, |
| 84 | path=path, |
| 85 | domain="code", |
| 86 | conflict_type="content", |
| 87 | blob_fingerprint=blob_fp, |
| 88 | semantic_fingerprint=semantic_fp, |
| 89 | ours_id=ours_id, |
| 90 | theirs_id=theirs_id, |
| 91 | description={}, |
| 92 | recorded_at=_utc_now(), |
| 93 | recorded_by="test", |
| 94 | ) |
| 95 | |
| 96 | |
| 97 | def _make_resolution(pattern_id: str, confidence: float = 0.9) -> Resolution: |
| 98 | rid = fake_id(f"res-{pattern_id}") |
| 99 | return Resolution( |
| 100 | resolution_id=rid, |
| 101 | pattern_id=pattern_id, |
| 102 | strategy=ResolutionStrategy.MANUAL, |
| 103 | policy_id=None, |
| 104 | outcome_blob=fake_id("outcome"), |
| 105 | resolved_by=AgentProvenance.human(), |
| 106 | human_verified=False, |
| 107 | confidence=confidence, |
| 108 | rationale="test resolution", |
| 109 | resolved_at=_utc_now(), |
| 110 | ) |
| 111 | |
| 112 | |
| 113 | # =========================================================================== |
| 114 | # Tier I — Unit: code_fingerprint() |
| 115 | # =========================================================================== |
| 116 | |
| 117 | |
| 118 | class TestCodeFingerprintShape: |
| 119 | """I: output is a non-empty string of space-separated tokens.""" |
| 120 | |
| 121 | def test_returns_string(self) -> None: |
| 122 | assert isinstance(code_fingerprint("def foo(): pass"), str) |
| 123 | |
| 124 | def test_non_empty_for_real_code(self) -> None: |
| 125 | assert code_fingerprint("def foo(): pass") != "" |
| 126 | |
| 127 | def test_empty_source_returns_empty(self) -> None: |
| 128 | assert code_fingerprint("") == "" |
| 129 | |
| 130 | def test_whitespace_only_returns_empty(self) -> None: |
| 131 | assert code_fingerprint(" \n\t ") == "" |
| 132 | |
| 133 | def test_comment_only_returns_empty(self) -> None: |
| 134 | assert code_fingerprint("# just a comment") == "" |
| 135 | |
| 136 | def test_tokens_are_space_separated(self) -> None: |
| 137 | fp = code_fingerprint("x = 1") |
| 138 | assert " " in fp or len(fp.split()) >= 1 |
| 139 | |
| 140 | |
| 141 | class TestCodeFingerprintNormalization: |
| 142 | """I: normalization rules for identifiers, literals, keywords.""" |
| 143 | |
| 144 | def test_identifiers_become_ID(self) -> None: |
| 145 | fp = code_fingerprint("foo = bar") |
| 146 | assert "ID" in fp |
| 147 | assert "foo" not in fp |
| 148 | assert "bar" not in fp |
| 149 | |
| 150 | def test_numbers_become_NUM(self) -> None: |
| 151 | fp = code_fingerprint("x = 42") |
| 152 | assert "NUM" in fp |
| 153 | assert "42" not in fp |
| 154 | |
| 155 | def test_string_literals_become_STR(self) -> None: |
| 156 | fp = code_fingerprint('msg = "hello world"') |
| 157 | assert "STR" in fp |
| 158 | assert "hello" not in fp |
| 159 | |
| 160 | def test_single_quoted_strings_become_STR(self) -> None: |
| 161 | fp = code_fingerprint("msg = 'hello'") |
| 162 | assert "STR" in fp |
| 163 | |
| 164 | def test_keywords_preserved(self) -> None: |
| 165 | fp = code_fingerprint("def foo(): return None") |
| 166 | assert "def" in fp |
| 167 | assert "return" in fp |
| 168 | |
| 169 | def test_class_keyword_preserved(self) -> None: |
| 170 | fp = code_fingerprint("class Foo: pass") |
| 171 | assert "class" in fp |
| 172 | assert "pass" in fp |
| 173 | |
| 174 | def test_import_keyword_preserved(self) -> None: |
| 175 | fp = code_fingerprint("import os") |
| 176 | assert "import" in fp |
| 177 | |
| 178 | def test_comments_stripped(self) -> None: |
| 179 | fp_with_comment = code_fingerprint("x = 1 # this is x") |
| 180 | fp_without = code_fingerprint("x = 1") |
| 181 | assert fp_with_comment == fp_without |
| 182 | |
| 183 | def test_operators_preserved(self) -> None: |
| 184 | fp = code_fingerprint("x + y") |
| 185 | assert "+" in fp |
| 186 | |
| 187 | def test_parens_preserved(self) -> None: |
| 188 | fp = code_fingerprint("foo(x)") |
| 189 | assert "(" in fp |
| 190 | assert ")" in fp |
| 191 | |
| 192 | |
| 193 | class TestCodeFingerprintDeterminism: |
| 194 | """I: same input → same output, always.""" |
| 195 | |
| 196 | def test_deterministic_same_call(self) -> None: |
| 197 | src = "def compute(a, b):\n return a * b + 1\n" |
| 198 | assert code_fingerprint(src) == code_fingerprint(src) |
| 199 | |
| 200 | def test_indentation_irrelevant(self) -> None: |
| 201 | src1 = "def foo(x):\n return x\n" |
| 202 | src2 = "def foo(x):\n return x\n" |
| 203 | assert code_fingerprint(src1) == code_fingerprint(src2) |
| 204 | |
| 205 | def test_extra_blank_lines_irrelevant(self) -> None: |
| 206 | src1 = "def foo():\n pass\n" |
| 207 | src2 = "\n\ndef foo():\n\n pass\n\n" |
| 208 | assert code_fingerprint(src1) == code_fingerprint(src2) |
| 209 | |
| 210 | def test_output_is_sorted(self) -> None: |
| 211 | fp = code_fingerprint("def foo(x): return x") |
| 212 | tokens = fp.split() |
| 213 | assert tokens == sorted(tokens) |
| 214 | |
| 215 | |
| 216 | # =========================================================================== |
| 217 | # Tier II — Integration: CodePlugin.similarity() |
| 218 | # =========================================================================== |
| 219 | |
| 220 | |
| 221 | class TestCodePluginIdentical: |
| 222 | """II: identical or structurally equivalent code → high similarity.""" |
| 223 | |
| 224 | def test_identical_source_is_1(self) -> None: |
| 225 | src = "def foo(x):\n return x + 1\n" |
| 226 | fp = code_fingerprint(src) |
| 227 | assert CodePlugin().similarity(fp, fp) == 1.0 |
| 228 | |
| 229 | def test_same_structure_different_names_is_1(self) -> None: |
| 230 | # Different identifiers, same keyword/operator structure |
| 231 | fp1 = code_fingerprint("def foo(x): return x + 1") |
| 232 | fp2 = code_fingerprint("def bar(y): return y + 2") |
| 233 | assert CodePlugin().similarity(fp1, fp2) == 1.0 |
| 234 | |
| 235 | def test_same_import_different_module_is_1(self) -> None: |
| 236 | fp1 = code_fingerprint("from typing import Optional") |
| 237 | fp2 = code_fingerprint("from os import path") |
| 238 | assert CodePlugin().similarity(fp1, fp2) == 1.0 |
| 239 | |
| 240 | def test_same_assignment_different_names_high(self) -> None: |
| 241 | fp1 = code_fingerprint("result = compute_value(a, b)") |
| 242 | fp2 = code_fingerprint("output = process_data(x, y)") |
| 243 | assert CodePlugin().similarity(fp1, fp2) > 0.8 |
| 244 | |
| 245 | |
| 246 | class TestCodePluginSimilar: |
| 247 | """II: structurally related code → intermediate similarity.""" |
| 248 | |
| 249 | def test_same_function_extra_parameter(self) -> None: |
| 250 | fp1 = code_fingerprint("def foo(x): return x + 1") |
| 251 | fp2 = code_fingerprint("def foo(x, y): return x + y") |
| 252 | sim = CodePlugin().similarity(fp1, fp2) |
| 253 | assert 0.5 < sim < 1.0 |
| 254 | |
| 255 | def test_function_vs_method(self) -> None: |
| 256 | fp1 = code_fingerprint("def foo(x):\n return x\n") |
| 257 | fp2 = code_fingerprint("def foo(self, x):\n return x\n") |
| 258 | sim = CodePlugin().similarity(fp1, fp2) |
| 259 | assert 0.5 < sim < 1.0 |
| 260 | |
| 261 | def test_added_return_type_annotation(self) -> None: |
| 262 | fp1 = code_fingerprint("def foo(x):\n return x\n") |
| 263 | fp2 = code_fingerprint("def foo(x) -> int:\n return x\n") |
| 264 | sim = CodePlugin().similarity(fp1, fp2) |
| 265 | assert sim > 0.6 |
| 266 | |
| 267 | def test_added_docstring(self) -> None: |
| 268 | fp1 = code_fingerprint("def foo(x):\n return x\n") |
| 269 | fp2 = code_fingerprint('def foo(x):\n """Return x."""\n return x\n') |
| 270 | sim = CodePlugin().similarity(fp1, fp2) |
| 271 | assert sim > 0.5 |
| 272 | |
| 273 | |
| 274 | class TestCodePluginDifferent: |
| 275 | """II: structurally unrelated code → low similarity.""" |
| 276 | |
| 277 | def test_function_vs_class_low(self) -> None: |
| 278 | fp1 = code_fingerprint("def foo(x): return x + 1") |
| 279 | fp2 = code_fingerprint("class Foo:\n pass\n") |
| 280 | assert CodePlugin().similarity(fp1, fp2) < 0.5 |
| 281 | |
| 282 | def test_completely_different_low(self) -> None: |
| 283 | fp1 = code_fingerprint( |
| 284 | "for item in collection:\n process(item)\n" |
| 285 | ) |
| 286 | fp2 = code_fingerprint( |
| 287 | "class DatabaseConnection:\n" |
| 288 | " def __init__(self, host, port):\n" |
| 289 | " self.host = host\n" |
| 290 | " self.port = port\n" |
| 291 | ) |
| 292 | assert CodePlugin().similarity(fp1, fp2) < 0.5 |
| 293 | |
| 294 | def test_import_vs_class_low(self) -> None: |
| 295 | fp1 = code_fingerprint("import os") |
| 296 | fp2 = code_fingerprint("class Foo:\n x = 1\n") |
| 297 | assert CodePlugin().similarity(fp1, fp2) < 0.5 |
| 298 | |
| 299 | |
| 300 | class TestCodePluginEdgeCases: |
| 301 | """II: empty, single-token, and other edge cases.""" |
| 302 | |
| 303 | def test_both_empty_returns_1(self) -> None: |
| 304 | assert CodePlugin().similarity("", "") == 1.0 |
| 305 | |
| 306 | def test_one_empty_returns_0(self) -> None: |
| 307 | fp = code_fingerprint("def foo(): pass") |
| 308 | assert CodePlugin().similarity(fp, "") == 0.0 |
| 309 | assert CodePlugin().similarity("", fp) == 0.0 |
| 310 | |
| 311 | def test_single_token_identical(self) -> None: |
| 312 | assert CodePlugin().similarity("def", "def") == 1.0 |
| 313 | |
| 314 | def test_single_token_different(self) -> None: |
| 315 | assert CodePlugin().similarity("def", "class") == 0.0 |
| 316 | |
| 317 | def test_returns_float(self) -> None: |
| 318 | fp = code_fingerprint("x = 1") |
| 319 | result = CodePlugin().similarity(fp, fp) |
| 320 | assert isinstance(result, float) |
| 321 | |
| 322 | |
| 323 | # =========================================================================== |
| 324 | # Tier III — End-to-end with harmony store |
| 325 | # =========================================================================== |
| 326 | |
| 327 | |
| 328 | class TestEndToEnd: |
| 329 | """III: CodePlugin + harmony store + engine find_similar.""" |
| 330 | |
| 331 | def test_engine_finds_similar_code_patterns(self, repo: pathlib.Path) -> None: |
| 332 | """Two structurally identical code conflicts → engine proposes via Tier 3.""" |
| 333 | src_a = "def process(item):\n return item.transform()\n" |
| 334 | src_b = "def handle(obj):\n return obj.transform()\n" |
| 335 | fp_a = code_fingerprint(src_a) |
| 336 | fp_b = code_fingerprint(src_b) |
| 337 | |
| 338 | # Both have the same fingerprint (same structure) |
| 339 | assert fp_a == fp_b |
| 340 | |
| 341 | pat_a = _make_pattern("service_a.py", fp_a, ours="oa", theirs="ta") |
| 342 | pat_b = _make_pattern("service_b.py", fp_b, ours="ob", theirs="tb") |
| 343 | record_pattern(repo, pat_a) |
| 344 | record_pattern(repo, pat_b) |
| 345 | |
| 346 | # Give pat_a a resolution |
| 347 | res = _make_resolution(pat_a.pattern_id, confidence=0.88) |
| 348 | save_resolution(repo, res) |
| 349 | |
| 350 | # find_similar for pat_b via CodePlugin should find pat_a |
| 351 | proposals = find_similar(repo, pat_b, plugin=CodePlugin(), |
| 352 | config=EngineConfig(semantic_threshold=0.70)) |
| 353 | assert len(proposals) >= 1 |
| 354 | assert proposals[0].similar_pattern_id == pat_a.pattern_id |
| 355 | assert proposals[0].similarity == 1.0 |
| 356 | |
| 357 | def test_dissimilar_patterns_not_proposed(self, repo: pathlib.Path) -> None: |
| 358 | """Structurally different code → similarity below threshold → no proposal.""" |
| 359 | fp_a = code_fingerprint("def foo(x): return x + 1") |
| 360 | fp_b = code_fingerprint("class DatabaseManager:\n def __init__(self): pass\n") |
| 361 | |
| 362 | pat_a = _make_pattern("utils.py", fp_a, ours="oa", theirs="ta") |
| 363 | pat_b = _make_pattern("db.py", fp_b, ours="ob", theirs="tb") |
| 364 | record_pattern(repo, pat_a) |
| 365 | record_pattern(repo, pat_b) |
| 366 | |
| 367 | res = _make_resolution(pat_a.pattern_id, confidence=0.9) |
| 368 | save_resolution(repo, res) |
| 369 | |
| 370 | proposals = find_similar(repo, pat_b, plugin=CodePlugin(), |
| 371 | config=EngineConfig(semantic_threshold=0.70)) |
| 372 | assert proposals == [] |
| 373 | |
| 374 | def test_code_plugin_satisfies_harmony_plugin_protocol(self) -> None: |
| 375 | from muse.core.harmony.engine import HarmonyPlugin |
| 376 | assert isinstance(CodePlugin(), HarmonyPlugin) |
| 377 | |
| 378 | def test_partial_match_above_threshold_proposed(self, repo: pathlib.Path) -> None: |
| 379 | """Partial structural match → sim in (0.5, 1.0) → proposed if above threshold.""" |
| 380 | fp_a = code_fingerprint("def foo(x):\n return x\n") |
| 381 | fp_b = code_fingerprint("def foo(x, y):\n return x + y\n") |
| 382 | |
| 383 | sim = CodePlugin().similarity(fp_a, fp_b) |
| 384 | assert 0.5 < sim < 1.0 |
| 385 | |
| 386 | pat_a = _make_pattern("a.py", fp_a, ours="oa", theirs="ta") |
| 387 | pat_b = _make_pattern("b.py", fp_b, ours="ob", theirs="tb") |
| 388 | record_pattern(repo, pat_a) |
| 389 | record_pattern(repo, pat_b) |
| 390 | |
| 391 | res = _make_resolution(pat_a.pattern_id) |
| 392 | save_resolution(repo, res) |
| 393 | |
| 394 | # Use a low threshold so partial matches are included |
| 395 | proposals = find_similar(repo, pat_b, plugin=CodePlugin(), |
| 396 | config=EngineConfig(semantic_threshold=0.50)) |
| 397 | assert len(proposals) >= 1 |
| 398 | |
| 399 | |
| 400 | # =========================================================================== |
| 401 | # Tier IV — Stress |
| 402 | # =========================================================================== |
| 403 | |
| 404 | |
| 405 | class TestStress: |
| 406 | """IV: large inputs; many-pattern similarity search.""" |
| 407 | |
| 408 | def test_fingerprint_500_line_file(self) -> None: |
| 409 | lines = [] |
| 410 | for i in range(50): |
| 411 | lines.append(f"def function_{i}(arg_{i}):") |
| 412 | lines.append(f" result = arg_{i} * {i}") |
| 413 | lines.append(f" return result") |
| 414 | lines.append("") |
| 415 | src = "\n".join(lines) |
| 416 | fp = code_fingerprint(src) |
| 417 | assert isinstance(fp, str) |
| 418 | assert len(fp) > 0 |
| 419 | |
| 420 | def test_similarity_of_large_fingerprints(self) -> None: |
| 421 | src = "\n".join( |
| 422 | f"def f{i}(x{i}): return x{i} + {i}" for i in range(200) |
| 423 | ) |
| 424 | fp1 = code_fingerprint(src) |
| 425 | fp2 = code_fingerprint(src.replace("return", "yield")) |
| 426 | sim = CodePlugin().similarity(fp1, fp2) |
| 427 | assert 0.0 <= sim <= 1.0 |
| 428 | |
| 429 | def test_find_similar_50_patterns(self, repo: pathlib.Path) -> None: |
| 430 | target_fp = code_fingerprint("def process(x): return x.run()") |
| 431 | target = _make_pattern("target.py", target_fp, ours="to", theirs="tt") |
| 432 | record_pattern(repo, target) |
| 433 | |
| 434 | for i in range(50): |
| 435 | fp = code_fingerprint(f"def handle_{i}(obj_{i}): return obj_{i}.run()") |
| 436 | pat = _make_pattern(f"s{i}.py", fp, ours=f"o{i}", theirs=f"t{i}") |
| 437 | record_pattern(repo, pat) |
| 438 | save_resolution(repo, _make_resolution(pat.pattern_id)) |
| 439 | |
| 440 | proposals = find_similar(repo, target, plugin=CodePlugin(), |
| 441 | config=EngineConfig(semantic_threshold=0.70, |
| 442 | max_proposals=5)) |
| 443 | assert len(proposals) <= 5 |
| 444 | assert len(proposals) >= 1 |
| 445 | |
| 446 | |
| 447 | # =========================================================================== |
| 448 | # Tier V — Data integrity |
| 449 | # =========================================================================== |
| 450 | |
| 451 | |
| 452 | class TestDataIntegrity: |
| 453 | """V: symmetry, bounds, determinism, Protocol conformance.""" |
| 454 | |
| 455 | def test_similarity_symmetric(self) -> None: |
| 456 | fp1 = code_fingerprint("def foo(x): return x + 1") |
| 457 | fp2 = code_fingerprint("class Bar:\n def method(self): pass\n") |
| 458 | plugin = CodePlugin() |
| 459 | assert plugin.similarity(fp1, fp2) == plugin.similarity(fp2, fp1) |
| 460 | |
| 461 | def test_similarity_always_in_01(self) -> None: |
| 462 | cases = [ |
| 463 | ("def foo(): pass", "def bar(): pass"), |
| 464 | ("x = 1", "y = 'hello'"), |
| 465 | ("import os", "class Foo: pass"), |
| 466 | ("", ""), |
| 467 | ("", "x = 1"), |
| 468 | ] |
| 469 | plugin = CodePlugin() |
| 470 | for a, b in cases: |
| 471 | sim = plugin.similarity(code_fingerprint(a), code_fingerprint(b)) |
| 472 | assert 0.0 <= sim <= 1.0, f"out of range: {sim} for {a!r}, {b!r}" |
| 473 | |
| 474 | def test_fingerprint_deterministic_across_calls(self) -> None: |
| 475 | src = "def compute(a, b, c):\n return (a + b) * c\n" |
| 476 | fps = [code_fingerprint(src) for _ in range(10)] |
| 477 | assert len(set(fps)) == 1 |
| 478 | |
| 479 | def test_self_similarity_is_1(self) -> None: |
| 480 | for src in [ |
| 481 | "x = 1", |
| 482 | "def foo(x): return x", |
| 483 | "class Foo:\n pass", |
| 484 | ]: |
| 485 | fp = code_fingerprint(src) |
| 486 | assert CodePlugin().similarity(fp, fp) == 1.0 |
| 487 | |
| 488 | def test_protocol_conformance(self) -> None: |
| 489 | from muse.core.harmony.engine import HarmonyPlugin |
| 490 | plugin = CodePlugin() |
| 491 | assert isinstance(plugin, HarmonyPlugin) |
| 492 | assert callable(plugin.similarity) |
| 493 | |
| 494 | def test_fingerprint_is_sorted(self) -> None: |
| 495 | src = "def foo(x, y):\n return x + y\n" |
| 496 | fp = code_fingerprint(src) |
| 497 | tokens = fp.split() |
| 498 | assert tokens == sorted(tokens) |
| 499 | |
| 500 | |
| 501 | # =========================================================================== |
| 502 | # Tier VI — Security / robustness |
| 503 | # =========================================================================== |
| 504 | |
| 505 | |
| 506 | class TestSecurity: |
| 507 | """VI: malformed input, oversized input, edge cases.""" |
| 508 | |
| 509 | def test_malformed_python_does_not_raise(self) -> None: |
| 510 | # Syntax error → fallback tokenizer |
| 511 | result = code_fingerprint("def foo(:\n return") |
| 512 | assert isinstance(result, str) |
| 513 | |
| 514 | def test_unclosed_string_does_not_raise(self) -> None: |
| 515 | result = code_fingerprint('x = "unclosed string') |
| 516 | assert isinstance(result, str) |
| 517 | |
| 518 | def test_binary_looking_text_does_not_raise(self) -> None: |
| 519 | # Non-Python that might confuse the tokenizer |
| 520 | result = code_fingerprint("SELECT * FROM users WHERE id = 1;") |
| 521 | assert isinstance(result, str) |
| 522 | |
| 523 | def test_very_large_input_does_not_oom(self) -> None: |
| 524 | # 500 KB of code-ish text |
| 525 | big = "x = 1\n" * 80_000 |
| 526 | result = code_fingerprint(big) |
| 527 | assert isinstance(result, str) |
| 528 | |
| 529 | def test_null_bytes_handled(self) -> None: |
| 530 | result = code_fingerprint("x = 1\x00y = 2") |
| 531 | assert isinstance(result, str) |
| 532 | |
| 533 | def test_unicode_identifiers_handled(self) -> None: |
| 534 | # Python 3 supports unicode identifiers |
| 535 | result = code_fingerprint("café = 1") |
| 536 | assert isinstance(result, str) |
| 537 | |
| 538 | def test_similarity_with_garbage_strings(self) -> None: |
| 539 | plugin = CodePlugin() |
| 540 | result = plugin.similarity("garbage###", "more%%%garbage") |
| 541 | assert 0.0 <= result <= 1.0 |
| 542 | |
| 543 | |
| 544 | # =========================================================================== |
| 545 | # Tier VII — Performance |
| 546 | # =========================================================================== |
| 547 | |
| 548 | |
| 549 | class TestPerformance: |
| 550 | """VII: fingerprint <10ms per function; similarity <1ms.""" |
| 551 | |
| 552 | def test_fingerprint_typical_function_under_10ms(self) -> None: |
| 553 | src = "\n".join([ |
| 554 | "def process_audio_track(track, sample_rate, channels):", |
| 555 | " buffer = AudioBuffer(sample_rate, channels)", |
| 556 | " for frame in track.frames:", |
| 557 | " normalized = frame.normalize()", |
| 558 | " filtered = apply_low_pass(normalized, cutoff=8000)", |
| 559 | " buffer.append(filtered)", |
| 560 | " return buffer.render(format='wav')", |
| 561 | ]) |
| 562 | start = time.monotonic() |
| 563 | code_fingerprint(src) |
| 564 | elapsed = (time.monotonic() - start) * 1000 |
| 565 | assert elapsed < 10, f"fingerprint took {elapsed:.1f}ms" |
| 566 | |
| 567 | def test_fingerprint_100_functions_under_100ms(self) -> None: |
| 568 | functions = "\n".join( |
| 569 | f"def f{i}(x, y):\n return x + y + {i}\n" |
| 570 | for i in range(100) |
| 571 | ) |
| 572 | start = time.monotonic() |
| 573 | code_fingerprint(functions) |
| 574 | elapsed = (time.monotonic() - start) * 1000 |
| 575 | assert elapsed < 100, f"fingerprint(100 fns) took {elapsed:.1f}ms" |
| 576 | |
| 577 | def test_similarity_under_1ms(self) -> None: |
| 578 | fp1 = code_fingerprint("def foo(x): return x + 1") |
| 579 | fp2 = code_fingerprint("def bar(y): return y + 2") |
| 580 | start = time.monotonic() |
| 581 | CodePlugin().similarity(fp1, fp2) |
| 582 | elapsed = (time.monotonic() - start) * 1000 |
| 583 | assert elapsed < 1, f"similarity took {elapsed:.2f}ms" |
| 584 | |
| 585 | def test_find_similar_20_patterns_under_100ms( |
| 586 | self, repo: pathlib.Path |
| 587 | ) -> None: |
| 588 | fp = code_fingerprint("def run(x): return x.execute()") |
| 589 | target = _make_pattern("target.py", fp, ours="to", theirs="tt") |
| 590 | record_pattern(repo, target) |
| 591 | |
| 592 | for i in range(20): |
| 593 | p = _make_pattern(f"s{i}.py", |
| 594 | code_fingerprint(f"def go_{i}(obj_{i}): return obj_{i}.execute()"), |
| 595 | ours=f"o{i}", theirs=f"t{i}") |
| 596 | record_pattern(repo, p) |
| 597 | save_resolution(repo, _make_resolution(p.pattern_id)) |
| 598 | |
| 599 | start = time.monotonic() |
| 600 | find_similar(repo, target, plugin=CodePlugin()) |
| 601 | elapsed = (time.monotonic() - start) * 1000 |
| 602 | assert elapsed < 100, f"find_similar(20) took {elapsed:.1f}ms" |
| 603 | |
| 604 | |
| 605 | # =========================================================================== |
| 606 | # CLI validation: --semantic-fingerprint accepts non-hex64 fingerprints |
| 607 | # =========================================================================== |
| 608 | |
| 609 | |
| 610 | class TestCliFingerprint: |
| 611 | """Verify _validate_fingerprint is used (not _validate_id) for semantic_fingerprint.""" |
| 612 | |
| 613 | def test_validate_fingerprint_accepts_token_string(self) -> None: |
| 614 | from muse.core.harmony import _validate_fingerprint |
| 615 | # Should not raise for a normalized token string |
| 616 | _validate_fingerprint("( ) + : ID ID ID NUM def return", "semantic_fingerprint") |
| 617 | |
| 618 | def test_validate_fingerprint_accepts_hex64(self) -> None: |
| 619 | from muse.core.harmony import _validate_fingerprint |
| 620 | _validate_fingerprint(fake_id("anything"), "semantic_fingerprint") |
| 621 | |
| 622 | def test_validate_fingerprint_rejects_empty(self) -> None: |
| 623 | from muse.core.harmony import _validate_fingerprint |
| 624 | with pytest.raises(ValueError): |
| 625 | _validate_fingerprint("", "semantic_fingerprint") |
| 626 | |
| 627 | def test_validate_fingerprint_rejects_null_byte(self) -> None: |
| 628 | from muse.core.harmony import _validate_fingerprint |
| 629 | with pytest.raises(ValueError): |
| 630 | _validate_fingerprint("valid\x00null", "semantic_fingerprint") |
| 631 | |
| 632 | def test_validate_fingerprint_rejects_oversized(self) -> None: |
| 633 | from muse.core.harmony import _validate_fingerprint |
| 634 | with pytest.raises(ValueError): |
| 635 | _validate_fingerprint("x " * 3000, "semantic_fingerprint") |
| 636 | |
| 637 | def test_cli_accepts_code_fingerprint_as_semantic( |
| 638 | self, tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch |
| 639 | ) -> None: |
| 640 | """muse harmony record --semantic-fingerprint <token-string> works.""" |
| 641 | from tests.cli_test_helper import CliRunner |
| 642 | muse_dir(tmp_path).mkdir() |
| 643 | config_toml_path(tmp_path).write_text('[repo]\nname="t"\nid="x"\n') |
| 644 | monkeypatch.chdir(tmp_path) |
| 645 | |
| 646 | runner = CliRunner() |
| 647 | fp = code_fingerprint("def foo(x): return x + 1") |
| 648 | r = runner.invoke(None, [ |
| 649 | "harmony", "record", |
| 650 | "--path", "src/foo.py", |
| 651 | "--domain", "code", |
| 652 | "--conflict-type", "content", |
| 653 | "--ours-id", fake_id("ours"), |
| 654 | "--theirs-id", fake_id("theirs"), |
| 655 | "--semantic-fingerprint", fp, |
| 656 | "--json", |
| 657 | ]) |
| 658 | assert r.exit_code == 0, r.output |
| 659 | import json |
| 660 | data = json.loads(r.output) |
| 661 | assert "pattern_id" in data |
File History
4 commits
sha256:81ae324db5ad375fbfe4834c6fcb378312cafad3cc92dec5d3e5c427306621a2
fix: remove commit_exists filter from have anchors — server…
Sonnet 4.6
patch
21 days ago
sha256:36c3cb3e76619d4c30a6d9bf81b5ec4ff148e30dcfed913e3114ca7b43b81c7e
fix: rename objects→blobs in push client and all stale test…
Sonnet 4.6
patch
22 days ago
sha256:c06a9b9b9fee26c68ea725b44d54b2c0a171301ce9de746d5b656617b4463a9a
fix: repair four test failures from post-migration audit
Sonnet 4.6
patch
28 days ago
sha256:1900655993c83c4107067375548a7be823e471d2515830842f1a12cba4bd3cdf
fix: unified object store migration — idempotent writes, JS…
Sonnet 4.6
minor
⚠
29 days ago