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.

30.7 KB
Raw Blame
"""Unit tests for the Python promotion-facts hooks (perf/dialects/python.py).

Covers ``loop_magnitude`` / ``batch_form`` / ``concurrency_bound`` through the
real walker (``walk_file`` -> ``FileComplexity.perf_hits[i].loop``), mirroring
``test_perf_io_in_loop.py``'s inline-fixture style. Every positive rule is
paired with the refusal(s) that protect precision (SPEC.md "Dialect hooks").
"""

from __future__ import annotations

import pytest

from repowise.core.analysis.health.complexity import walk_file
from repowise.core.analysis.health.perf.loop_facts import LoopFacts


def _hits(src: bytes, kind: str = "io_in_loop") -> list:
    fc = walk_file("f.py", "python", src)
    return [h for h in fc.perf_hits if h.kind == kind]


def _loop(src: bytes, kind: str = "io_in_loop", index: int = 0) -> LoopFacts | None:
    hits = _hits(src, kind)
    assert hits, f"no {kind!r} hit produced"
    return hits[index].loop


# ---------------------------------------------------------------------------
# loop_magnitude
# ---------------------------------------------------------------------------


def test_magnitude_grows_via_lexical_reaching_assignment():
    """``rows = await session.execute(...)`` then ``for r in rows`` -> grows (G1)."""
    facts = _loop(
        b"from sqlalchemy import select\n"
        b"async def f(session):\n"
        b"    rows = await session.execute(select(1))\n"
        b"    for r in rows:\n"
        b"        await session.execute(select(r))\n"
    )
    assert facts.magnitude == "grows_with_data"


def test_magnitude_grows_via_projection_chain():
    """The iterable itself is a ``.scalars().all()`` projection of a sink call."""
    facts = _loop(
        b"from sqlalchemy import select\n"
        b"async def f(session):\n"
        b"    for r in session.execute(select(1)).scalars().all():\n"
        b"        await session.execute(select(r))\n"
    )
    assert facts.magnitude == "grows_with_data"


def test_magnitude_range_len_of_grown_source_grows():
    """``range(len(rows))`` resolved through ``rows`` the same way as G1."""
    facts = _loop(
        b"from sqlalchemy import select\n"
        b"async def f(session):\n"
        b"    rows = await session.execute(select(1))\n"
        b"    for i in range(len(rows)):\n"
        b"        await session.execute(select(rows))\n"
    )
    assert facts.magnitude == "grows_with_data"


def test_a_directory_listing_is_as_unknown_as_the_path_it_is_given():
    facts = _loop(
        b"import os\n"
        b"from sqlalchemy import select\n"
        b"async def f(session):\n"
        b"    for root_, dirs, files in os.walk('/tmp'):\n"
        b"        await session.execute(select(root_))\n"
    )
    assert facts is None or facts.magnitude == "unknown"


def test_a_read_capped_in_the_query_does_not_grow():
    facts = _loop(
        b"def f(sb, repo_id, max_snaps):\n"
        b"    rows = sb.table('s').select('*').eq('repo_id', repo_id).limit(max_snaps).execute().data\n"
        b"    for row in rows:\n"
        b"        sb.table('t').delete().eq('id', row['id']).execute()\n"
    )
    assert facts.magnitude == "unknown"


def test_magnitude_range_all_caps_parameter_is_unknown():
    """``range(N)`` where N is an ALL_CAPS parameter: no literal proves it."""
    facts = _loop(
        b"from sqlalchemy import select\n"
        b"async def f(session, MAX_RETRIES):\n"
        b"    for i in range(MAX_RETRIES):\n"
        b"        await session.execute(select(i))\n"
    )
    assert facts is None or facts.magnitude == "unknown"


