test_python_ast.py

tests/test_python_ast.py

Python AST edge-layer tests (task #58): call edges, spawns, reachability seeds.

test_an_aliased_thread_entry_is_resolved_through_the_import_map

None test_python_ast.test_an_aliased_thread_entry_is_resolved_through_the_import_map(Path tmp_path)

A module-aliased thread ENTRY must be resolved through the same import map as the callee.

tests/test_python_ast.py:828

Checks

  • assert bindings.resolve("dox") == "clew.doxygen"
  • assert bindings.resolve("ts") == "clew.testscope"
  • assert "clew.doxygen._write_doxyfile_stdin" in qualified, (f"an aliased entry was stored unresolved; doxygen records the real module path, so a " f"raw alias can never match the qualified lookup. Got: {sorted(qualified)}" )
  • assert "clew.testscope.is_test_path" in qualified, (f"`import x.y as z` form not resolved either. Got: {sorted(qualified)}" )
  • assert "Holder._run" in qualified, (f"the self.method -> Class.method rewrite regressed. Got: {sorted(qualified)}" )

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-PIPE-003measuredtest_an_aliased_thread_entry_is_resolved_through_the_import_map → collect_bindings
REQ-DDB-PIPE-011measured
REQ-DDB-SCHEMA-001measuredtest_an_aliased_thread_entry_is_resolved_through_the_import_map → load_thread_patterns
REQ-DDB-SCHEMA-012inferredtest_an_aliased_thread_entry_is_resolved_through_the_import_map → load_thread_patterns → declaration_origin
Source · 63 lines
def test_an_aliased_thread_entry_is_resolved_through_the_import_map(tmp_path: Path) -> None:
    """#498. The CALLEE has been resolved through `PyBindings` since the Python thread layer
    landed — `bindings.resolve("th.Thread") == "threading.Thread"` is asserted just above. The
    ENTRY was not, so `threading.Thread(target=dox.func)` stored the raw source text
    `"dox.func"`, doxygen's `definition` holds the real `clew.doxygen.func`, and the qualified
    lookup could never match. The row was inserted with a NULL entry rowid.

    THAT IS A RESOLUTION FAILURE RATHER THAN FAIL-CLOSED BEHAVIOUR, by this repo's own invariant:
    `test_self_index_thread_layer_resolves_its_entries` says a NULL is correct ONLY when the
    entry's own tail is genuinely absent from the index. Here the tail is present and unique.

    THE FIX IS NOT A TAIL MATCH, deliberately. Falling back to the bare tail would resolve this
    case and silently borrow a same-named stranger's rowid the day a second `func` appears —
    the gh#347 shape, and exactly what the no-fallback rule in `_insert_threads` exists to
    prevent. Resolving the ALIAS is different in kind: the module is then KNOWN rather than
    guessed, so the qualified lookup stays exact.

    @brief An aliased entry resolves to its real dotted path.
    @return None.
    @version 1
    """
    src = tmp_path / "c.py"
    src.write_text(
        "import threading\n"
        "from clew import doxygen as dox\n"
        "import clew.testscope as ts\n"
        "\n"
        "class Holder:\n"
        "    def _run(self):\n"
        "        pass\n"
        "    def go(self):\n"
        "        threading.Thread(target=self._run).start()\n"
        "\n"
        "def spawn():\n"
        "    threading.Thread(target=dox._write_doxyfile_stdin).start()\n"
        "    threading.Thread(target=ts.is_test_path).start()\n",
        encoding="utf-8",
    )
    tree, data = _parse(tmp_path, "c.py")
    bindings = collect_bindings(tree, data)

    ## The import map already knows both aliases — this is the machinery the entry path must use.
    assert bindings.resolve("dox") == "clew.doxygen"
    assert bindings.resolve("ts") == "clew.testscope"

    sites = _walk_spawn_sites(tree, data, patterns_by_name(load_thread_patterns(None)))
    ## A site is a flat septet; index 3 is the QUALIFIED entry, which is the field the
    ## resolver matches against doxygen's `definition`. Indexed rather than named because the
    ## walker returns plain lists for the harvest cache, not `_SpawnSite` objects.
    qualified = {row[3] for row in sites}

    assert "clew.doxygen._write_doxyfile_stdin" in qualified, (
        f"an aliased entry was stored unresolved; doxygen records the real module path, so a "
        f"raw alias can never match the qualified lookup. Got: {sorted(qualified)}"
    )
    assert "clew.testscope.is_test_path" in qualified, (
        f"`import x.y as z` form not resolved either. Got: {sorted(qualified)}"
    )
    ## AND THE self.method REWRITE MUST SURVIVE. It is the one entry form that already worked, so
    ## it is the regression most worth pinning while changing this code path.
    assert "Holder._run" in qualified, (
        f"the self.method -> Class.method rewrite regressed. Got: {sorted(qualified)}"
    )

1 more lines, not shown

Activity · 11 steps
lines 849–849src = tmp_path / "c.py"lines 850–865src.write_text( "import threading\n" "from clew import doxygen as dox\n" "import clew.testscope as ts\n" "\n" "class Holder:\n" " def _run(self):\n" " pass\n" " def go(self):\n" " threading.Thread(target=self._run).start()\n" "\n" "def spawn():\n" " threading.Thread(target=dox._write_doxyfile_stdin).start()\n" " threading.Thread(target=ts.is_test_path).start()\n", encoding="utf-8", )lines 866–866tree, data = _parse(tmp_path, "c.py")lines 867–867bindings = collect_bindings(tree, data)lines 870–870assert bindings.resolve("dox") == "clew.doxygen"lines 871–871assert bindings.resolve("ts") == "clew.testscope"lines 873–873sites = _walk_spawn_sites(tree, data, patterns_by_name(load_thread_patterns(None)))lines 877–877qualified = {row[3] for row in sites}lines 879–882assert "clew.doxygen._write_doxyfile_stdin" in qualified, ( f"an aliased entry was stored unresolved; doxygen records the real module path, so a " f"raw alias can never match the qualified lookup. Got: {sorted(qualified)}" )lines 883–885assert "clew.testscope.is_test_path" in qualified, ( f"`import x.y as z` form not resolved either. Got: {sorted(qualified)}" )lines 888–890assert "Holder._run" in qualified, ( f"the self.method -> Class.method rewrite regressed. Got: {sorted(qualified)}" )

test_bindings_bind_receiver_only_from_resolvable_constructor

None test_python_ast.test_bindings_bind_receiver_only_from_resolvable_constructor(Path tmp_path)

A receiver bound to a resolvable constructor gets a type; one bound to an attribute does not. That asymmetry is what stops `.submit(` from matching on any object with a `submit` method.

tests/test_python_ast.py:307

Checks

  • assert bindings.resolve("pool.submit") == "concurrent.futures.ThreadPoolExecutor.submit"
  • assert bindings.resolve("loop.run_in_executor") == "asyncio.AbstractEventLoop.run_in_executor"
  • assert bindings.resolve("other.run_in_executor") is None

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-PIPE-003measuredtest_bindings_bind_receiver_only_from_resolvable_constructor → collect_bindings
REQ-DDB-PIPE-011measured
Source · 21 lines
def test_bindings_bind_receiver_only_from_resolvable_constructor(tmp_path: Path) -> None:
    """A receiver bound to a resolvable constructor gets a type; one bound to an
    attribute does not. That asymmetry is what stops `.submit(` from matching on
    any object with a `submit` method."""
    src = tmp_path / "b.py"
    src.write_text(
        "import asyncio\n"
        "from concurrent.futures import ThreadPoolExecutor\n"
        "def f(self):\n"
        "    pool = ThreadPoolExecutor()\n"
        "    loop = asyncio.get_event_loop()\n"
        "    other = self._loop\n",
    )
    tree, data = _parse(tmp_path, "b.py")
    bindings = collect_bindings(tree, data)
    assert bindings.resolve("pool.submit") == "concurrent.futures.ThreadPoolExecutor.submit"
    assert bindings.resolve("loop.run_in_executor") == "asyncio.AbstractEventLoop.run_in_executor"
    # `self._loop` is not a constructor, so `other` stays unbound — fail closed.
    assert bindings.resolve("other.run_in_executor") is None

Activity · 7 steps
lines 311–311src = tmp_path / "b.py"lines 312–319src.write_text( "import asyncio\n" "from concurrent.futures import ThreadPoolExecutor\n" "def f(self):\n" " pool = ThreadPoolExecutor()\n" " loop = asyncio.get_event_loop()\n" " other = self._loop\n", )lines 320–320tree, data = _parse(tmp_path, "b.py")lines 321–321bindings = collect_bindings(tree, data)lines 322–322assert bindings.resolve("pool.submit") == "concurrent.futures.ThreadPoolExecutor.submit"lines 323–323assert bindings.resolve("loop.run_in_executor") == "asyncio.AbstractEventLoop.run_in_executor"lines 325–325assert bindings.resolve("other.run_in_executor") is None

test_bindings_refuse_unbound_and_foreign_names

None test_python_ast.test_bindings_refuse_unbound_and_foreign_names(Path tmp_path)

An unbound name resolves to None (never to itself), and a name imported from elsewhere resolves to THAT origin — the mechanism that refuses clew's own `Thread` dataclass.

tests/test_python_ast.py:294

Checks

  • assert bindings.resolve("Thread") == ".models.Thread"
  • assert bindings.resolve("Thread") != "threading.Thread"
  • assert bindings.resolve("SomethingLocal") is None

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-PIPE-003measuredtest_bindings_refuse_unbound_and_foreign_names → collect_bindings
REQ-DDB-PIPE-011measured
Source · 13 lines
def test_bindings_refuse_unbound_and_foreign_names(tmp_path: Path) -> None:
    """An unbound name resolves to None (never to itself), and a name imported
    from elsewhere resolves to THAT origin — the mechanism that refuses
    clew's own `Thread` dataclass."""
    src = tmp_path / "b.py"
    src.write_text("from .models import Thread\n")
    tree, data = _parse(tmp_path, "b.py")
    bindings = collect_bindings(tree, data)
    assert bindings.resolve("Thread") == ".models.Thread"
    assert bindings.resolve("Thread") != "threading.Thread"
    assert bindings.resolve("SomethingLocal") is None

Activity · 7 steps
lines 298–298src = tmp_path / "b.py"lines 299–299src.write_text("from .models import Thread\n")lines 300–300tree, data = _parse(tmp_path, "b.py")lines 301–301bindings = collect_bindings(tree, data)lines 302–302assert bindings.resolve("Thread") == ".models.Thread"lines 303–303assert bindings.resolve("Thread") != "threading.Thread"lines 304–304assert bindings.resolve("SomethingLocal") is None

test_bindings_resolve_module_alias_and_from_import

None test_python_ast.test_bindings_resolve_module_alias_and_from_import(Path tmp_path)

All three real spellings of the same import must resolve to one dotted name, because that is what lets a single dotted pattern match them all.

tests/test_python_ast.py:274

Checks

  • assert bindings.resolve("threading.Thread") == "threading.Thread"
  • assert bindings.resolve("th.Thread") == "threading.Thread"
  • assert bindings.resolve("Thread") == "threading.Thread"
  • assert bindings.resolve("T") == "threading.Thread"
  • assert bindings.resolve("ThreadPoolExecutor") == "concurrent.futures.ThreadPoolExecutor"

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-PIPE-003measuredtest_bindings_resolve_module_alias_and_from_import → collect_bindings
REQ-DDB-PIPE-011measured
Source · 20 lines
def test_bindings_resolve_module_alias_and_from_import(tmp_path: Path) -> None:
    """All three real spellings of the same import must resolve to one dotted
    name, because that is what lets a single dotted pattern match them all."""
    src = tmp_path / "b.py"
    src.write_text(
        "import threading\n"
        "import threading as th\n"
        "from threading import Thread\n"
        "from threading import Thread as T\n"
        "from concurrent.futures import ThreadPoolExecutor\n",
    )
    tree, data = _parse(tmp_path, "b.py")
    bindings = collect_bindings(tree, data)
    assert bindings.resolve("threading.Thread") == "threading.Thread"
    assert bindings.resolve("th.Thread") == "threading.Thread"
    assert bindings.resolve("Thread") == "threading.Thread"
    assert bindings.resolve("T") == "threading.Thread"
    assert bindings.resolve("ThreadPoolExecutor") == "concurrent.futures.ThreadPoolExecutor"

Activity · 9 steps
lines 277–277src = tmp_path / "b.py"lines 278–284src.write_text( "import threading\n" "import threading as th\n" "from threading import Thread\n" "from threading import Thread as T\n" "from concurrent.futures import ThreadPoolExecutor\n", )lines 285–285tree, data = _parse(tmp_path, "b.py")lines 286–286bindings = collect_bindings(tree, data)lines 287–287assert bindings.resolve("threading.Thread") == "threading.Thread"lines 288–288assert bindings.resolve("th.Thread") == "threading.Thread"lines 289–289assert bindings.resolve("Thread") == "threading.Thread"lines 290–290assert bindings.resolve("T") == "threading.Thread"lines 291–291assert bindings.resolve("ThreadPoolExecutor") == "concurrent.futures.ThreadPoolExecutor"

test_c_harvest_output_unchanged_on_the_c_fixture

None test_python_ast.test_c_harvest_output_unchanged_on_the_c_fixture()

THE GUARD against the Python work leaking into the C path.

tests/test_python_ast.py:223

Show on the map →

Called by none

Calls _ast_harvest_calls, _ast_parse_one_file, _walk_spawn_sites, load_thread_patterns, patterns_by_name

Checks

  • assert (files, calls, plain, member, spawns) == (21, 39, 39, 0, 0)

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-PIPE-003measuredtest_c_harvest_output_unchanged_on_the_c_fixture → _walk_spawn_sites → is_python_tree
REQ-DDB-PIPE-011measuredtest_c_harvest_output_unchanged_on_the_c_fixture → _ast_parse_one_file → _parseable_file
REQ-DDB-PIPE-012inferredtest_c_harvest_output_unchanged_on_the_c_fixture → _ast_parse_one_file → _ts_language_for → _grammar_available → has_language
REQ-DDB-SCHEMA-001measuredtest_c_harvest_output_unchanged_on_the_c_fixture → load_thread_patterns
REQ-DDB-SCHEMA-012inferredtest_c_harvest_output_unchanged_on_the_c_fixture → load_thread_patterns → declaration_origin
Source · 35 lines
def test_c_harvest_output_unchanged_on_the_c_fixture() -> None:
    """THE GUARD against the Python work leaking into the C path.

    RE-BASELINED when `sample/` was deleted, and that is worth being explicit
    about. The original pin — 26 files / 97 calls — was measured on the demobot
    tree before the Python layers landed, so it guarded that specific change. This
    one is measured on `tests/data/csample/` (real C, the tree that replaced the
    dummy project) and therefore guards DRIFT FROM NOW rather than fidelity to that
    original moment. A re-derived pin is weaker evidence than an original one and
    should not be described as if it were the same thing.

    What survives the re-baseline intact is the part that actually carries the
    claim, because it is structural rather than numeric: every call site is plain
    `ast` with ZERO `ast_member` (this is C, so there are no member-access callees
    to unwrap), and ZERO spawn sites. If the Python work had leaked into the C
    walkers, those two zeros are what would break — not the file count.
    """
    patterns = patterns_by_name(load_thread_patterns(None))
    files = calls = plain = member = spawns = 0
    for path in sorted(CSAMPLE_ROOT.rglob("*")):
        if path.suffix not in (".c", ".h", ".cpp"):
            continue
        rel = str(path.relative_to(CSAMPLE_ROOT))
        parsed = _ast_parse_one_file(rel, path, {})
        if parsed is None:
            continue
        files += 1
        sites = _ast_harvest_calls(parsed[0], parsed[1])
        calls += len(sites)
        plain += sum(1 for s in sites if s[2] == "ast")
        member += sum(1 for s in sites if s[2] == "ast_member")
        spawns += len(_walk_spawn_sites(parsed[0], parsed[1], patterns))
    assert (files, calls, plain, member, spawns) == (21, 39, 39, 0, 0)

Activity · 16 steps
lines 240–240patterns = patterns_by_name(load_thread_patterns(None))lines 241–241files = calls = plain = member = spawns = 0lines 242–242◇ for path in sorted(CSAMPLE_ROOT.rglob("*"))lines 243–243◇ if path.suffix not in (".c", ".h", ".cpp")lines 244–244continuelines 245–245rel = str(path.relative_to(CSAMPLE_ROOT))lines 246–246parsed = _ast_parse_one_file(rel, path, {})lines 247–247◇ if parsed is Nonelines 248–248continuelines 249–249files += 1lines 250–250sites = _ast_harvest_calls(parsed[0], parsed[1])lines 251–251calls += len(sites)lines 252–252plain += sum(1 for s in sites if s[2] == "ast")lines 253–253member += sum(1 for s in sites if s[2] == "ast_member")lines 254–254spawns += len(_walk_spawn_sites(parsed[0], parsed[1], patterns))lines 255–255assert (files, calls, plain, member, spawns) == (21, 39, 39, 0, 0)

test_c_spawn_defaults_still_present_and_unchanged

None test_python_ast.test_c_spawn_defaults_still_present_and_unchanged()

Adding the Python primitives must not displace the C/C++ ones, and the merged map must keep each C pattern's argument positions.

tests/test_python_ast.py:258

Checks

  • assert name in by_name, f"{name} lost from defaults"
  • assert by_name["pthread_create"].entry_arg_index == 2
  • assert by_name["xTaskCreate"].name_arg_index == 1
  • assert by_name["pthread_create"].entry_kwarg is None
  • assert by_name["threading.Thread"].entry_kwarg == "target"

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-SCHEMA-001measuredtest_c_spawn_defaults_still_present_and_unchanged → load_thread_patterns
REQ-DDB-SCHEMA-012inferredtest_c_spawn_defaults_still_present_and_unchanged → load_thread_patterns → declaration_origin
Source · 16 lines
def test_c_spawn_defaults_still_present_and_unchanged() -> None:
    """Adding the Python primitives must not displace the C/C++ ones, and the
    merged map must keep each C pattern's argument positions."""
    by_name = {p.name: p for p in load_thread_patterns(None)}
    for name in ("pthread_create", "xTaskCreate", "osThreadNew", "std::thread", "std::jthread"):
        assert name in by_name, f"{name} lost from defaults"
    assert by_name["pthread_create"].entry_arg_index == 2
    assert by_name["xTaskCreate"].name_arg_index == 1
    # The C primitives carry NO keyword form; only Python's do.
    assert by_name["pthread_create"].entry_kwarg is None
    assert by_name["threading.Thread"].entry_kwarg == "target"


# ─── import bindings ────────────────────────────────────────────────────────

Activity · 7 steps
lines 261–261by_name = {p.name: p for p in load_thread_patterns(None)}lines 262–262◇ for name in ("pthread_create", "xTaskCreate", "osThreadNew", "std::thread", "std::jthread")lines 263–263assert name in by_name, f"{name} lost from defaults"lines 264–264assert by_name["pthread_create"].entry_arg_index == 2lines 265–265assert by_name["xTaskCreate"].name_arg_index == 1lines 267–267assert by_name["pthread_create"].entry_kwarg is Nonelines 268–268assert by_name["threading.Thread"].entry_kwarg == "target"

test_console_script_seed_resolves_the_declared_module

None test_python_ast.test_console_script_seed_resolves_the_declared_module(Path tmp_path)

clew declares two entry points that share the bare name `main`. The seed must resolve against the fully dotted `definition`, so a declared `pkg.cli:main` seeds cli's `main` and not the other one.

tests/test_python_ast.py:630

Checks

  • assert seeds == {1}, "console script resolved to the wrong same-named function"

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-PIPE-003measuredtest_console_script_seed_resolves_the_declared_module → python_entry_seeds → run_harvest
REQ-DDB-PIPE-004measuredtest_console_script_seed_resolves_the_declared_module → python_entry_seeds
REQ-DDB-PIPE-011inferredtest_console_script_seed_resolves_the_declared_module → python_entry_seeds → run_harvest → _harvest_one_file → _parseable_file
REQ-DDB-PIPE-012inferredtest_console_script_seed_resolves_the_declared_module → python_entry_seeds → run_harvest → _harvest_one_file → _ts_language_for → _grammar_available → has_language
Source · 27 lines
def test_console_script_seed_resolves_the_declared_module(tmp_path: Path) -> None:
    """clew declares two entry points that share the bare name `main`. The
    seed must resolve against the fully dotted `definition`, so a declared
    `pkg.cli:main` seeds cli's `main` and not the other one."""
    db = tmp_path / "clew.db"
    conn = sqlite3.connect(str(db))
    conn.executescript(
        """
        CREATE TABLE path (name TEXT);
        CREATE TABLE memberdef (
            rowid INTEGER PRIMARY KEY, kind TEXT, name TEXT, definition TEXT,
            file_id INTEGER, bodyfile_id INTEGER, bodystart INTEGER, bodyend INTEGER
        );
        """,
    )
    conn.executemany(
        "INSERT INTO memberdef (rowid, kind, name, definition, file_id, bodyfile_id, "
        "bodystart, bodyend) VALUES (?, 'function', 'main', ?, 1, 1, 1, 2)",
        [(1, "None pkg.cli.main"), (2, "None pkg.server.main")],
    )
    conn.commit()
    conn.close()
    (tmp_path / "pyproject.toml").write_text('[project.scripts]\nx = "pkg.cli:main"\n')
    seeds = python_entry_seeds(db, tmp_path)
    assert seeds == {1}, "console script resolved to the wrong same-named function"

Activity · 9 steps
lines 634–634db = tmp_path / "clew.db"lines 635–635conn = sqlite3.connect(str(db))lines 636–644conn.executescript( """ CREATE TABLE path (name TEXT); CREATE TABLE memberdef ( rowid INTEGER PRIMARY KEY, kind TEXT, name TEXT, definition TEXT, file_id INTEGER, bodyfile_id INTEGER, bodystart INTEGER, bodyend INTEGER ); """, )lines 645–649conn.executemany( "INSERT INTO memberdef (rowid, kind, name, definition, file_id, bodyfile_id, " "bodystart, bodyend) VALUES (?, 'function', 'main', ?, 1, 1, 1, 2)", [(1, "None pkg.cli.main"), (2, "None pkg.server.main")], )lines 650–650conn.commit()lines 651–651conn.close()lines 652–652(tmp_path / "pyproject.toml").write_text('[project.scripts]\nx = "pkg.cli:main"\n')lines 653–653seeds = python_entry_seeds(db, tmp_path)lines 654–654assert seeds == {1}, "console script resolved to the wrong same-named function"

test_console_script_targets_reads_both_table_spellings

None test_python_ast.test_console_script_targets_reads_both_table_spellings(Path tmp_path)

PEP 621 and poetry are both real, so both tables are read rather than one build backend being assumed.

tests/test_python_ast.py:619

Checks

  • assert set(targets) == {"pkg.mod:main", "pkg.other:run"}
  • assert console_script_targets(tmp_path / "nope") == []

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-PIPE-004measuredtest_console_script_targets_reads_both_table_spellings → console_script_targets
Source · 11 lines
def test_console_script_targets_reads_both_table_spellings(tmp_path: Path) -> None:
    """PEP 621 and poetry are both real, so both tables are read rather than one
    build backend being assumed."""
    (tmp_path / "pyproject.toml").write_text(
        '[project.scripts]\nfoo = "pkg.mod:main"\n[tool.poetry.scripts]\nbar = "pkg.other:run"\n',
    )
    targets = console_script_targets(tmp_path)
    assert set(targets) == {"pkg.mod:main", "pkg.other:run"}
    assert console_script_targets(tmp_path / "nope") == []

Activity · 4 steps
lines 622–624(tmp_path / "pyproject.toml").write_text( '[project.scripts]\nfoo = "pkg.mod:main"\n[tool.poetry.scripts]\nbar = "pkg.other:run"\n', )lines 625–625targets = console_script_targets(tmp_path)lines 626–626assert set(targets) == {"pkg.mod:main", "pkg.other:run"}lines 627–627assert console_script_targets(tmp_path / "nope") == []

test_dotted_name_refuses_non_static_chain

None test_python_ast.test_dotted_name_refuses_non_static_chain(Path tmp_path)

A chain containing a call or subscript has no static name and must be refused rather than having its source text taken literally.

tests/test_python_ast.py:328

Show on the map →

Called by none

Calls dotted_name

Checks

  • assert "h.i.j" in found
  • assert None in found # f().b / d['k'].e refused

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-PIPE-003measuredtest_dotted_name_refuses_non_static_chain → dotted_name
REQ-DDB-PIPE-011measured
Source · 20 lines
def test_dotted_name_refuses_non_static_chain(tmp_path: Path) -> None:
    """A chain containing a call or subscript has no static name and must be
    refused rather than having its source text taken literally."""
    src = tmp_path / "b.py"
    src.write_text("a = f().b\nc = d['k'].e\ng = h.i.j\n")
    tree, data = _parse(tmp_path, "b.py")
    found = []
    stack = [tree.root_node]
    while stack:
        node = stack.pop()
        stack.extend(node.children)
        if node.type == "attribute":
            found.append(dotted_name(node, data))
    assert "h.i.j" in found
    assert None in found  # f().b / d['k'].e refused


# ─── argument reading ───────────────────────────────────────────────────────

Activity · 12 steps
lines 331–331src = tmp_path / "b.py"lines 332–332src.write_text("a = f().b\nc = d['k'].e\ng = h.i.j\n")lines 333–333tree, data = _parse(tmp_path, "b.py")lines 334–334found = []lines 335–335stack = [tree.root_node]lines 336–336◇ while stacklines 337–337node = stack.pop()lines 338–338stack.extend(node.children)lines 339–339◇ if node.type == "attribute"lines 340–340found.append(dotted_name(node, data))lines 341–341assert "h.i.j" in foundlines 342–342assert None in found

test_extra_seeds_rescue_a_self_loop_false_orphan

None test_python_ast.test_extra_seeds_rescue_a_self_loop_false_orphan(Path tmp_path)

The exact shape measured on `a Python codebase`: doxygen attributes a `__main__` guard's call to the guarded function ITSELF, so the function has a non-fuzzy incoming edge (excluding it from the zero-incoming source) and its only caller is itself. Without a structural seed it is a FALSE orphan; with one it is live. `dead_helper` must stay orphan either way, proving the seed does not simply mark everything live.

tests/test_python_ast.py:688

Checks

  • assert before[1] == "orphan", "expected the self-loop entry to be a false orphan"
  • assert after[1] == "live", "structural seed did not rescue the entry point"
  • assert after[2] == "live", "the entry's callee should now be reachable"
  • assert after[3] == "orphan", "a genuinely dead function must stay orphan"
  • assert after[4] == "orphan"

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-PIPE-004measuredtest_extra_seeds_rescue_a_self_loop_false_orphan → mark_reachability
REQ-DDB-SCHEMA-012measured
Source · 49 lines
def test_extra_seeds_rescue_a_self_loop_false_orphan(tmp_path: Path) -> None:
    """The exact shape measured on `a Python codebase`: doxygen attributes a
    `__main__` guard's call to the guarded function ITSELF, so the function has a
    non-fuzzy incoming edge (excluding it from the zero-incoming source) and its
    only caller is itself. Without a structural seed it is a FALSE orphan; with
    one it is live. `dead_helper` must stay orphan either way, proving the seed
    does not simply mark everything live."""
    db = tmp_path / "clew.db"
    conn = sqlite3.connect(str(db))
    conn.executescript(
        """
        CREATE TABLE memberdef (
            rowid INTEGER PRIMARY KEY, kind TEXT, name TEXT,
            file_id INTEGER, bodyfile_id INTEGER, bodystart INTEGER, bodyend INTEGER
        );
        CREATE TABLE call_edges (caller_rowid INTEGER, callee_rowid INTEGER,
            source TEXT, confidence TEXT);
        """,
    )
    conn.executemany(
        "INSERT INTO memberdef (rowid, kind, name, file_id, bodyfile_id, bodystart, "
        "bodyend) VALUES (?, 'function', ?, 1, 1, ?, ?)",
        [(1, "guarded", 1, 2), (2, "reached", 3, 4), (3, "dead_helper", 5, 6), (4, "dead2", 7, 8)],
    )
    conn.executemany(
        "INSERT INTO call_edges VALUES (?, ?, 'ast', 'resolved')",
        # guarded -> guarded (the doxygen self-loop), guarded -> reached,
        # and a dead mutually-recursive pair so neither is zero-incoming.
        [(1, 1), (1, 2), (3, 4), (4, 3)],
    )
    conn.commit()
    conn.close()

    mark_reachability(db, entry_patterns=["nothing_matches"])
    conn = sqlite3.connect(str(db))
    before = dict(conn.execute("SELECT memberdef_rowid, status FROM symbol_liveness"))
    conn.close()
    assert before[1] == "orphan", "expected the self-loop entry to be a false orphan"

    mark_reachability(db, entry_patterns=["nothing_matches"], extra_seeds={1})
    conn = sqlite3.connect(str(db))
    after = dict(conn.execute("SELECT memberdef_rowid, status FROM symbol_liveness"))
    conn.close()
    assert after[1] == "live", "structural seed did not rescue the entry point"
    assert after[2] == "live", "the entry's callee should now be reachable"
    assert after[3] == "orphan", "a genuinely dead function must stay orphan"
    assert after[4] == "orphan"

Activity · 20 steps
lines 695–695db = tmp_path / "clew.db"lines 696–696conn = sqlite3.connect(str(db))lines 697–706conn.executescript( """ CREATE TABLE memberdef ( rowid INTEGER PRIMARY KEY, kind TEXT, name TEXT, file_id INTEGER, bodyfile_id INTEGER, bodystart INTEGER, bodyend INTEGER ); CREATE TABLE call_edges (caller_rowid INTEGER, callee_rowid INTEGER, source TEXT, confidence TEXT); """, )lines 707–711conn.executemany( "INSERT INTO memberdef (rowid, kind, name, file_id, bodyfile_id, bodystart, " "bodyend) VALUES (?, 'function', ?, 1, 1, ?, ?)", [(1, "guarded", 1, 2), (2, "reached", 3, 4), (3, "dead_helper", 5, 6), (4, "dead2", 7, 8)], )lines 712–717conn.executemany( "INSERT INTO call_edges VALUES (?, ?, 'ast', 'resolved')", # guarded -> guarded (the doxygen self-loop), guarded -> reached, # and a dead mutually-recursive pair so neither is zero-incoming. [(1, 1), (1, 2), (3, 4), (4, 3)], )lines 718–718conn.commit()lines 719–719conn.close()lines 721–721mark_reachability(db, entry_patterns=["nothing_matches"])lines 722–722conn = sqlite3.connect(str(db))lines 723–723before = dict(conn.execute("SELECT memberdef_rowid, status FROM symbol_liveness"))lines 724–724conn.close()lines 725–725assert before[1] == "orphan", "expected the self-loop entry to be a false orphan"lines 727–727mark_reachability(db, entry_patterns=["nothing_matches"], extra_seeds={1})lines 728–728conn = sqlite3.connect(str(db))lines 729–729after = dict(conn.execute("SELECT memberdef_rowid, status FROM symbol_liveness"))lines 730–730conn.close()lines 731–731assert after[1] == "live", "structural seed did not rescue the entry point"lines 732–732assert after[2] == "live", "the entry's callee should now be reachable"lines 733–733assert after[3] == "orphan", "a genuinely dead function must stay orphan"lines 734–734assert after[4] == "orphan"

test_is_python_tree_discriminates_by_root_type

None test_python_ast.test_is_python_tree_discriminates_by_root_type()

Dialect selection reads the grammar's own root node type, so it must be true for a Python parse and false for a C one.

tests/test_python_ast.py:211

Checks

  • assert is_python_tree(py_tree) is True
  • assert is_python_tree(c_tree) is False

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-PIPE-003measuredtest_is_python_tree_discriminates_by_root_type → is_python_tree
REQ-DDB-PIPE-011measured
Source · 12 lines
def test_is_python_tree_discriminates_by_root_type() -> None:
    """Dialect selection reads the grammar's own root node type, so it must be
    true for a Python parse and false for a C one."""
    py_tree, _ = _parse(FIXTURE_ROOT, FIXTURE_REL)
    c_tree, _ = _parse(CSAMPLE_ROOT, "src/main.c")
    assert is_python_tree(py_tree) is True
    assert is_python_tree(c_tree) is False


# ─── C/C++ REGRESSION PIN ───────────────────────────────────────────────────

Activity · 4 steps
lines 214–214py_tree, _ = _parse(FIXTURE_ROOT, FIXTURE_REL)lines 215–215c_tree, _ = _parse(CSAMPLE_ROOT, "src/main.c")lines 216–216assert is_python_tree(py_tree) is Truelines 217–217assert is_python_tree(c_tree) is False

test_main_guard_calls_are_harvested

None test_python_ast.test_main_guard_calls_are_harvested()

The guard's callee is the entry point; a call elsewhere in the file is not. Matching the CONDITION is what keeps this from seeding any conditional call.

tests/test_python_ast.py:657

Checks

  • assert harvest_main_guard_calls(tree, src) == ["guarded_main"]

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-PIPE-003measuredtest_main_guard_calls_are_harvested → harvest_main_guard_calls → _called_names → dotted_name
REQ-DDB-PIPE-004measuredtest_main_guard_calls_are_harvested → harvest_main_guard_calls
REQ-DDB-PIPE-011measured
Source · 8 lines
def test_main_guard_calls_are_harvested() -> None:
    """The guard's callee is the entry point; a call elsewhere in the file is
    not. Matching the CONDITION is what keeps this from seeding any conditional
    call."""
    tree, src = _parse(FIXTURE_ROOT, FIXTURE_REL)
    assert harvest_main_guard_calls(tree, src) == ["guarded_main"]

Activity · 2 steps
lines 661–661tree, src = _parse(FIXTURE_ROOT, FIXTURE_REL)lines 662–662assert harvest_main_guard_calls(tree, src) == ["guarded_main"]

test_main_guard_ignores_a_plain_if_and_a_mere_mention

None test_python_ast.test_main_guard_ignores_a_plain_if_and_a_mere_mention(Path tmp_path)

A module that merely mentions the string `"__main__"`, or has an unrelated `if`, must contribute no seed.

tests/test_python_ast.py:665

Checks

  • assert harvest_main_guard_calls(tree, data) == []

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-PIPE-003inferredtest_main_guard_ignores_a_plain_if_and_a_mere_mention → harvest_main_guard_calls → _called_names → dotted_name
REQ-DDB-PIPE-004measuredtest_main_guard_ignores_a_plain_if_and_a_mere_mention → harvest_main_guard_calls
REQ-DDB-PIPE-011measured
Source · 11 lines
def test_main_guard_ignores_a_plain_if_and_a_mere_mention(tmp_path: Path) -> None:
    """A module that merely mentions the string `"__main__"`, or has an unrelated
    `if`, must contribute no seed."""
    src = tmp_path / "b.py"
    src.write_text(
        "LABEL = '__main__'\ndef f(flag):\n    if flag:\n        side_effect()\n",
    )
    tree, data = _parse(tmp_path, "b.py")
    assert harvest_main_guard_calls(tree, data) == []

Activity · 4 steps
lines 668–668src = tmp_path / "b.py"lines 669–671src.write_text( "LABEL = '__main__'\ndef f(flag):\n if flag:\n side_effect()\n", )lines 672–672tree, data = _parse(tmp_path, "b.py")lines 673–673assert harvest_main_guard_calls(tree, data) == []

test_main_guard_seed_resolves_to_the_guarded_function

None test_python_ast.test_main_guard_seed_resolves_to_the_guarded_function(Path tmp_path)

End-to-end: the fixture's `guarded_main` must be seeded.

tests/test_python_ast.py:676

Show on the map →

Called by none

Calls _make_py_db, python_entry_seeds

Checks

  • assert "guarded_main" in names

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-PIPE-003measuredtest_main_guard_seed_resolves_to_the_guarded_function → python_entry_seeds → run_harvest
REQ-DDB-PIPE-004measuredtest_main_guard_seed_resolves_to_the_guarded_function → python_entry_seeds
REQ-DDB-PIPE-011measuredtest_main_guard_seed_resolves_to_the_guarded_function → python_entry_seeds → run_harvest → _harvest_one_file → _parseable_file
REQ-DDB-PIPE-012inferredtest_main_guard_seed_resolves_to_the_guarded_function → python_entry_seeds → run_harvest → _harvest_one_file → _ts_language_for → _grammar_available → has_language
Source · 12 lines
def test_main_guard_seed_resolves_to_the_guarded_function(tmp_path: Path) -> None:
    """End-to-end: the fixture's `guarded_main` must be seeded."""
    db = _make_py_db(tmp_path)
    seeds = python_entry_seeds(db, FIXTURE_ROOT)
    conn = sqlite3.connect(str(db))
    names = {
        conn.execute("SELECT name FROM memberdef WHERE rowid=?", (r,)).fetchone()[0] for r in seeds
    }
    conn.close()
    assert "guarded_main" in names

Activity · 6 steps
lines 678–678db = _make_py_db(tmp_path)lines 679–679seeds = python_entry_seeds(db, FIXTURE_ROOT)lines 680–680conn = sqlite3.connect(str(db))lines 681–683names = { conn.execute("SELECT name FROM memberdef WHERE rowid=?", (r,)).fetchone()[0] for r in seeds }lines 684–684conn.close()lines 685–685assert "guarded_main" in names

test_new_thread_kinds_are_registered_in_the_vocabulary

None test_python_ast.test_new_thread_kinds_are_registered_in_the_vocabulary(str kind)

Both new kinds must be real vocabulary members, so the `threads.kind` CHECK accepts them and a declared manifest can validate against them.

tests/test_python_ast.py:814

Show on the map →

Called by none

Calls none

Checks

  • assert kind in THREAD_KIND
  • assert THREAD_KIND.validated(kind, owner="test", field="kind") == kind

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-SCHEMA-012measured
Source · 9 lines
def test_new_thread_kinds_are_registered_in_the_vocabulary(kind: str) -> None:
    """Both new kinds must be real vocabulary members, so the `threads.kind`
    CHECK accepts them and a declared manifest can validate against them."""
    from clew.vocabulary import THREAD_KIND

    assert kind in THREAD_KIND
    assert THREAD_KIND.validated(kind, owner="test", field="kind") == kind

Activity · 3 steps
lines 817–817from clew.vocabulary import THREAD_KINDlines 819–819assert kind in THREAD_KINDlines 820–820assert THREAD_KIND.validated(kind, owner="test", field="kind") == kind

test_no_builtin_python_accessor_default_exists

None test_python_ast.test_no_builtin_python_accessor_default_exists()

`publish` / `subscribe` / `get` / `set` are ordinary method names on countless unrelated objects, so shipping them as defaults would manufacture a dataflow graph out of coincidence. The built-in accessor defaults must stay the ingot C convention only.

tests/test_python_ast.py:764

Checks

  • assert prefixes == {"DataModel_Set_", "DataModel_Get_"}

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-CONFIG-006measuredtest_no_builtin_python_accessor_default_exists → resolve_shared_key_patterns
REQ-DDB-SCHEMA-005measuredtest_no_builtin_python_accessor_default_exists → resolve_shared_key_patterns
REQ-DDB-SCHEMA-012inferredtest_no_builtin_python_accessor_default_exists → resolve_shared_key_patterns → load_shared_key_patterns → declaration_origin
Source · 10 lines
def test_no_builtin_python_accessor_default_exists() -> None:
    """`publish` / `subscribe` / `get` / `set` are ordinary method names on
    countless unrelated objects, so shipping them as defaults would manufacture a
    dataflow graph out of coincidence. The built-in accessor defaults must stay
    the ingot C convention only."""
    writers, readers, _aliases = resolve_shared_key_patterns(None)
    prefixes = {getattr(p, "prefix", None) for p in (*writers, *readers)}
    assert prefixes == {"DataModel_Set_", "DataModel_Get_"}

Activity · 3 steps
lines 769–769writers, readers, _aliases = resolve_shared_key_patterns(None)lines 770–770prefixes = {getattr(p, "prefix", None) for p in (*writers, *readers)}lines 771–771assert prefixes == {"DataModel_Set_", "DataModel_Get_"}

test_positional_argument_skips_keyword_arguments

None test_python_ast.test_positional_argument_skips_keyword_arguments(Path tmp_path)

`Thread(group, target, name=...)`: counting every named child (the C helper's rule) would let a keyword argument occupy a positional slot and shift every index after it.

tests/test_python_ast.py:348

Checks

  • assert dotted_name(positional_argument(call, 0), data) == "a"
  • assert dotted_name(positional_argument(call, 1), data) == "b"
  • assert positional_argument(call, 2) is None # only two positionals exist
  • assert dotted_name(keyword_argument(call, "kw"), data) == "c"
  • assert keyword_argument(call, "absent") is None

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-PIPE-003measuredtest_positional_argument_skips_keyword_arguments → dotted_name
REQ-DDB-PIPE-011measured
Source · 15 lines
def test_positional_argument_skips_keyword_arguments(tmp_path: Path) -> None:
    """`Thread(group, target, name=...)`: counting every named child (the C
    helper's rule) would let a keyword argument occupy a positional slot and
    shift every index after it."""
    src = tmp_path / "b.py"
    src.write_text("f(a, b, kw=c, other=d)\n")
    tree, data = _parse(tmp_path, "b.py")
    call = next(n for n in _walk_nodes(tree) if n.type == "call")
    assert dotted_name(positional_argument(call, 0), data) == "a"
    assert dotted_name(positional_argument(call, 1), data) == "b"
    assert positional_argument(call, 2) is None  # only two positionals exist
    assert dotted_name(keyword_argument(call, "kw"), data) == "c"
    assert keyword_argument(call, "absent") is None

Activity · 9 steps
lines 352–352src = tmp_path / "b.py"lines 353–353src.write_text("f(a, b, kw=c, other=d)\n")lines 354–354tree, data = _parse(tmp_path, "b.py")lines 355–355call = next(n for n in _walk_nodes(tree) if n.type == "call")lines 356–356assert dotted_name(positional_argument(call, 0), data) == "a"lines 357–357assert dotted_name(positional_argument(call, 1), data) == "b"lines 358–358assert positional_argument(call, 2) is Nonelines 359–359assert dotted_name(keyword_argument(call, "kw"), data) == "c"lines 360–360assert keyword_argument(call, "absent") is None

test_py_declared_accessors_pair_enum_keys

None test_python_ast.test_py_declared_accessors_pair_enum_keys(Path tmp_path)

A DECLARED Python accessor convention must actually produce paired sites. The key shape is an enum member (`Topic.ALPHA`) — an `attribute`, not the bare identifier C uses — which is what a real repo writes (measured on `a Python codebase`: every keyed publish keys on `EventType.*`).

tests/test_python_ast.py:774

Show on the map →

Called by none

Calls _walk_shared_key_calls, resolve_shared_key_patterns

Checks

  • assert [w[1] for w in out["w"]] == ["Topic.ALPHA"]
  • assert [r[1] for r in out["r"]] == ["Topic.ALPHA"]
  • assert len(out["u"]) == 1

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-CONFIG-006measuredtest_py_declared_accessors_pair_enum_keys → resolve_shared_key_patterns
REQ-DDB-PIPE-003measuredtest_py_declared_accessors_pair_enum_keys → _walk_shared_key_calls → is_python_tree
REQ-DDB-PIPE-011measured
REQ-DDB-SCHEMA-005measuredtest_py_declared_accessors_pair_enum_keys → resolve_shared_key_patterns
REQ-DDB-SCHEMA-012measuredtest_py_declared_accessors_pair_enum_keys → resolve_shared_key_patterns → load_shared_key_patterns → declaration_origin
Source · 28 lines
def test_py_declared_accessors_pair_enum_keys(tmp_path: Path) -> None:
    """A DECLARED Python accessor convention must actually produce paired sites.
    The key shape is an enum member (`Topic.ALPHA`) — an `attribute`, not the bare
    identifier C uses — which is what a real repo writes (measured on
    `a Python codebase`: every keyed publish keys on `EventType.*`)."""
    src = tmp_path / "bus.py"
    src.write_text(
        "def emit_alpha(bus):\n"
        "    bus.publish(Topic.ALPHA, 1)\n"
        "def on_alpha(bus):\n"
        "    bus.subscribe(Topic.ALPHA, handler)\n"
        "def emit_computed(bus, t):\n"
        "    bus.publish(t, 2)\n",
    )
    manifest = tmp_path / "keys.yaml"
    manifest.write_text(
        "writers:\n  - pattern: publish\n    key_arg_index: 0\n"
        "readers:\n  - pattern: subscribe\n    key_arg_index: 0\n",
    )
    tree, data = _parse(tmp_path, "bus.py")
    writers, readers, aliases = resolve_shared_key_patterns(manifest)
    out = _walk_shared_key_calls(tree, data, _SharedKeyPatterns(writers, readers, aliases))
    assert [w[1] for w in out["w"]] == ["Topic.ALPHA"]
    assert [r[1] for r in out["r"]] == ["Topic.ALPHA"]
    # `publish(t, 2)` keys on a variable — computed, so fail-closed unresolved.
    assert len(out["u"]) == 1

Activity · 10 steps
lines 779–779src = tmp_path / "bus.py"lines 780–787src.write_text( "def emit_alpha(bus):\n" " bus.publish(Topic.ALPHA, 1)\n" "def on_alpha(bus):\n" " bus.subscribe(Topic.ALPHA, handler)\n" "def emit_computed(bus, t):\n" " bus.publish(t, 2)\n", )lines 788–788manifest = tmp_path / "keys.yaml"lines 789–792manifest.write_text( "writers:\n - pattern: publish\n key_arg_index: 0\n" "readers:\n - pattern: subscribe\n key_arg_index: 0\n", )lines 793–793tree, data = _parse(tmp_path, "bus.py")lines 794–794writers, readers, aliases = resolve_shared_key_patterns(manifest)lines 795–795out = _walk_shared_key_calls(tree, data, _SharedKeyPatterns(writers, readers, aliases))lines 796–796assert [w[1] for w in out["w"]] == ["Topic.ALPHA"]lines 797–797assert [r[1] for r in out["r"]] == ["Topic.ALPHA"]lines 799–799assert len(out["u"]) == 1

test_py_declared_local_wrapper_matches_by_raw_name

None test_python_ast.test_py_declared_local_wrapper_matches_by_raw_name(Path tmp_path)

A module-local spawn wrapper has no import binding, so it falls through to raw-text matching and a declared `--thread-patterns` entry still works. No built-in default can reach that path, since every default is dotted.

tests/test_python_ast.py:587

Show on the map →

Called by none

Calls _walk_spawn_sites, load_thread_patterns, patterns_by_name

Checks

  • assert [s[1] for s in sites] == ["entry"]
  • assert [s[0] for s in sites] == ["w"]

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-PIPE-003measuredtest_py_declared_local_wrapper_matches_by_raw_name → _walk_spawn_sites → is_python_tree
REQ-DDB-PIPE-011measured
REQ-DDB-SCHEMA-001measuredtest_py_declared_local_wrapper_matches_by_raw_name → load_thread_patterns
REQ-DDB-SCHEMA-012measuredtest_py_declared_local_wrapper_matches_by_raw_name → load_thread_patterns → declaration_origin
Source · 17 lines
def test_py_declared_local_wrapper_matches_by_raw_name(tmp_path: Path) -> None:
    """A module-local spawn wrapper has no import binding, so it falls through to
    raw-text matching and a declared `--thread-patterns` entry still works. No
    built-in default can reach that path, since every default is dotted."""
    src = tmp_path / "w.py"
    src.write_text("def entry():\n    pass\ndef boot():\n    spawn_task(entry, 'w')\n")
    tree, data = _parse(tmp_path, "w.py")
    manifest = tmp_path / "spawns.yaml"
    manifest.write_text(
        "spawns:\n  - name: spawn_task\n    entry_arg_index: 0\n    name_arg_index: 1\n",
    )
    patterns = patterns_by_name(load_thread_patterns(manifest))
    sites = _walk_spawn_sites(tree, data, patterns)
    assert [s[1] for s in sites] == ["entry"]
    assert [s[0] for s in sites] == ["w"]

Activity · 9 steps
lines 591–591src = tmp_path / "w.py"lines 592–592src.write_text("def entry():\n pass\ndef boot():\n spawn_task(entry, 'w')\n")lines 593–593tree, data = _parse(tmp_path, "w.py")lines 594–594manifest = tmp_path / "spawns.yaml"lines 595–597manifest.write_text( "spawns:\n - name: spawn_task\n entry_arg_index: 0\n name_arg_index: 1\n", )lines 598–598patterns = patterns_by_name(load_thread_patterns(manifest))lines 599–599sites = _walk_spawn_sites(tree, data, patterns)lines 600–600assert [s[1] for s in sites] == ["entry"]lines 601–601assert [s[0] for s in sites] == ["w"]

test_py_lookalike_constructor_is_refused

None test_python_ast.test_py_lookalike_constructor_is_refused(Path tmp_path)

`Decoy(target=noop)` is shaped exactly like a spawn but imported from `.models`. Resolving the callee through the file's own imports must refuse it. This is the committed regression for clew's own `Thread` dataclass.

tests/test_python_ast.py:556

Show on the map →

Called by none

Calls _make_py_db, _threads, extract_threads

Checks

  • assert "noop" not in names, "a look-alike constructor fabricated a thread"
  • assert not any("Decoy" in n for n in names)

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-INDEX-002inferredtest_py_lookalike_constructor_is_refused → extract_threads → spawn_harvester → manifest_key → hash_file
REQ-DDB-PIPE-003measuredtest_py_lookalike_constructor_is_refused → extract_threads → spawn_harvester → manifest_key
REQ-DDB-PIPE-004measuredtest_py_lookalike_constructor_is_refused → extract_threads → _populate_membership → _bfs_live_set
REQ-DDB-PIPE-011measuredtest_py_lookalike_constructor_is_refused → _make_py_db → _parse → _ast_parse_one_file → _parseable_file
REQ-DDB-PIPE-012inferredtest_py_lookalike_constructor_is_refused → _make_py_db → _parse → _ast_parse_one_file → _ts_language_for → _grammar_available → has_language
REQ-DDB-QUERY-003measuredtest_py_lookalike_constructor_is_refused → extract_threads → _definition_preferring_name_index
REQ-DDB-QUERY-011measuredtest_py_lookalike_constructor_is_refused → extract_threads → _ensure_threads_tables
REQ-DDB-SCHEMA-001measuredtest_py_lookalike_constructor_is_refused → extract_threads
REQ-DDB-SCHEMA-007measuredtest_py_lookalike_constructor_is_refused → extract_threads → _ensure_threads_tables
REQ-DDB-SCHEMA-012measuredtest_py_lookalike_constructor_is_refused → extract_threads → spawn_harvester → load_thread_patterns → declaration_origin
Source · 11 lines
def test_py_lookalike_constructor_is_refused(tmp_path: Path) -> None:
    """`Decoy(target=noop)` is shaped exactly like a spawn but imported from
    `.models`. Resolving the callee through the file's own imports must refuse
    it. This is the committed regression for clew's own `Thread` dataclass."""
    db = _make_py_db(tmp_path)
    extract_threads(db, FIXTURE_ROOT, None)
    names = {name for name, _entry, _kind in _threads(db)}
    assert "noop" not in names, "a look-alike constructor fabricated a thread"
    assert not any("Decoy" in n for n in names)

Activity · 5 steps
lines 560–560db = _make_py_db(tmp_path)lines 561–561extract_threads(db, FIXTURE_ROOT, None)lines 562–562names = {name for name, _entry, _kind in _threads(db)}lines 563–563assert "noop" not in names, "a look-alike constructor fabricated a thread"lines 564–564assert not any("Decoy" in n for n in names)

test_py_multicall_lambda_entry_fails_closed

None test_python_ast.test_py_multicall_lambda_entry_fails_closed(Path tmp_path)

A lambda body with MORE THAN ONE call is ambiguous, so no thread may be recorded — never one attributed to an arbitrary leading helper.

tests/test_python_ast.py:576

Show on the map →

Called by none

Calls _walk_spawn_sites, load_thread_patterns, patterns_by_name

Checks

  • assert "noop" not in entries, "a multi-call lambda produced a thread entry"

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-PIPE-003measuredtest_py_multicall_lambda_entry_fails_closed → _walk_spawn_sites → is_python_tree
REQ-DDB-PIPE-011measured
REQ-DDB-SCHEMA-001measuredtest_py_multicall_lambda_entry_fails_closed → load_thread_patterns
REQ-DDB-SCHEMA-012inferredtest_py_multicall_lambda_entry_fails_closed → load_thread_patterns → declaration_origin
Source · 11 lines
def test_py_multicall_lambda_entry_fails_closed(tmp_path: Path) -> None:
    """A lambda body with MORE THAN ONE call is ambiguous, so no thread may be
    recorded — never one attributed to an arbitrary leading helper."""
    tree, src = _parse(FIXTURE_ROOT, FIXTURE_REL)
    patterns = patterns_by_name(load_thread_patterns(None))
    sites = _walk_spawn_sites(tree, src, patterns)
    # `spawn_multi_lambda` uses (noop(), helper()); `noop` must never be an entry.
    entries = {site[1] for site in sites}
    assert "noop" not in entries, "a multi-call lambda produced a thread entry"

Activity · 5 steps
lines 579–579tree, src = _parse(FIXTURE_ROOT, FIXTURE_REL)lines 580–580patterns = patterns_by_name(load_thread_patterns(None))lines 581–581sites = _walk_spawn_sites(tree, src, patterns)lines 583–583entries = {site[1] for site in sites}lines 584–584assert "noop" not in entries, "a multi-call lambda produced a thread entry"

test_py_same_entry_through_two_primitives_stays_two_threads

None test_python_ast.test_py_same_entry_through_two_primitives_stays_two_threads(Path tmp_path)

A function spawned as BOTH a thread and a process is TWO execution contexts, and `kind` is the column a consumer reads to decide whether they can share memory. The `threads` UNIQUE key used to be (name, entry_memberdef_rowid) with no `kind`, so the two rows collapsed and the survivor's kind was whichever tree-sitter's DFS popped first — a wrong answer, not a missing one. Both must survive with their own kinds.

tests/test_python_ast.py:534

Show on the map →

Called by none

Calls _make_py_db, _threads, extract_threads

Checks

  • assert sorted(kind for _n, kind in rows) == ["process", "pthread"]

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-INDEX-002inferredtest_py_same_entry_through_two_primitives_stays_two_threads → extract_threads → spawn_harvester → manifest_key → hash_file
REQ-DDB-PIPE-003measuredtest_py_same_entry_through_two_primitives_stays_two_threads → extract_threads → spawn_harvester → manifest_key
REQ-DDB-PIPE-004measuredtest_py_same_entry_through_two_primitives_stays_two_threads → extract_threads → _populate_membership → _bfs_live_set
REQ-DDB-PIPE-011measuredtest_py_same_entry_through_two_primitives_stays_two_threads → _make_py_db → _parse → _ast_parse_one_file → _parseable_file
REQ-DDB-PIPE-012inferredtest_py_same_entry_through_two_primitives_stays_two_threads → _make_py_db → _parse → _ast_parse_one_file → _ts_language_for → _grammar_available → has_language
REQ-DDB-QUERY-003measuredtest_py_same_entry_through_two_primitives_stays_two_threads → extract_threads → _definition_preferring_name_index
REQ-DDB-QUERY-011measuredtest_py_same_entry_through_two_primitives_stays_two_threads → extract_threads → _ensure_threads_tables
REQ-DDB-SCHEMA-001measuredtest_py_same_entry_through_two_primitives_stays_two_threads → extract_threads
REQ-DDB-SCHEMA-007measuredtest_py_same_entry_through_two_primitives_stays_two_threads → extract_threads → _ensure_threads_tables
REQ-DDB-SCHEMA-012measuredtest_py_same_entry_through_two_primitives_stays_two_threads → extract_threads → spawn_harvester → load_thread_patterns → declaration_origin
Source · 22 lines
def test_py_same_entry_through_two_primitives_stays_two_threads(tmp_path: Path) -> None:
    """A function spawned as BOTH a thread and a process is TWO execution
    contexts, and `kind` is the column a consumer reads to decide whether they
    can share memory. The `threads` UNIQUE key used to be (name,
    entry_memberdef_rowid) with no `kind`, so the two rows collapsed and the
    survivor's kind was whichever tree-sitter's DFS popped first — a wrong
    answer, not a missing one. Both must survive with their own kinds."""
    (tmp_path / "dual.py").write_text(
        "import multiprocessing\n"
        "import threading\n"
        "def body():\n"
        "    pass\n"
        "def boot():\n"
        "    threading.Thread(target=body).start()\n"
        "    multiprocessing.Process(target=body).start()\n",
    )
    db = _make_py_db(tmp_path, module="dual", root=tmp_path, rel="dual.py")
    extract_threads(db, tmp_path, None)
    rows = [(name, kind) for name, _entry, kind in _threads(db) if name == "body"]
    assert sorted(kind for _n, kind in rows) == ["process", "pthread"]

Activity · 5 steps
lines 541–549(tmp_path / "dual.py").write_text( "import multiprocessing\n" "import threading\n" "def body():\n" " pass\n" "def boot():\n" " threading.Thread(target=body).start()\n" " multiprocessing.Process(target=body).start()\n", )lines 550–550db = _make_py_db(tmp_path, module="dual", root=tmp_path, rel="dual.py")lines 551–551extract_threads(db, tmp_path, None)lines 552–552rows = [(name, kind) for name, _entry, kind in _threads(db) if name == "body"]lines 553–553assert sorted(kind for _n, kind in rows) == ["process", "pthread"]

test_py_same_method_name_in_two_classes_resolves_distinctly

None test_python_ast.test_py_same_method_name_in_two_classes_resolves_distinctly(Path tmp_path)

THE FABRICATION GUARD. `Poller._run` and `Reader._run` share a bare name, and both are spawned via `target=self._run`. Each thread must resolve to its OWN class's rowid; collapsing them onto one rowid would invent a shared entry point. Measured motivation: `target=self._run` occurs 5 times in 5 unrelated classes in `a Python codebase`.

tests/test_python_ast.py:511

Show on the map →

Called by none

Calls _make_py_db, extract_threads

Checks

  • assert len(rows) == 2, f"expected both _run threads to resolve, got {rows}"
  • assert len(rowids) == 2, f"both _run threads collapsed onto one rowid: {rows}"
  • assert any("Poller._run" in d for d in definitions)
  • assert any("Reader._run" in d for d in definitions)

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-INDEX-002inferredtest_py_same_method_name_in_two_classes_resolves_distinctly → extract_threads → spawn_harvester → manifest_key → hash_file
REQ-DDB-PIPE-003measuredtest_py_same_method_name_in_two_classes_resolves_distinctly → extract_threads → spawn_harvester → manifest_key
REQ-DDB-PIPE-004measuredtest_py_same_method_name_in_two_classes_resolves_distinctly → extract_threads → _populate_membership → _bfs_live_set
REQ-DDB-PIPE-011measuredtest_py_same_method_name_in_two_classes_resolves_distinctly → _make_py_db → _parse → _ast_parse_one_file → _parseable_file
REQ-DDB-PIPE-012inferredtest_py_same_method_name_in_two_classes_resolves_distinctly → _make_py_db → _parse → _ast_parse_one_file → _ts_language_for → _grammar_available → has_language
REQ-DDB-QUERY-003measuredtest_py_same_method_name_in_two_classes_resolves_distinctly → extract_threads → _definition_preferring_name_index
REQ-DDB-QUERY-011measuredtest_py_same_method_name_in_two_classes_resolves_distinctly → extract_threads → _ensure_threads_tables
REQ-DDB-SCHEMA-001measuredtest_py_same_method_name_in_two_classes_resolves_distinctly → extract_threads
REQ-DDB-SCHEMA-007measuredtest_py_same_method_name_in_two_classes_resolves_distinctly → extract_threads → _ensure_threads_tables
REQ-DDB-SCHEMA-012measuredtest_py_same_method_name_in_two_classes_resolves_distinctly → extract_threads → spawn_harvester → load_thread_patterns → declaration_origin
Source · 23 lines
def test_py_same_method_name_in_two_classes_resolves_distinctly(tmp_path: Path) -> None:
    """THE FABRICATION GUARD. `Poller._run` and `Reader._run` share a bare name,
    and both are spawned via `target=self._run`. Each thread must resolve to its
    OWN class's rowid; collapsing them onto one rowid would invent a shared entry
    point. Measured motivation: `target=self._run` occurs 5 times in 5 unrelated
    classes in `a Python codebase`."""
    db = _make_py_db(tmp_path)
    extract_threads(db, FIXTURE_ROOT, None)
    conn = sqlite3.connect(str(db))
    rows = conn.execute(
        "SELECT t.name, t.entry_memberdef_rowid, m.definition FROM threads t "
        "JOIN memberdef m ON m.rowid = t.entry_memberdef_rowid WHERE m.name='_run' "
        "ORDER BY t.name",
    ).fetchall()
    conn.close()
    assert len(rows) == 2, f"expected both _run threads to resolve, got {rows}"
    rowids = {r[1] for r in rows}
    assert len(rowids) == 2, f"both _run threads collapsed onto one rowid: {rows}"
    definitions = {r[2] for r in rows}
    assert any("Poller._run" in d for d in definitions)
    assert any("Reader._run" in d for d in definitions)

Activity · 11 steps
lines 517–517db = _make_py_db(tmp_path)lines 518–518extract_threads(db, FIXTURE_ROOT, None)lines 519–519conn = sqlite3.connect(str(db))lines 520–524rows = conn.execute( "SELECT t.name, t.entry_memberdef_rowid, m.definition FROM threads t " "JOIN memberdef m ON m.rowid = t.entry_memberdef_rowid WHERE m.name='_run' " "ORDER BY t.name", ).fetchall()lines 525–525conn.close()lines 526–526assert len(rows) == 2, f"expected both _run threads to resolve, got {rows}"lines 527–527rowids = {r[1] for r in rows}lines 528–528assert len(rowids) == 2, f"both _run threads collapsed onto one rowid: {rows}"lines 529–529definitions = {r[2] for r in rows}lines 530–530assert any("Poller._run" in d for d in definitions)lines 531–531assert any("Reader._run" in d for d in definitions)

test_py_shared_key_walk_is_empty_without_a_declaration

None test_python_ast.test_py_shared_key_walk_is_empty_without_a_declaration(Path tmp_path)

With no declared convention the Python walk must produce nothing, however many `publish`/`subscribe` calls the file contains.

tests/test_python_ast.py:802

Show on the map →

Called by none

Calls _walk_shared_key_calls, resolve_shared_key_patterns

Checks

  • assert out == {"w": [], "r": [], "u": []}

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-CONFIG-006measuredtest_py_shared_key_walk_is_empty_without_a_declaration → resolve_shared_key_patterns
REQ-DDB-PIPE-003measuredtest_py_shared_key_walk_is_empty_without_a_declaration → _walk_shared_key_calls → is_python_tree
REQ-DDB-PIPE-011measured
REQ-DDB-SCHEMA-005measuredtest_py_shared_key_walk_is_empty_without_a_declaration → resolve_shared_key_patterns
REQ-DDB-SCHEMA-012inferredtest_py_shared_key_walk_is_empty_without_a_declaration → resolve_shared_key_patterns → load_shared_key_patterns → declaration_origin
Source · 12 lines
def test_py_shared_key_walk_is_empty_without_a_declaration(tmp_path: Path) -> None:
    """With no declared convention the Python walk must produce nothing, however
    many `publish`/`subscribe` calls the file contains."""
    src = tmp_path / "bus.py"
    src.write_text("def f(bus):\n    bus.publish(Topic.ALPHA, 1)\n    bus.subscribe(cb)\n")
    tree, data = _parse(tmp_path, "bus.py")
    writers, readers, aliases = resolve_shared_key_patterns(None)
    out = _walk_shared_key_calls(tree, data, _SharedKeyPatterns(writers, readers, aliases))
    assert out == {"w": [], "r": [], "u": []}


@pytest.mark.parametrize("kind", ["process", "coroutine"])

test_py_single_call_lambda_entry_resolves

None test_python_ast.test_py_single_call_lambda_entry_resolves(Path tmp_path)

`target=lambda: helper()` — a lambda body with exactly one call resolves to that callee, matching the C++ layer's rule.

tests/test_python_ast.py:567

Show on the map →

Called by none

Calls _make_py_db, _threads, extract_threads

Checks

  • assert entries.get("helper") == "helper"

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-INDEX-002inferredtest_py_single_call_lambda_entry_resolves → extract_threads → spawn_harvester → manifest_key → hash_file
REQ-DDB-PIPE-003measuredtest_py_single_call_lambda_entry_resolves → extract_threads → spawn_harvester → manifest_key
REQ-DDB-PIPE-004measuredtest_py_single_call_lambda_entry_resolves → extract_threads → _populate_membership → _bfs_live_set
REQ-DDB-PIPE-011measuredtest_py_single_call_lambda_entry_resolves → _make_py_db → _parse → _ast_parse_one_file → _parseable_file
REQ-DDB-PIPE-012inferredtest_py_single_call_lambda_entry_resolves → _make_py_db → _parse → _ast_parse_one_file → _ts_language_for → _grammar_available → has_language
REQ-DDB-QUERY-003measuredtest_py_single_call_lambda_entry_resolves → extract_threads → _definition_preferring_name_index
REQ-DDB-QUERY-011measuredtest_py_single_call_lambda_entry_resolves → extract_threads → _ensure_threads_tables
REQ-DDB-SCHEMA-001measuredtest_py_single_call_lambda_entry_resolves → extract_threads
REQ-DDB-SCHEMA-007measuredtest_py_single_call_lambda_entry_resolves → extract_threads → _ensure_threads_tables
REQ-DDB-SCHEMA-012measuredtest_py_single_call_lambda_entry_resolves → extract_threads → spawn_harvester → load_thread_patterns → declaration_origin
Source · 9 lines
def test_py_single_call_lambda_entry_resolves(tmp_path: Path) -> None:
    """`target=lambda: helper()` — a lambda body with exactly one call resolves
    to that callee, matching the C++ layer's rule."""
    db = _make_py_db(tmp_path)
    extract_threads(db, FIXTURE_ROOT, None)
    entries = {name: entry for name, entry, _kind in _threads(db)}
    assert entries.get("helper") == "helper"

Activity · 4 steps
lines 570–570db = _make_py_db(tmp_path)lines 571–571extract_threads(db, FIXTURE_ROOT, None)lines 572–572entries = {name: entry for name, entry, _kind in _threads(db)}lines 573–573assert entries.get("helper") == "helper"

test_py_spawn_kinds_map_each_primitive_honestly

None test_python_ast.test_py_spawn_kinds_map_each_primitive_honestly(Path tmp_path)

The kind column is what a consumer reads to decide whether two functions can race, so each primitive must carry its real execution context: a thread is 'pthread', a Process is 'process' (separate address space), a task is 'coroutine' (same OS thread), a pool submission is 'task'.

tests/test_python_ast.py:477

Show on the map →

Called by none

Calls _make_py_db, _threads, extract_threads

Checks

  • assert kinds.get("worker") == "pthread" # Thread(target=worker) — bare import
  • assert "process" in kinds.values()
  • assert "coroutine" in kinds.values()
  • assert "task" in kinds.values()

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-INDEX-002inferredtest_py_spawn_kinds_map_each_primitive_honestly → extract_threads → spawn_harvester → manifest_key → hash_file
REQ-DDB-PIPE-003measuredtest_py_spawn_kinds_map_each_primitive_honestly → extract_threads → spawn_harvester → manifest_key
REQ-DDB-PIPE-004measuredtest_py_spawn_kinds_map_each_primitive_honestly → extract_threads → _populate_membership → _bfs_live_set
REQ-DDB-PIPE-011measuredtest_py_spawn_kinds_map_each_primitive_honestly → _make_py_db → _parse → _ast_parse_one_file → _parseable_file
REQ-DDB-PIPE-012inferredtest_py_spawn_kinds_map_each_primitive_honestly → _make_py_db → _parse → _ast_parse_one_file → _ts_language_for → _grammar_available → has_language
REQ-DDB-QUERY-003measuredtest_py_spawn_kinds_map_each_primitive_honestly → extract_threads → _definition_preferring_name_index
REQ-DDB-QUERY-011measuredtest_py_spawn_kinds_map_each_primitive_honestly → extract_threads → _ensure_threads_tables
REQ-DDB-SCHEMA-001measuredtest_py_spawn_kinds_map_each_primitive_honestly → extract_threads
REQ-DDB-SCHEMA-007measuredtest_py_spawn_kinds_map_each_primitive_honestly → extract_threads → _ensure_threads_tables
REQ-DDB-SCHEMA-012measuredtest_py_spawn_kinds_map_each_primitive_honestly → extract_threads → spawn_harvester → load_thread_patterns → declaration_origin
Source · 14 lines
def test_py_spawn_kinds_map_each_primitive_honestly(tmp_path: Path) -> None:
    """The kind column is what a consumer reads to decide whether two functions
    can race, so each primitive must carry its real execution context: a thread
    is 'pthread', a Process is 'process' (separate address space), a task is
    'coroutine' (same OS thread), a pool submission is 'task'."""
    db = _make_py_db(tmp_path)
    extract_threads(db, FIXTURE_ROOT, None)
    kinds = {name: kind for name, _entry, kind in _threads(db)}
    assert kinds.get("worker") == "pthread"  # Thread(target=worker) — bare import
    assert "process" in kinds.values()
    assert "coroutine" in kinds.values()
    assert "task" in kinds.values()

Activity · 7 steps
lines 482–482db = _make_py_db(tmp_path)lines 483–483extract_threads(db, FIXTURE_ROOT, None)lines 484–484kinds = {name: kind for name, _entry, kind in _threads(db)}lines 485–485assert kinds.get("worker") == "pthread"lines 486–486assert "process" in kinds.values()lines 487–487assert "coroutine" in kinds.values()lines 488–488assert "task" in kinds.values()

test_py_thread_keyword_target_resolves_entry_rowid

None test_python_ast.test_py_thread_keyword_target_resolves_entry_rowid(Path tmp_path)

`target=` is a KEYWORD argument in essentially all real Python (all 40 measured sites), so the keyword path — not the positional index — is what must resolve the entry to a rowid.

tests/test_python_ast.py:491

Show on the map →

Called by none

Calls _make_py_db, _threads, extract_threads

Checks

  • assert entries.get("worker") == "worker", "keyword target= did not resolve"

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-INDEX-002inferredtest_py_thread_keyword_target_resolves_entry_rowid → extract_threads → spawn_harvester → manifest_key → hash_file
REQ-DDB-PIPE-003measuredtest_py_thread_keyword_target_resolves_entry_rowid → extract_threads → spawn_harvester → manifest_key
REQ-DDB-PIPE-004measuredtest_py_thread_keyword_target_resolves_entry_rowid → extract_threads → _populate_membership → _bfs_live_set
REQ-DDB-PIPE-011measuredtest_py_thread_keyword_target_resolves_entry_rowid → _make_py_db → _parse → _ast_parse_one_file → _parseable_file
REQ-DDB-PIPE-012inferredtest_py_thread_keyword_target_resolves_entry_rowid → _make_py_db → _parse → _ast_parse_one_file → _ts_language_for → _grammar_available → has_language
REQ-DDB-QUERY-003measuredtest_py_thread_keyword_target_resolves_entry_rowid → extract_threads → _definition_preferring_name_index
REQ-DDB-QUERY-011measuredtest_py_thread_keyword_target_resolves_entry_rowid → extract_threads → _ensure_threads_tables
REQ-DDB-SCHEMA-001measuredtest_py_thread_keyword_target_resolves_entry_rowid → extract_threads
REQ-DDB-SCHEMA-007measuredtest_py_thread_keyword_target_resolves_entry_rowid → extract_threads → _ensure_threads_tables
REQ-DDB-SCHEMA-012measuredtest_py_thread_keyword_target_resolves_entry_rowid → extract_threads → spawn_harvester → load_thread_patterns → declaration_origin
Source · 10 lines
def test_py_thread_keyword_target_resolves_entry_rowid(tmp_path: Path) -> None:
    """`target=` is a KEYWORD argument in essentially all real Python (all 40
    measured sites), so the keyword path — not the positional index — is what
    must resolve the entry to a rowid."""
    db = _make_py_db(tmp_path)
    extract_threads(db, FIXTURE_ROOT, None)
    entries = {name: entry for name, entry, _kind in _threads(db)}
    assert entries.get("worker") == "worker", "keyword target= did not resolve"

Activity · 4 steps
lines 495–495db = _make_py_db(tmp_path)lines 496–496extract_threads(db, FIXTURE_ROOT, None)lines 497–497entries = {name: entry for name, entry, _kind in _threads(db)}lines 498–498assert entries.get("worker") == "worker", "keyword target= did not resolve"

test_py_thread_membership_is_populated

None test_python_ast.test_py_thread_membership_is_populated(Path tmp_path)

A resolved entry must produce a call-closure membership, so the thread layer is queryable and not merely present.

tests/test_python_ast.py:604

Show on the map →

Called by none

Calls _make_py_db, extract_threads, import_ast_call_edges

Checks

  • assert count > 0

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-INDEX-002inferredtest_py_thread_membership_is_populated → extract_threads → spawn_harvester → manifest_key → hash_file
REQ-DDB-PIPE-003measuredtest_py_thread_membership_is_populated → import_ast_call_edges → run_harvest
REQ-DDB-PIPE-004measuredtest_py_thread_membership_is_populated → extract_threads → _populate_membership → _bfs_live_set
REQ-DDB-PIPE-011measuredtest_py_thread_membership_is_populated → _make_py_db → _parse → _ast_parse_one_file → _parseable_file
REQ-DDB-PIPE-012inferredtest_py_thread_membership_is_populated → _make_py_db → _parse → _ast_parse_one_file → _ts_language_for → _grammar_available → has_language
REQ-DDB-QUERY-003measuredtest_py_thread_membership_is_populated → extract_threads → _definition_preferring_name_index
REQ-DDB-QUERY-011measuredtest_py_thread_membership_is_populated → extract_threads → _ensure_threads_tables
REQ-DDB-SCHEMA-001measuredtest_py_thread_membership_is_populated → extract_threads
REQ-DDB-SCHEMA-007measuredtest_py_thread_membership_is_populated → extract_threads → _ensure_threads_tables
REQ-DDB-SCHEMA-012measuredtest_py_thread_membership_is_populated → extract_threads → spawn_harvester → load_thread_patterns → declaration_origin
REQ-DDB-WIKI-054inferredtest_py_thread_membership_is_populated → import_ast_call_edges → _fold_all_files → _fold_call_payload → _ast_record_call_edge → _narrow_by_receiver → _one_class → all
Source · 15 lines
def test_py_thread_membership_is_populated(tmp_path: Path) -> None:
    """A resolved entry must produce a call-closure membership, so the thread
    layer is queryable and not merely present."""
    db = _make_py_db(tmp_path)
    import_ast_call_edges(db, FIXTURE_ROOT)
    extract_threads(db, FIXTURE_ROOT, None)
    conn = sqlite3.connect(str(db))
    count = conn.execute("SELECT COUNT(*) FROM thread_membership").fetchone()[0]
    conn.close()
    assert count > 0


# ─── reachability seeds ─────────────────────────────────────────────────────

Activity · 7 steps
lines 607–607db = _make_py_db(tmp_path)lines 608–608import_ast_call_edges(db, FIXTURE_ROOT)lines 609–609extract_threads(db, FIXTURE_ROOT, None)lines 610–610conn = sqlite3.connect(str(db))lines 611–611count = conn.execute("SELECT COUNT(*) FROM thread_membership").fetchone()[0]lines 612–612conn.close()lines 613–613assert count > 0

test_py_thread_name_literal_wins_over_qualified_entry

None test_python_ast.test_py_thread_name_literal_wins_over_qualified_entry(Path tmp_path)

`name="poller"` is the author's own label and must become the thread's name; a spawn with no literal falls back to the qualified entry.

tests/test_python_ast.py:501

Show on the map →

Called by none

Calls _make_py_db, _threads, extract_threads

Checks

  • assert "poller" in names # Poller.start passes name="poller"
  • assert "Reader._run" in names # Reader.start passes no name

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-INDEX-002inferredtest_py_thread_name_literal_wins_over_qualified_entry → extract_threads → spawn_harvester → manifest_key → hash_file
REQ-DDB-PIPE-003measuredtest_py_thread_name_literal_wins_over_qualified_entry → extract_threads → spawn_harvester → manifest_key
REQ-DDB-PIPE-004measuredtest_py_thread_name_literal_wins_over_qualified_entry → extract_threads → _populate_membership → _bfs_live_set
REQ-DDB-PIPE-011measuredtest_py_thread_name_literal_wins_over_qualified_entry → _make_py_db → _parse → _ast_parse_one_file → _parseable_file
REQ-DDB-PIPE-012inferredtest_py_thread_name_literal_wins_over_qualified_entry → _make_py_db → _parse → _ast_parse_one_file → _ts_language_for → _grammar_available → has_language
REQ-DDB-QUERY-003measuredtest_py_thread_name_literal_wins_over_qualified_entry → extract_threads → _definition_preferring_name_index
REQ-DDB-QUERY-011measuredtest_py_thread_name_literal_wins_over_qualified_entry → extract_threads → _ensure_threads_tables
REQ-DDB-SCHEMA-001measuredtest_py_thread_name_literal_wins_over_qualified_entry → extract_threads
REQ-DDB-SCHEMA-007measuredtest_py_thread_name_literal_wins_over_qualified_entry → extract_threads → _ensure_threads_tables
REQ-DDB-SCHEMA-012measuredtest_py_thread_name_literal_wins_over_qualified_entry → extract_threads → spawn_harvester → load_thread_patterns → declaration_origin
Source · 10 lines
def test_py_thread_name_literal_wins_over_qualified_entry(tmp_path: Path) -> None:
    """`name="poller"` is the author's own label and must become the thread's
    name; a spawn with no literal falls back to the qualified entry."""
    db = _make_py_db(tmp_path)
    extract_threads(db, FIXTURE_ROOT, None)
    names = {name for name, _entry, _kind in _threads(db)}
    assert "poller" in names  # Poller.start passes name="poller"
    assert "Reader._run" in names  # Reader.start passes no name

Activity · 5 steps
lines 504–504db = _make_py_db(tmp_path)lines 505–505extract_threads(db, FIXTURE_ROOT, None)lines 506–506names = {name for name, _entry, _kind in _threads(db)}lines 507–507assert "poller" in nameslines 508–508assert "Reader._run" in names

test_python_call_edges_land_in_db

None test_python_ast.test_python_call_edges_land_in_db(Path tmp_path)

End-to-end: the Python harvest must actually produce `call_edges` rows, the layer that measured exactly ZERO before this change.

tests/test_python_ast.py:431

Show on the map →

Called by none

Calls _make_py_db, import_ast_call_edges

Checks

  • assert sources.get("ast", 0) > 0, "no plain-identifier Python call edges"
  • assert sum(sources.values()) > 0

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-PIPE-003measuredtest_python_call_edges_land_in_db → import_ast_call_edges → run_harvest
REQ-DDB-PIPE-011measuredtest_python_call_edges_land_in_db → _make_py_db → _parse → _ast_parse_one_file → _parseable_file
REQ-DDB-PIPE-012inferredtest_python_call_edges_land_in_db → _make_py_db → _parse → _ast_parse_one_file → _ts_language_for → _grammar_available → has_language
REQ-DDB-WIKI-054inferredtest_python_call_edges_land_in_db → import_ast_call_edges → _fold_all_files → _fold_call_payload → _ast_record_call_edge → _narrow_by_receiver → _one_class → all
Source · 15 lines
def test_python_call_edges_land_in_db(tmp_path: Path) -> None:
    """End-to-end: the Python harvest must actually produce `call_edges` rows,
    the layer that measured exactly ZERO before this change."""
    db = _make_py_db(tmp_path)
    import_ast_call_edges(db, FIXTURE_ROOT)
    conn = sqlite3.connect(str(db))
    rows = conn.execute(
        "SELECT source, COUNT(*) FROM call_edges GROUP BY source ORDER BY source",
    ).fetchall()
    conn.close()
    sources = dict(rows)
    assert sources.get("ast", 0) > 0, "no plain-identifier Python call edges"
    assert sum(sources.values()) > 0

Activity · 8 steps
lines 434–434db = _make_py_db(tmp_path)lines 435–435import_ast_call_edges(db, FIXTURE_ROOT)lines 436–436conn = sqlite3.connect(str(db))lines 437–439rows = conn.execute( "SELECT source, COUNT(*) FROM call_edges GROUP BY source ORDER BY source", ).fetchall()lines 440–440conn.close()lines 441–441sources = dict(rows)lines 442–442assert sources.get("ast", 0) > 0, "no plain-identifier Python call edges"lines 443–443assert sum(sources.values()) > 0

test_python_call_provenance_splits_plain_and_attribute

None test_python_ast.test_python_call_provenance_splits_plain_and_attribute()

A bare-identifier callee is `ast`; an attribute-qualified one is `ast_member`, REUSING the C++ tags because it is the same fact — the callee was reduced to its unqualified tail, which may match several classes.

tests/test_python_ast.py:398

Show on the map →

Called by none

Calls _ast_harvest_calls

Checks

  • assert ("helper", "ast") in by_name
  • assert ("worker", "ast") in by_name
  • assert ("Thread", "ast_member") in by_name
  • assert ("start", "ast_member") in by_name
  • assert ("worker", "binding") in by_name
  • assert {s[2] for s in sites} <= {"ast", "ast_member", "binding"}

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-PIPE-003measuredtest_python_call_provenance_splits_plain_and_attribute → _ast_harvest_calls → is_python_tree
REQ-DDB-PIPE-011measured
Source · 23 lines
def test_python_call_provenance_splits_plain_and_attribute() -> None:
    """A bare-identifier callee is `ast`; an attribute-qualified one is
    `ast_member`, REUSING the C++ tags because it is the same fact — the callee
    was reduced to its unqualified tail, which may match several classes.

    The closed-world bound at the end is the point of the test: a THIRD provenance
    reaching this harvest must be a deliberate act. `binding` (gh#1) is the third,
    and it is pinned by name below so widening the bound cannot silently re-admit a
    stray tag."""
    tree, src = _parse(FIXTURE_ROOT, FIXTURE_REL)
    sites = _ast_harvest_calls(tree, src)
    by_name = {(s[0], s[2]) for s in sites}
    # `worker()` inside a lambda / `helper()` — bare identifiers.
    assert ("helper", "ast") in by_name
    assert ("worker", "ast") in by_name
    # `threading.Thread(...)` and `.start()` — attribute-qualified tails.
    assert ("Thread", "ast_member") in by_name
    assert ("start", "ast_member") in by_name
    # The fixture's `threading.Thread(target=worker)` BINDS `worker` (gh#1).
    assert ("worker", "binding") in by_name
    assert {s[2] for s in sites} <= {"ast", "ast_member", "binding"}

Activity · 9 steps
lines 407–407tree, src = _parse(FIXTURE_ROOT, FIXTURE_REL)lines 408–408sites = _ast_harvest_calls(tree, src)lines 409–409by_name = {(s[0], s[2]) for s in sites}lines 411–411assert ("helper", "ast") in by_namelines 412–412assert ("worker", "ast") in by_namelines 414–414assert ("Thread", "ast_member") in by_namelines 415–415assert ("start", "ast_member") in by_namelines 417–417assert ("worker", "binding") in by_namelines 418–418assert {s[2] for s in sites} <= {"ast", "ast_member", "binding"}

test_python_comprehension_and_decorator_calls_are_reached

None test_python_ast.test_python_comprehension_and_decorator_calls_are_reached(Path tmp_path)

Comprehension bodies and decorator invocations need no special case — each is a `call` node — but that must be verified rather than assumed.

tests/test_python_ast.py:446

Show on the map →

Called by none

Calls _ast_harvest_calls

Checks

  • assert "inner" in names # comprehension body
  • assert "range" in names
  • assert "register" in names # decorator call, attribute-qualified

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-PIPE-003measuredtest_python_comprehension_and_decorator_calls_are_reached → _ast_harvest_calls → is_python_tree
REQ-DDB-PIPE-011measured
Source · 22 lines
def test_python_comprehension_and_decorator_calls_are_reached(tmp_path: Path) -> None:
    """Comprehension bodies and decorator invocations need no special case — each
    is a `call` node — but that must be verified rather than assumed."""
    src = tmp_path / "b.py"
    src.write_text(
        "def outer():\n"
        "    xs = [inner(i) for i in range(3)]\n"
        "    return xs\n"
        "@registry.register('x')\n"
        "def handler():\n"
        "    pass\n",
    )
    tree, data = _parse(tmp_path, "b.py")
    names = {s[0] for s in _ast_harvest_calls(tree, data)}
    assert "inner" in names  # comprehension body
    assert "range" in names
    assert "register" in names  # decorator call, attribute-qualified


# ─── thread spawns ──────────────────────────────────────────────────────────

Activity · 7 steps
lines 449–449src = tmp_path / "b.py"lines 450–457src.write_text( "def outer():\n" " xs = [inner(i) for i in range(3)]\n" " return xs\n" "@registry.register('x')\n" "def handler():\n" " pass\n", )lines 458–458tree, data = _parse(tmp_path, "b.py")lines 459–459names = {s[0] for s in _ast_harvest_calls(tree, data)}lines 460–460assert "inner" in nameslines 461–461assert "range" in nameslines 462–462assert "register" in names

test_python_entry_seeds_empty_for_a_c_repo

None test_python_ast.test_python_entry_seeds_empty_for_a_c_repo(Path tmp_path)

A C/C++ codebase has no pyproject.toml and no Python files, so the seed set must be empty and the C seed set bit-identical to before.

tests/test_python_ast.py:737

Checks

  • assert python_entry_seeds(db, CSAMPLE_ROOT) == set()

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-PIPE-003measuredtest_python_entry_seeds_empty_for_a_c_repo → python_entry_seeds → run_harvest
REQ-DDB-PIPE-004measuredtest_python_entry_seeds_empty_for_a_c_repo → python_entry_seeds
REQ-DDB-PIPE-011measuredtest_python_entry_seeds_empty_for_a_c_repo → python_entry_seeds → run_harvest → _harvest_one_file → _parseable_file
REQ-DDB-PIPE-012inferredtest_python_entry_seeds_empty_for_a_c_repo → python_entry_seeds → run_harvest → _harvest_one_file → _ts_language_for → _grammar_available → has_language
Source · 27 lines
def test_python_entry_seeds_empty_for_a_c_repo(tmp_path: Path) -> None:
    """A C/C++ codebase has no pyproject.toml and no Python files, so the seed set
    must be empty and the C seed set bit-identical to before."""
    db = tmp_path / "clew.db"
    conn = sqlite3.connect(str(db))
    conn.executescript(
        """
        CREATE TABLE path (name TEXT);
        CREATE TABLE memberdef (
            rowid INTEGER PRIMARY KEY, kind TEXT, name TEXT, definition TEXT,
            file_id INTEGER, bodyfile_id INTEGER, bodystart INTEGER, bodyend INTEGER
        );
        """,
    )
    conn.execute("INSERT INTO path (rowid, name) VALUES (1, 'src/main.c')")
    conn.execute(
        "INSERT INTO memberdef (rowid, kind, name, definition, file_id, bodyfile_id, "
        "bodystart, bodyend) VALUES (1, 'function', 'main', 'int main()', 1, 1, 1, 3)",
    )
    conn.commit()
    conn.close()
    assert python_entry_seeds(db, CSAMPLE_ROOT) == set()


# ─── shared-key dataflow ────────────────────────────────────────────────────

Activity · 8 steps
lines 740–740db = tmp_path / "clew.db"lines 741–741conn = sqlite3.connect(str(db))lines 742–750conn.executescript( """ CREATE TABLE path (name TEXT); CREATE TABLE memberdef ( rowid INTEGER PRIMARY KEY, kind TEXT, name TEXT, definition TEXT, file_id INTEGER, bodyfile_id INTEGER, bodystart INTEGER, bodyend INTEGER ); """, )lines 751–751conn.execute("INSERT INTO path (rowid, name) VALUES (1, 'src/main.c')")lines 752–755conn.execute( "INSERT INTO memberdef (rowid, kind, name, definition, file_id, bodyfile_id, " "bodystart, bodyend) VALUES (1, 'function', 'main', 'int main()', 1, 1, 1, 3)", )lines 756–756conn.commit()lines 757–757conn.close()lines 758–758assert python_entry_seeds(db, CSAMPLE_ROOT) == set()

test_python_self_qualified_call_is_member_provenance

None test_python_ast.test_python_self_qualified_call_is_member_provenance()

`self.method()` is the Python analogue of C++'s `obj.method()`; its tail is what `memberdef.name` stores, so it must be recorded as `ast_member`.

tests/test_python_ast.py:421

Show on the map →

Called by none

Calls _ast_harvest_calls, all

Checks

  • assert starts, "expected `.start()` call sites in the fixture"
  • assert all(s[2] == "ast_member" for s in starts)

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-PIPE-003measuredtest_python_self_qualified_call_is_member_provenance → _ast_harvest_calls → is_python_tree
REQ-DDB-PIPE-011measured
REQ-DDB-WIKI-054inferredtest_python_self_qualified_call_is_member_provenance → all
Source · 10 lines
def test_python_self_qualified_call_is_member_provenance() -> None:
    """`self.method()` is the Python analogue of C++'s `obj.method()`; its tail
    is what `memberdef.name` stores, so it must be recorded as `ast_member`."""
    tree, src = _parse(FIXTURE_ROOT, FIXTURE_REL)
    sites = _ast_harvest_calls(tree, src)
    starts = [s for s in sites if s[0] == "start"]
    assert starts, "expected `.start()` call sites in the fixture"
    assert all(s[2] == "ast_member" for s in starts)

Activity · 5 steps
lines 424–424tree, src = _parse(FIXTURE_ROOT, FIXTURE_REL)lines 425–425sites = _ast_harvest_calls(tree, src)lines 426–426starts = [s for s in sites if s[0] == "start"]lines 427–427assert starts, "expected `.start()` call sites in the fixture"lines 428–428assert all(s[2] == "ast_member" for s in starts)

test_string_value_reads_content_not_quotes

None test_python_ast.test_string_value_reads_content_not_quotes(Path tmp_path)

Python strings carry their quotes in the node text and vary in style, so the C path's `strip('"')` would leave quotes on a single-quoted literal. An interpolated f-string is refused rather than recorded as a key.

tests/test_python_ast.py:363

Show on the map →

Called by none

Calls _walk_nodes, string_value

Checks

  • assert "single" in values
  • assert "double" in values
  • assert None in values # the interpolated f-string

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-PIPE-003measuredtest_string_value_reads_content_not_quotes → string_value
REQ-DDB-PIPE-011measured
Source · 13 lines
def test_string_value_reads_content_not_quotes(tmp_path: Path) -> None:
    """Python strings carry their quotes in the node text and vary in style, so
    the C path's `strip('"')` would leave quotes on a single-quoted literal. An
    interpolated f-string is refused rather than recorded as a key."""
    src = tmp_path / "b.py"
    src.write_text("a = 'single'\nb = \"double\"\nc = f'x{a}y'\n")
    tree, data = _parse(tmp_path, "b.py")
    values = [string_value(n, data) for n in _walk_nodes(tree) if n.type == "string"]
    assert "single" in values
    assert "double" in values
    assert None in values  # the interpolated f-string

Activity · 7 steps
lines 367–367src = tmp_path / "b.py"lines 368–368src.write_text("a = 'single'\nb = \"double\"\nc = f'x{a}y'\n")lines 369–369tree, data = _parse(tmp_path, "b.py")lines 370–370values = [string_value(n, data) for n in _walk_nodes(tree) if n.type == "string"]lines 371–371assert "single" in valueslines 372–372assert "double" in valueslines 373–373assert None in values

test_ts_language_for_routes_python

None test_python_ast.test_ts_language_for_routes_python()

Python now routes to a grammar. This REPLACES the previous assertion that `.py` returned None: that was a statement of the C/C++-only limitation task

tests/test_python_ast.py:196

Checks

  • assert _ts_language_for("dir/file.py") is not None
  • assert _ts_language_for("dir/stub.pyi") is not None
  • assert _ts_language_for("dir/file.c") is not None
  • assert _ts_language_for("dir/file.cpp") is not None
  • assert _ts_language_for("dir/file.rs") is not None
  • assert _ts_language_for("foo.txt") is None

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-PIPE-012inferredtest_ts_language_for_routes_python → _ts_language_for → _grammar_available → has_language
Source · 15 lines
def test_ts_language_for_routes_python() -> None:
    """Python now routes to a grammar. This REPLACES the previous assertion that
    `.py` returned None: that was a statement of the C/C++-only limitation task
    #58 exists to remove, not a behaviour to preserve. C/C++ routing is asserted
    alongside it so the addition is visibly additive. `.rs` now routes too
    (Rust support) — see tests/test_rust_ast.py for its own routing/dialect
    tests, pinned separately the way Python's are."""
    assert _ts_language_for("dir/file.py") is not None
    assert _ts_language_for("dir/stub.pyi") is not None
    assert _ts_language_for("dir/file.c") is not None
    assert _ts_language_for("dir/file.cpp") is not None
    assert _ts_language_for("dir/file.rs") is not None
    assert _ts_language_for("foo.txt") is None

Activity · 6 steps
lines 203–203assert _ts_language_for("dir/file.py") is not Nonelines 204–204assert _ts_language_for("dir/stub.pyi") is not Nonelines 205–205assert _ts_language_for("dir/file.c") is not Nonelines 206–206assert _ts_language_for("dir/file.cpp") is not Nonelines 207–207assert _ts_language_for("dir/file.rs") is not Nonelines 208–208assert _ts_language_for("foo.txt") is None