gabriel / musehub public
conftest.py python
957 lines 38.2 KB Hotspot Cold Blast
Raw
sha256:4f1496efd3bb9b1e764c31d3d9ae8218a550c06f78e351b15fe58409e4223282 fix(releases,wire): the rc channel is accepted like Muse's … Opus 5.5 minor ⚠ breaking 1 day ago
1 """Pytest configuration and fixtures."""
2 from __future__ import annotations
3
4 from pathlib import Path
5
6 import logging
7 import os
8 import typing
9 from collections.abc import AsyncGenerator, Generator
10
11 if not os.environ.get("MUSE_ENV"):
12 os.environ["MUSE_ENV"] = "test"
13
14 import pytest
15 import pytest_asyncio
16 from httpx import AsyncClient, ASGITransport
17 from sqlalchemy.ext.asyncio import (
18 AsyncSession,
19 async_sessionmaker,
20 create_async_engine,
21 )
22 from sqlalchemy.pool import NullPool
23
24 from musehub.core.genesis import compute_identity_id
25 from musehub.db import database
26 from musehub.db.database import Base, get_db
27 from musehub.db.musehub_identity_models import MusehubIdentity
28 from musehub.types.json_types import JSONValue
29 # Force all ORM models into Base.metadata before any create_all/drop_all.
30 # muse_cli_models is only imported inside init_db() in production; without
31 # this explicit import, Base.metadata is non-deterministic in tests (depends
32 # on import order), causing drop_all to miss tables that create_all later
33 # tries to create — resulting in duplicate-key errors on pg_type.
34 import musehub.db.muse_cli_models as _muse_cli_models # noqa: F401
35 from musehub.auth.request_signing import MSignContext, optional_signed_request, require_signed_request
36 from musehub.main import app
37 from musehub.rate_limits import limiter
38
39 type _JobPayload = dict[str, str | int | bool | None]
40 import musehub.auth.failure_limiter as _failure_limiter
41
42
43 @pytest.fixture()
44 def _stub_push_background_tasks(monkeypatch: pytest.MonkeyPatch) -> None:
45 """Spy fixture for tests that need to assert enqueue_push_intel was called.
46
47 Opt-in only — add this as an explicit parameter to tests that need it.
48 Tests that exercise enqueue logic directly should NOT use this fixture;
49 they should call the real implementation and verify DB state.
50 """
51 import musehub.services.musehub_jobs as _jobs
52 import musehub.services.musehub_wire as _wire
53
54 _jobs._test_enqueued_calls.clear()
55
56 async def _spy_enqueue(
57 session: AsyncSession, repo_id: str, head: str, domain_id: str | None = None, branch: str = "", owner: str | None = None,
58 ) -> None:
59 _jobs._test_enqueued_calls.append((repo_id, "enqueue_push_intel", {"head": head, "domain_id": domain_id, "branch": branch}))
60
61 monkeypatch.setattr(_jobs, "enqueue_push_intel", _spy_enqueue)
62 monkeypatch.setattr(_wire, "enqueue_push_intel", _spy_enqueue)
63
64
65 @pytest.fixture(autouse=True)
66 def _tmp_objects_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
67 """Redirect object storage to the local MinIO instance for tests.
68
69 Uses the same BlobBackend (boto3 + S3-compatible) that runs in staging/prod,
70 pointed at MinIO on localhost:9000. Content-addressing gives natural test
71 isolation — tests cannot read each other's objects unless they wrote
72 identical bytes (correct behaviour).
73
74 Requires MinIO to be running: docker compose up minio createbuckets -d
75 """
76 import musehub.storage.backends as _backends_mod
77 import musehub.services.musehub_wire as _wire_svc
78 import musehub.services.musehub_wire_fetch as _wire_fetch_svc
79 import musehub.services.musehub_wire_push as _wire_push_svc
80 import musehub.services.musehub_wire_shared as _wire_shared_svc
81 import musehub.services.musehub_gc as _gc_svc
82 import musehub.api.routes.wire as _wire_route
83 from musehub.config import settings
84 from musehub.storage.backends import MemoryBackend
85
86 test_backend = MemoryBackend()
87 import importlib
88 _backend_fn = lambda *_a, **_kw: test_backend
89 monkeypatch.setattr(_backends_mod, "get_backend", _backend_fn)
90 monkeypatch.setattr(_wire_svc, "get_backend", _backend_fn)
91 monkeypatch.setattr(_wire_fetch_svc, "get_backend", _backend_fn)
92 monkeypatch.setattr(_wire_push_svc, "get_backend", _backend_fn)
93 monkeypatch.setattr(_wire_shared_svc, "get_backend", _backend_fn)
94 monkeypatch.setattr(_gc_svc, "get_backend", _backend_fn)
95 monkeypatch.setattr(_wire_route, "get_backend", _backend_fn)
96 try:
97 _repair_mod = importlib.import_module("deploy.repair_objects")
98 monkeypatch.setattr(_repair_mod, "get_backend", _backend_fn)
99 except ModuleNotFoundError:
100 pass
101 monkeypatch.setattr(settings, "musehub_repos_dir", str(tmp_path))
102
103 # Redirect the /releases StaticFiles mount to a temp dir so tests that
104 # hit /releases/* don't fail because /data/releases doesn't exist locally.
105 releases_dir = f"{tmp_path}/releases"
106 os.makedirs(releases_dir, exist_ok=True)
107 from musehub.main import app as _app
108 for _route in _app.routes:
109 if getattr(_route, "name", None) == "releases":
110 _static = _route.app # type: ignore[attr-defined]
111 _static.directory = releases_dir
112 _static.config_checked = False # force re-check with new dir
113 break
114
115
116 def pytest_configure(config: pytest.Config) -> None:
117 """Ensure asyncio_mode is auto so async fixtures work (e.g. in Docker when pyproject not in cwd)."""
118 if hasattr(config.option, "asyncio_mode") and config.option.asyncio_mode is None:
119 config.option.asyncio_mode = "auto"
120 # Suppress verbose library loggers that flood the test output with DEBUG lines.
121 for name in ("httpcore", "httpx", "sqlalchemy", "asyncio", "faker"):
122 logging.getLogger(name).setLevel(logging.WARNING)
123
124
125 @pytest.fixture(autouse=True)
126 def reset_rate_limiter() -> Generator[None, None, None]:
127 """Reset in-memory rate-limit counters before every test.
128
129 Without this, the shared MemoryStorage accumulates hits across all tests
130 in a session. Auth endpoints cap at 20/minute; running 30+ auth tests
131 back-to-back exhausts that budget and causes 429s for legitimate calls.
132 """
133 limiter.reset()
134 _failure_limiter._failures.clear()
135 yield
136
137
138 @pytest.fixture
139 def anyio_backend() -> str:
140 return "asyncio"
141
142
143 _WIRE_CONTEXT = MSignContext(
144 handle="test-user-wire",
145 identity_id="wire-test-user-id",
146 is_agent=False,
147 is_admin=False,
148 )
149
150
151 @pytest.fixture
152 def wire_headers() -> Generator[dict[str, str], None, None]:
153 """Override auth deps to inject a fake MSignContext for wire protocol tests."""
154 app.dependency_overrides[require_signed_request] = lambda: _WIRE_CONTEXT
155 app.dependency_overrides[optional_signed_request] = lambda: _WIRE_CONTEXT
156 yield {
157 "Content-Type": "application/x-msgpack",
158 "Accept": "application/x-msgpack",
159 }
160 app.dependency_overrides.pop(require_signed_request, None)
161 app.dependency_overrides.pop(optional_signed_request, None)
162
163
164 @pytest.fixture(autouse=True)
165 def _reset_variation_store() -> Generator[None, None, None]:
166 """Reset the singleton VariationStore between tests to prevent cross-test pollution.
167
168 Gracefully no-ops if the variation module has been removed (MuseHub extraction).
169 """
170 yield
171 try:
172 from musehub.variation.storage.variation_store import reset_variation_store
173 reset_variation_store()
174 except ModuleNotFoundError:
175 pass
176
177
178 _TEST_DATABASE_URL = os.environ.get(
179 "TEST_DATABASE_URL",
180 "postgresql+asyncpg://musehub:musehub@localhost:5434/musehub_test",
181 )
182
183 # Sync URL for psycopg2 — used by the session-scoped schema fixture.
184 _TEST_DATABASE_URL_SYNC = _TEST_DATABASE_URL.replace("+asyncpg", "")
185
186 # Shared async engine for the whole test session (NullPool = no connection
187 # reuse between tests, but engine object creation is cheap so we create it
188 # once and share it).
189 _TEST_ENGINE = create_async_engine(_TEST_DATABASE_URL, poolclass=NullPool)
190 _TEST_SESSION_FACTORY = async_sessionmaker(
191 bind=_TEST_ENGINE,
192 class_=AsyncSession,
193 expire_on_commit=False,
194 )
195
196 # Pre-compute the TRUNCATE statement for all tables so we don't rebuild it
197 # each test. Reversed sorted_tables respects FK dependency order.
198 _TRUNCATE_SQL = "TRUNCATE {} RESTART IDENTITY CASCADE".format(
199 ", ".join(t.name for t in reversed(Base.metadata.sorted_tables))
200 )
201
202
203 # Suites that never use the database. A session collecting only these must not connect to (let alone
204 # drop and recreate the schema of) a Postgres instance: the release gates run them in a hermetic
205 # environment that has no database, and a gate result must not depend on one being reachable.
206 # tests/docs_contract/ is database-free by directory (musehub#273): a new docs module needs no marker.
207 _NO_DB_PREFIXES = (
208 "tests/install_e2e/",
209 "tests/test_release_",
210 "tests/test_prune_releases.py",
211 "tests/test_build_context.py",
212 "tests/docs_contract/",
213 )
214
215 # The fixtures that depend on _db_schema. ``item.fixturenames`` is the transitive closure, so a test that
216 # reaches one indirectly (client → db_session) is DB-backed too.
217 _DB_FIXTURES = frozenset({"db_session", "session_factory"})
218
219
220 def pytest_collection_modifyitems(config: pytest.Config, items: list[pytest.Item]) -> None:
221 for item in items:
222 # per test, not per file: a DB-backed test inside one of these paths (fixture closure includes a
223 # DB fixture) keeps the schema fixture alive for the whole session.
224 if item.nodeid.startswith(_NO_DB_PREFIXES) and _DB_FIXTURES.isdisjoint(getattr(item, "fixturenames", ())):
225 item.add_marker(pytest.mark.no_db)
226
227
228 @pytest.fixture(scope="session", autouse=True)
229 def _db_schema(request: pytest.FixtureRequest) -> Generator[None, None, None]:
230 """Create the test schema once per test session using a sync psycopg2 engine.
231
232 Skipped entirely when every collected test is marked ``no_db``.
233
234 This replaces per-test drop_all/create_all (which took ~3 s per test on
235 PostgreSQL) with a single DDL pass at session start and end. Individual
236 tests get a clean slate via TRUNCATE in the db_session fixture instead.
237 """
238 if request.session.items and all(item.get_closest_marker("no_db") for item in request.session.items):
239 yield
240 return
241
242 from sqlalchemy import create_engine as _create_engine
243
244 from sqlalchemy import text as _text
245
246 # connect_timeout=10: if postgres is unreachable or still starting (e.g.
247 # Docker container not ready), fail fast instead of blocking in C forever.
248 # Without this, Ctrl+C cannot kill the process because psycopg2's socket
249 # read is a non-interruptible C-level call.
250 sync_engine = _create_engine(
251 _TEST_DATABASE_URL_SYNC,
252 connect_args={"connect_timeout": 10},
253 )
254 # Terminate any leftover connections from interrupted test runs before
255 # running drop_all. If a previous pytest session was killed with SIGQUIT
256 # (Ctrl+\) it leaves postgres backends idle-in-transaction holding locks on
257 # the test tables. drop_all then waits forever for those locks, which
258 # makes the next test run freeze with Ctrl+C unresponsive.
259 with sync_engine.connect() as _conn:
260 _conn.execute(_text(
261 "SELECT pg_terminate_backend(pid) FROM pg_stat_activity "
262 "WHERE datname = current_database() AND pid != pg_backend_pid()"
263 ))
264 _conn.commit()
265 # Dispose so drop_all / create_all get fresh connections — the
266 # pg_terminate_backend above may have killed pooled connections.
267 sync_engine.dispose()
268 sync_engine2 = _create_engine(
269 _TEST_DATABASE_URL_SYNC,
270 connect_args={"connect_timeout": 10},
271 )
272 Base.metadata.drop_all(sync_engine2)
273 sync_engine2.dispose()
274 sync_engine2 = _create_engine(
275 _TEST_DATABASE_URL_SYNC,
276 connect_args={"connect_timeout": 10},
277 )
278 Base.metadata.create_all(sync_engine2)
279 # Seed claim types (mirrors alembic/versions/0043 seed logic)
280 from musehub.services.musehub_attestations import _CLAIM_TYPES
281 with sync_engine2.connect() as _conn:
282 for ct in _CLAIM_TYPES.values():
283 _conn.execute(_text(
284 "INSERT INTO musehub_attestation_claim_types "
285 "(type_key, category, label, description, valid_scopes, introduced_at) "
286 "VALUES (:key, :cat, :label, :desc, :scopes, NOW()) "
287 "ON CONFLICT (type_key) DO NOTHING"
288 ), {"key": ct["type_key"], "cat": ct["category"], "label": ct["label"],
289 "desc": ct["description"], "scopes": ct["valid_scopes"]})
290 _conn.commit()
291 sync_engine2.dispose()
292 yield
293 sync_engine3 = _create_engine(
294 _TEST_DATABASE_URL_SYNC,
295 connect_args={"connect_timeout": 10},
296 )
297 with sync_engine3.connect() as _conn:
298 _conn.execute(_text(
299 "SELECT pg_terminate_backend(pid) FROM pg_stat_activity "
300 "WHERE datname = current_database() AND pid != pg_backend_pid()"
301 ))
302 _conn.commit()
303 sync_engine3.dispose()
304 sync_engine4 = _create_engine(
305 _TEST_DATABASE_URL_SYNC,
306 connect_args={"connect_timeout": 10},
307 )
308 Base.metadata.drop_all(sync_engine4)
309 sync_engine4.dispose()
310
311
312 @pytest_asyncio.fixture
313 async def db_session(_db_schema: None) -> AsyncGenerator[AsyncSession, None]:
314 """Provide a clean DB session for each test.
315
316 Tables are truncated (not dropped/recreated) between tests — a single
317 TRUNCATE … CASCADE is ~100× faster than drop_all + create_all on
318 PostgreSQL, cutting per-test overhead from ~3 s to ~30 ms.
319 """
320 from sqlalchemy import text as _text
321
322 async with _TEST_ENGINE.begin() as conn:
323 # Terminate ALL other backends before TRUNCATE. A failed test can
324 # leave a connection in any state (idle in transaction, idle in
325 # transaction (aborted), active) — filtering by state misses some
326 # cases and causes deadlocks when TRUNCATE races the stale transaction.
327 await conn.execute(_text(
328 "SELECT pg_terminate_backend(pid) FROM pg_stat_activity "
329 "WHERE datname = current_database() AND pid != pg_backend_pid()"
330 ))
331 await conn.execute(_text(_TRUNCATE_SQL))
332 # Re-seed reference tables that are wiped by TRUNCATE CASCADE.
333 from musehub.services.musehub_attestations import _CLAIM_TYPES
334 for _ct in _CLAIM_TYPES.values():
335 await conn.execute(_text(
336 "INSERT INTO musehub_attestation_claim_types "
337 "(type_key, category, label, description, valid_scopes, introduced_at) "
338 "VALUES (:key, :cat, :label, :desc, :scopes, NOW()) "
339 "ON CONFLICT (type_key) DO NOTHING"
340 ), {"key": _ct["type_key"], "cat": _ct["category"], "label": _ct["label"],
341 "desc": _ct["description"], "scopes": _ct["valid_scopes"]})
342
343 old_engine = database._engine
344 old_factory = database._async_session_factory
345 database._engine = _TEST_ENGINE
346 database._async_session_factory = _TEST_SESSION_FACTORY
347 try:
348 async with _TEST_SESSION_FACTORY() as session:
349 async def override_get_db() -> AsyncGenerator[AsyncSession, None]:
350 # Each request gets its own session so concurrent requests
351 # (e.g. stress tests) don't share a single connection and
352 # raise "concurrent operations are not permitted".
353 # All test setup data is committed, so independent sessions
354 # see it without needing to share the test session.
355 async with _TEST_SESSION_FACTORY() as req_session:
356 yield req_session
357 app.dependency_overrides[get_db] = override_get_db
358 yield session
359 app.dependency_overrides.clear()
360 finally:
361 database._engine = old_engine
362 database._async_session_factory = old_factory
363
364
365 @pytest_asyncio.fixture
366 async def session_factory(_db_schema: None) -> async_sessionmaker:
367 """Expose the test session factory for tests needing multiple concurrent sessions."""
368 return _TEST_SESSION_FACTORY
369
370
371 class _Asgi24Wrapper:
372 """Inject spec_version='2.4' into every HTTP scope.
373
374 ASGI 2.4 tells Starlette to skip listen_for_disconnect on streaming responses,
375 which is required for correct behaviour with async body reads.
376 """
377
378 def __init__(self, app: typing.Any) -> None:
379 self._app = app
380
381 async def __call__(self, scope: typing.MutableMapping[str, typing.Any], receive: typing.Any, send: typing.Any) -> None:
382 if scope.get("type") == "http":
383 scope.setdefault("asgi", {})["spec_version"] = "2.4"
384 await self._app(scope, receive, send)
385
386
387 @pytest_asyncio.fixture
388 async def client(db_session: AsyncSession) -> AsyncGenerator[AsyncClient, None]:
389 """Create an async test client. Depends on db_session so auth revocation check uses test DB."""
390 transport = ASGITransport(app=_Asgi24Wrapper(app))
391 async with AsyncClient(transport=transport, base_url="http://test") as ac:
392 yield ac
393
394
395 # -----------------------------------------------------------------------------
396 # Auth fixtures for API contract and integration tests
397 # Uses dependency_overrides to inject a fake MSignContext so tests don't need
398 # real Ed25519 key pairs. Only active for tests that request auth_headers.
399 # -----------------------------------------------------------------------------
400
401 _TEST_IDENTITY_ID = compute_identity_id(b"testuser")
402 _TEST_HANDLE = "testuser"
403
404 _TEST_CONTEXT = MSignContext(
405 handle=_TEST_HANDLE,
406 identity_id=_TEST_IDENTITY_ID,
407 is_agent=False,
408 is_admin=False,
409 )
410
411
412 @pytest_asyncio.fixture
413 async def test_user(db_session: AsyncSession) -> MusehubIdentity:
414 """Create a test identity in the DB for authenticated route tests."""
415 identity = MusehubIdentity(
416 identity_id=_TEST_IDENTITY_ID,
417 handle=_TEST_HANDLE,
418 display_name="Test User",
419 identity_type="human",
420 )
421 db_session.add(identity)
422 await db_session.commit()
423 await db_session.refresh(identity)
424 # Close the autobegin transaction started by refresh() so subsequent
425 # test-body commits don't hit "another operation is in progress".
426 await db_session.commit()
427 return identity
428
429
430 @pytest.fixture
431 def auth_headers(test_user: MusehubIdentity) -> Generator[dict[str, str], None, None]:
432 """Override auth dependencies to inject a fake MSignContext for the test duration.
433
434 Tests that need to verify 401 behaviour for *unauthenticated* requests should
435 use a separate client call without passing ``auth_headers`` — note that while
436 this fixture is active the app-level dep overrides are set globally, so any
437 request made within the same test function will be treated as authenticated.
438 Tests that need to distinguish authed/unauthed flows within one function should
439 use ``app.dependency_overrides`` directly or split into two test functions.
440 """
441 app.dependency_overrides[require_signed_request] = lambda: _TEST_CONTEXT
442 app.dependency_overrides[optional_signed_request] = lambda: _TEST_CONTEXT
443 yield {"Content-Type": "application/json"}
444 app.dependency_overrides.pop(require_signed_request, None)
445 app.dependency_overrides.pop(optional_signed_request, None)
446
447
448 # ---------------------------------------------------------------------------
449 # Symbol-detail fixtures
450 # Used by test_symbol_detail_phase1.py (T2–T7 tiers).
451 # ---------------------------------------------------------------------------
452
453 import datetime as _dt
454 import contextlib as _contextlib
455 import time as _time
456 from muse.core.types import blob_id
457
458
459 def _utc_now() -> _dt.datetime:
460 return _dt.datetime.now(tz=_dt.timezone.utc)
461
462
463 async def _make_repo_row(session: AsyncSession, owner: str, slug: str) -> "MusehubRepo":
464 from musehub.db.musehub_repo_models import MusehubRepo
465 from musehub.core.genesis import compute_identity_id, compute_repo_id
466 owner_user_id = compute_identity_id(owner.encode())
467 created_at = _utc_now()
468 repo_id = compute_repo_id(owner_user_id, slug, "code", created_at.isoformat())
469 repo = MusehubRepo(
470 repo_id=repo_id,
471 name=slug,
472 owner=owner,
473 slug=slug,
474 visibility="public",
475 owner_user_id=owner_user_id,
476 description="",
477 tags=[],
478 created_at=created_at,
479 )
480 session.add(repo)
481 await session.commit()
482 return repo
483
484
485 async def _make_commit_row(session: AsyncSession, repo_id: str, commit_id: str, **kwargs: JSONValue) -> None:
486 from musehub.db.musehub_repo_models import MusehubCommit, MusehubCommitRef
487 defaults = dict(
488 commit_id=commit_id,
489 branch="dev",
490 parent_ids=[],
491 message="feat: test",
492 author="gabriel",
493 timestamp=_utc_now(),
494 snapshot_id=blob_id(f"snap-{commit_id}".encode()),
495 agent_id="claude-code",
496 model_id="claude-sonnet-4-6",
497 commit_branch="task/test",
498 signature="",
499 )
500 defaults.update(kwargs)
501 session.add(MusehubCommit(**defaults))
502 await session.flush()
503 session.add(MusehubCommitRef(repo_id=repo_id, commit_id=commit_id))
504 await session.commit()
505
506
507 async def _make_history_entry(
508 session: AsyncSession, repo_id: str, address: str, commit_id: str,
509 op: str = "add", content_id: str | None = None,
510 committed_at: _dt.datetime | None = None,
511 message: str | None = None,
512 ) -> None:
513 from musehub.db.musehub_intel_models import MusehubSymbolHistoryEntry
514 session.add(MusehubSymbolHistoryEntry(
515 repo_id=repo_id,
516 address=address,
517 commit_id=commit_id,
518 committed_at=committed_at or _utc_now(),
519 author="gabriel",
520 op=op,
521 content_id=content_id or blob_id(f"body-{address}-{commit_id}".encode()),
522 message=message,
523 ))
524 await session.commit()
525
526
527 @pytest_asyncio.fixture
528 async def repo_fixture(db_session: AsyncSession) -> tuple[str, str]:
529 """Create a bare repo with no symbol history. Returns (owner, slug)."""
530 repo = await _make_repo_row(db_session, "gabriel", "test-repo")
531 return ("gabriel", repo.slug)
532
533
534 @pytest_asyncio.fixture
535 async def seed_symbol(db_session: AsyncSession) -> tuple[str, str, str]:
536 """Create a repo with one symbol history entry and a commit. Returns (owner, slug, address)."""
537 owner, slug = "gabriel", "seed-repo"
538 address = "src/core.py::compute"
539 repo = await _make_repo_row(db_session, owner, slug)
540 commit_id = blob_id(f"commit-seed-{slug}".encode())
541 await _make_commit_row(db_session, repo.repo_id, commit_id)
542 await _make_history_entry(db_session, repo.repo_id, address, commit_id)
543 return (owner, slug, address)
544
545
546 @pytest_asyncio.fixture
547 async def seed_type_intel(db_session: AsyncSession, seed_symbol: tuple[str, str, str]) -> None:
548 """Add a MusehubIntelType row for the seeded symbol."""
549 from musehub.db.musehub_intel_models import MusehubIntelType
550 from musehub.db.musehub_repo_models import MusehubRepo
551 from sqlalchemy import select
552 owner, slug, address = seed_symbol
553 result = await db_session.execute(select(MusehubRepo).where(MusehubRepo.owner == owner, MusehubRepo.slug == slug))
554 repo = result.scalar_one()
555 db_session.add(MusehubIntelType(
556 repo_id=repo.repo_id,
557 address=address,
558 kind="function",
559 return_is_any=False,
560 params_total=2,
561 params_annotated=2,
562 params_with_any=0,
563 type_score=0.95,
564 ref="dev",
565 ))
566 await db_session.commit()
567
568
569 @pytest_asyncio.fixture
570 async def seed_sym_intel(db_session: AsyncSession, seed_symbol: tuple[str, str, str]) -> None:
571 """Add a MusehubSymbolIntel row for the seeded symbol."""
572 from musehub.db.musehub_intel_models import MusehubSymbolIntel
573 from musehub.db.musehub_repo_models import MusehubRepo
574 from sqlalchemy import select
575 owner, slug, address = seed_symbol
576 result = await db_session.execute(select(MusehubRepo).where(MusehubRepo.owner == owner, MusehubRepo.slug == slug))
577 repo = result.scalar_one()
578 db_session.add(MusehubSymbolIntel(
579 repo_id=repo.repo_id,
580 address=address,
581 churn=5,
582 churn_30d=2,
583 churn_90d=4,
584 blast=3,
585 blast_direct=2,
586 blast_cross=1,
587 blast_top=[],
588 author_count=1,
589 gravity=0.1,
590 weekly=[],
591 gravity_pct=10.0,
592 gravity_direct_dependents=2,
593 gravity_transitive_dependents=3,
594 gravity_max_depth=2,
595 ))
596 await db_session.commit()
597
598
599 @pytest_asyncio.fixture
600 async def seed_api_intel(db_session: AsyncSession, seed_symbol: tuple[str, str, str]) -> None:
601 """Add a MusehubIntelApiSurface row for the seeded symbol."""
602 from musehub.db.musehub_intel_models import MusehubIntelApiSurface
603 from musehub.db.musehub_repo_models import MusehubRepo
604 from sqlalchemy import select
605 owner, slug, address = seed_symbol
606 result = await db_session.execute(select(MusehubRepo).where(MusehubRepo.owner == owner, MusehubRepo.slug == slug))
607 repo = result.scalar_one()
608 db_session.add(MusehubIntelApiSurface(
609 repo_id=repo.repo_id,
610 address=address,
611 kind="function",
612 visibility="public",
613 ref="dev",
614 ))
615 await db_session.commit()
616
617
618 @pytest_asyncio.fixture
619 async def seed_many_refactor_events(db_session: AsyncSession, seed_symbol: tuple[str, str, str]) -> None:
620 """Add 25 MusehubIntelRefactorEvent rows for the seeded symbol."""
621 from musehub.db.musehub_intel_models import MusehubIntelRefactorEvent
622 from musehub.db.musehub_repo_models import MusehubRepo
623 from sqlalchemy import select
624 owner, slug, address = seed_symbol
625 result = await db_session.execute(select(MusehubRepo).where(MusehubRepo.owner == owner, MusehubRepo.slug == slug))
626 repo = result.scalar_one()
627 for i in range(25):
628 db_session.add(MusehubIntelRefactorEvent(
629 event_id=blob_id(f"refactor-{i}-{slug}".encode()),
630 repo_id=repo.repo_id,
631 kind="implementation",
632 address=address,
633 detail=f"refactor event {i}",
634 commit_id=blob_id(f"rc-{i}".encode()),
635 committed_at=_utc_now(),
636 ))
637 await db_session.commit()
638
639
640 @pytest_asyncio.fixture
641 async def seed_refactor_event(db_session: AsyncSession, seed_symbol: tuple[str, str, str]) -> None:
642 """Add one MusehubIntelRefactorEvent with kind=implementation."""
643 from musehub.db.musehub_intel_models import MusehubIntelRefactorEvent
644 from musehub.db.musehub_repo_models import MusehubRepo
645 from sqlalchemy import select
646 owner, slug, address = seed_symbol
647 result = await db_session.execute(select(MusehubRepo).where(MusehubRepo.owner == owner, MusehubRepo.slug == slug))
648 repo = result.scalar_one()
649 db_session.add(MusehubIntelRefactorEvent(
650 event_id=blob_id(f"refactor-single-{slug}".encode()),
651 repo_id=repo.repo_id,
652 kind="implementation",
653 address=address,
654 detail="extracted helper",
655 commit_id=blob_id(f"rc-single-{slug}".encode()),
656 committed_at=_utc_now(),
657 ))
658 await db_session.commit()
659
660
661 @pytest_asyncio.fixture
662 async def seed_refactor_event_with_xss(db_session: AsyncSession, seed_symbol: tuple[str, str, str]) -> None:
663 """Add a refactor event whose detail field contains an XSS payload."""
664 from musehub.db.musehub_intel_models import MusehubIntelRefactorEvent
665 from musehub.db.musehub_repo_models import MusehubRepo
666 from sqlalchemy import select
667 owner, slug, address = seed_symbol
668 result = await db_session.execute(select(MusehubRepo).where(MusehubRepo.owner == owner, MusehubRepo.slug == slug))
669 repo = result.scalar_one()
670 db_session.add(MusehubIntelRefactorEvent(
671 event_id=blob_id(f"refactor-xss-{slug}".encode()),
672 repo_id=repo.repo_id,
673 kind="implementation",
674 address=address,
675 detail='<img src=x onerror=alert(1)>',
676 commit_id=blob_id(f"rc-xss-{slug}".encode()),
677 committed_at=_utc_now(),
678 ))
679 await db_session.commit()
680
681
682 @pytest_asyncio.fixture
683 async def seed_symbol_with_xss_commit(db_session: AsyncSession) -> tuple[str, str, str]:
684 """Create a symbol whose commit message contains an XSS payload."""
685 owner, slug = "gabriel", "xss-repo"
686 address = "src/evil.py::fn"
687 repo = await _make_repo_row(db_session, owner, slug)
688 commit_id = blob_id(f"commit-xss-{slug}".encode())
689 await _make_commit_row(
690 db_session, repo.repo_id, commit_id,
691 message='<img src=x onerror=alert(1)> feat: xss test',
692 )
693 await _make_history_entry(db_session, repo.repo_id, address, commit_id)
694 return (owner, slug, address)
695
696
697 @pytest_asyncio.fixture
698 async def seed_symbol_with_large_history(db_session: AsyncSession) -> tuple[str, str, str]:
699 """Create a symbol with 200 history entries (stress test — not 10k, keeps test fast)."""
700 owner, slug = "gabriel", "large-history-repo"
701 address = "src/big.py::process"
702 repo = await _make_repo_row(db_session, owner, slug)
703 for i in range(200):
704 cid = blob_id(f"commit-large-{i}-{slug}".encode())
705 await _make_commit_row(db_session, repo.repo_id, cid)
706 await _make_history_entry(db_session, repo.repo_id, address, cid, op="modify")
707 return (owner, slug, address)
708
709
710 @pytest_asyncio.fixture
711 async def seed_symbol_high_coupling(db_session: AsyncSession) -> tuple[str, str, str]:
712 """Create a symbol that co-changes with many partners."""
713 from musehub.db.musehub_intel_models import MusehubSymbolHistoryEntry
714 owner, slug = "gabriel", "coupling-repo"
715 address = "src/hub.py::dispatch"
716 repo = await _make_repo_row(db_session, owner, slug)
717 commit_id = blob_id(f"commit-coupling-{slug}".encode())
718 await _make_commit_row(db_session, repo.repo_id, commit_id)
719 await _make_history_entry(db_session, repo.repo_id, address, commit_id)
720 # 25 co-changing partners in the same commit
721 for i in range(25):
722 partner = f"src/partner_{i}.py::fn"
723 db_session.add(MusehubSymbolHistoryEntry(
724 repo_id=repo.repo_id,
725 address=partner,
726 commit_id=commit_id,
727 committed_at=_utc_now(),
728 author="gabriel",
729 op="modify",
730 content_id=blob_id(f"body-partner-{i}".encode()),
731 ))
732 await db_session.commit()
733 return (owner, slug, address)
734
735
736 @pytest_asyncio.fixture
737 async def seed_symbol_with_clones(db_session: AsyncSession) -> tuple[str, str, str]:
738 """Create a symbol with a clone entry."""
739 from musehub.db.musehub_intel_models import MusehubHashOccurrenceEntry
740 owner, slug = "gabriel", "clones-repo"
741 address = "src/original.py::fn"
742 repo = await _make_repo_row(db_session, owner, slug)
743 commit_id = blob_id(f"commit-clone-{slug}".encode())
744 content_id = blob_id(f"shared-body-{slug}".encode())
745 await _make_commit_row(db_session, repo.repo_id, commit_id)
746 await _make_history_entry(db_session, repo.repo_id, address, commit_id, content_id=content_id)
747 # Clone: same content_id, different address
748 db_session.add(MusehubHashOccurrenceEntry(
749 repo_id=repo.repo_id,
750 content_id=content_id,
751 address="src/copy.py::fn",
752 ))
753 db_session.add(MusehubHashOccurrenceEntry(
754 repo_id=repo.repo_id,
755 content_id=content_id,
756 address=address,
757 ))
758 await db_session.commit()
759 return (owner, slug, address)
760
761
762 @pytest.fixture
763 def benchmark_timer() -> typing.Callable[[float], typing.ContextManager[None]]:
764 """Context manager that asserts elapsed time stays under max_ms."""
765 @_contextlib.contextmanager
766 def _timer(max_ms: float) -> Generator[None, None, None]:
767 start = _time.monotonic()
768 yield
769 elapsed_ms = (_time.monotonic() - start) * 1000
770 assert elapsed_ms < max_ms, f"took {elapsed_ms:.0f}ms, limit {max_ms}ms"
771 return _timer
772
773
774 # ---------------------------------------------------------------------------
775 # Pagination fixtures
776 # Used by test_symbol_detail_pagination.py.
777 # ---------------------------------------------------------------------------
778
779 async def _seed_history_entries(
780 db_session: AsyncSession,
781 owner: str,
782 slug: str,
783 count: int,
784 ) -> tuple[str, str, str]:
785 """Create a repo + symbol with *count* history entries spaced 1 hour apart.
786
787 Commit messages are ``entry-{i}`` for i in 0..count-1.
788 entry-0 is the oldest, entry-(count-1) is the newest.
789 Returns (owner, slug, address).
790 """
791 from musehub.db.musehub_intel_models import MusehubSymbolHistoryEntry
792 address = "src/core.py::paginate_fn"
793 repo = await _make_repo_row(db_session, owner, slug)
794 base_ts = _dt.datetime(2026, 1, 1, 0, 0, 0, tzinfo=_dt.timezone.utc)
795 for i in range(count):
796 committed_at = base_ts + _dt.timedelta(hours=i)
797 commit_id = blob_id(f"commit-hist-{i}-{slug}".encode())
798 await _make_commit_row(
799 db_session, repo.repo_id, commit_id,
800 message=f"entry-{i}",
801 timestamp=committed_at,
802 )
803 await _make_history_entry(
804 db_session, repo.repo_id, address, commit_id,
805 op="modify", committed_at=committed_at,
806 message=f"entry-{i}",
807 )
808 return (owner, slug, address)
809
810
811 async def _seed_coupling_partners(
812 db_session: AsyncSession,
813 owner: str,
814 slug: str,
815 partner_count: int,
816 ) -> tuple[str, str, str]:
817 """Create a repo + symbol with *partner_count* coupling partners.
818
819 The target symbol appears in all *partner_count* commits.
820 Partner i appears in commits i..(partner_count-1), giving it
821 shared_commits = partner_count - i (descending: partner_0 has the most).
822 Returns (owner, slug, address).
823 """
824 from musehub.db.musehub_intel_models import MusehubSymbolHistoryEntry
825 address = "src/hub.py::dispatch"
826 repo = await _make_repo_row(db_session, owner, slug)
827 base_ts = _dt.datetime(2026, 2, 1, 0, 0, 0, tzinfo=_dt.timezone.utc)
828 for j in range(partner_count):
829 committed_at = base_ts + _dt.timedelta(hours=j)
830 commit_id = blob_id(f"commit-coup-{j}-{slug}".encode())
831 await _make_commit_row(
832 db_session, repo.repo_id, commit_id,
833 message=f"coupling-commit-{j}",
834 timestamp=committed_at,
835 )
836 # Target symbol in every commit
837 db_session.add(MusehubSymbolHistoryEntry(
838 repo_id=repo.repo_id,
839 address=address,
840 commit_id=commit_id,
841 committed_at=committed_at,
842 author="gabriel",
843 op="modify",
844 content_id=blob_id(f"body-target-{j}-{slug}".encode()),
845 ))
846 # Partner i appears in commit j only when i <= j
847 for i in range(j + 1):
848 partner = f"src/partner_{i}.py::fn_{i}"
849 db_session.add(MusehubSymbolHistoryEntry(
850 repo_id=repo.repo_id,
851 address=partner,
852 commit_id=commit_id,
853 committed_at=committed_at,
854 author="gabriel",
855 op="modify",
856 content_id=blob_id(f"body-partner-{i}-{j}-{slug}".encode()),
857 ))
858 await db_session.commit()
859 # Insert pre-computed coupling rows: partner_i appears in partner_count-i commits.
860 from musehub.db.musehub_intel_models import MusehubSymbolCoupling
861 for i in range(partner_count):
862 db_session.add(MusehubSymbolCoupling(
863 repo_id=repo.repo_id,
864 address=address,
865 co_address=f"src/partner_{i}.py::fn_{i}",
866 shared_commits=partner_count - i,
867 ))
868 await db_session.commit()
869 return (owner, slug, address)
870
871
872 @pytest_asyncio.fixture
873 async def seed_symbol_with_26_history(db_session: AsyncSession) -> tuple[str, str, str]:
874 return await _seed_history_entries(db_session, "gabriel", "hist26-repo", 26)
875
876
877 @pytest_asyncio.fixture
878 async def seed_symbol_with_exactly_10_history(db_session: AsyncSession) -> tuple[str, str, str]:
879 return await _seed_history_entries(db_session, "gabriel", "hist10-repo", 10)
880
881
882 @pytest_asyncio.fixture
883 async def seed_symbol_with_11_history(db_session: AsyncSession) -> tuple[str, str, str]:
884 return await _seed_history_entries(db_session, "gabriel", "hist11-repo", 11)
885
886
887 @pytest_asyncio.fixture
888 async def seed_symbol_high_coupling_40(db_session: AsyncSession) -> tuple[str, str, str]:
889 return await _seed_coupling_partners(db_session, "gabriel", "coup40-repo", 40)
890
891
892 @pytest_asyncio.fixture
893 async def seed_symbol_with_exactly_15_coupling(db_session: AsyncSession) -> tuple[str, str, str]:
894 return await _seed_coupling_partners(db_session, "gabriel", "coup15-repo", 15)
895
896
897 @pytest_asyncio.fixture
898 async def seed_symbol_with_16_coupling(db_session: AsyncSession) -> tuple[str, str, str]:
899 return await _seed_coupling_partners(db_session, "gabriel", "coup16-repo", 16)
900
901
902 @pytest_asyncio.fixture
903 async def seed_symbol_with_26_history_and_40_coupling(
904 db_session: AsyncSession,
905 ) -> tuple[str, str, str]:
906 """26 history entries + 26 coupling partners (from the same commits).
907
908 The target appears in all 26 commits. Partner_i appears in commits i..25,
909 giving shared_commits = 26 - i (descending). This yields 26 partners with
910 positive shared counts → 2 coupling pages (15 + 11) and 3 history pages
911 (10 + 10 + 6). Keeping partners in the history commits avoids inflating the
912 target's change_count with extra coupling-only commits.
913 """
914 from musehub.db.musehub_intel_models import MusehubSymbolHistoryEntry
915 owner, slug = "gabriel", "hist26-coup26-repo"
916 address = "src/core.py::paginate_fn"
917 repo = await _make_repo_row(db_session, owner, slug)
918 base_ts = _dt.datetime(2026, 1, 1, 0, 0, 0, tzinfo=_dt.timezone.utc)
919
920 # 26 commits — target appears in all; partner_i appears in commits i..25.
921 for i in range(26):
922 committed_at = base_ts + _dt.timedelta(hours=i)
923 commit_id = blob_id(f"commit-combo-{i}-{slug}".encode())
924 await _make_commit_row(
925 db_session, repo.repo_id, commit_id,
926 message=f"entry-{i}", timestamp=committed_at,
927 )
928 await _make_history_entry(
929 db_session, repo.repo_id, address, commit_id,
930 op="modify", committed_at=committed_at,
931 message=f"entry-{i}",
932 )
933 # Every partner whose index <= i is added to this commit.
934 # Partner_j appears in commits j..25 → shared = 26 - j.
935 for j in range(i + 1):
936 partner = f"src/partner_{j}.py::fn_{j}"
937 db_session.add(MusehubSymbolHistoryEntry(
938 repo_id=repo.repo_id,
939 address=partner,
940 commit_id=commit_id,
941 committed_at=committed_at,
942 author="gabriel",
943 op="modify",
944 content_id=blob_id(f"body-combo-partner-{j}-{i}-{slug}".encode()),
945 ))
946 await db_session.commit()
947 # Insert pre-computed coupling rows: partner_j appears in 26-j commits.
948 from musehub.db.musehub_intel_models import MusehubSymbolCoupling
949 for j in range(26):
950 db_session.add(MusehubSymbolCoupling(
951 repo_id=repo.repo_id,
952 address=address,
953 co_address=f"src/partner_{j}.py::fn_{j}",
954 shared_commits=26 - j,
955 ))
956 await db_session.commit()
957 return (owner, slug, address)
File History 20 commits
sha256:4f1496efd3bb9b1e764c31d3d9ae8218a550c06f78e351b15fe58409e4223282 fix(releases,wire): the rc channel is accepted like Muse's … Opus 5.5 minor ⚠ 1 day ago
sha256:369f691c7aaec3ca84a864ad1d099d5409045ddc12d185a922b3c84b9e2a1bad merge: 100% passing, parallelized MuseHub test suite (task/… Sonnet 5.5 patch 3 days ago
sha256:8166b51ae53275831023a7ce334228b3ccc8237b55d68a35172389db9ff46ad5 test: 100% passing MuseHub suite, parallelized (xdist, one … Sonnet 5.5 patch 3 days ago
sha256:3733f942311ecd1beecb0d6f112f3ebd87b2801a5a410bf35b2415a84a238f1b fix(intel): one-shot child, reap confirmed before the refer… Sonnet 5.5 minor ⚠ 4 days ago
sha256:64d53876b5299082b6b4bfbe92721976ec7bb5f1d9a88fdf6eafc1490148d27c fix(intel): explicit, fail-closed deployment identity repla… Sonnet 5.5 minor ⚠ 4 days ago
sha256:cb4b05e9d6caea5f351e3cb452ee6a1db8856169328ad96bfba9ee8e04b8afa6 fix(jobs): fence every execution of a job; an expired or su… Sonnet 5.5 minor ⚠ 4 days ago
sha256:f0ce9f515a530043854b2549a902d0df78837898e9e9439fe32abeee180bef85 feat(worker): run intel jobs in a bounded child process; th… Sonnet 5.5 patch 4 days ago
sha256:bdc0664ea517f0343fee86e1998df5d9ee2d833bb76e4ce43f85d9f8fb8dd621 perf(intel): share bounded, immutable source-object reads a… Sonnet 5.5 patch 4 days ago
sha256:4c1d427f8ff7e2e3557a355edc72231e039930d280d65d299999a1cc898649d2 test(prebuild): RED — bounded ranged-read blob extraction w… Sonnet 5.5 4 days ago
sha256:f7413c1abec6d6a8e5bdabcd4cc7ad5fcd059ce6a6f50f566e2b0118a0a8b578 tests: make tests/docs_contract/ database-free by directory… Opus 5.5 10 days ago
sha256:a977b39d08e15683210a33608e25712fe3ed9c8f05f0388fb69ef38acf835426 feat(release): hermetic release gates in a provisioned, pin… Opus 5.5 minor ⚠ 12 days ago
sha256:77fc45e703f90c0d603ecb1a0ce21ff21095728ca7dd0e146eb5e966c8f9fcc9 more passing tests from full test suite fun Human patch 158 days ago
sha256:ef10830ce231e0a20efcb0e2586cb879471247e916616e6fdd0d51df459e2595 fix: typing audit — 0 violations, 0 untyped defs across all… Sonnet 4.6 minor ⚠ 172 days ago
sha256:1bb2b2331b696382042e1249385aafd0c7bdd17167b7b972be72b90ae625bd80 fix: repair 400+ failing tests, fix mpack integrity check, … Sonnet 4.6 minor ⚠ 173 days ago
sha256:b8884c81af5e135510894a537784c16158ee9c2c05d074f978611bbcb611ca10 fix: port security checks inline, remove repo_id from Museh… Sonnet 4.6 minor ⚠ 181 days ago
sha256:931e49567532561236ada9097864a0c484f101d6c25c50943af4ec2c1f5690f2 refactor: erase all streaming wire protocol traces — commen… Sonnet 4.6 minor ⚠ 184 days ago
sha256:2e9f6b5cc193e07b2c23d17fb71851db72e6160ba472013f5bccab8351264e79 refactor: migrate all musehub_models shim call sites to dom… Sonnet 4.6 minor ⚠ 188 days ago
sha256:fb3555532c8b745813c43f33dd99e4eb623805d02ee9816e7972e74e98a80373 perf: merge profile.snapshot into push intel batch — saves … Sonnet 4.6 minor ⚠ 190 days ago
sha256:34844ccdc278ce0371354d4b298302848ce48f8399946af20d41dd7a1ef5d8cd fix: batch enqueue_push_intel from O(N) to O(1) DB round-trips Sonnet 4.6 patch 190 days ago
sha256:d3e70ae9c7a7d8c43904a471fd7b8826c42bbe319a326651ce4e9419b4e95877 fix: repair test suite after BlobBackend migration Sonnet 4.6 minor ⚠ 191 days ago