@pytest.mark.parametrize(
    "src",
    [
        b"async def f(session, cfg):\n    for i in range(cfg.max_attempts):\n",
        b"from config import MAX_RETRIES\nasync def f(session):\n"
        b"    for i in range(MAX_RETRIES):\n",
        b"class C:\n    async def f(self, session):\n        for i in range(self.max_retries):\n"
        b"    ",
    ],
)
def test_a_retry_name_alone_never_proves_a_loop_bounded(src):
    """A bounded loop is hidden as expected, so the name needs the proof a number has."""
    facts = _loop(
        b"from sqlalchemy import select\n" + src + b"        await session.execute(select(i))\n"
    )
    assert facts is None or facts.magnitude == "unknown"


def test_magnitude_range_retry_constant_bound_to_a_literal_bounded():
    facts = _loop(
        b"from sqlalchemy import select\n"
        b"MAX_RETRIES = 3\n"
        b"async def f(session):\n"
        b"    for i in range(MAX_RETRIES):\n"
        b"        await session.execute(select(i))\n"
    )
    assert facts.magnitude == "bounded"


def test_magnitude_slice_constant_upper_bound_bounded():
    """B1: ``xs[:5]``."""
    facts = _loop(
        b"from sqlalchemy import select\n"
        b"async def f(session, xs):\n"
        b"    for x in xs[:5]:\n"
        b"        await session.execute(select(x))\n"
    )
    assert facts.magnitude == "bounded"


def test_magnitude_slice_named_constant_bounded():
    """B1: ``xs[:LIMIT]`` where the module binds ``LIMIT`` to an integer literal."""
    facts = _loop(
        b"from sqlalchemy import select\n"
        b"LIMIT = 50\n"
        b"async def f(session, xs):\n"
        b"    for x in xs[:LIMIT]:\n"
        b"        await session.execute(select(x))\n"
    )
    assert facts.magnitude == "bounded"


@pytest.mark.parametrize(
    "src",
    [
        # A parameter spelled in capitals is still a parameter.
        b"async def f(session, xs, LIMIT):\n    for x in xs[:LIMIT]:\n"
        b"        await session.execute(select(x))\n",
        # Bound, but not to a literal: the user count grows.
        b"NUM_USERS = load_users()\nasync def f(session):\n    for i in range(NUM_USERS):\n"
        b"        await session.execute(select(i))\n",
        # Never bound in this module.
        b"from config import NUM_USERS\nasync def f(session):\n"
        b"    for i in range(NUM_USERS):\n        await session.execute(select(i))\n",
        # Rebound later in the module.
        b"MAX = 5\nMAX = load()\nasync def f(session):\n    for i in range(MAX):\n"
        b"        await session.execute(select(i))\n",
        # Augmented.
        b"MAX = 5\nMAX += extra()\nasync def f(session):\n    for i in range(MAX):\n"
        b"        await session.execute(select(i))\n",
        # Written through ``global`` by some function.
        b"MAX = 5\ndef grow(n):\n    global MAX\n    MAX = n\nasync def f(session):\n"
        b"    for i in range(MAX):\n        await session.execute(select(i))\n",
        # Shadowed by a local of the loop's function.
        b"MAX = 5\nasync def f(session):\n    MAX = count_rows()\n    for i in range(MAX):\n"
        b"        await session.execute(select(i))\n",
        # Shadowed by a parameter.
        b"MAX = 5\nasync def f(session, MAX):\n    for i in range(MAX):\n"
        b"        await session.execute(select(i))\n",
    ],
)
def test_capitals_alone_never_prove_a_loop_bounded(src):
    facts = _loop(b"from sqlalchemy import select\n" + src)
    assert facts is None or facts.magnitude == "unknown"


def test_magnitude_range_module_int_constant_bounded():
    facts = _loop(
        b"from sqlalchemy import select\n"
        b"MAX_PAGES = 5\n"
        b"async def f(session):\n"
        b"    for i in range(MAX_PAGES):\n"
        b"        await session.execute(select(i))\n"
    )
    assert facts.magnitude == "bounded"


def test_magnitude_slice_variable_width_int_literal_bounded():
    """B1: ``xs[a:a+4]`` — same start name, integer-literal width."""
    facts = _loop(
        b"from sqlalchemy import select\n"
        b"async def f(session, xs, a):\n"
        b"    for x in xs[a:a+4]:\n"
        b"        await session.execute(select(x))\n"
    )
    assert facts.magnitude == "bounded"


