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.

clew/threads.py:501

Show on the map →

Called by _context_db, _ported_db, extract_threads, schema_db

Calls none

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
lines 547–571conn.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) ) """, )lines 572–581conn.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) ) """, )lines 582–584conn.execute( "CREATE INDEX IF NOT EXISTS idx_thread_membership_thread ON thread_membership(thread_id)", )lines 585–588conn.execute( "CREATE INDEX IF NOT EXISTS idx_thread_membership_member " "ON thread_membership(memberdef_rowid)", )lines 589–589conn.commit()

Requirements

REQ-DDB-QUERY-011 REQ-DDB-SCHEMA-001 REQ-DDB-SCHEMA-007

_populate_membership

int clew.threads._populate_membership(sqlite3.Connection conn)

Compute + insert thread_membership via per-entry BFS over call_edges.

clew/threads.py:1742

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
lines 1752–1754threads = conn.execute( "SELECT id, entry_memberdef_rowid FROM threads WHERE entry_memberdef_rowid IS NOT NULL", ).fetchall()lines 1755–1755membership_rows: list[tuple[int, int]] = []lines 1756–1756◇ for thread_id, entry_rowid in threadslines 1757–1757live = _bfs_live_set(conn, {entry_rowid})lines 1758–1758◇ for member_rowid in livelines 1759–1759membership_rows.append((member_rowid, thread_id))lines 1760–1764return conn.executemany( "INSERT OR IGNORE INTO thread_membership " "(memberdef_rowid, thread_id, source) VALUES (?, ?, 'call_closure')", membership_rows, ).rowcount

Requirements

REQ-DDB-SCHEMA-001

annotate_thread_boundaries

None clew.threads.annotate_thread_boundaries(Path db_path)

UPDATE shared_key_edges crosses_thread/to_thread_id from membership.

clew/threads.py:1868

Show on the map →

Called by _build_stages, run_real_stages

Tested by

1 teststest_annotate_thread_boundaries_marks_queue_hop_crossing

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
lines 1877–1877conn = sqlite3.connect(str(db_path))lines 1878–1878_ensure_shared_key_edges_table(conn)lines 1879–1879membership = _membership_map(conn)lines 1880–1882edges = conn.execute( "SELECT rowid, writer_rowid, reader_rowid FROM shared_key_edges", ).fetchall()lines 1883–1883updates: list[tuple[int | None, int | None, int]] = []lines 1884–1884◇ for edge_rowid, writer_rowid, reader_rowid in edgeslines 1885–1888crosses, to_thread = _boundary_flags( membership.get(writer_rowid, set()), membership.get(reader_rowid, set()), )lines 1889–1889updates.append((crosses, to_thread, edge_rowid))lines 1890–1893conn.executemany( "UPDATE shared_key_edges SET crosses_thread = ?, to_thread_id = ? WHERE rowid = ?", updates, )lines 1894–1894conn.commit()lines 1895–1895conn.close()lines 1896–1896annotated = sum(1 for c, _t, _r in updates if c is not None)lines 1897–1901logger.info( "threads: annotated %d/%d shared-key edges with boundary flags", annotated, len(updates), )

Requirements

REQ-DDB-SCHEMA-001

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.

clew/threads.py:1940

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
lines 1995–1995covered = {p.name.lower() for p in patterns}lines 1999–1999covered |= {name.rsplit(".", 1)[-1].rsplit("::", 1)[-1] for name in covered}lines 2000–2000trylines 2001–2008names = { 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, ) }lines 2009–2009except sqlite3.Errorlines 2010–2010return []lines 2011–2011return [name for name in sorted(names) if name.lower() not in covered and _spawn_shaped(name)]

Requirements

REQ-DDB-CONFIG-007

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.

clew/threads.py:1775

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
lines 1794–1794conn = sqlite3.connect(str(db_path))lines 1795–1795_ensure_threads_tables(conn)lines 1797–1797name_index = _definition_preferring_name_index(conn)lines 1798–1803sites, macro_registrations = _harvest_all_spawn_sites( conn, repo_root, harvester or spawn_harvester(thread_patterns_path), cache, )lines 1804–1804from .call_edges import _build_function_indexeslines 1806–1806_names, file_funcs = _build_function_indexes(conn)lines 1807–1807inserted_threads = _insert_threads(conn, sites, name_index, file_funcs)lines 1808–1808conn.commit()lines 1809–1809inserted_members = _populate_membership(conn)lines 1810–1810conn.commit()lines 1811–1811conn.close()lines 1812–1824logger.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 "", )

Requirements

REQ-DDB-SCHEMA-001

harvest

Any clew.threads._SpawnHarvester.harvest(self, Any tree, bytes src_bytes)

Harvest one file's spawn call sites.

clew/threads.py:1365

Show on the map →

Called by none

Calls _walk_spawn_sites, count_macro_body_registrations

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
lines 1371–1376return { "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) ), }

Requirements

REQ-DDB-SCHEMA-001

load_thread_patterns

list[SpawnPattern] clew.threads.load_thread_patterns(Path|dict|None path)

Load thread-patterns YAML, merged over the built-in defaults.

clew/threads.py:405

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
lines 439–439merged: dict[str, list[SpawnPattern]] = {}lines 440–440◇ for builtin in (*DEFAULT_SPAWN_PATTERNS, *DEFAULT_PY_SPAWN_PATTERNS)lines 441–441merged.setdefault(builtin.name, []).append(builtin)lines 442–442◇ if path is Nonelines 443–443return [p for patterns in merged.values() for p in patterns]lines 444–444◇ if isinstance(path, dict)lines 445–445data = pathlines 446–446elselines 447–447import yamllines 449–449data = yaml.safe_load(Path(path).read_text(encoding="utf-8")) or {}lines 450–450origin = declaration_origin(path, SECTION_THREADS)lines 451–451◇ for entry in data.get("spawns", []) or []lines 452–452name = entry.get("name")lines 453–453◇ if not namelines 454–454continuelines 455–455name_arg = entry.get("name_arg_index")lines 456–456entry_kwarg = entry.get("entry_kwarg")lines 457–457name_kwarg = entry.get("name_kwarg")lines 458–471merged[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), ) ]lines 472–472return [p for patterns in merged.values() for p in patterns]

Requirements

REQ-DDB-SCHEMA-001

patterns_by_name

dict[str, list[SpawnPattern]] clew.threads.patterns_by_name(list[SpawnPattern] patterns)

Index spawn patterns by the callee name they match.

clew/threads.py:480

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
lines 489–489grouped: dict[str, list[SpawnPattern]] = {}lines 490–490◇ for pattern in patternslines 491–491grouped.setdefault(pattern.name, []).append(pattern)lines 492–492return grouped

Requirements

REQ-DDB-SCHEMA-001

spawn_harvester

Harvester clew.threads.spawn_harvester(Path|dict|None thread_patterns_path=None)

The thread stage's harvester for one declared spawn vocabulary.

clew/threads.py:1384

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))

Activity · 2 steps
lines 1393–1393patterns = load_thread_patterns(thread_patterns_path)lines 1394–1394return _SpawnHarvester(patterns_by_name(patterns), manifest_key(thread_patterns_path))

Requirements

REQ-DDB-SCHEMA-001