threads.py¶
clew/threads.py
R1 thread layer: spawn-site harvest, membership closure, boundary flags.
_ensure_threads_tables
None clew.threads._ensure_threads_tables(sqlite3.Connection conn)
Create threads + thread_membership tables (+ indexes) if absent.
Source · 91 lines
def _ensure_threads_tables(conn: sqlite3.Connection) -> None:
"""Create the `threads` and `thread_membership` tables and their
indexes if they don't already exist. Always run (even when no spawns
are found) so consumers never branch on table existence.
`kind` JOINED the UNIQUE key (was `(name, entry_memberdef_rowid)`). Two
spawns of the SAME entry through DIFFERENT primitives are two execution
contexts, not one — and the old key silently kept whichever the AST walk
popped first. Measured on the committed Python fixture: `worker` is spawned
as `threading.Thread`, `multiprocessing.Process`, `asyncio.create_task` and
a pool `submit`; all four fall back to the same qualified-entry name, three
were discarded, and the survivor's `kind` was `task` purely because
tree-sitter's DFS pops the last statement first. `kind` is exactly the column
a consumer reads to decide whether two functions can race, so answering it
from walk order is a wrong answer, not a missing one. Repeat spawns of one
entry through ONE primitive still collapse, which is the dedup the key was
added for (a `for i in ...: Thread(target=w, name="rx").start()` loop stays
one row).
THE SPAWN SITE IS RECORDED (gh#346), and it is what makes a thread ATTRIBUTABLE. A thread
row used to be anchored only to its ENTRY symbol, which is legitimately NULL: the entry NAME
is read off the spawn call, but `_insert_threads` refuses to resolve it when a
member-function pointer names a class this index does not cover, or when a bare name is not
uniquely indexed. A row with no entry has no file, so it cannot be tagged external, so a
submodule's threads counted as FIRST PARTY. That inflates the one figure gh#335's invariance
control rests on. Measured on entropic: 12 rows, 4 resolving into entropic, 6 into the
submodule, and 2 to no file at all — those 2 being exactly the mis-attributed ones.
(A multi-call lambda produces NO ROW rather than a NULL-entry row — that limitation is real
but it is a DIFFERENT one, and stating it here as the source of NULL entries would send the
next reader to the wrong mechanism. Checked against
`test_extract_threads_std_thread_multicall_lambda_fail_closed`, which asserts zero rows.)
THE SPAWN SITE ALWAYS HAS A FILE, because it is where the spawn construct was MATCHED, and
it answers the question the tag actually asks: where is this thread CREATED. The entry
symbol answers a different question — what the thread RUNS — and that one is sometimes
unknowable. So this is the right anchor rather than a workaround for a NULL.
IT IS DELIBERATELY NOT IN THE UNIQUE KEY. Adding it would un-collapse the loop case the key
exists to collapse. When one entry is spawned through one primitive from several sites, the
FIRST in path order wins — deterministic, because `run_harvest` walks paths in order, but
still one site standing for several. `_insert_threads` says so.
@brief Idempotent threads/thread_membership table creation.
@version 5
"""
conn.execute(
f"""
CREATE TABLE IF NOT EXISTS threads (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
entry_memberdef_rowid INTEGER REFERENCES memberdef(rowid),
kind TEXT NOT NULL {check("threads", "kind")},
source TEXT NOT NULL {check("threads", "source")},
confidence TEXT NOT NULL {check("threads", "confidence")},
spawn_path_rowid INTEGER REFERENCES path(rowid),
spawn_line INTEGER,
-- WHO creates the thread, as TEXT. `spawn_path_rowid` + `spawn_line` say where; this
-- says the name an agent can ask a follow-up about. Not a memberdef reference, because
-- a spawn commonly sits in a function doxygen emitted no row for (a `static` helper in
-- a sample program is exactly the mbedtls case), and requiring a rowid would drop the
-- row this column exists to serve.
spawn_function TEXT,
-- 2.1: how the thread ends (`threadlife`), and the line that says so. NULL for a row
-- with no spawn call (an interrupt handler): the question does not apply.
lifecycle TEXT {check("threads", "lifecycle")},
lifecycle_line INTEGER,
UNIQUE(name, entry_memberdef_rowid, kind)
)
""",
)
conn.execute(
f"""
CREATE TABLE IF NOT EXISTS thread_membership (
memberdef_rowid INTEGER NOT NULL REFERENCES memberdef(rowid),
thread_id INTEGER NOT NULL REFERENCES threads(id),
source TEXT NOT NULL {check("thread_membership", "source")},
UNIQUE(memberdef_rowid, thread_id)
)
""",
)
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_thread_membership_thread ON thread_membership(thread_id)",
)
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_thread_membership_member "
"ON thread_membership(memberdef_rowid)",
)
conn.commit()
Activity · 5 steps
Requirements
_populate_membership
int clew.threads._populate_membership(sqlite3.Connection conn)
Compute + insert thread_membership via per-entry BFS over call_edges.
Source · 25 lines
def _populate_membership(conn: sqlite3.Connection) -> int:
"""For every thread with a resolved entry rowid, forward-BFS over
`call_edges` (non-fuzzy — reusing `reachability._bfs_live_set`) and file
each reached function as a `call_closure` member. Multi-membership is
expected (a hot shared helper belongs to every thread that reaches it);
the UNIQUE(memberdef_rowid, thread_id) constraint dedups within a thread.
@brief Populate thread_membership from per-entry call-edge closures.
@version 2
"""
threads = conn.execute(
"SELECT id, entry_memberdef_rowid FROM threads WHERE entry_memberdef_rowid IS NOT NULL",
).fetchall()
membership_rows: list[tuple[int, int]] = []
for thread_id, entry_rowid in threads:
live = _bfs_live_set(conn, {entry_rowid})
for member_rowid in live:
membership_rows.append((member_rowid, thread_id))
return conn.executemany(
"INSERT OR IGNORE INTO thread_membership "
"(memberdef_rowid, thread_id, source) VALUES (?, ?, 'call_closure')",
membership_rows,
).rowcount
Activity · 7 steps
Requirements
annotate_thread_boundaries
None clew.threads.annotate_thread_boundaries(Path db_path)
UPDATE shared_key_edges crosses_thread/to_thread_id from membership.
Called by _build_stages, run_real_stages
Tested by
Calls _boundary_flags, _ensure_shared_key_edges_table, _membership_map
Source · 36 lines
def annotate_thread_boundaries(db_path: Path) -> None:
"""For every `shared_key_edges` row, set `crosses_thread` and
`to_thread_id` from the writer's and reader's thread membership. Ensures
the shared_key_edges table exists first (so the full pipeline always has
the enriched schema even when no shared-key stage produced rows).
@brief Annotate shared-key edges with thread-boundary flags.
@version 2
"""
conn = sqlite3.connect(str(db_path))
_ensure_shared_key_edges_table(conn)
membership = _membership_map(conn)
edges = conn.execute(
"SELECT rowid, writer_rowid, reader_rowid FROM shared_key_edges",
).fetchall()
updates: list[tuple[int | None, int | None, int]] = []
for edge_rowid, writer_rowid, reader_rowid in edges:
crosses, to_thread = _boundary_flags(
membership.get(writer_rowid, set()),
membership.get(reader_rowid, set()),
)
updates.append((crosses, to_thread, edge_rowid))
conn.executemany(
"UPDATE shared_key_edges SET crosses_thread = ?, to_thread_id = ? WHERE rowid = ?",
updates,
)
conn.commit()
conn.close()
annotated = sum(1 for c, _t, _r in updates if c is not None)
logger.info(
"threads: annotated %d/%d shared-key edges with boundary flags",
annotated,
len(updates),
)
Activity · 13 steps
Requirements
detect_undeclared_spawn_primitives
list[str] clew.threads.detect_undeclared_spawn_primitives(sqlite3.Connection conn, list[SpawnPattern] patterns)
Suggest spawn primitives a build should declare, because none of its patterns cover them.
Source · 74 lines
def detect_undeclared_spawn_primitives(
conn: sqlite3.Connection, patterns: list[SpawnPattern]
) -> list[str]:
"""THE THREAD LAYER'S COUNTERPART TO `detect_undeclared_lock_primitives`, and it exists
because the same gap was found here one issue later. `diagnostics.py` already records the
lock hint as existing "because that counterpart was missing"; this closes the third instance.
IT IS ALSO A PROMISE THE PAYLOAD NOW MAKES. `_roster_meaning` was rewritten to stop calling
its matched-pattern count the repository's thread count, and to route a reader to
`status.diagnostics` for families the build did not cover. Shipping that sentence without
this function would have been the exact defect the rewrite fixed: a tool asserting something
it cannot deliver.
WHY NOT `propose_thread_patterns`. That detector is SEEDED on `DEFAULT_SPAWN_PATTERNS` —
it finds wrappers that forward into a primitive already known — so an unknown primitive is
not a wrapper of anything and can never be proposed by it. The gap it leaves is precisely
the one that made mbedtls's `_beginthread` invisible.
PURELY ADVISORY, and deliberately biased toward missing a hint rather than inventing one:
a missed hint costs an operator nothing they were not already paying, while a false hint
costs real time chasing a primitive that does not exist. Same asymmetry `AccessorFamily`
records.
WHAT IT CANNOT SEE, MEASURED AGAINST ITS OWN MOTIVATING CASE AND NAMED HERE BECAUSE THE
ANSWER IS UNCOMFORTABLE. It reads `memberdef`, which holds the names this repository
DECLARES. Run against mbedtls with the pattern list emptied — i.e. asked to find what a
build with no Windows coverage was missing — it returns `thread_create` and NOT
`_beginthread`, because `_beginthread` is declared in `<process.h>` and mbedtls only CALLS
it. So this hint would not have found the very gap that prompted it.
That is a real limit, not a rounding error, and it splits the space cleanly:
* A repo's OWN spawn wrapper (`sys_thread_create`, `SYSTEM_TASKCREATE`) is declared here
and IS found — a genuine and common class, and the one `propose_thread_patterns` cannot
reach because it only recognises wrappers of already-known primitives.
* An EXTERNAL platform API that is only called is invisible to this query. Finding those
needs unresolved CALLEE names, which no table carries — `critical_section_calls` has
one but only inside an already-detected critical section, which is the same shape of
chicken-and-egg the lock hint documents.
The lock hint escapes this because mbedtls DECLARES `mbedtls_mutex_lock` itself, as an
extern pointer in its own header. The asymmetry is a property of the two repos, not of the
two detectors, and assuming the lock hint's success would transfer is what made this worth
checking rather than believing.
The payload wording is bounded to match: `_roster_meaning` leads with the DECLARABLE fix
(`thread_patterns`) and offers diagnostics as the secondary route, rather than promising a
hint that a whole class of primitive cannot produce.
A NAME DEFINED ONLY IN A TEST FILE IS NOT OFFERED (2.0.0, R5-CORE D3): the `test_` prefix in
`_spawn_shaped` is one language's convention; `test_scope` knows the files.
@brief Suggest spawn primitives this build's patterns did not cover.
@return Candidate names, sorted.
@version 4
"""
covered = {p.name.lower() for p in patterns}
## A declared or default pattern may be dotted (`threading.Thread`) or qualified
## (`std::thread`); a bare `memberdef` name never is, so compare on the TAIL too or every
## Python default would leave its own primitive looking undeclared.
covered |= {name.rsplit(".", 1)[-1].rsplit("::", 1)[-1] for name in covered}
try:
names = {
row[0]
for row in conn.execute(
"SELECT DISTINCT name FROM memberdef WHERE name<>'' AND kind IN (?, ?)"
+ _OUTSIDE_TESTS.format(col="file_id") * _has_test_scope(conn),
_CALLABLE_KINDS,
)
}
except sqlite3.Error:
return []
return [name for name in sorted(names) if name.lower() not in covered and _spawn_shaped(name)]
Activity · 7 steps
Requirements
extract_threads
None clew.threads.extract_threads(Path db_path, Path repo_root, Path|dict|None thread_patterns_path=None, IndexCache|None cache=None, Harvester|None harvester=None)
R1 thread stage: harvest spawns → threads + thread_membership.
Called by _build_stages, measure_threads, run_real_stages
Tested by 20 tests
test_annotate_thread_boundaries_marks_queue_hop_crossing, test_extract_threads_always_creates_empty_tables, test_extract_threads_pthread_uses_entry_name, test_extract_threads_records_the_spawn_site_from_the_real_harvest, test_extract_threads_std_thread_free_function, test_extract_threads_std_thread_member_pointer_qualified, test_extract_threads_std_thread_multicall_lambda_fail_closed, test_extract_threads_std_thread_single_call_lambda, test_extract_threads_taskcreate_name_literal_and_entry, test_py_lookalike_constructor_is_refused, test_py_same_entry_through_two_primitives_stays_two_threads, test_py_same_method_name_in_two_classes_resolves_distinctly 8 more
test_py_single_call_lambda_entry_resolves, test_py_spawn_kinds_map_each_primitive_honestly, test_py_thread_keyword_target_resolves_entry_rowid, test_py_thread_membership_is_populated, test_py_thread_name_literal_wins_over_qualified_entry, test_thread_membership_is_call_closure, test_two_definitions_of_one_handler_in_one_file_each_resolve, test_two_handlers_of_the_same_name_resolve_to_their_own_file
Calls _build_function_indexes, _definition_preferring_name_index, _ensure_threads_tables, _harvest_all_spawn_sites, _insert_threads, _populate_membership, spawn_harvester
Source · 52 lines
def extract_threads(
db_path: Path,
repo_root: Path,
thread_patterns_path: Path | dict | None = None,
cache: IndexCache | None = None,
harvester: Harvester | None = None,
) -> None:
"""Harvest thread-spawn sites into `threads` and compute
`thread_membership` as a per-entry call-edge closure. Tables are always
created (empty when no spawn matches), so
consumers never branch on existence. Runs after the call-edge layers so
membership sees the complete non-fuzzy call graph (including fnptr edges).
`harvester` is the pre-built one from gh#358's shared parse pass; omitted, it is
built here from `thread_patterns_path` exactly as before.
@brief Import threads + thread_membership (spawn harvest + BFS closure).
@version 4
"""
conn = sqlite3.connect(str(db_path))
_ensure_threads_tables(conn)
name_index = _definition_preferring_name_index(conn)
sites, macro_registrations = _harvest_all_spawn_sites(
conn,
repo_root,
harvester or spawn_harvester(thread_patterns_path),
cache,
)
from .call_edges import _build_function_indexes
_names, file_funcs = _build_function_indexes(conn)
inserted_threads = _insert_threads(conn, sites, name_index, file_funcs)
conn.commit()
inserted_members = _populate_membership(conn)
conn.commit()
conn.close()
logger.info(
"threads: harvested %d spawn sites, inserted %d threads, %d membership rows%s",
len(sites),
inserted_threads,
inserted_members,
## NOT HARVESTED, AND SAID SO. A registration written inside a `#define` body is opaque
## text to the parser; Zephyr writes about two thirds of its `IRQ_CONNECT` sites that
## way. Printing the count is what keeps a low handler count from reading as a measured
## zero. Omitted entirely when there are none, so the ordinary line does not grow.
f" ({macro_registrations} registration(s) inside macro bodies were not harvested)"
if macro_registrations
else "",
)
Activity · 12 steps
Requirements
harvest
Any clew.threads._SpawnHarvester.harvest(self, Any tree, bytes src_bytes)
Harvest one file's spawn call sites.
Source · 14 lines
def harvest(self, tree: Any, src_bytes: bytes) -> Any:
## A MAPPING since gh#47, not the bare site list: it carries the sites AND the number of
## interrupt registrations this walk could not read because they are written inside a
## `#define` body. A count of what was refused is the difference between "this tree has
## no interrupt handler" and "this layer could not see two thirds of them" — Zephyr
## writes 718 of its 1110 `IRQ_CONNECT` sites that way.
return {
"sites": _walk_spawn_sites(tree, src_bytes, self.patterns_by_name),
"macro_registrations": count_macro_body_registrations(
tree, src_bytes, frozenset(self.patterns_by_name)
),
}
Activity · 1 steps
Requirements
load_thread_patterns
list[SpawnPattern] clew.threads.load_thread_patterns(Path|dict|None path)
Load thread-patterns YAML, merged over the built-in defaults.
Called by _sites, collect, spawn_harvester
Tested by 20 tests
test_a_declaration_still_overrides_a_windows_default, test_a_lambda_bodied_spawn_is_harvested, test_a_registration_inside_a_macro_body_is_counted_not_ignored, test_a_wrapped_entry_argument_still_resolves, test_an_aliased_thread_entry_is_resolved_through_the_import_map, test_c_harvest_output_unchanged_on_the_c_fixture, test_c_spawn_defaults_still_present_and_unchanged, test_load_thread_patterns_merges_overrides, test_py_declared_local_wrapper_matches_by_raw_name, test_py_multicall_lambda_entry_fails_closed, test_sections_mirror_the_standalone_manifest_formats, test_the_enclosing_name_strips_a_pointer_return_sigil 8 more
test_the_named_entry_control_still_resolves, test_the_spawn_diagnostic_ignores_non_callable_symbols, test_the_spawn_hint_finds_a_declared_wrapper_and_not_an_external_api, test_the_spawn_site_names_its_enclosing_function, test_thread_spawn_aliased_import_form, test_thread_spawn_resolves_closure_entry, test_unnamed_spawns_get_distinct_names, test_windows_spawns_are_harvested_and_posix_still_is
Calls declaration_origin
Source · 70 lines
def load_thread_patterns(path: Path | dict | None) -> list[SpawnPattern]:
"""Merge an optional `--thread-patterns` YAML over `DEFAULT_SPAWN_PATTERNS`.
Expected shape (mirrors the accessor/data-model manifests)::
spawns:
- name: "SYSTEM_TASKCREATE"
entry_arg_index: 0
name_arg_index: 1
kind: "task"
- name: "svc_start_task"
entry_arg_index: 0
name_arg_index: 1
A loaded entry whose `name` matches a default replaces that default
(override); other loaded entries are appended. `kind` defaults to
`'task'`; `name_arg_index` is optional (None when omitted).
An invalid declared `kind` raises `DeclarationError` naming the file, the
token and the allowed set. It used to normalize to `'unknown'` with a
warning; that is a fabrication — it labels a thread with an execution
context its author never wrote, and the warning is one INFO-looking line in
a several-hundred-line build log.
@brief Merge declared spawn patterns over the built-in defaults.
@version 6
"""
## ONE CALLEE NAME, SEVERAL PATTERNS (gh#47 part 1). `request_threaded_irq(irq, handler,
## thread_fn, ...)` registers TWO functions in TWO execution contexts: `handler` runs in
## hard interrupt context and `thread_fn` on a kernel thread created for it, where blocking
## is the whole point. A single pattern per name can express one of them, and filing the
## bottom half as an ISR would report every lock it takes as an interrupt-context conflict.
## A DECLARED entry still replaces the whole list for its name, so a repo can correct a
## built-in rather than add to it.
merged: dict[str, list[SpawnPattern]] = {}
for builtin in (*DEFAULT_SPAWN_PATTERNS, *DEFAULT_PY_SPAWN_PATTERNS):
merged.setdefault(builtin.name, []).append(builtin)
if path is None:
return [p for patterns in merged.values() for p in patterns]
if isinstance(path, dict):
data = path
else:
import yaml
data = yaml.safe_load(Path(path).read_text(encoding="utf-8")) or {}
origin = declaration_origin(path, SECTION_THREADS)
for entry in data.get("spawns", []) or []:
name = entry.get("name")
if not name:
continue
name_arg = entry.get("name_arg_index")
entry_kwarg = entry.get("entry_kwarg")
name_kwarg = entry.get("name_kwarg")
merged[name] = [
SpawnPattern(
name=name,
entry_arg_index=int(entry.get("entry_arg_index", 0)),
name_arg_index=None if name_arg is None else int(name_arg),
kind=THREAD_KIND.validated(
str(entry.get("kind", "task")),
owner=f"{origin}: spawn pattern {name!r}",
field="kind",
),
entry_kwarg=None if entry_kwarg is None else str(entry_kwarg),
name_kwarg=None if name_kwarg is None else str(name_kwarg),
)
]
return [p for patterns in merged.values() for p in patterns]
Activity · 20 steps
Requirements
patterns_by_name
dict[str, list[SpawnPattern]] clew.threads.patterns_by_name(list[SpawnPattern] patterns)
Index spawn patterns by the callee name they match.
Called by _sites, spawn_harvester
Tested by 13 tests
test_a_lambda_bodied_spawn_is_harvested, test_a_wrapped_entry_argument_still_resolves, test_an_aliased_thread_entry_is_resolved_through_the_import_map, test_c_harvest_output_unchanged_on_the_c_fixture, test_py_declared_local_wrapper_matches_by_raw_name, test_py_multicall_lambda_entry_fails_closed, test_the_enclosing_name_strips_a_pointer_return_sigil, test_the_named_entry_control_still_resolves, test_the_spawn_site_names_its_enclosing_function, test_thread_spawn_aliased_import_form, test_thread_spawn_resolves_closure_entry, test_unnamed_spawns_get_distinct_names
Calls none
Source · 15 lines
def patterns_by_name(patterns: list[SpawnPattern]) -> dict[str, list[SpawnPattern]]:
"""THE ONE PLACE THE MAP IS BUILT, because a name can carry several patterns since gh#47
and every consumer building `{p.name: p for p in ...}` for itself would silently keep only
the last of them.
@brief Group spawn patterns by callee name.
@return The grouping.
@version 1
"""
grouped: dict[str, list[SpawnPattern]] = {}
for pattern in patterns:
grouped.setdefault(pattern.name, []).append(pattern)
return grouped
Activity · 4 steps
Requirements
spawn_harvester
Harvester clew.threads.spawn_harvester(Path|dict|None thread_patterns_path=None)
The thread stage's harvester for one declared spawn vocabulary.
Called by build_harvest_plan, extract_threads
Tested by
Source · 13 lines
def spawn_harvester(thread_patterns_path: Path | dict | None = None) -> Harvester:
"""The ONE construction site, so gh#358's shared parse pass and this stage key on
the same `(stage, stage_version, extra_key)` by construction. A declaration that
raises `DeclarationError` still raises — earlier in the build now, which is the
right direction for a refusal.
@brief Build this stage's harvester.
@version 2
"""
patterns = load_thread_patterns(thread_patterns_path)
return _SpawnHarvester(patterns_by_name(patterns), manifest_key(thread_patterns_path))