def test_magnitude_parameter_iterable_is_unknown():
    """Parameters are unknown on purpose — no reaching assignment to resolve."""
    facts = _loop(
        b"from sqlalchemy import select\n"
        b"async def f(session, items):\n"
        b"    for r in items:\n"
        b"        await session.execute(select(r))\n"
    )
    assert facts is not None and facts.magnitude == "unknown"
    assert facts.iterates == "parameter"


# ---------------------------------------------------------------------------
# batch_form
# ---------------------------------------------------------------------------


def test_batch_supabase_select_eq_equivalent():
    facts = _loop(
        b"async def f(client, repos):\n"
        b"    for r in repos:\n"
        b"        await client.table('t').select('*').eq('repo_id', r.id).execute()\n"
    )
    assert facts.batch.call == '.in_("repo_id", keys)'
    assert facts.batch.equivalent is True


def test_batch_supabase_delete_eq_equivalent():
    facts = _loop(
        b"async def f(client, repos):\n"
        b"    for r in repos:\n"
        b"        await client.table('t').delete().eq('repo_id', r.id).execute()\n"
    )
    assert facts.batch.call == '.in_("repo_id", keys)'
    assert facts.batch.equivalent is True


def test_batch_sqlalchemy_execute_where_equality():
    facts = _loop(
        b"from sqlalchemy import select\n"
        b"async def f(session, ids):\n"
        b"    for i in ids:\n"
        b"        await session.execute(select(Model).where(Model.id == i))\n"
    )
    assert facts.batch.call == "Model.id.in_(keys)"
    assert facts.batch.equivalent is True


def test_batch_sqlalchemy_query_filter_first_not_equivalent():
    """``.first()`` is itself a per-key limiting verb -> form returned, not equivalent."""
    facts = _loop(
        b"from sqlalchemy import select\n"
        b"def f(session, ids):\n"
        b"    for i in ids:\n"
        b"        session.query(Model).filter(Model.id == i).first()\n"
    )
    assert facts.batch.call == "Model.id.in_(keys)"
    assert facts.batch.equivalent is False


# -- refusals ----------------------------------------------------------------


def test_batch_none_when_loop_var_used_twice_in_chain():
    """Two ``.eq()`` calls each reference the loop var -> not a single-key chain."""
    facts = _loop(
        b"async def f(client, repos):\n"
        b"    for r in repos:\n"
        b"        await client.table('t').select('*')"
        b".eq('repo_id', r.id).eq('name', r.name).execute()\n"
    )
    assert facts is None or facts.batch is None


def test_batch_supabase_limit_makes_not_equivalent():
    facts = _loop(
        b"async def f(client, repos):\n"
        b"    for r in repos:\n"
        b"        await client.table('t').select('*')"
        b".eq('repo_id', r.id).limit(1).execute()\n"
    )
    assert facts.batch.equivalent is False


def test_batch_supabase_single_makes_not_equivalent():
    facts = _loop(
        b"async def f(client, repos):\n"
        b"    for r in repos:\n"
        b"        await client.table('t').select('*')"
        b".eq('repo_id', r.id).single().execute()\n"
    )
    assert facts.batch.equivalent is False


def test_batch_second_sink_in_body_makes_not_equivalent():
    hits = _hits(
        b"from sqlalchemy import select\n"
        b"async def f(client, repos, session):\n"
        b"    for r in repos:\n"
        b"        session.execute(select(r))\n"
        b"        await client.table('t').select('*').eq('repo_id', r.id).execute()\n"
    )
    supabase_hit = next(h for h in hits if h.line == 5)
    assert supabase_hit.loop.batch.equivalent is False


