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.
Called by none
Calls _walk_spawn_sites, collect_bindings, load_thread_patterns, patterns_by_name
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
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-PIPE-003 | measured | test_an_aliased_thread_entry_is_resolved_through_the_import_map → collect_bindings |
| REQ-DDB-PIPE-011 | measured | |
| REQ-DDB-SCHEMA-001 | measured | test_an_aliased_thread_entry_is_resolved_through_the_import_map → load_thread_patterns |
| REQ-DDB-SCHEMA-012 | inferred | test_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
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.
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
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-PIPE-003 | measured | test_bindings_bind_receiver_only_from_resolvable_constructor → collect_bindings |
| REQ-DDB-PIPE-011 | measured |
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
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.
Checks
assert bindings.resolve("Thread") == ".models.Thread"assert bindings.resolve("Thread") != "threading.Thread"assert bindings.resolve("SomethingLocal") is None
Result: passed
Verifies
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-PIPE-003 | measured | test_bindings_refuse_unbound_and_foreign_names → collect_bindings |
| REQ-DDB-PIPE-011 | measured |
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
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.
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
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-PIPE-003 | measured | test_bindings_resolve_module_alias_and_from_import → collect_bindings |
| REQ-DDB-PIPE-011 | measured |
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
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.
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
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-PIPE-003 | measured | test_c_harvest_output_unchanged_on_the_c_fixture → _walk_spawn_sites → is_python_tree |
| REQ-DDB-PIPE-011 | measured | test_c_harvest_output_unchanged_on_the_c_fixture → _ast_parse_one_file → _parseable_file |
| REQ-DDB-PIPE-012 | inferred | test_c_harvest_output_unchanged_on_the_c_fixture → _ast_parse_one_file → _ts_language_for → _grammar_available → has_language |
| REQ-DDB-SCHEMA-001 | measured | test_c_harvest_output_unchanged_on_the_c_fixture → load_thread_patterns |
| REQ-DDB-SCHEMA-012 | inferred | test_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
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.
Checks
assert name in by_name, f"{name} lost from defaults"assert by_name["pthread_create"].entry_arg_index == 2assert by_name["xTaskCreate"].name_arg_index == 1assert by_name["pthread_create"].entry_kwarg is Noneassert by_name["threading.Thread"].entry_kwarg == "target"
Result: passed
Verifies
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-SCHEMA-001 | measured | test_c_spawn_defaults_still_present_and_unchanged → load_thread_patterns |
| REQ-DDB-SCHEMA-012 | inferred | test_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
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.
Checks
assert seeds == {1}, "console script resolved to the wrong same-named function"
Result: passed
Verifies
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-PIPE-003 | measured | test_console_script_seed_resolves_the_declared_module → python_entry_seeds → run_harvest |
| REQ-DDB-PIPE-004 | measured | test_console_script_seed_resolves_the_declared_module → python_entry_seeds |
| REQ-DDB-PIPE-011 | inferred | test_console_script_seed_resolves_the_declared_module → python_entry_seeds → run_harvest → _harvest_one_file → _parseable_file |
| REQ-DDB-PIPE-012 | inferred | test_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
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.
Checks
assert set(targets) == {"pkg.mod:main", "pkg.other:run"}assert console_script_targets(tmp_path / "nope") == []
Result: passed
Verifies
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-PIPE-004 | measured | test_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
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.
Checks
assert "h.i.j" in foundassert None in found # f().b / d['k'].e refused
Result: passed
Verifies
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-PIPE-003 | measured | test_dotted_name_refuses_non_static_chain → dotted_name |
| REQ-DDB-PIPE-011 | measured |
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
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.
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
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-PIPE-004 | measured | test_extra_seeds_rescue_a_self_loop_false_orphan → mark_reachability |
| REQ-DDB-SCHEMA-012 | measured |
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
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.
Checks
assert is_python_tree(py_tree) is Trueassert is_python_tree(c_tree) is False
Result: passed
Verifies
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-PIPE-003 | measured | test_is_python_tree_discriminates_by_root_type → is_python_tree |
| REQ-DDB-PIPE-011 | measured |
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
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.
Checks
assert harvest_main_guard_calls(tree, src) == ["guarded_main"]
Result: passed
Verifies
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-PIPE-003 | measured | test_main_guard_calls_are_harvested → harvest_main_guard_calls → _called_names → dotted_name |
| REQ-DDB-PIPE-004 | measured | test_main_guard_calls_are_harvested → harvest_main_guard_calls |
| REQ-DDB-PIPE-011 | measured |
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
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.
Checks
assert harvest_main_guard_calls(tree, data) == []
Result: passed
Verifies
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-PIPE-003 | inferred | test_main_guard_ignores_a_plain_if_and_a_mere_mention → harvest_main_guard_calls → _called_names → dotted_name |
| REQ-DDB-PIPE-004 | measured | test_main_guard_ignores_a_plain_if_and_a_mere_mention → harvest_main_guard_calls |
| REQ-DDB-PIPE-011 | measured |
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
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.
Checks
assert "guarded_main" in names
Result: passed
Verifies
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-PIPE-003 | measured | test_main_guard_seed_resolves_to_the_guarded_function → python_entry_seeds → run_harvest |
| REQ-DDB-PIPE-004 | measured | test_main_guard_seed_resolves_to_the_guarded_function → python_entry_seeds |
| REQ-DDB-PIPE-011 | measured | test_main_guard_seed_resolves_to_the_guarded_function → python_entry_seeds → run_harvest → _harvest_one_file → _parseable_file |
| REQ-DDB-PIPE-012 | inferred | test_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
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.
Checks
assert kind in THREAD_KINDassert THREAD_KIND.validated(kind, owner="test", field="kind") == kind
Result: passed
Verifies
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-SCHEMA-012 | measured |
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
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.
Checks
assert prefixes == {"DataModel_Set_", "DataModel_Get_"}
Result: passed
Verifies
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-CONFIG-006 | measured | test_no_builtin_python_accessor_default_exists → resolve_shared_key_patterns |
| REQ-DDB-SCHEMA-005 | measured | test_no_builtin_python_accessor_default_exists → resolve_shared_key_patterns |
| REQ-DDB-SCHEMA-012 | inferred | test_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
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.
Called by none
Calls _walk_nodes, dotted_name, keyword_argument, positional_argument
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 existassert dotted_name(keyword_argument(call, "kw"), data) == "c"assert keyword_argument(call, "absent") is None
Result: passed
Verifies
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-PIPE-003 | measured | test_positional_argument_skips_keyword_arguments → dotted_name |
| REQ-DDB-PIPE-011 | measured |
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
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.*`).
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
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-CONFIG-006 | measured | test_py_declared_accessors_pair_enum_keys → resolve_shared_key_patterns |
| REQ-DDB-PIPE-003 | measured | test_py_declared_accessors_pair_enum_keys → _walk_shared_key_calls → is_python_tree |
| REQ-DDB-PIPE-011 | measured | |
| REQ-DDB-SCHEMA-005 | measured | test_py_declared_accessors_pair_enum_keys → resolve_shared_key_patterns |
| REQ-DDB-SCHEMA-012 | measured | test_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
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.
Checks
assert [s[1] for s in sites] == ["entry"]assert [s[0] for s in sites] == ["w"]
Result: passed
Verifies
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-PIPE-003 | measured | test_py_declared_local_wrapper_matches_by_raw_name → _walk_spawn_sites → is_python_tree |
| REQ-DDB-PIPE-011 | measured | |
| REQ-DDB-SCHEMA-001 | measured | test_py_declared_local_wrapper_matches_by_raw_name → load_thread_patterns |
| REQ-DDB-SCHEMA-012 | measured | test_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
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.
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
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-INDEX-002 | inferred | test_py_lookalike_constructor_is_refused → extract_threads → spawn_harvester → manifest_key → hash_file |
| REQ-DDB-PIPE-003 | measured | test_py_lookalike_constructor_is_refused → extract_threads → spawn_harvester → manifest_key |
| REQ-DDB-PIPE-004 | measured | test_py_lookalike_constructor_is_refused → extract_threads → _populate_membership → _bfs_live_set |
| REQ-DDB-PIPE-011 | measured | test_py_lookalike_constructor_is_refused → _make_py_db → _parse → _ast_parse_one_file → _parseable_file |
| REQ-DDB-PIPE-012 | inferred | test_py_lookalike_constructor_is_refused → _make_py_db → _parse → _ast_parse_one_file → _ts_language_for → _grammar_available → has_language |
| REQ-DDB-QUERY-003 | measured | test_py_lookalike_constructor_is_refused → extract_threads → _definition_preferring_name_index |
| REQ-DDB-QUERY-011 | measured | test_py_lookalike_constructor_is_refused → extract_threads → _ensure_threads_tables |
| REQ-DDB-SCHEMA-001 | measured | test_py_lookalike_constructor_is_refused → extract_threads |
| REQ-DDB-SCHEMA-007 | measured | test_py_lookalike_constructor_is_refused → extract_threads → _ensure_threads_tables |
| REQ-DDB-SCHEMA-012 | measured | test_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
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.
Checks
assert "noop" not in entries, "a multi-call lambda produced a thread entry"
Result: passed
Verifies
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-PIPE-003 | measured | test_py_multicall_lambda_entry_fails_closed → _walk_spawn_sites → is_python_tree |
| REQ-DDB-PIPE-011 | measured | |
| REQ-DDB-SCHEMA-001 | measured | test_py_multicall_lambda_entry_fails_closed → load_thread_patterns |
| REQ-DDB-SCHEMA-012 | inferred | test_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
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.
Checks
assert sorted(kind for _n, kind in rows) == ["process", "pthread"]
Result: passed
Verifies
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-INDEX-002 | inferred | test_py_same_entry_through_two_primitives_stays_two_threads → extract_threads → spawn_harvester → manifest_key → hash_file |
| REQ-DDB-PIPE-003 | measured | test_py_same_entry_through_two_primitives_stays_two_threads → extract_threads → spawn_harvester → manifest_key |
| REQ-DDB-PIPE-004 | measured | test_py_same_entry_through_two_primitives_stays_two_threads → extract_threads → _populate_membership → _bfs_live_set |
| REQ-DDB-PIPE-011 | measured | test_py_same_entry_through_two_primitives_stays_two_threads → _make_py_db → _parse → _ast_parse_one_file → _parseable_file |
| REQ-DDB-PIPE-012 | inferred | test_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-003 | measured | test_py_same_entry_through_two_primitives_stays_two_threads → extract_threads → _definition_preferring_name_index |
| REQ-DDB-QUERY-011 | measured | test_py_same_entry_through_two_primitives_stays_two_threads → extract_threads → _ensure_threads_tables |
| REQ-DDB-SCHEMA-001 | measured | test_py_same_entry_through_two_primitives_stays_two_threads → extract_threads |
| REQ-DDB-SCHEMA-007 | measured | test_py_same_entry_through_two_primitives_stays_two_threads → extract_threads → _ensure_threads_tables |
| REQ-DDB-SCHEMA-012 | measured | test_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
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`.
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
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-INDEX-002 | inferred | test_py_same_method_name_in_two_classes_resolves_distinctly → extract_threads → spawn_harvester → manifest_key → hash_file |
| REQ-DDB-PIPE-003 | measured | test_py_same_method_name_in_two_classes_resolves_distinctly → extract_threads → spawn_harvester → manifest_key |
| REQ-DDB-PIPE-004 | measured | test_py_same_method_name_in_two_classes_resolves_distinctly → extract_threads → _populate_membership → _bfs_live_set |
| REQ-DDB-PIPE-011 | measured | test_py_same_method_name_in_two_classes_resolves_distinctly → _make_py_db → _parse → _ast_parse_one_file → _parseable_file |
| REQ-DDB-PIPE-012 | inferred | test_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-003 | measured | test_py_same_method_name_in_two_classes_resolves_distinctly → extract_threads → _definition_preferring_name_index |
| REQ-DDB-QUERY-011 | measured | test_py_same_method_name_in_two_classes_resolves_distinctly → extract_threads → _ensure_threads_tables |
| REQ-DDB-SCHEMA-001 | measured | test_py_same_method_name_in_two_classes_resolves_distinctly → extract_threads |
| REQ-DDB-SCHEMA-007 | measured | test_py_same_method_name_in_two_classes_resolves_distinctly → extract_threads → _ensure_threads_tables |
| REQ-DDB-SCHEMA-012 | measured | test_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
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.
Checks
assert entries.get("helper") == "helper"
Result: passed
Verifies
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-INDEX-002 | inferred | test_py_single_call_lambda_entry_resolves → extract_threads → spawn_harvester → manifest_key → hash_file |
| REQ-DDB-PIPE-003 | measured | test_py_single_call_lambda_entry_resolves → extract_threads → spawn_harvester → manifest_key |
| REQ-DDB-PIPE-004 | measured | test_py_single_call_lambda_entry_resolves → extract_threads → _populate_membership → _bfs_live_set |
| REQ-DDB-PIPE-011 | measured | test_py_single_call_lambda_entry_resolves → _make_py_db → _parse → _ast_parse_one_file → _parseable_file |
| REQ-DDB-PIPE-012 | inferred | test_py_single_call_lambda_entry_resolves → _make_py_db → _parse → _ast_parse_one_file → _ts_language_for → _grammar_available → has_language |
| REQ-DDB-QUERY-003 | measured | test_py_single_call_lambda_entry_resolves → extract_threads → _definition_preferring_name_index |
| REQ-DDB-QUERY-011 | measured | test_py_single_call_lambda_entry_resolves → extract_threads → _ensure_threads_tables |
| REQ-DDB-SCHEMA-001 | measured | test_py_single_call_lambda_entry_resolves → extract_threads |
| REQ-DDB-SCHEMA-007 | measured | test_py_single_call_lambda_entry_resolves → extract_threads → _ensure_threads_tables |
| REQ-DDB-SCHEMA-012 | measured | test_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
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'.
Checks
assert kinds.get("worker") == "pthread" # Thread(target=worker) — bare importassert "process" in kinds.values()assert "coroutine" in kinds.values()assert "task" in kinds.values()
Result: passed
Verifies
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-INDEX-002 | inferred | test_py_spawn_kinds_map_each_primitive_honestly → extract_threads → spawn_harvester → manifest_key → hash_file |
| REQ-DDB-PIPE-003 | measured | test_py_spawn_kinds_map_each_primitive_honestly → extract_threads → spawn_harvester → manifest_key |
| REQ-DDB-PIPE-004 | measured | test_py_spawn_kinds_map_each_primitive_honestly → extract_threads → _populate_membership → _bfs_live_set |
| REQ-DDB-PIPE-011 | measured | test_py_spawn_kinds_map_each_primitive_honestly → _make_py_db → _parse → _ast_parse_one_file → _parseable_file |
| REQ-DDB-PIPE-012 | inferred | test_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-003 | measured | test_py_spawn_kinds_map_each_primitive_honestly → extract_threads → _definition_preferring_name_index |
| REQ-DDB-QUERY-011 | measured | test_py_spawn_kinds_map_each_primitive_honestly → extract_threads → _ensure_threads_tables |
| REQ-DDB-SCHEMA-001 | measured | test_py_spawn_kinds_map_each_primitive_honestly → extract_threads |
| REQ-DDB-SCHEMA-007 | measured | test_py_spawn_kinds_map_each_primitive_honestly → extract_threads → _ensure_threads_tables |
| REQ-DDB-SCHEMA-012 | measured | test_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
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.
Checks
assert entries.get("worker") == "worker", "keyword target= did not resolve"
Result: passed
Verifies
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-INDEX-002 | inferred | test_py_thread_keyword_target_resolves_entry_rowid → extract_threads → spawn_harvester → manifest_key → hash_file |
| REQ-DDB-PIPE-003 | measured | test_py_thread_keyword_target_resolves_entry_rowid → extract_threads → spawn_harvester → manifest_key |
| REQ-DDB-PIPE-004 | measured | test_py_thread_keyword_target_resolves_entry_rowid → extract_threads → _populate_membership → _bfs_live_set |
| REQ-DDB-PIPE-011 | measured | test_py_thread_keyword_target_resolves_entry_rowid → _make_py_db → _parse → _ast_parse_one_file → _parseable_file |
| REQ-DDB-PIPE-012 | inferred | test_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-003 | measured | test_py_thread_keyword_target_resolves_entry_rowid → extract_threads → _definition_preferring_name_index |
| REQ-DDB-QUERY-011 | measured | test_py_thread_keyword_target_resolves_entry_rowid → extract_threads → _ensure_threads_tables |
| REQ-DDB-SCHEMA-001 | measured | test_py_thread_keyword_target_resolves_entry_rowid → extract_threads |
| REQ-DDB-SCHEMA-007 | measured | test_py_thread_keyword_target_resolves_entry_rowid → extract_threads → _ensure_threads_tables |
| REQ-DDB-SCHEMA-012 | measured | test_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
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.
Checks
assert count > 0
Result: passed
Verifies
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-INDEX-002 | inferred | test_py_thread_membership_is_populated → extract_threads → spawn_harvester → manifest_key → hash_file |
| REQ-DDB-PIPE-003 | measured | test_py_thread_membership_is_populated → import_ast_call_edges → run_harvest |
| REQ-DDB-PIPE-004 | measured | test_py_thread_membership_is_populated → extract_threads → _populate_membership → _bfs_live_set |
| REQ-DDB-PIPE-011 | measured | test_py_thread_membership_is_populated → _make_py_db → _parse → _ast_parse_one_file → _parseable_file |
| REQ-DDB-PIPE-012 | inferred | test_py_thread_membership_is_populated → _make_py_db → _parse → _ast_parse_one_file → _ts_language_for → _grammar_available → has_language |
| REQ-DDB-QUERY-003 | measured | test_py_thread_membership_is_populated → extract_threads → _definition_preferring_name_index |
| REQ-DDB-QUERY-011 | measured | test_py_thread_membership_is_populated → extract_threads → _ensure_threads_tables |
| REQ-DDB-SCHEMA-001 | measured | test_py_thread_membership_is_populated → extract_threads |
| REQ-DDB-SCHEMA-007 | measured | test_py_thread_membership_is_populated → extract_threads → _ensure_threads_tables |
| REQ-DDB-SCHEMA-012 | measured | test_py_thread_membership_is_populated → extract_threads → spawn_harvester → load_thread_patterns → declaration_origin |
| REQ-DDB-WIKI-054 | inferred | test_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
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.
Checks
assert "poller" in names # Poller.start passes name="poller"assert "Reader._run" in names # Reader.start passes no name
Result: passed
Verifies
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-INDEX-002 | inferred | test_py_thread_name_literal_wins_over_qualified_entry → extract_threads → spawn_harvester → manifest_key → hash_file |
| REQ-DDB-PIPE-003 | measured | test_py_thread_name_literal_wins_over_qualified_entry → extract_threads → spawn_harvester → manifest_key |
| REQ-DDB-PIPE-004 | measured | test_py_thread_name_literal_wins_over_qualified_entry → extract_threads → _populate_membership → _bfs_live_set |
| REQ-DDB-PIPE-011 | measured | test_py_thread_name_literal_wins_over_qualified_entry → _make_py_db → _parse → _ast_parse_one_file → _parseable_file |
| REQ-DDB-PIPE-012 | inferred | test_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-003 | measured | test_py_thread_name_literal_wins_over_qualified_entry → extract_threads → _definition_preferring_name_index |
| REQ-DDB-QUERY-011 | measured | test_py_thread_name_literal_wins_over_qualified_entry → extract_threads → _ensure_threads_tables |
| REQ-DDB-SCHEMA-001 | measured | test_py_thread_name_literal_wins_over_qualified_entry → extract_threads |
| REQ-DDB-SCHEMA-007 | measured | test_py_thread_name_literal_wins_over_qualified_entry → extract_threads → _ensure_threads_tables |
| REQ-DDB-SCHEMA-012 | measured | test_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
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.
Checks
assert sources.get("ast", 0) > 0, "no plain-identifier Python call edges"assert sum(sources.values()) > 0
Result: passed
Verifies
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-PIPE-003 | measured | test_python_call_edges_land_in_db → import_ast_call_edges → run_harvest |
| REQ-DDB-PIPE-011 | measured | test_python_call_edges_land_in_db → _make_py_db → _parse → _ast_parse_one_file → _parseable_file |
| REQ-DDB-PIPE-012 | inferred | test_python_call_edges_land_in_db → _make_py_db → _parse → _ast_parse_one_file → _ts_language_for → _grammar_available → has_language |
| REQ-DDB-WIKI-054 | inferred | test_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
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.
Checks
assert ("helper", "ast") in by_nameassert ("worker", "ast") in by_nameassert ("Thread", "ast_member") in by_nameassert ("start", "ast_member") in by_nameassert ("worker", "binding") in by_nameassert {s[2] for s in sites} <= {"ast", "ast_member", "binding"}
Result: passed
Verifies
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-PIPE-003 | measured | test_python_call_provenance_splits_plain_and_attribute → _ast_harvest_calls → is_python_tree |
| REQ-DDB-PIPE-011 | measured |
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
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.
Checks
assert "inner" in names # comprehension bodyassert "range" in namesassert "register" in names # decorator call, attribute-qualified
Result: passed
Verifies
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-PIPE-003 | measured | test_python_comprehension_and_decorator_calls_are_reached → _ast_harvest_calls → is_python_tree |
| REQ-DDB-PIPE-011 | measured |
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
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.
Checks
assert python_entry_seeds(db, CSAMPLE_ROOT) == set()
Result: passed
Verifies
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-PIPE-003 | measured | test_python_entry_seeds_empty_for_a_c_repo → python_entry_seeds → run_harvest |
| REQ-DDB-PIPE-004 | measured | test_python_entry_seeds_empty_for_a_c_repo → python_entry_seeds |
| REQ-DDB-PIPE-011 | measured | test_python_entry_seeds_empty_for_a_c_repo → python_entry_seeds → run_harvest → _harvest_one_file → _parseable_file |
| REQ-DDB-PIPE-012 | inferred | test_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
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`.
Checks
assert starts, "expected `.start()` call sites in the fixture"assert all(s[2] == "ast_member" for s in starts)
Result: passed
Verifies
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-PIPE-003 | measured | test_python_self_qualified_call_is_member_provenance → _ast_harvest_calls → is_python_tree |
| REQ-DDB-PIPE-011 | measured | |
| REQ-DDB-WIKI-054 | inferred | test_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
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.
Checks
assert "single" in valuesassert "double" in valuesassert None in values # the interpolated f-string
Result: passed
Verifies
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-PIPE-003 | measured | test_string_value_reads_content_not_quotes → string_value |
| REQ-DDB-PIPE-011 | measured |
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
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
Checks
assert _ts_language_for("dir/file.py") is not Noneassert _ts_language_for("dir/stub.pyi") is not Noneassert _ts_language_for("dir/file.c") is not Noneassert _ts_language_for("dir/file.cpp") is not Noneassert _ts_language_for("dir/file.rs") is not Noneassert _ts_language_for("foo.txt") is None
Result: passed
Verifies
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-PIPE-012 | inferred | test_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