test_background_indexing.py

tests/test_background_indexing.py

gh#48 — the server builds and refreshes indexes the way a language server does.

test_a_directory_that_is_not_a_repository_is_never_built_automatically

None test_background_indexing.test_a_directory_that_is_not_a_repository_is_never_built_automatically(Path tmp_path, Path rich_db)

No automatic build for an unregistered non-git directory.

tests/test_background_indexing.py:205

Checks

  • assert build.built == []

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-CONFIG-001measured
REQ-DDB-CONFIG-006measured
REQ-DDB-CONFIG-007measured
REQ-DDB-MCP-001measuredtest_a_directory_that_is_not_a_repository_is_never_built_automatically → build_server
REQ-DDB-MCP-003measured
REQ-DDB-MCP-004measuredtest_a_directory_that_is_not_a_repository_is_never_built_automatically → build_server → _refusal_as_tool_error
REQ-DDB-QUERY-010measured
REQ-DDB-WIKI-034measuredtest_a_directory_that_is_not_a_repository_is_never_built_automatically → build_server → _register_prompts
REQ-DDB-WIKI-054measured
Source · 24 lines
async def test_a_directory_that_is_not_a_repository_is_never_built_automatically(
    tmp_path: Path, rich_db: Path
) -> None:
    """A QUERY NAMING A DIRECTORY IS NOT CONSENT TO INDEX IT. `target=` accepts any directory, and a
    mistyped path must not start doxygen over a home directory. Without a git root or a registry
    record, the refusal still names the explicit build.

    @brief No automatic build for an unregistered non-git directory.
    @version 1
    """
    loose = tmp_path / "loose"
    loose.mkdir()
    _mcp, state = build_server(st.TargetRegistry(tmp_path / "state"))
    build = _RecordingBuild(rich_db)
    state._run_build = build

    await state._auto_refresh(str(loose))

    assert build.built == []
    with pytest.raises(RuntimeError, match=r"index\(action='refresh'"):
        state.tools.dossier("sensor_poll", target=str(loose))


@pytest.mark.anyio

test_a_failed_first_build_is_reported_and_not_retried_by_every_query

None test_background_indexing.test_a_failed_first_build_is_reported_and_not_retried_by_every_query(Path tmp_path, Path rich_db)

One failed automatic build; later queries report it instead of repeating it.

tests/test_background_indexing.py:178

Show on the map →

Called by none

Calls _git_repo, build_server

Checks

  • assert build.built == [None], f"one attempt, not one per query: {build.built}"
  • assert "FAILED" in str(exc.value) and "doxygen was not found on PATH" in str(exc.value), (exc.value )

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-CONFIG-001measured
REQ-DDB-CONFIG-006measured
REQ-DDB-CONFIG-007measured
REQ-DDB-INDEX-002measured
REQ-DDB-MCP-001measuredtest_a_failed_first_build_is_reported_and_not_retried_by_every_query → build_server
REQ-DDB-MCP-003measured
REQ-DDB-MCP-004measuredtest_a_failed_first_build_is_reported_and_not_retried_by_every_query → build_server → _refusal_as_tool_error
REQ-DDB-QUERY-010measured
REQ-DDB-WIKI-034measuredtest_a_failed_first_build_is_reported_and_not_retried_by_every_query → build_server → _register_prompts
REQ-DDB-WIKI-054measured
Source · 27 lines
async def test_a_failed_first_build_is_reported_and_not_retried_by_every_query(
    tmp_path: Path, rich_db: Path
) -> None:
    """A BUILD THAT FAILS DETERMINISTICALLY must not be relaunched by each call — that is the retry
    loop gh#48 saw agents fall into, moved inside the server. The refusal carries the failure, so
    the caller learns why instead of being told to build what just failed to build.

    @brief One failed automatic build; later queries report it instead of repeating it.
    @version 1
    """
    repo = _git_repo(tmp_path / "broken")
    _mcp, state = build_server(st.TargetRegistry(tmp_path / "state"))
    build = _RecordingBuild(rich_db, error="doxygen was not found on PATH")
    state._run_build = build

    await state._auto_refresh(str(repo))
    await state._auto_refresh(str(repo))
    with pytest.raises(RuntimeError) as exc:
        state.tools.dossier("sensor_poll", target=str(repo))

    assert build.built == [None], f"one attempt, not one per query: {build.built}"
    assert "FAILED" in str(exc.value) and "doxygen was not found on PATH" in str(exc.value), (
        exc.value
    )