def test_batch_delete_with_break_not_equivalent():
    """An early exit could skip work the batched delete would still do."""
    facts = _loop(
        b"async def f(client, repos):\n"
        b"    for r in repos:\n"
        b"        if r.id == 0:\n"
        b"            break\n"
        b"        await client.table('t').delete().eq('repo_id', r.id).execute()\n"
    )
    assert facts.batch.call == '.in_("repo_id", keys)'
    assert facts.batch.equivalent is False


def test_batch_none_when_iterable_appended_in_body():
    facts = _loop(
        b"async def f(client, repos):\n"
        b"    for r in repos:\n"
        b"        repos.append(r)\n"
        b"        await client.table('t').select('*').eq('repo_id', r.id).execute()\n"
    )
    assert facts is None or facts.batch is None


def test_batch_none_for_while_loop():
    facts = _loop(
        b"async def f(client, repos):\n"
        b"    r = repos.pop()\n"
        b"    while r is not None:\n"
        b"        await client.table('t').select('*').eq('repo_id', r.id).execute()\n"
        b"        r = repos.pop() if repos else None\n"
    )
    # A cursor loop binds no element, so nothing per-key reaches the call.
    assert facts is not None and facts.batch is None and facts.key_unused


# ---------------------------------------------------------------------------
# concurrency_bound
# ---------------------------------------------------------------------------


def test_concurrency_bound_async_with_self_attribute():
    facts = _loop(
        b"from sqlalchemy import select\n"
        b"async def f(self, items, session):\n"
        b"    for x in items:\n"
        b"        async with self._sem:\n"
        b"            await session.execute(select(x))\n"
    )
    assert facts.concurrency_bound == "self._sem"


def test_a_semaphore_built_inside_the_loop_bounds_nothing():
    facts = _loop(
        b"import asyncio\n"
        b"from sqlalchemy import select\n"
        b"async def f(items, session):\n"
        b"    for x in items:\n"
        b"        async with asyncio.Semaphore(5):\n"
        b"            await session.execute(select(x))\n"
    )
    assert facts is None or facts.concurrency_bound is None


def test_concurrency_bound_none_when_loop_has_break():
    """Spec amendment: an early-exit loop refuses concurrency_bound — fan-out
    under the semaphore would run work the sequential loop skips past the exit."""
    facts = _loop(
        b"from sqlalchemy import select\n"
        b"async def f(self, items, session):\n"
        b"    for x in items:\n"
        b"        if x.bad:\n"
        b"            break\n"
        b"        async with self._sem:\n"
        b"            await session.execute(select(x))\n"
    )
    assert facts is None or facts.concurrency_bound is None


def test_concurrency_bound_none_when_loop_has_return():
    facts = _loop(
        b"from sqlalchemy import select\n"
        b"async def f(self, items, session):\n"
        b"    for x in items:\n"
        b"        if x.bad:\n"
        b"            return None\n"
        b"        async with self._sem:\n"
        b"            await session.execute(select(x))\n"
    )
    assert facts is None or facts.concurrency_bound is None


def test_concurrency_bound_none_for_sync_with():
    """Only an ``async with`` counts — a plain ``with`` never yields to other tasks."""
    facts = _loop(
        b"from sqlalchemy import select\n"
        b"async def f(self, items, session):\n"
        b"    for x in items:\n"
        b"        with self._sem:\n"
        b"            await session.execute(select(x))\n"
    )
    assert facts is None or facts.concurrency_bound is None


def test_batch_none_when_the_key_is_computed_from_the_element():
    facts = _loop(
        b"async def f(client, repos):\n"
        b"    for r in repos:\n"
        b"        await client.table('t').select('*').eq('id', slug(r)).execute()\n"
    )
    assert facts is None or facts.batch is None


def test_a_sync_network_write_in_the_body_breaks_equivalence():
    facts = _loop(
        b"import requests\n"
        b"def f(client, repos):\n"
        b"    for r in repos:\n"
        b"        client.table('t').select('*').eq('id', r.id).execute()\n"
        b"        requests.post('https://x', json={})\n"
    )
    assert facts.batch is not None and facts.batch.equivalent is False


