Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

6.7 KB
Raw Blame
"""Tests for APScheduler background jobs."""

from __future__ import annotations

import asyncio
import json
import logging
from datetime import UTC, datetime
from types import SimpleNamespace
from unittest.mock import AsyncMock, patch

from sqlalchemy import event, select

from repowise.core.persistence import crud
from repowise.core.persistence.database import get_session
from repowise.core.persistence.models import GenerationJob, Page
from repowise.server.scheduler import _inspect_repository, setup_scheduler


async def test_staleness_checker_counts_in_sql(
    session_factory, test_engine, tmp_path, caplog
) -> None:
    """Report only stale/expired pages per repo without selecting their content."""
    async with get_session(session_factory) as session:
        first = await crud.upsert_repository(
            session, name="first", local_path=str(tmp_path / "first")
        )
        second = await crud.upsert_repository(
            session, name="second", local_path=str(tmp_path / "second")
        )
        for repo, statuses in ((first, ("stale", "expired", "fresh")), (second, ("stale",))):
            for index, status in enumerate(statuses):
                session.add(
                    Page(
                        id=f"file_page:{repo.name}:{index}",
                        repository_id=repo.id,
                        page_type="file_page",
                        title=f"Page {index}",
                        content="long rendered markdown " * 100,
                        target_path=f"{repo.name}/{index}",
                        source_hash="hash",
                        model_name="test",
                        provider_name="test",
                        freshness_status=status,
                        created_at=datetime.now(UTC),
                        updated_at=datetime.now(UTC),
                    )
                )
        await session.commit()

    statements: list[str] = []

    def capture_sql(_connection, _cursor, statement, _parameters, _context, _executemany) -> None:
        if "wiki_pages" in statement:
            statements.append(statement)

    scheduler = setup_scheduler(session_factory)
    staleness_job = next(job for job in scheduler.get_jobs() if job.id == "staleness_check")
    event.listen(test_engine.sync_engine, "before_cursor_execute", capture_sql)
    try:
        with caplog.at_level(logging.INFO, logger="repowise.server.scheduler"):
            await staleness_job.func()
    finally:
        event.remove(test_engine.sync_engine, "before_cursor_execute", capture_sql)

    assert len(statements) == 2
    assert all(
        "count(" in statement.lower() and "wiki_pages.content" not in statement
        for statement in statements
    )
    records = [record for record in caplog.records if record.msg == "staleness_check"]
    assert {record.repo_name: record.stale_count for record in records} == {"first": 2, "second": 1}


async def test_polling_fallback_launches_persisted_job(session_factory, tmp_path) -> None:
    """A diverged repository should launch the sync job that was persisted."""
    repo_path = tmp_path / "repo"
    state_path = repo_path / ".repowise" / "state.json"
    state_path.parent.mkdir(parents=True)
    state_path.write_text(json.dumps({"last_sync_commit": "old-sha"}), encoding="utf-8")

    async with get_session(session_factory) as session:
        repo = await crud.upsert_repository(
            session,
            name="test-repo",
            local_path=str(repo_path),
        )
        repo_id = repo.id

    app_state = SimpleNamespace(background_tasks=set())
    scheduler = setup_scheduler(session_factory, app_state=app_state)
    polling_job = next(job for job in scheduler.get_jobs() if job.id == "polling_fallback")
    head_result = SimpleNamespace(returncode=0, stdout="new-sha\n")
    execute_job = AsyncMock()

    with (
        patch("subprocess.run", return_value=head_result),
        patch("repowise.server.job_executor.execute_job", execute_job),
    ):
        await polling_job.func()
        if app_state.background_tasks:
            await asyncio.gather(*app_state.background_tasks)

    execute_job.assert_awaited_once()
    job_id, launched_state = execute_job.await_args.args
    assert launched_state is app_state

    async with get_session(session_factory) as session:
        result = await session.execute(
            select(GenerationJob).where(GenerationJob.repository_id == repo_id)
        )
        persisted_job = result.scalar_one()

    assert job_id == persisted_job.id
    assert persisted_job.status == "pending"
    assert json.loads(persisted_job.config_json) == {
        "mode": "sync",
        "trigger": "polling_fallback",
        "before": "old-sha",
        "after": "new-sha",
    }


async def test_polling_fallback_offloads_repository_inspection(session_factory, tmp_path) -> None:
    """The scheduler must not inspect state or run Git on the event loop."""
    async with get_session(session_factory) as session:
        await crud.upsert_repository(
            session,
            name="test-repo",
            local_path=str(tmp_path),
        )

    scheduler = setup_scheduler(session_factory)
    polling_job = next(job for job in scheduler.get_jobs() if job.id == "polling_fallback")
    to_thread = AsyncMock(return_value=None)

    with patch("repowise.server.scheduler.asyncio.to_thread", to_thread):
        await polling_job.func()

    to_thread.assert_awaited_once_with(_inspect_repository, str(tmp_path))


async def test_polling_fallback_skips_a_repo_while_an_update_holds_its_lock(
    session_factory, tmp_path
) -> None:
    """A running `repowise update` advances the baseline; no sync job races it."""
    from repowise.core.update_lock import release_update_lock, try_acquire_update_lock

    state_path = tmp_path / ".repowise" / "state.json"
    state_path.parent.mkdir(parents=True)
    state_path.write_text(json.dumps({"last_sync_commit": "old-sha"}), encoding="utf-8")
    async with get_session(session_factory) as session:
        repo = await crud.upsert_repository(session, name="test-repo", local_path=str(tmp_path))
        repo_id = repo.id

    scheduler = setup_scheduler(session_factory, app_state=SimpleNamespace(background_tasks=set()))
    polling_job = next(job for job in scheduler.get_jobs() if job.id == "polling_fallback")
    head_result = SimpleNamespace(returncode=0, stdout="new-sha\n")
    assert try_acquire_update_lock(tmp_path, "new-sha") is None
    try:
        with patch("subprocess.run", return_value=head_result):
            await polling_job.func()
    finally:
        release_update_lock(tmp_path)

    async with get_session(session_factory) as session:
        result = await session.execute(
            select(GenerationJob).where(GenerationJob.repository_id == repo_id)
        )
        assert result.scalars().all() == []