返回 last30days-skill
test_rust_accel.py
根目录 / tests / test_rust_accel.py
1 """Differential parity and fallback tests for the Rust core accelerator."""
2
3 from __future__ import annotations
4
5 import hashlib
6 import http.client
7 import os
8 import random
9 import stat
10 import sys
11 import time
12 from pathlib import Path
13 from unittest import mock
14
15 import pytest
16
17 from lib import cluster, dedupe, doctor, library, library_index, rust_accel, schema, setup_wizard, signals
18
19
20 def _has_rust_binary() -> bool:
21 return rust_accel.find_binary() is not None
22
23
24 requires_rust = pytest.mark.skipif(
25 not _has_rust_binary(),
26 reason="last30days-core release binary not built",
27 )
28
29
30 def test_python_fallback_works_when_binary_missing(monkeypatch):
31 monkeypatch.setenv("LAST30DAYS_ENGINE", "auto")
32 monkeypatch.setattr(rust_accel, "find_binary", lambda: None)
33
34 assert rust_accel.is_available() is False
35 items = [
36 schema.SourceItem(
37 item_id=f"id-{i}",
38 source="reddit",
39 title=f"Rust performance test item {i}",
40 body="Benchmarking fallback behavior without any Rust toolchain.",
41 url=f"https://example.com/{i}",
42 )
43 for i in range(15)
44 ]
45 kept = dedupe.dedupe_items(items, threshold=0.7)
46 assert len(kept) >= 1
47
48
49 def test_forced_rust_mode_raises_when_binary_missing(monkeypatch):
50 monkeypatch.setenv("LAST30DAYS_ENGINE", "rust")
51 monkeypatch.setattr(rust_accel, "find_binary", lambda: None)
52
53 with pytest.raises(rust_accel.RustAccelError):
54 rust_accel.dedupe_kept_indices([{"mode": "fuzzy", "text": "hello"}], 0.7)
55
56
57 @requires_rust
58 def test_dedupe_differential_parity(monkeypatch):
59 rng = random.Random(1337)
60 vocab = [
61 "rust", "python", "tokio", "async", "claude", "codex", "benchmark",
62 "latency", "memory", "sqlite", "markdown", "unicode", "café", "国产大模型",
63 "测评", "github", "reddit", "youtube", "performance", "clippy",
64 ]
65 items: list[schema.SourceItem] = []
66 for i in range(80):
67 if i > 5 and i % 6 == 0:
68 title = items[i - 4].title + " follow-up"
69 body = items[i - 4].body
70 else:
71 title = " ".join(rng.sample(vocab, 6))
72 body = " ".join(rng.sample(vocab, 14))
73 source = "jobs" if i % 17 == 0 else ("polymarket" if i % 19 == 0 else "reddit")
74 meta = {"matched_market": {"question": title}} if source == "polymarket" else {}
75 items.append(
76 schema.SourceItem(
77 item_id=f"it-{i}",
78 source=source,
79 title=title,
80 body=body,
81 url=f"https://example.com/{source}/{i}",
82 author=f"author_{i % 10}",
83 container=f"r/sub{i % 5}",
84 metadata=meta,
85 )
86 )
87
88 for threshold in (0.3, 0.7, 0.95):
89 monkeypatch.setenv("LAST30DAYS_ENGINE", "python")
90 py_kept = [it.item_id for it in dedupe.dedupe_items(items, threshold=threshold)]
91 monkeypatch.setenv("LAST30DAYS_ENGINE", "rust")
92 rs_kept = [it.item_id for it in dedupe.dedupe_items(items, threshold=threshold)]
93 assert rs_kept == py_kept, f"mismatch at threshold={threshold}"
94
95
96 @requires_rust
97 def test_annotate_stream_differential_parity(monkeypatch):
98 sources = [
99 "reddit", "x", "youtube", "tiktok", "instagram", "hackernews",
100 "github", "digg", "polymarket", "amazon", "jobs", "grounding",
101 ]
102 base_items: list[schema.SourceItem] = []
103 for i, src in enumerate(sources * 3):
104 eng: dict[str, object] = {}
105 meta: dict[str, object] = {}
106 if src == "reddit":
107 eng = {"score": 10 * i, "num_comments": 3 * i, "upvote_ratio": 0.85}
108 meta = {"top_comments": [{"score": i * 5}]}
109 elif src in {"youtube", "tiktok", "instagram"}:
110 eng = {"views": 5000 * (i + 1), "likes": 120 * i, "comments": 15 * i}
111 meta = {"hashtags": ["claudecode", "rustlang"], "top_comments": [{"score": 25 * i}]}
112 elif src == "github":
113 eng = {"stars": 4000} if i % 2 == 0 else {"reactions": 40, "comments": 12}
114 if i % 3 == 0:
115 meta = {"labels": ["project-mode"]}
116 elif src == "digg":
117 eng = {"digg_score": 120 if i % 2 == 0 else 0, "postCount": 20, "uniqueAuthors": 15}
118 elif src == "polymarket":
119 eng = {"volume": 50000, "liquidity": 8000}
120 elif src == "amazon":
121 eng = {"ratings": 1200}
122 meta = {"grounding_exempt": True}
123 elif src == "hackernews":
124 eng = {"points": 150, "comments": 65}
125 elif src == "x":
126 eng = {"likes": 90, "reposts": 12, "replies": 5, "quotes": 2}
127 base_items.append(
128 schema.SourceItem(
129 item_id=f"{src}-{i}",
130 source=src,
131 title=f"Claude Code Rust rewrite benchmark {i}",
132 body="Comparing JS and JavaScript tooling with AI agents in 2026.",
133 snippet="Rust performance analysis.",
134 url=f"https://example.com/{src}/{i}",
135 published_at=f"2026-11-{(i % 25) + 1:02d}",
136 engagement=eng,
137 metadata=meta,
138 )
139 )
140
141 for mode in ("strict_recent", "balanced_recent", "evergreen_ok"):
142 py_items = [
143 schema.SourceItem(**{**it.__dict__, "engagement": dict(it.engagement), "metadata": dict(it.metadata)})
144 for it in base_items
145 ]
146 rs_items = [
147 schema.SourceItem(**{**it.__dict__, "engagement": dict(it.engagement), "metadata": dict(it.metadata)})
148 for it in base_items
149 ]
150 monkeypatch.setenv("LAST30DAYS_ENGINE", "python")
151 py_res = signals.annotate_stream(py_items, "Claude Code JS benchmark", mode, reference_date="2026-11-26")
152 monkeypatch.setenv("LAST30DAYS_ENGINE", "rust")
153 rs_res = signals.annotate_stream(rs_items, "Claude Code JS benchmark", mode, reference_date="2026-11-26")
154
155 assert [x.item_id for x in rs_res] == [x.item_id for x in py_res], f"order mismatch ({mode})"
156 for py_it, rs_it in zip(py_res, rs_res):
157 assert rs_it.local_relevance == pytest.approx(py_it.local_relevance, abs=1e-9)
158 assert rs_it.freshness == py_it.freshness
159 assert rs_it.engagement_score == py_it.engagement_score
160 assert rs_it.source_quality == pytest.approx(py_it.source_quality, abs=1e-9)
161 assert rs_it.local_rank_score == pytest.approx(py_it.local_rank_score, abs=1e-9)
162
163
164 @requires_rust
165 def test_cluster_differential_parity(monkeypatch):
166 def _make_cands():
167 return [
168 schema.Candidate(
169 candidate_id=f"c{i}",
170 item_id=f"c{i}",
171 source=src,
172 title=title,
173 url=f"https://example.com/c{i}",
174 snippet=snip,
175 subquery_labels=["primary"],
176 native_ranks={"primary": i + 1},
177 local_relevance=0.8,
178 freshness=80,
179 engagement=50,
180 source_quality=0.7,
181 rrf_score=0.02,
182 final_score=score,
183 source_items=[
184 schema.SourceItem(
185 item_id=f"c{i}",
186 source=src,
187 title=title,
188 body=snip,
189 url=f"https://example.com/c{i}",
190 published_at=pub,
191 date_confidence="high",
192 )
193 ],
194 metadata={"range_from": "2026-10-27", "range_to": "2026-11-26"},
195 )
196 for i, (src, title, snip, score, pub) in enumerate(
197 [
198 ("reddit", "Kanye West headlines Wireless Festival 2026", "Three nights in London.", 85.0, "2026-11-20"),
199 ("x", "BREAKING: Kanye West UK comeback at Wireless Festival", "July festival dates.", 80.0, "2026-11-21"),
200 ("polymarket", "Sam Altman equity stake in OpenAI 2026", "Will Sam Altman receive equity?", 78.0, "2026-11-22"),
201 ("reddit", "Sam Altman rivalry with Elon Musk escalates", "Feud continues over OpenAI.", 82.0, "2026-11-22"),
202 ("youtube", "Rust 1.97 compiler benchmark deep dive", "Release performance numbers.", 74.0, "2026-11-18"),
203 ("hackernews", "Rust 1.97 compiler benchmark results", "Release performance numbers discussed.", 72.0, "2026-11-19"),
204 ("reddit", "Rust 1.97 compiler benchmark archive", "Release performance numbers old post.", 99.0, "2025-06-01"),
205 ]
206 )
207 ]
208
209 plan = schema.QueryPlan(
210 intent="breaking_news",
211 freshness_mode="strict_recent",
212 cluster_mode="story",
213 raw_topic="tech news",
214 subqueries=[],
215 source_weights={},
216 )
217 monkeypatch.setenv("LAST30DAYS_ENGINE", "python")
218 py_clusters = cluster.cluster_candidates(_make_cands(), plan)
219 monkeypatch.setenv("LAST30DAYS_ENGINE", "rust")
220 rs_clusters = cluster.cluster_candidates(_make_cands(), plan)
221
222 assert len(rs_clusters) == len(py_clusters)
223 for py_cl, rs_cl in zip(py_clusters, rs_clusters):
224 assert rs_cl.title == py_cl.title
225 assert rs_cl.candidate_ids == py_cl.candidate_ids
226 assert rs_cl.representative_ids == py_cl.representative_ids
227 assert rs_cl.sources == py_cl.sources
228 assert rs_cl.score == pytest.approx(py_cl.score, abs=1e-9)
229 assert rs_cl.uncertainty == py_cl.uncertainty
230
231
232 @requires_rust
233 def test_library_sync_differential_parity(tmp_path: Path, monkeypatch):
234 memory = tmp_path / "memory"
235 memory.mkdir()
236 briefs = tmp_path / "briefs"
237 (memory / "public-raw.md").write_text(
238 "# last30days v4.6.0: Rust Accelerator\n\n"
239 "- Date range: 2026-10-27 to 2026-11-26\n\n"
240 "## Ranked Evidence Clusters\n\n"
241 "### 1. Rust speeds up dedupe and markdown scanning (score 88, 2 items, sources: Reddit, HN)\n"
242 "1. [reddit] Thread\n"
243 " - Evidence: Speedups exceeded 50x.\n",
244 encoding="utf-8",
245 )
246 (memory / "mixed-private-raw.md").write_text(
247 "# last30days v4.6.0: Mixed Report\n\n"
248 "- Date range: 2026-10-27 to 2026-11-26\n\n"
249 f"{library.PRIVATE_CORPUS_START}\n## From your files\nTop secret note.\n{library.PRIVATE_CORPUS_END}\n\n"
250 "## Ranked Evidence Clusters\n\n"
251 "### 1. Public cluster title (score 70, 1 item, sources: Reddit)\n"
252 "1. [reddit] Public thread\n"
253 " - Evidence: Public evidence.\n",
254 encoding="utf-8",
255 )
256
257 py_db = tmp_path / "py.db"
258 rs_db = tmp_path / "rs.db"
259
260 monkeypatch.setenv("LAST30DAYS_ENGINE", "python")
261 py_sync = library_index.sync_library(memory, briefs, db_path=py_db)
262 monkeypatch.setenv("LAST30DAYS_ENGINE", "rust")
263 rs_sync = library_index.sync_library(memory, briefs, db_path=rs_db)
264
265 assert (rs_sync.indexed, rs_sync.removed, rs_sync.unchanged) == (
266 py_sync.indexed,
267 py_sync.removed,
268 py_sync.unchanged,
269 )
270 # Second sync in Rust must report all unchanged (fingerprint parity!).
271 rs_sync_2 = library_index.sync_library(memory, briefs, db_path=rs_db)
272 assert rs_sync_2.indexed == 0
273 assert rs_sync_2.unchanged == py_sync.indexed
274
275 # Cross-sync: Rust reading the DB populated by Python must ALSO see 0 changes!
276 rs_on_py_db = library_index.sync_library(memory, briefs, db_path=py_db)
277 assert rs_on_py_db.indexed == 0
278 assert rs_on_py_db.removed == 0
279 assert rs_on_py_db.unchanged == py_sync.indexed
280
281
282 @requires_rust
283 def test_library_sync_nested_emphasis_titles_match_and_persist(tmp_path: Path, monkeypatch):
284 memory = tmp_path / "memory"
285 memory.mkdir()
286 briefs = tmp_path / "briefs"
287 (memory / "nested-a-raw.md").write_text(
288 "# **__Rust__**\n\n- Date range: 2026-10-27 to 2026-11-26\n\nNested bold underscore body.\n",
289 encoding="utf-8",
290 )
291 (memory / "nested-b-raw.md").write_text(
292 "# __**Rust**__\n\n- Date range: 2026-10-27 to 2026-11-26\n\nNested underscore bold body.\n",
293 encoding="utf-8",
294 )
295 (memory / "mixed-bold-raw.md").write_text(
296 "# **bold** and __bold2__\n\n- Date range: 2026-10-27 to 2026-11-26\n\nSeparate bold tokens.\n",
297 encoding="utf-8",
298 )
299
300 py_db = tmp_path / "py.db"
301 rs_db = tmp_path / "rs.db"
302
303 monkeypatch.setenv("LAST30DAYS_ENGINE", "python")
304 py_sync = library_index.sync_library(memory, briefs, db_path=py_db)
305 monkeypatch.setenv("LAST30DAYS_ENGINE", "rust")
306 rs_sync = library_index.sync_library(memory, briefs, db_path=rs_db)
307
308 assert (rs_sync.indexed, rs_sync.removed, rs_sync.unchanged) == (3, 0, 0)
309 assert (py_sync.indexed, py_sync.removed, py_sync.unchanged) == (3, 0, 0)
310
311 # Repeated warm sync must retain all rows with zero churn.
312 rs_sync_2 = library_index.sync_library(memory, briefs, db_path=rs_db)
313 assert (rs_sync_2.indexed, rs_sync_2.removed, rs_sync_2.unchanged) == (0, 0, 3)
314
315 # Cross-sync against Python's DB must also agree on every entry_id and fingerprint.
316 rs_on_py_db = library_index.sync_library(memory, briefs, db_path=py_db)
317 assert (rs_on_py_db.indexed, rs_on_py_db.removed, rs_on_py_db.unchanged) == (0, 0, 3)
318
319 matches = library_index.search("Nested", db_path=rs_db, store_db_path=tmp_path / "none.db")
320 assert len(matches) == 2
321
322
323 @requires_rust
324 @pytest.mark.skipif(os.name != "posix", reason="POSIX directory symlink swap regression")
325 def test_library_sync_rust_rejects_parent_symlink_swap_before_upsert(tmp_path: Path, monkeypatch):
326 memory = tmp_path / "memory"
327 finished = memory / "finished"
328 finished.mkdir(parents=True)
329 briefs = tmp_path / "briefs"
330 outside = tmp_path / "outside"
331 outside.mkdir()
332
333 (finished / "target.md").write_text(
334 "# Original Safe Brief\n\n- Date range: 2026-10-27 to 2026-11-26\n\nSafe content.\n",
335 encoding="utf-8",
336 )
337 (outside / "target.md").write_text(
338 "# Outside Secret Brief\n\n- Date range: 2026-10-27 to 2026-11-26\n\nLeaked outside secret payload.\n",
339 encoding="utf-8",
340 )
341
342 real_scan = rust_accel.scan_markdown_files
343 swapped = False
344
345 def _swap_after_scan(requests):
346 nonlocal swapped
347 result = real_scan(requests)
348 if not swapped:
349 swapped = True
350 moved = tmp_path / "finished_backup"
351 finished.rename(moved)
352 os.symlink(outside, finished)
353 return result
354
355 monkeypatch.setenv("LAST30DAYS_ENGINE", "rust")
356 monkeypatch.setattr(rust_accel, "scan_markdown_files", _swap_after_scan)
357
358 db_path = tmp_path / "lib.db"
359 synced = library_index.sync_library(memory, briefs, db_path=db_path)
360
361 assert swapped is True
362 assert synced.indexed == 0
363 assert any("Skipped" in note for note in synced.notes)
364 assert library_index.search("Leaked", db_path=db_path, store_db_path=tmp_path / "none.db") == []
365 assert library_index.search("Outside", db_path=db_path, store_db_path=tmp_path / "none.db") == []
366
367
368 @pytest.mark.skipif(os.name != "posix", reason="POSIX executable script helper")
369 def test_worker_timeout_falls_back_in_auto_and_raises_in_rust(tmp_path: Path, monkeypatch):
370 stall_script = tmp_path / "stall-worker"
371 stall_script.write_text(
372 f"#!{sys.executable}\n"
373 "import json, sys, time\n"
374 "for line in sys.stdin:\n"
375 " req = json.loads(line)\n"
376 " if req.get('op') == 'ping':\n"
377 " sys.stdout.write(json.dumps({'status': 'ok', 'protocol': 1}) + '\\n')\n"
378 " sys.stdout.flush()\n"
379 " else:\n"
380 " time.sleep(60)\n",
381 encoding="utf-8",
382 )
383 stall_script.chmod(stall_script.stat().st_mode | stat.S_IXUSR)
384
385 monkeypatch.setenv("LAST30DAYS_RUST_BIN", str(stall_script))
386 monkeypatch.setenv("LAST30DAYS_RUST_TIMEOUT", "0.25")
387 rust_accel.shutdown()
388 rust_accel._POOL._disabled_for_bin = None
389 try:
390 # Auto mode: kills stalled worker, returns None, and falls back to pure Python.
391 monkeypatch.setenv("LAST30DAYS_ENGINE", "auto")
392 t0 = time.monotonic()
393 res = rust_accel.dedupe_kept_indices([{"mode": "fuzzy", "text": "hello"}], 0.7)
394 elapsed = time.monotonic() - t0
395 assert res is None
396 assert elapsed < 3.0
397 assert rust_accel._POOL._proc is None
398 assert rust_accel._POOL._disabled_for_bin == str(stall_script)
399
400 # Forced rust mode: raises RustAccelError within the deadline.
401 rust_accel.shutdown()
402 rust_accel._POOL._disabled_for_bin = None
403 monkeypatch.setenv("LAST30DAYS_ENGINE", "rust")
404 t1 = time.monotonic()
405 with pytest.raises(rust_accel.RustAccelError, match="timed out"):
406 rust_accel.dedupe_kept_indices([{"mode": "fuzzy", "text": "hello"}], 0.7)
407 assert time.monotonic() - t1 < 3.0
408 assert rust_accel._POOL._proc is None
409 finally:
410 rust_accel.shutdown()
411 rust_accel._POOL._disabled_for_bin = None
412
413
414 @requires_rust
415 @pytest.mark.skipif(not hasattr(os, "mkfifo"), reason="POSIX FIFO required")
416 def test_rust_scan_rejects_fifo_without_blocking(tmp_path: Path, monkeypatch):
417 fifo_path = tmp_path / "named-pipe.md"
418 os.mkfifo(fifo_path)
419
420 monkeypatch.setenv("LAST30DAYS_ENGINE", "rust")
421 monkeypatch.setenv("LAST30DAYS_RUST_TIMEOUT", "2.0")
422 t0 = time.monotonic()
423 outcomes = rust_accel.scan_markdown_files(
424 [
425 {
426 "path": str(fifo_path),
427 "stem": "named-pipe",
428 "source_format": "markdown",
429 "expected_dev_ino": None,
430 "fallback_date": "2026-11-26",
431 }
432 ]
433 )
434 elapsed = time.monotonic() - t0
435 assert elapsed < 1.5
436 assert outcomes is not None
437 assert len(outcomes) == 1
438 assert outcomes[0]["status"] == "skipped"
439
440
441 def test_platform_asset_name_and_checksums_and_url_validation():
442 assert rust_accel.platform_asset_name("darwin", "arm64") == "last30days-core-darwin-arm64"
443 assert rust_accel.platform_asset_name("darwin", "x86_64") == "last30days-core-darwin-amd64"
444 assert rust_accel.platform_asset_name("linux", "x86_64") == "last30days-core-linux-amd64"
445 assert rust_accel.platform_asset_name("linux", "aarch64") == "last30days-core-linux-arm64"
446 assert rust_accel.platform_asset_name("win32", "AMD64") == "last30days-core-windows-amd64.exe"
447 assert rust_accel.platform_asset_name("freebsd", "x86_64") is None
448
449 valid_hex = "a" * 64
450 parsed = rust_accel.parse_checksums(
451 f"# comment\n"
452 f"{valid_hex} last30days-core-darwin-arm64\n"
453 f"{valid_hex} *last30days-core-windows-amd64.exe\n"
454 f"short ignored-bin\n"
455 f"{valid_hex} ../escape-bin\n"
456 )
457 assert parsed == {
458 "last30days-core-darwin-arm64": valid_hex,
459 "last30days-core-windows-amd64.exe": valid_hex,
460 }
461
462 assert rust_accel._validate_download_url(
463 "https://github.com/mvanhorn/last30days-skill/releases/download/v4.7.0/last30days-core-darwin-arm64"
464 ).startswith("https://")
465 for bad_url in (
466 "http://github.com/mvanhorn/last30days-skill/releases/download/v4.7.0/bin",
467 "https://evil.example.com/last30days-core-darwin-arm64",
468 "https://user:pass@github.com/mvanhorn/last30days-skill/releases/download/v4.7.0/bin",
469 "file:///etc/passwd",
470 ):
471 with pytest.raises(ValueError, match="disallowed download URL"):
472 rust_accel._validate_download_url(bad_url)
473
474
475 @pytest.mark.skipif(os.name != "posix", reason="POSIX executable stub installer test")
476 def test_install_release_binary_verifies_sha256_installs_upgrades_and_rejects_bad_digest(
477 tmp_path: Path, monkeypatch
478 ):
479 fake_home = tmp_path / "home"
480 fake_home.mkdir()
481 monkeypatch.setenv("HOME", str(fake_home))
482 monkeypatch.setenv("LAST30DAYS_ENGINE", "auto")
483 monkeypatch.delenv("LAST30DAYS_RUST_BIN", raising=False)
484
485 # Hide dev checkout binary so discovery uses only managed ~/.local/share/last30days/bin/
486 managed = rust_accel.install_bin_path()
487 monkeypatch.setattr(rust_accel, "_candidate_binary_paths", lambda: [managed])
488 monkeypatch.setattr(rust_accel, "platform_asset_name", lambda *_a, **_k: "last30days-core-test-bin")
489
490 good_script = (
491 f"#!{sys.executable}\n"
492 "import json, sys\n"
493 "for line in sys.stdin:\n"
494 " if json.loads(line).get('op') == 'ping':\n"
495 " sys.stdout.write(json.dumps({'status': 'ok', 'version': '0.1.0', 'protocol': 1}) + '\\n')\n"
496 " sys.stdout.flush()\n"
497 ).encode("utf-8")
498 good_sha = hashlib.sha256(good_script).hexdigest()
499 checksums_text = f"{good_sha} last30days-core-test-bin\n".encode("utf-8")
500
501 fetch_calls: list[str] = []
502
503 def _fake_fetch(url: str, *, max_bytes: int, timeout: float = 30.0) -> bytes:
504 fetch_calls.append(url)
505 if url.endswith(rust_accel.CHECKSUMS_ASSET):
506 return checksums_text
507 if url.endswith("last30days-core-test-bin"):
508 return good_script
509 raise AssertionError(f"unexpected URL: {url}")
510
511 monkeypatch.setattr(rust_accel, "_https_fetch_bytes", _fake_fetch)
512
513 try:
514 # 1. Fresh install succeeds with SHA-256 + ping verification.
515 res1 = rust_accel.install_release_binary(version="4.7.0")
516 assert res1["installed"] is True
517 assert res1["action"] == "installed"
518 assert res1["version"] == "4.7.0"
519 assert managed.is_file()
520 assert len(fetch_calls) == 2
521
522 # 2. Same version is idempotent with zero downloads.
523 res2 = rust_accel.install_release_binary(version="4.7.0")
524 assert res2["installed"] is True
525 assert res2["action"] == "already_installed"
526 assert len(fetch_calls) == 2
527
528 # 3. Version bump triggers verified upgrade.
529 res3 = rust_accel.install_release_binary(version="4.8.0")
530 assert res3["installed"] is True
531 assert res3["action"] == "upgraded"
532 assert res3["version"] == "4.8.0"
533 assert len(fetch_calls) == 4
534
535 # 4. Doctor status reports active rust core without network calls.
536 st = rust_accel.status()
537 assert st["active"] is True
538 assert st["installed_version"] == "4.8.0"
539 assert st["fallback"] is None
540
541 # 5. Tampered binary fails SHA-256 check and keeps existing binary intact.
542 def _tampered_fetch(url: str, *, max_bytes: int, timeout: float = 30.0) -> bytes:
543 if url.endswith(rust_accel.CHECKSUMS_ASSET):
544 return checksums_text
545 return b"corrupted payload"
546
547 monkeypatch.setattr(rust_accel, "_https_fetch_bytes", _tampered_fetch)
548 res4 = rust_accel.install_release_binary(version="4.9.0")
549 assert res4["action"] == "install_failed"
550 assert "SHA-256 mismatch" in res4["detail"]
551 assert res4["installed"] is True
552 assert managed.read_bytes() == good_script
553 finally:
554 rust_accel.shutdown()
555
556
557 def test_ensure_installed_for_run_records_cooldown_on_failure(tmp_path: Path, monkeypatch):
558 fake_home = tmp_path / "home"
559 fake_home.mkdir()
560 monkeypatch.setenv("HOME", str(fake_home))
561 monkeypatch.setenv("LAST30DAYS_ENGINE", "auto")
562 managed = rust_accel.install_bin_path()
563 monkeypatch.setattr(rust_accel, "_candidate_binary_paths", lambda: [managed])
564 monkeypatch.setattr(rust_accel, "platform_asset_name", lambda *_a, **_k: "last30days-core-test-bin")
565 monkeypatch.setattr(rust_accel, "expected_skill_version", lambda: "4.7.0")
566
567 attempts = 0
568
569 def _failing_fetch(url: str, *, max_bytes: int, timeout: float = 30.0) -> bytes:
570 nonlocal attempts
571 attempts += 1
572 raise OSError("network unreachable")
573
574 monkeypatch.setattr(rust_accel, "_https_fetch_bytes", _failing_fetch)
575
576 first = rust_accel.ensure_installed_for_run()
577 assert first is not None and first["action"] == "install_failed"
578 assert attempts == 1
579
580 # Second call within cooldown must skip network entirely.
581 second = rust_accel.ensure_installed_for_run()
582 assert second is None
583 assert attempts == 1
584
585
586 def test_install_release_binary_catches_incomplete_read(tmp_path: Path, monkeypatch):
587 fake_home = tmp_path / "home"
588 fake_home.mkdir()
589 monkeypatch.setenv("HOME", str(fake_home))
590 monkeypatch.setenv("LAST30DAYS_ENGINE", "auto")
591 managed = rust_accel.install_bin_path()
592 monkeypatch.setattr(rust_accel, "_candidate_binary_paths", lambda: [managed])
593 monkeypatch.setattr(rust_accel, "platform_asset_name", lambda *_a, **_k: "last30days-core-test-bin")
594 monkeypatch.setattr(rust_accel, "expected_skill_version", lambda: "4.7.0")
595
596 def _truncated_fetch(url: str, *, max_bytes: int, timeout: float = 30.0) -> bytes:
597 raise http.client.IncompleteRead(b"partial")
598
599 monkeypatch.setattr(rust_accel, "_https_fetch_bytes", _truncated_fetch)
600
601 res = rust_accel.ensure_installed_for_run()
602 assert res is not None
603 assert res["installed"] is False
604 assert res["action"] == "install_failed"
605 assert not managed.exists()
606
607
608 def test_expected_skill_version_reads_mcp_sentinel_without_skill_md(tmp_path: Path):
609 bundle_root = tmp_path / "last30days-pp-mcp" / "v4.7.0"
610 fake_mod = bundle_root / "lib" / "rust_accel.py"
611 fake_mod.parent.mkdir(parents=True)
612 fake_mod.write_text("", encoding="utf-8")
613 (bundle_root / ".version").write_text("v4.7.0\n", encoding="utf-8")
614
615 assert rust_accel.expected_skill_version(fake_mod) == "4.7.0"
616
617 (bundle_root / ".version").write_text("dev\n", encoding="utf-8")
618 assert rust_accel.expected_skill_version(fake_mod) is None
619
620
621 @requires_rust
622 def test_library_sync_rust_preserves_distinct_topics_sharing_slug(tmp_path: Path, monkeypatch):
623 memory = tmp_path / "memory"
624 finished = memory / "finished"
625 finished.mkdir(parents=True)
626 briefs = tmp_path / "briefs"
627 (finished / "c-2026-07-10.md").write_text(
628 "🌐 last30days · C# · Jun 10 to Jul 10, 2026 · v4.6.0\n\nC# finished brief.\n",
629 encoding="utf-8",
630 )
631 (memory / "c-raw.md").write_text(
632 "# last30days v4.6.0: C++\n\n- Date range: 2026-06-10 to 2026-07-10\n\nC++ raw report.\n",
633 encoding="utf-8",
634 )
635 (memory / "c-raw-2026-07-10.md").write_text(
636 "# last30days v4.6.0: c#\n\n- Date range: 2026-06-10 to 2026-07-10\n\nSuperseded C# raw.\n",
637 encoding="utf-8",
638 )
639
640 py_db = tmp_path / "py.db"
641 rs_db = tmp_path / "rs.db"
642 monkeypatch.setenv("LAST30DAYS_ENGINE", "python")
643 py_sync = library_index.sync_library(memory, briefs, db_path=py_db)
644 monkeypatch.setenv("LAST30DAYS_ENGINE", "rust")
645 rs_sync = library_index.sync_library(memory, briefs, db_path=rs_db)
646
647 assert (rs_sync.indexed, rs_sync.removed, rs_sync.unchanged) == (2, 0, 0)
648 assert (py_sync.indexed, py_sync.removed, py_sync.unchanged) == (2, 0, 0)
649 found_topics = {
650 m.topic
651 for m in library_index.search("C", db_path=rs_db, store_db_path=tmp_path / "none.db")
652 }
653 assert found_topics == {"C#", "C++"}
654 assert len(library_index.search("Superseded", db_path=rs_db, store_db_path=tmp_path / "none.db")) == 0
655
656
657 @requires_rust
658 def test_v2ex_signal_parity(monkeypatch):
659 items_py = [
660 schema.SourceItem(
661 item_id="v2ex-1",
662 source="v2ex",
663 title="Rust async runtime discussion",
664 body="Comparing Tokio and smol in production.",
665 url="https://www.v2ex.com/t/12345",
666 published_at="2026-11-25",
667 engagement={"replies": 85},
668 )
669 ]
670 items_rs = [
671 schema.SourceItem(**{**items_py[0].__dict__, "engagement": dict(items_py[0].engagement)})
672 ]
673 monkeypatch.setenv("LAST30DAYS_ENGINE", "python")
674 py_res = signals.annotate_stream(items_py, "Rust async runtime", "balanced_recent", reference_date="2026-11-26")
675 monkeypatch.setenv("LAST30DAYS_ENGINE", "rust")
676 rs_res = signals.annotate_stream(items_rs, "Rust async runtime", "balanced_recent", reference_date="2026-11-26")
677 assert rs_res[0].source_quality == pytest.approx(py_res[0].source_quality, abs=1e-9)
678 assert rs_res[0].engagement_score == py_res[0].engagement_score
679 assert rs_res[0].local_rank_score == pytest.approx(py_res[0].local_rank_score, abs=1e-9)
680
681
682 @requires_rust
683 def test_juejin_signal_parity(monkeypatch):
684 items_py = [
685 schema.SourceItem(
686 item_id="juejin-1",
687 source="juejin",
688 title="Rust async runtime discussion",
689 body="Comparing Tokio and smol in production.",
690 url="https://juejin.cn/post/12345",
691 published_at="2026-11-25",
692 engagement={"likes": 8, "comments": 3, "saves": 4, "views": 1200},
693 )
694 ]
695 items_rs = [
696 schema.SourceItem(**{**items_py[0].__dict__, "engagement": dict(items_py[0].engagement)})
697 ]
698 monkeypatch.setenv("LAST30DAYS_ENGINE", "python")
699 py_res = signals.annotate_stream(items_py, "Rust async runtime", "balanced_recent", reference_date="2026-11-26")
700 monkeypatch.setenv("LAST30DAYS_ENGINE", "rust")
701 rs_res = signals.annotate_stream(items_rs, "Rust async runtime", "balanced_recent", reference_date="2026-11-26")
702 assert rs_res[0].source_quality == pytest.approx(py_res[0].source_quality, abs=1e-9)
703 assert rs_res[0].engagement_score == py_res[0].engagement_score
704 assert rs_res[0].local_rank_score == pytest.approx(py_res[0].local_rank_score, abs=1e-9)
705
706
707 def test_setup_status_and_doctor_render_rust_core(monkeypatch):
708 text = setup_wizard.get_setup_status_text(
709 {
710 "cookies_found": {},
711 "ytdlp_installed": True,
712 "ytdlp_action": "already_installed",
713 "rust_core": {"installed": True, "action": "installed", "version": "4.7.0"},
714 }
715 )
716 assert "Installed native Rust core (v4.7.0)" in text
717
718 monkeypatch.setattr(
719 rust_accel,
720 "status",
721 lambda: {
722 "mode": "auto",
723 "active": True,
724 "binary_path": "/tmp/last30days-core",
725 "installed_version": "4.7.0",
726 "expected_version": "4.7.0",
727 "platform_asset": "last30days-core-darwin-arm64",
728 "fallback": None,
729 },
730 )
731 report = doctor.build_report({})
732 assert report["rust_core"]["active"] is True
733 rendered = doctor.render_text(report)
734 assert "compute core: rust (last30days-core v4.7.0, /tmp/last30days-core)" in rendered
735
736
737 @requires_rust
738 def test_public_markdown_unicode_line_breaks_parity(monkeypatch):
739 padding = "Public context line.\n" * 120
740 for brk in ("\u2028", "\u2029", "\u0085", "\x0b", "\x0c", "\x1c", "\x1d", "\x1e"):
741 doc = f"{padding}Intro{brk}## From your files\nTop secret note\n## Public\nVisible\n"
742 monkeypatch.setenv("LAST30DAYS_ENGINE", "python")
743 py_out = library.public_markdown(doc)
744 monkeypatch.setenv("LAST30DAYS_ENGINE", "rust")
745 rs_out = library.public_markdown(doc)
746 monkeypatch.setenv("LAST30DAYS_ENGINE", "auto")
747 auto_out = library.public_markdown(doc)
748 assert "Top secret note" not in py_out
749 assert rs_out == py_out, f"rust mismatch for {brk!r}"
750 assert auto_out == py_out, f"auto mismatch for {brk!r}"
751
752 nbsp_doc = f"{padding}## Ranked Evidence Clusters\n### 1. Notes\n\u00a0**From your files**\nSecret\n"
753 monkeypatch.setenv("LAST30DAYS_ENGINE", "python")
754 py_nbsp = library.public_markdown(nbsp_doc)
755 monkeypatch.setenv("LAST30DAYS_ENGINE", "rust")
756 rs_nbsp = library.public_markdown(nbsp_doc)
757 assert "Secret" not in py_nbsp
758 assert rs_nbsp == py_nbsp
759
760 for variant in ("## From your f\u0131les", "## From your file\u017f", "## From your f\u0130les"):
761 case_doc = f"{padding}{variant}\nSecret\n## Public\nVisible\n"
762 monkeypatch.setenv("LAST30DAYS_ENGINE", "python")
763 py_case = library.public_markdown(case_doc)
764 monkeypatch.setenv("LAST30DAYS_ENGINE", "rust")
765 rs_case = library.public_markdown(case_doc)
766 monkeypatch.setenv("LAST30DAYS_ENGINE", "auto")
767 auto_case = library.public_markdown(case_doc)
768 assert "Secret" not in py_case
769 assert rs_case == py_case, f"rust mismatch for {variant!r}"
770 assert auto_case == py_case, f"auto mismatch for {variant!r}"
771
772
773 def test_annotate_stream_jieba_fallback_checks_cjk_hashtags(monkeypatch):
774 from types import SimpleNamespace
775 from lib import cjk
776
777 monkeypatch.setenv("LAST30DAYS_ENGINE", "rust")
778 monkeypatch.setattr(cjk, "_jieba", SimpleNamespace(cut=lambda text: [text]))
779 called = []
780 monkeypatch.setattr(
781 rust_accel,
782 "annotate_stream",
783 lambda *args, **kwargs: called.append(args) or [],
784 )
785 items = [
786 schema.SourceItem(
787 item_id="tt-1",
788 source="tiktok",
789 title="English review clip",
790 body="Hands-on comparison",
791 url="https://example.com/tt/1",
792 published_at="2026-11-25",
793 metadata={"hashtags": ["国产大模型"]},
794 )
795 ]
796 signals.annotate_stream(items, "English review", "balanced_recent", reference_date="2026-11-26")
797 assert called == []
798
799
800 def test_status_distinguishes_unverified_and_disabled_worker(tmp_path: Path, monkeypatch):
801 fake_bin = tmp_path / "custom-core"
802 fake_bin.write_text("#!/bin/sh\nexit 1\n", encoding="utf-8")
803 fake_bin.chmod(fake_bin.stat().st_mode | stat.S_IXUSR)
804
805 monkeypatch.setenv("LAST30DAYS_ENGINE", "auto")
806 monkeypatch.setenv("LAST30DAYS_RUST_BIN", str(fake_bin))
807 monkeypatch.setattr(rust_accel, "_candidate_binary_paths", lambda: [fake_bin])
808 rust_accel.shutdown()
809 rust_accel._POOL._disabled_for_bin = None
810 rust_accel._POOL._verified_bin = None
811 rust_accel._POOL._last_error = None
812 try:
813 st_unverified = rust_accel.status()
814 assert st_unverified["active"] is False
815 assert st_unverified["verified"] is False
816 assert st_unverified["state"] == "discovered_unverified"
817 assert st_unverified["binary_path"] == str(fake_bin)
818
819 # Trigger a failing call in auto mode -> worker disables itself and status reflects it.
820 assert rust_accel.dedupe_kept_indices([{"mode": "fuzzy", "text": "hello"}], 0.7) is None
821 st_disabled = rust_accel.status()
822 assert st_disabled["active"] is False
823 assert st_disabled["state"] == "disabled_after_error"
824 assert st_disabled["fallback"] == "python"
825 assert st_disabled["detail"]
826 rendered = doctor.render_text(doctor.build_report({}))
827 assert "disabled after runtime error" in rendered
828 finally:
829 rust_accel.shutdown()
830 rust_accel._POOL._disabled_for_bin = None
831 rust_accel._POOL._verified_bin = None
832 rust_accel._POOL._last_error = None
833
834
835 def test_preflight_discloses_native_core_auto_install_when_missing(tmp_path: Path, monkeypatch, capsys):
836 import json
837 import last30days as cli
838 from lib import permission_preflight
839
840 fake_home = tmp_path / "home"
841 fake_home.mkdir()
842 monkeypatch.setenv("HOME", str(fake_home))
843 monkeypatch.setenv("LAST30DAYS_ENGINE", "auto")
844 managed = rust_accel.install_bin_path()
845 monkeypatch.setattr(rust_accel, "_candidate_binary_paths", lambda: [managed])
846 monkeypatch.setattr(rust_accel, "platform_asset_name", lambda *_a, **_k: "last30days-core-test-bin")
847 monkeypatch.setattr(rust_accel, "expected_skill_version", lambda: "4.7.0")
848 monkeypatch.setattr(sys, "argv", ["last30days.py", "--preflight", "--emit=json", "--no-browser-cookies"])
849
850 assert cli.main() == 0
851 payload = json.loads(capsys.readouterr().out)
852 assert {"kind": "native_core_on_first_run", "path": str(managed)} in payload["conditional_writes"]
853 rendered = permission_preflight.render_text(payload)
854 assert "Native Rust core binary" in rendered
855 assert "SHA-256 verification" in rendered
856
857 # When LAST30DAYS_ENGINE=python, no download/install is disclosed.
858 monkeypatch.setenv("LAST30DAYS_ENGINE", "python")
859 assert cli.main() == 0
860 py_payload = json.loads(capsys.readouterr().out)
861 assert not any(w.get("kind") == "native_core_on_first_run" for w in py_payload["conditional_writes"])
862
862 lines PYTHON