def test_magnitude_grows_through_a_result_attribute():
    facts = _loop(
        b"def f(client):\n"
        b"    res = client.table('repos').select('*').execute()\n"
        b"    for row in res.data:\n"
        b"        client.table('t').select('*').eq('id', row['id']).execute()\n"
    )
    assert facts.magnitude == "grows_with_data"


def test_a_retry_loop_inside_a_loop_over_rows_is_not_bounded():
    facts = _loop(
        b"from sqlalchemy import select\n"
        b"async def f(session):\n"
        b"    rows = (await session.execute(q)).scalars().all()\n"
        b"    for row in rows:\n"
        b"        for attempt in range(MAX_RETRIES):\n"
        b"            await session.execute(select(row))\n"
    )
    assert facts.magnitude == "grows_with_data"


def test_a_delete_behind_a_continue_is_not_equivalent():
    """Collected up front, the keys would include the records the loop skips."""
    facts = _loop(
        b"from sqlalchemy import delete\n"
        b"async def f(session, rows):\n"
        b"    for rec in rows:\n"
        b"        if not rec.files:\n"
        b"            continue\n"
        b"        await session.execute(delete(Link).where(Link.decision_id == rec.id))\n"
    )
    assert facts.batch is not None and facts.batch.equivalent is False


def test_a_result_cut_to_one_row_after_the_call_is_not_equivalent():
    facts = _loop(
        b"from sqlalchemy import select\n"
        b"async def f(session, targets):\n"
        b"    for t in targets:\n"
        b"        res = await session.execute(select(Meta).where(Meta.path == t))\n"
        b"        meta = res.scalar_one_or_none()\n"
    )
    assert facts.batch is not None and facts.batch.equivalent is False


def test_no_batch_form_when_the_filter_also_reads_a_loop_local():
    """The key is (src, kind), not the element: IN on one column is the wrong query."""
    facts = _loop(
        b"from sqlalchemy import select\n"
        b"async def f(session, edges):\n"
        b"    for edge in edges:\n"
        b"        src = remap(edge)\n"
        b"        await session.execute(select(E).where(E.src == src, E.kind == edge.kind))\n"
    )
    assert facts is None or facts.batch is None


def test_a_parenthesised_await_is_still_the_sinks_own():
    facts = _loop(
        b"async def f(supabase, payload, installation_id):\n"
        b"    for repo in payload.get('repositories_removed', []):\n"
        b"        await (\n"
        b"            supabase.table('app_repos').delete()\n"
        b"            .eq('installation_id', installation_id).eq('repo_id', repo['id']).execute()\n"
        b"        )\n"
    )
    assert facts.batch is not None
    assert facts.batch.call == '.in_("repo_id", keys)'
    assert facts.batch.equivalent is True


def test_writing_through_the_element_does_not_make_it_loop_local():
    facts = _loop(
        b"from sqlalchemy import select\n"
        b"async def f(session, targets, out):\n"
        b"    for t in targets:\n"
        b"        res = await session.execute(select(Meta).where(Meta.path == t))\n"
        b"        out[t] = res\n"
    )
    assert facts.batch is not None and facts.batch.call == "Meta.path.in_(keys)"


def test_magnitude_sees_through_an_empty_fallback():
    facts = _loop(
        b"def f(sb):\n"
        b"    rows = (sb.table('repos').select('*').execute()).data or []\n"
        b"    for row in rows:\n"
        b"        sb.table('t').select('*').eq('id', row['id']).execute()\n"
    )
    assert facts.magnitude == "grows_with_data"


# ---------------------------------------------------------------------------
# session.get(Model, key): a db sink
# ---------------------------------------------------------------------------