@pytest.mark.anyio

test_a_query_during_a_long_first_build_says_so_without_waiting_again

None test_background_indexing.test_a_query_during_a_long_first_build_says_so_without_waiting_again(Path tmp_path, Path rich_db, pytest.MonkeyPatch monkeypatch)

In-progress first builds are reported immediately and answer once finished.

tests/test_background_indexing.py:135

Show on the map →

Called by none

Calls _git_repo, build_server, list

Checks

  • assert time.monotonic() - started < 1.0, "a second query must not wait the bound again"
  • assert "found" not in state.tools.dossier("sensor_poll", target=str(repo))

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-CONFIG-001measured
REQ-DDB-CONFIG-006measured
REQ-DDB-CONFIG-007measured
REQ-DDB-INDEX-002measured
REQ-DDB-INDEX-003measured
REQ-DDB-INDEX-004measured
REQ-DDB-MCP-001measuredtest_a_query_during_a_long_first_build_says_so_without_waiting_again → build_server
REQ-DDB-MCP-003measured
REQ-DDB-MCP-004measuredtest_a_query_during_a_long_first_build_says_so_without_waiting_again → build_server → _refusal_as_tool_error
REQ-DDB-PIPE-005measured
REQ-DDB-QUERY-001measured
REQ-DDB-QUERY-002measured
REQ-DDB-QUERY-003measured
REQ-DDB-QUERY-004measured
REQ-DDB-QUERY-006measured
REQ-DDB-QUERY-009measured
REQ-DDB-QUERY-010measured
REQ-DDB-QUERY-012measured
REQ-DDB-QUERY-014measured
REQ-DDB-SCHEMA-011measured
REQ-DDB-WIKI-034measuredtest_a_query_during_a_long_first_build_says_so_without_waiting_again → build_server → _register_prompts
REQ-DDB-WIKI-054measured
Source · 43 lines
async def test_a_query_during_a_long_first_build_says_so_without_waiting_again(
    tmp_path: Path, rich_db: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    """THE LONG-BUILD CASE. Only the call that started a build waits out the bound; the next one
    refuses at once, saying the index is being built — not that none exists, and not after another
    wait. Once the build lands, the same call answers.

    @brief In-progress first builds are reported immediately and answer once finished.
    @version 1
    """
    import threading
    import time

    ## HEADROOM (owner Q/A 2026-11-23): the bound was 0.2 s and the check < 0.15 s, so 0.05 s of
    ## headroom; the gate failed twice on 2026-11-23 at load ~13 (0.156 s), passing 5/5 alone. A
    ## second query that WAITED would take >= the bound, so a 2.0 s bound and a < 1.0 s check
    ## state the same property with 1.0 s of headroom.
    monkeypatch.setattr(server_module, "_FIRST_BUILD_WAIT_SECONDS", 2.0)
    repo = _git_repo(tmp_path / "slow")
    _mcp, state = build_server(st.TargetRegistry(tmp_path / "state"))
    release = threading.Event()
    finish = _RecordingBuild(rich_db)

    def _slow_build(target: st.Target, *args: object) -> dict[str, object]:
        release.wait(10)
        return finish(target, *args)

    state._run_build = _slow_build

    await state._auto_refresh(str(repo))
    started = time.monotonic()
    await state._auto_refresh(str(repo))
    assert time.monotonic() - started < 1.0, "a second query must not wait the bound again"
    with pytest.raises(RuntimeError, match="being built in the background"):
        state.tools.dossier("sensor_poll", target=str(repo))

    release.set()
    for job in list(state._first_builds.values()):
        await anyio.to_thread.run_sync(job.done.wait, 10)
    assert "found" not in state.tools.dossier("sensor_poll", target=str(repo))


@pytest.mark.anyio

test_a_query_on_an_unbuilt_repository_builds_it_and_then_answers

None test_background_indexing.test_a_query_on_an_unbuilt_repository_builds_it_and_then_answers(Path tmp_path, Path rich_db)

An absent index is built by the query that needed it.

tests/test_background_indexing.py:86

Show on the map →

Called by none

Calls _git_repo, build_server

Checks

  • assert build.built == [None], f"the unsplit repository is built whole, got {build.built}"
  • assert "found" not in reply, reply

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-CONFIG-001measured
REQ-DDB-CONFIG-006measured
REQ-DDB-CONFIG-007measured
REQ-DDB-INDEX-002measured
REQ-DDB-INDEX-003measured
REQ-DDB-INDEX-004measured
REQ-DDB-MCP-001measuredtest_a_query_on_an_unbuilt_repository_builds_it_and_then_answers → build_server
REQ-DDB-MCP-003measured
REQ-DDB-MCP-004measuredtest_a_query_on_an_unbuilt_repository_builds_it_and_then_answers → build_server → _refusal_as_tool_error
REQ-DDB-PIPE-005measured
REQ-DDB-QUERY-001measured
REQ-DDB-QUERY-002measured
REQ-DDB-QUERY-003measured
REQ-DDB-QUERY-004measured
REQ-DDB-QUERY-006measured
REQ-DDB-QUERY-009measured
REQ-DDB-QUERY-010measured
REQ-DDB-QUERY-012measured
REQ-DDB-QUERY-014measured
REQ-DDB-SCHEMA-011measured
REQ-DDB-WIKI-034measuredtest_a_query_on_an_unbuilt_repository_builds_it_and_then_answers → build_server → _register_prompts
REQ-DDB-WIKI-054measured
Source · 22 lines
async def test_a_query_on_an_unbuilt_repository_builds_it_and_then_answers(
    tmp_path: Path, rich_db: Path
) -> None:
    """THE LSP CASE. A git repository nobody has indexed is asked about; the query starts the
    build and, because this one finishes inside the bounded wait, the same call answers.

    @brief An absent index is built by the query that needed it.
    @version 1
    """
    repo = _git_repo(tmp_path / "plain")
    _mcp, state = build_server(st.TargetRegistry(tmp_path / "state"))
    build = _RecordingBuild(rich_db)
    state._run_build = build

    await state._auto_refresh(str(repo))
    reply = state.tools.dossier("sensor_poll", target=str(repo))

    assert build.built == [None], f"the unsplit repository is built whole, got {build.built}"
    assert "found" not in reply, reply


@pytest.mark.anyio

test_a_query_takes_the_fast_tier_and_the_tick_runs_the_full_build

None test_background_indexing.test_a_query_takes_the_fast_tier_and_the_tick_runs_the_full_build(Path tmp_path, Path rich_db, pytest.MonkeyPatch monkeypatch)

Fast on the query path, full on the following tick.

tests/test_background_indexing.py:423

Checks

  • assert fast_calls == [True] and build.built == [], "the fast tier must answer a data-stale tick"
  • assert fast_calls == [True], "a pending fast refresh must not be answered by another fast one"
  • assert build.built == [None], "the pending fast refresh must get its full build"

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-CONFIG-006measured
REQ-DDB-CONFIG-007measured
REQ-DDB-INDEX-003measured
REQ-DDB-INDEX-004measured
REQ-DDB-INDEX-006measured
REQ-DDB-MCP-001measuredtest_a_query_takes_the_fast_tier_and_the_tick_runs_the_full_build → build_server
REQ-DDB-MCP-002measured
REQ-DDB-MCP-003measured
REQ-DDB-MCP-004measuredtest_a_query_takes_the_fast_tier_and_the_tick_runs_the_full_build → build_server → _refusal_as_tool_error
REQ-DDB-PIPE-005measured
REQ-DDB-QUERY-001measured
REQ-DDB-QUERY-002measured
REQ-DDB-QUERY-003measured
REQ-DDB-QUERY-004measured
REQ-DDB-QUERY-006measured
REQ-DDB-QUERY-009measured
REQ-DDB-QUERY-010measured
REQ-DDB-QUERY-012measured
REQ-DDB-QUERY-014measured
REQ-DDB-SCHEMA-011measured
REQ-DDB-WIKI-034measuredtest_a_query_takes_the_fast_tier_and_the_tick_runs_the_full_build → build_server → _register_prompts
REQ-DDB-WIKI-054measured
Source · 31 lines
async def test_a_query_takes_the_fast_tier_and_the_tick_runs_the_full_build(
    tmp_path: Path, rich_db: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    """THE TWO TIERS, IN ORDER (1.3.5). A data-stale index the fast tier can refresh is refreshed
    in place, with no full build on the path anyone waits on; the next background tick sees the
    pending fast record and runs the full build — not another fast one.

    @brief Fast on the query path, full on the following tick.
    @version 1
    """
    registry = st.TargetRegistry(tmp_path / "state")
    _mcp, state = build_server(registry)
    repo = tmp_path / "used"
    repo.mkdir()
    target = registry.register(repo)
    Path(target.db_path).write_bytes(rich_db.read_bytes())
    state.tools.dossier("sensor_poll", target=str(repo))
    build = _RecordingBuild(rich_db)
    state._run_build = build
    fast_calls: list[bool] = []
    monkeypatch.setattr(state, "_try_fast", lambda _t: fast_calls.append(True) or True)

    monkeypatch.setattr(state, "_data_stale", lambda _target: True)
    await state.refresh_touched()
    assert fast_calls == [True] and build.built == [], "the fast tier must answer a data-stale tick"

    monkeypatch.setattr(state, "_data_stale", lambda _target: False)
    monkeypatch.setattr(state, "_derived_pending", lambda _target: True)
    await state.refresh_touched()
    assert fast_calls == [True], "a pending fast refresh must not be answered by another fast one"
    assert build.built == [None], "the pending fast refresh must get its full build"

1 more lines, not shown

Activity · 19 steps
lines 433–433registry = st.TargetRegistry(tmp_path / "state")lines 434–434_mcp, state = build_server(registry)lines 435–435repo = tmp_path / "used"lines 436–436repo.mkdir()lines 437–437target = registry.register(repo)lines 438–438Path(target.db_path).write_bytes(rich_db.read_bytes())lines 439–439state.tools.dossier("sensor_poll", target=str(repo))lines 440–440build = _RecordingBuild(rich_db)lines 441–441state._run_build = buildlines 442–442fast_calls: list[bool] = []lines 443–443monkeypatch.setattr(state, "_try_fast", lambda _t: fast_calls.append(True) or True)lines 445–445monkeypatch.setattr(state, "_data_stale", lambda _target: True)lines 446–446await state.refresh_touched()lines 447–447assert fast_calls == [True] and build.built == [], "the fast tier must answer a data-stale tick"lines 449–449monkeypatch.setattr(state, "_data_stale", lambda _target: False)lines 450–450monkeypatch.setattr(state, "_derived_pending", lambda _target: True)lines 451–451await state.refresh_touched()lines 452–452assert fast_calls == [True], "a pending fast refresh must not be answered by another fast one"lines 453–453assert build.built == [None], "the pending fast refresh must get its full build"

test_an_explicit_refresh_still_builds_any_named_directory

None test_background_indexing.test_an_explicit_refresh_still_builds_any_named_directory(Path tmp_path, Path rich_db)

An explicit refresh of a plain directory builds it; only the automatic path refuses.

tests/test_background_indexing.py:327

Checks

  • assert build.built == [], f"the automatic path built an unvouched directory: {build.built}"
  • assert result.get("ok") is True, result
  • assert build.built == [None], f"an explicit refresh must build what it names: {build.built}"

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-CONFIG-001measured
REQ-DDB-CONFIG-006measured
REQ-DDB-CONFIG-007measured
REQ-DDB-CONFIG-008measured
REQ-DDB-INDEX-003measured
REQ-DDB-MCP-001measuredtest_an_explicit_refresh_still_builds_any_named_directory → build_server
REQ-DDB-MCP-002measured
REQ-DDB-MCP-003measured
REQ-DDB-MCP-004measuredtest_an_explicit_refresh_still_builds_any_named_directory → build_server → _refusal_as_tool_error
REQ-DDB-PIPE-005measured
REQ-DDB-WIKI-034measuredtest_an_explicit_refresh_still_builds_any_named_directory → build_server → _register_prompts
REQ-DDB-WIKI-054measured
Source · 35 lines
async def test_an_explicit_refresh_still_builds_any_named_directory(
    tmp_path: Path, rich_db: Path
) -> None:
    """THE BOUNDARY, PINNED FROM THE OTHER SIDE. A 1.1.0 audit finding asked for the consent gate
    to cover `index(action='refresh', target=…)` as well. It must not: a ROUTED BUILD OF A NAMED
    REPOSITORY IS THE CONTRACT (gh#1, gh#22) — `test_a_routed_build_registers_the_target_without_adopting_it`
    and three sibling tests encode it, and a project that indexes vendored source drops and
    non-git trees needs it. Tightening it here broke all four.

    So the asymmetry is deliberate and this test is what keeps it deliberate: an AUTOMATIC build,
    started by a query the caller did not aim at a build, demands evidence of intent; an EXPLICIT
    refresh is the evidence. `docs/SECURITY.md` states the consequence — `target` is not a
    security boundary, and the MCP server holds the privileges of whoever launched it.

    @brief An explicit refresh of a plain directory builds it; only the automatic path refuses.
    @version 1
    """
    loose = tmp_path / "loose"
    loose.mkdir()
    (loose / "a.c").write_text("int a(void){return 0;}\n", encoding="utf-8")
    _mcp, state = build_server(st.TargetRegistry(tmp_path / "state"))
    build = _RecordingBuild(rich_db)
    state._run_build = build

    ## The automatic path refuses it — no git tree, no registration.
    await state._auto_refresh(str(loose))
    assert build.built == [], f"the automatic path built an unvouched directory: {build.built}"

    ## The explicit one builds it, because asking IS the consent.
    result = await state.build_or_refresh(_FakeCtx(), target=str(loose))
    assert result.get("ok") is True, result
    assert build.built == [None], f"an explicit refresh must build what it names: {build.built}"


@pytest.mark.anyio

test_an_unbuilt_split_repository_builds_first_party_never_the_whole

None test_background_indexing.test_an_unbuilt_split_repository_builds_first_party_never_the_whole(Path tmp_path, Path rich_db)

A bare query on an unbuilt split repository builds its first-party index.

tests/test_background_indexing.py:108

Show on the map →

Called by none

Calls _git_repo, build_server

Checks

  • assert build.built == [FIRST_PARTY_INDEX], f"expected only first-party, got {build.built}"
  • assert reply.get("sub_index") == FIRST_PARTY_INDEX, reply

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-CONFIG-001measured
REQ-DDB-CONFIG-006measured
REQ-DDB-CONFIG-007measured
REQ-DDB-INDEX-002measured
REQ-DDB-INDEX-003measured
REQ-DDB-INDEX-004measured
REQ-DDB-MCP-001measuredtest_an_unbuilt_split_repository_builds_first_party_never_the_whole → build_server
REQ-DDB-MCP-003measured
REQ-DDB-MCP-004measuredtest_an_unbuilt_split_repository_builds_first_party_never_the_whole → build_server → _refusal_as_tool_error
REQ-DDB-PIPE-005measured
REQ-DDB-QUERY-001measured
REQ-DDB-QUERY-002measured
REQ-DDB-QUERY-003measured
REQ-DDB-QUERY-004measured
REQ-DDB-QUERY-006measured
REQ-DDB-QUERY-009measured
REQ-DDB-QUERY-010measured
REQ-DDB-QUERY-012measured
REQ-DDB-QUERY-014measured
REQ-DDB-SCHEMA-011measured
REQ-DDB-WIKI-034measuredtest_an_unbuilt_split_repository_builds_first_party_never_the_whole → build_server → _register_prompts
REQ-DDB-WIKI-054measured
Source · 27 lines
async def test_an_unbuilt_split_repository_builds_first_party_never_the_whole(
    tmp_path: Path, rich_db: Path
) -> None:
    """THE BUILD gh#48 RECORDED DYING. A bare query on a split repository resolves to the whole
    target; building THAT indexes every vendored tree. First-party is what a bare call defaults
    to, so it is what gets built, and the reply says which part answered.

    @brief A bare query on an unbuilt split repository builds its first-party index.
    @version 1
    """
    repo = _git_repo(tmp_path / "split")
    (repo / "app.c").write_text("int app(void) { return 0; }\n", encoding="utf-8")
    nested = repo / "deps" / "vendored"
    nested.mkdir(parents=True)
    (nested / ".git").write_text("gitdir: ../../.git/modules/vendored\n", encoding="utf-8")
    _mcp, state = build_server(st.TargetRegistry(tmp_path / "state"))
    build = _RecordingBuild(rich_db)
    state._run_build = build

    await state._auto_refresh(str(repo))
    reply = state.tools.dossier("sensor_poll", target=str(repo))

    assert build.built == [FIRST_PARTY_INDEX], f"expected only first-party, got {build.built}"
    assert reply.get("sub_index") == FIRST_PARTY_INDEX, reply


@pytest.mark.anyio

test_concurrent_absent_indexes_do_not_run_their_builds_at_once

None test_background_indexing.test_concurrent_absent_indexes_do_not_run_their_builds_at_once(Path tmp_path, Path rich_db)

Two concurrent first builds never run their pipelines simultaneously.

tests/test_background_indexing.py:362

Show on the map →

Called by none

Calls _git_repo, build_server

Checks

  • assert overlap["max"] == 1, (f"{overlap['max']} first-build pipelines ran at once; each one is a doxygen and a " f"cargo invocation over a repository the server was merely asked about" )
  • assert len(real_build.built) == len(repos), (f"every asked build must still happen, serialised: {real_build.built}" )

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-CONFIG-001measured
REQ-DDB-CONFIG-006measured
REQ-DDB-CONFIG-007measured
REQ-DDB-INDEX-002measured
REQ-DDB-MCP-001measuredtest_concurrent_absent_indexes_do_not_run_their_builds_at_once → build_server
REQ-DDB-MCP-003measured
REQ-DDB-MCP-004measuredtest_concurrent_absent_indexes_do_not_run_their_builds_at_once → build_server → _refusal_as_tool_error
REQ-DDB-WIKI-034measuredtest_concurrent_absent_indexes_do_not_run_their_builds_at_once → build_server → _register_prompts
REQ-DDB-WIKI-054measured
Source · 61 lines
async def test_concurrent_absent_indexes_do_not_run_their_builds_at_once(
    tmp_path: Path, rich_db: Path
) -> None:
    """M8, 1.1.0 SECURITY AUDIT — in code this session shipped. One build per asked index per
    session bounds RETRIES, not CONCURRENCY: four queries naming four absent git trees started
    four pipelines, each running doxygen and cargo over a different repository, each holding a
    worker thread for the full 20 s bound on a limiter the transport shares. An agent sweeping
    a directory of checkouts does exactly that, and nothing in the product said no.

    The builds are SERIALISED rather than refused, because each one was asked for; what is
    refused is an unbounded QUEUE of them, through the same return-a-reason contract the
    consent gate uses.

    @brief Two concurrent first builds never run their pipelines simultaneously.
    @version 1
    """
    ## FIXTURE CHANGE (round 5, W10): these were empty `.git` DIRECTORIES, which a real git does
    ## not take for a repository. The first-build gate now asks git (so a linked worktree's `.git`
    ## FILE qualifies and a planted one does not), and refused them. The property guarded here —
    ## concurrent first builds are serialised — is unchanged; the trees are now real ones.
    repos = [_git_repo(tmp_path / name) for name in ("one", "two", "three")]

    _mcp, state = build_server(st.TargetRegistry(tmp_path / "state"))

    overlap = {"max": 0, "live": 0}
    lock = threading.Lock()
    real_build = _RecordingBuild(rich_db)

    ## @brief Stand-in build that measures how many run at once.
    ## @param target The Target being built.
    ## @param args Remaining positional build arguments.
    ## @return A `_run_build`-shaped result dict.
    ## @version 1
    def counting_build(target: st.Target, *args: object) -> dict[str, object]:
        """@brief Count overlapping builds. @return The result dict. @version 1"""
        with lock:
            overlap["live"] += 1
            overlap["max"] = max(overlap["max"], overlap["live"])
        try:
            time.sleep(0.3)
            return real_build(target, *args)
        finally:
            with lock:
                overlap["live"] -= 1

    state._run_build = counting_build

    async with anyio.create_task_group() as tg:
        for repo in repos:
            tg.start_soon(state._auto_refresh, str(repo))

    assert overlap["max"] == 1, (
        f"{overlap['max']} first-build pipelines ran at once; each one is a doxygen and a "
        f"cargo invocation over a repository the server was merely asked about"
    )
    assert len(real_build.built) == len(repos), (
        f"every asked build must still happen, serialised: {real_build.built}"
    )


@pytest.mark.anyio

test_serve_runs_the_background_loop_beside_the_transport

None test_background_indexing.test_serve_runs_the_background_loop_beside_the_transport(Path tmp_path)

serve starts the refresh loop when enabled and not when disabled.

tests/test_background_indexing.py:258

Checks

  • assert passes, "an enabled loop must run beside the transport"
  • assert passes == [], "interval 0 disables the loop"

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-INDEX-006measured
REQ-DDB-MCP-001measuredtest_serve_runs_the_background_loop_beside_the_transport → build_server
REQ-DDB-MCP-003measured
REQ-DDB-MCP-004measuredtest_serve_runs_the_background_loop_beside_the_transport → serve
REQ-DDB-WIKI-032measuredtest_serve_runs_the_background_loop_beside_the_transport → serve → start_if_enabled
REQ-DDB-WIKI-033measuredtest_serve_runs_the_background_loop_beside_the_transport → serve → attach
REQ-DDB-WIKI-034measuredtest_serve_runs_the_background_loop_beside_the_transport → build_server → _register_prompts
REQ-DDB-WIKI-054measuredtest_serve_runs_the_background_loop_beside_the_transport → serve → enabled
Source · 35 lines
async def test_serve_runs_the_background_loop_beside_the_transport(tmp_path: Path) -> None:
    """THE WIRING. `keep_current` can be perfect and never run; this drives `serve` with a stand-in
    transport that returns only once a background pass has happened, and with the loop disabled
    asserts no pass happens at all.

    @brief serve starts the refresh loop when enabled and not when disabled.
    @version 1
    """
    _mcp, state = build_server(st.TargetRegistry(tmp_path / "state"))
    passes: list[int] = []
    ran = anyio.Event()

    async def _pass() -> list[str]:
        passes.append(1)
        ran.set()
        return []

    state.refresh_touched = _pass

    async def _until_a_pass(_mcp: object) -> None:
        await ran.wait()

    with anyio.fail_after(5):
        await serve(_mcp, state, 0.01, _until_a_pass)
    assert passes, "an enabled loop must run beside the transport"

    passes.clear()

    async def _immediately(_mcp: object) -> None:
        await anyio.sleep(0.05)

    await serve(_mcp, state, 0, _immediately)
    assert passes == [], "interval 0 disables the loop"

Activity · 13 steps
lines 266–266_mcp, state = build_server(st.TargetRegistry(tmp_path / "state"))lines 267–267passes: list[int] = []lines 268–268ran = anyio.Event()lines 270–273async def _pass() -> list[str]: passes.append(1) ran.set() return []lines 275–275state.refresh_touched = _passlines 277–278async def _until_a_pass(_mcp: object) -> None: await ran.wait()lines 280–280with anyio.fail_after(5)lines 281–281await serve(_mcp, state, 0.01, _until_a_pass)lines 282–282assert passes, "an enabled loop must run beside the transport"lines 284–284passes.clear()lines 286–287async def _immediately(_mcp: object) -> None: await anyio.sleep(0.05)lines 289–289await serve(_mcp, state, 0, _immediately)lines 290–290assert passes == [], "interval 0 disables the loop"

test_the_background_pass_refreshes_only_indexes_this_session_used

None test_background_indexing.test_the_background_pass_refreshes_only_indexes_this_session_used(Path tmp_path, Path rich_db, pytest.MonkeyPatch monkeypatch)

refresh_touched rebuilds a stale index the session queried, and nothing else.

tests/test_background_indexing.py:229

Checks

  • assert refreshed == [st.target_for(used, registry.home).slug], refreshed
  • assert build.built == [None]

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-CONFIG-006measured
REQ-DDB-CONFIG-007measured
REQ-DDB-INDEX-002measured
REQ-DDB-INDEX-003measured
REQ-DDB-INDEX-004measured
REQ-DDB-INDEX-006measured
REQ-DDB-MCP-001measuredtest_the_background_pass_refreshes_only_indexes_this_session_used → build_server
REQ-DDB-MCP-002measured
REQ-DDB-MCP-003measured
REQ-DDB-MCP-004measuredtest_the_background_pass_refreshes_only_indexes_this_session_used → build_server → _refusal_as_tool_error
REQ-DDB-PIPE-005measured
REQ-DDB-QUERY-001measured
REQ-DDB-QUERY-002measured
REQ-DDB-QUERY-003measured
REQ-DDB-QUERY-004measured
REQ-DDB-QUERY-006measured
REQ-DDB-QUERY-009measured
REQ-DDB-QUERY-010measured
REQ-DDB-QUERY-012measured
REQ-DDB-QUERY-014measured
REQ-DDB-SCHEMA-011measured
REQ-DDB-WIKI-034measuredtest_the_background_pass_refreshes_only_indexes_this_session_used → build_server → _register_prompts
REQ-DDB-WIKI-054measured
Source · 29 lines
async def test_the_background_pass_refreshes_only_indexes_this_session_used(
    tmp_path: Path, rich_db: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    """THE WORKING SET, NOT THE DISK. A session keeps current what it has answered from; a
    repository some other session registered is not this process's to rebuild on a timer.

    @brief refresh_touched rebuilds a stale index the session queried, and nothing else.
    @version 1
    """
    registry = st.TargetRegistry(tmp_path / "state")
    _mcp, state = build_server(registry)
    used, other = tmp_path / "used", tmp_path / "other"
    for repo in (used, other):
        repo.mkdir()
        target = registry.register(repo)
        Path(target.db_path).write_bytes(rich_db.read_bytes())
    state.tools.dossier("sensor_poll", target=str(used))

    monkeypatch.setattr(state, "_data_stale", lambda _target: True)
    build = _RecordingBuild(rich_db)
    state._run_build = build

    refreshed = await state.refresh_touched()

    assert refreshed == [st.target_for(used, registry.home).slug], refreshed
    assert build.built == [None]


@pytest.mark.anyio

test_the_refresh_interval_reads_the_environment

None test_background_indexing.test_the_refresh_interval_reads_the_environment()

Default, disabled, explicit and malformed interval values.

tests/test_background_indexing.py:293

Checks

  • assert refresh_interval({}) == server_module.DEFAULT_REFRESH_INTERVAL_SECONDS
  • assert refresh_interval({server_module.REFRESH_INTERVAL_ENV: "0"}) == 0
  • assert refresh_interval({server_module.REFRESH_INTERVAL_ENV: "5"}) == 5
  • assert (refresh_interval({server_module.REFRESH_INTERVAL_ENV: "soon"}) == server_module.DEFAULT_REFRESH_INTERVAL_SECONDS )

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-MCP-004measuredtest_the_refresh_interval_reads_the_environment → refresh_interval
Source · 12 lines
def test_the_refresh_interval_reads_the_environment() -> None:
    """@brief Default, disabled, explicit and malformed interval values. @version 1"""
    assert refresh_interval({}) == server_module.DEFAULT_REFRESH_INTERVAL_SECONDS
    assert refresh_interval({server_module.REFRESH_INTERVAL_ENV: "0"}) == 0
    assert refresh_interval({server_module.REFRESH_INTERVAL_ENV: "5"}) == 5
    assert (
        refresh_interval({server_module.REFRESH_INTERVAL_ENV: "soon"})
        == server_module.DEFAULT_REFRESH_INTERVAL_SECONDS
    )


@pytest.mark.anyio