@pytest.mark.parametrize(
    ("call", "db_import", "sink"),
    [
        ("await session.get(Repo, i)", True, True),
        ("await session.get(models.Repo, i)", True, True),
        ("await session.get(DBUser, i)", True, True),
        ("await self.get(User, i)", False, False),  # no db evidence in the file
        ("await session.get(User)", True, False),
        ("d.get(i, None)", True, False),
        ("cache.get('k', None)", True, False),
        ("os.environ.get('KEY', i)", True, False),
        ("requests.get(API_URL, i)", True, False),  # an ALL_CAPS constant, not a model
        ("session.get(*args)", True, False),
    ],
)
def test_session_get_sink_shape(call, db_import, sink):
    header = "from sqlalchemy import select\n" if db_import else ""
    src = f"{header}async def f(session, self, d, cache, args, ids):\n    for i in ids:\n        {call}\n"
    hits = _hits(src.encode())
    assert [h.detail for h in hits] == (["db"] if sink else [])


# ---------------------------------------------------------------------------
# session.get(Model, key): the batch form
# ---------------------------------------------------------------------------


def test_batch_session_get_is_named_but_never_proven():
    """``get`` may be an identity-map hit, so batching it is not a proven saving."""
    facts = _loop(
        b"from sqlalchemy import select\n"
        b"async def f(session, rows):\n"
        b"    for r in rows:\n"
        b"        obj = await session.get(Repo, r.id)\n"
    )
    assert facts.batch.call == "select(Repo).where(inspect(Repo).primary_key[0].in_(keys))"
    assert facts.batch.equivalent is False


def test_batch_session_get_second_sink_in_body_not_equivalent():
    hits = _hits(
        b"from sqlalchemy import select\n"
        b"async def f(session, others, ids):\n"
        b"    for rid in ids:\n"
        b"        session.execute(select(Other))\n"
        b"        obj = await session.get(Repo, rid)\n"
    )
    get_hit = next(h for h in hits if h.loop is not None and h.loop.batch is not None)
    assert get_hit.loop.batch.equivalent is False


def test_batch_session_get_none_when_key_computed_from_element():
    facts = _loop(
        b"from sqlalchemy import select\n"
        b"async def f(session, ids):\n"
        b"    for rid in ids:\n"
        b"        obj = await session.get(Repo, f'x:{rid}')\n"
    )
    assert facts is None or facts.batch is None



def test_a_result_built_in_key_order_is_not_equivalent():
    """One IN query returns rows in its own order, not grouped by the loop's keys."""
    facts = _loop(
        b"from sqlalchemy import select\n"
        b"def f(session, events):\n"
        b"    out = []\n"
        b"    for e in events:\n"
        b"        rows = session.query(A).filter(A.event_id == e.id).all()\n"
        b"        out.extend(rows)\n"
        b"    return out\n"
    )
    assert facts.batch is not None and facts.batch.equivalent is False


def test_session_get_of_a_key_already_used_in_the_iteration_is_not_a_sink():
    """The earlier call may have loaded the row, so the second ``get`` is served from memory."""
    hits = _hits(
        b"from sqlalchemy import select\n"
        b"async def f(session, recs):\n"
        b"    for rec in recs:\n"
        b"        await upsert(session, rec.id)\n"
        b"        meta = await session.get(Meta, rec.id)\n"
    )
    assert all(h.line != 5 for h in hits)


def test_a_read_filtered_to_one_chunk_of_keys_does_not_grow():
    facts = _loop(
        b"from sqlalchemy import select\n"
        b"async def f(session, paths):\n"
        b"    for i in range(0, len(paths), BATCH):\n"
        b"        result = await session.execute(select(G).where(G.path.in_(paths[i : i + BATCH])))\n"
        b"        for g in result.scalars().all():\n"
        b"            await session.execute(select(H).where(H.id == g.id))\n"
    )
    assert facts.magnitude != "grows_with_data"


def test_a_read_filtered_to_a_chunk_loops_element_does_not_grow():
    facts = _loop(
        b"from sqlalchemy import select\n"
        b"async def f(session, paths):\n"
        b"    for chunk in chunked(paths):\n"
        b"        result = await session.execute(select(G).where(G.path.in_(chunk)))\n"
        b"        for g in result.all():\n"
        b"            await session.execute(select(H).where(H.id == g.id))\n"
    )
    assert facts.magnitude != "grows_with_data"


def test_a_read_filtered_to_a_set_of_keys_does_not_grow():
    facts = _loop(
        b"from sqlalchemy import select\n"
        b"async def f(session, paths):\n"
        b"    result = await session.execute(select(G).where(G.path.in_(paths)))\n"
        b"    for g in result.scalars().all():\n"
        b"        await session.execute(select(H).where(H.id == g.id))\n"
    )
    assert facts.magnitude != "grows_with_data"


@pytest.mark.parametrize("values", ['("a", "b")', "SOURCES", "sources"])
def test_a_fixed_set_of_values_is_a_state_filter_that_grows(values):
    facts = _loop(
        b"from sqlalchemy import select\n"
        b"async def f(session):\n"
        b"    sources = ('a', 'b')\n"
        b"    result = await session.execute(select(G).where(G.source.in_(" + values.encode() + b")))\n"
        b"    for g in result.scalars().all():\n"
        b"        await session.execute(select(H).where(H.id == g.id))\n"
    )
    assert facts.magnitude == "grows_with_data"


def test_keys_a_subquery_yields_still_grow():
    facts = _loop(
        b"from sqlalchemy import select\n"
        b"async def f(session):\n"
        b"    ids = select(R.id).subquery()\n"
        b"    result = await session.execute(select(G).where(G.repo_id.in_(ids)))\n"
        b"    for g in result.scalars().all():\n"
        b"        await session.execute(select(H).where(H.id == g.id))\n"
    )
    assert facts.magnitude == "grows_with_data"


def test_a_limit_on_a_statement_built_before_the_loop_caps_the_read():
    facts = _loop(
        b"from sqlalchemy import select\n"
        b"async def f(session, limit):\n"
        b"    stmt = select(G).limit(limit)\n"
        b"    rows = (await session.execute(stmt)).scalars().all()\n"
        b"    for g in rows:\n"
        b"        await session.execute(select(H).where(H.id == g.id))\n"
    )
    assert facts.magnitude != "grows_with_data"


def test_a_dict_lookup_of_the_key_does_not_hide_the_session_get():
    hits = _hits(
        b"from sqlalchemy import select\n"
        b"async def f(session, rows, quotes):\n"
        b"    for row in rows:\n"
        b"        quote = quotes.get(row.old_id)\n"
        b"        rec = await session.get(Rec, row.old_id)\n"
    )
    assert any(h.line == 5 for h in hits)


def test_a_result_read_from_one_chunk_of_keys_does_not_grow():
    facts = _loop(
        b"from sqlalchemy import select\n"
        b"async def f(session, paths):\n"
        b"    for chunk in chunked(paths):\n"
        b"        result = await session.execute(select(G).where(G.path.in_(chunk)))\n"
        b"        for g in result.scalars().all():\n"
        b"            await session.execute(select(H).where(H.id == g.id))\n"
    )
    assert facts.magnitude != "grows_with_data"


# ``.all()`` on a bare name is a query result only when the function binds that name;
# an imported registry (dispatch's ``plugins.all()``) is not.


@pytest.mark.parametrize(
    ("setup", "receiver_call", "sink"),
    [
        ("from dispatch.plugins.base import plugins\n", "plugins.all()", False),
        ("registry = Registry()\n", "registry.all()", False),  # module global, lower-case
        ("REGISTRY = Registry()\n", "REGISTRY.all()", False),  # module global, ALL_CAPS
        ("", "query.all()", True),  # a function parameter
    ],
)
def test_ambiguous_db_method_receiver_gate(setup, receiver_call, sink):
    src = (
        "from sqlalchemy import select\n"
        + setup
        + "def f(query, ids):\n"
        + "    for i in ids:\n"
        + f"        {receiver_call}\n"
    )
    hits = _hits(src.encode())
    assert [h.detail for h in hits] == (["db"] if sink else [])


def test_ambiguous_db_method_on_a_locally_assigned_result_is_still_a_sink():
    hits = _hits(
        b"from sqlalchemy import select\n"
        b"def f(session, ids):\n"
        b"    for i in ids:\n"
        b"        res = session.execute(select(i))\n"
        b"        res.all()\n"
    )
    assert [h.detail for h in hits] == ["db", "db"]


def test_ambiguous_db_method_on_an_imported_registry_does_not_grow():
    facts = _loop(
        b"from sqlalchemy import select\n"
        b"from dispatch.plugins.base import plugins\n"
        b"def f(session, ids):\n"
        b"    for p in plugins.all():\n"
        b"        session.execute(select(p))\n"
    )
    assert facts is None or facts.magnitude != "grows_with_data"


def test_ambiguous_db_method_on_a_locally_assigned_result_still_grows():
    facts = _loop(
        b"from sqlalchemy import select\n"
        b"async def f(session, ids):\n"
        b"    res = await session.execute(select(1))\n"
        b"    for r in res.all():\n"
        b"        session.execute(select(r))\n"
    )
    assert facts.magnitude == "grows_with_data"


@pytest.mark.parametrize("stmt", ["run_task(document_id=doc.id)", "t = run_task(doc.id)"])
def test_a_read_after_a_call_made_for_its_effect_is_not_equivalent(stmt):
    """dify: the loop runs a task, then reads what it wrote; read up front, it runs first."""
    facts = _loop(
        b"from sqlalchemy import select\n"
        b"def f(session, docs):\n"
        b"    for doc in docs:\n"
        + f"        {stmt}\n".encode()
        + b"        session.scalars(select(Seg).where(Seg.document_id == doc.id)).all()\n"
    )
    assert facts.batch is not None and facts.batch.equivalent is False


def test_a_local_collection_update_keeps_the_read_equivalent():
    facts = _loop(
        b"from sqlalchemy import select\n"
        b"async def f(session, grants):\n"
        b"    seen = set()\n"
        b"    for g in grants:\n"
        b"        res = await session.execute(select(M).where(M.id == g.member_id))\n"
        b"        key = str(g.member_id)\n"
        b"        seen.add(key)\n"
    )
    assert facts.batch is not None and facts.batch.equivalent is True


def test_a_raw_sql_read_capped_in_its_text_does_not_grow():
    """dify: ``sa.text("... LIMIT 1000")`` pages a table; one page is as large as its cap."""
    facts = _loop(
        b"import sqlalchemy as sa\n"
        b"def f(conn, session):\n"
        b'    sql = "SELECT id FROM apps ORDER BY created_at LIMIT 1000"\n'
        b"    rs = conn.execute(sa.text(sql))\n"
        b"    for i in rs:\n"
        b"        session.execute(sa.text('DELETE FROM x WHERE id = :id'), {'id': i.id})\n"
    )
    assert facts is None or facts.magnitude != "grows_with_data"


def test_a_write_through_a_local_session_before_the_read_is_not_equivalent():
    facts = _loop(
        b"from sqlalchemy import select\n"
        b"def f(rows):\n"
        b"    session = SessionLocal()\n"
        b"    for r in rows:\n"
        b"        session.add(r)\n"
        b"        session.execute(select(M).where(M.id == r.id))\n"
    )
    assert facts.batch is not None and facts.batch.equivalent is False


@pytest.mark.parametrize(
    "text",
    [
        "note = 'throttle limit 5 per user'",  # not SQL
        "note = 'SELECT id FROM apps -- was LIMIT 1000'",  # the cap is commented out
    ],
)
def test_a_limit_outside_live_sql_does_not_cap_the_read(text):
    facts = _loop(
        b"import sqlalchemy as sa\n"
        b"def f(conn, session):\n"
        + f"    {text}\n".encode()
        + b"    rs = conn.execute(sa.text('SELECT id FROM apps'), note)\n"
        b"    for i in rs:\n"
        b"        session.execute(sa.text('DELETE FROM x WHERE id = :id'), {'id': i.id})\n"
    )
    assert facts.magnitude == "grows_with_data"