threads_detect.py

clew/propose/threads_detect.py

Detect repo-specific thread-spawn WRAPPERS by transitive forwarding.

chain_text

str clew.propose.threads_detect.chain_text(str name, dict[str, Derived] known)

Render the resolution chain for one candidate as one line of evidence.

clew/propose/threads_detect.py:407

Show on the map →

Called by _evidence

Calls seed_map

Source · 13 lines
def chain_text(name: str, known: dict[str, Derived]) -> str:
    """@brief Describe how a candidate reaches a spawn primitive."""
    seeds = seed_map()
    hops = [name]
    cur = name
    while cur in known and known[cur].via and cur not in seeds and len(hops) < 8:
        cur = known[cur].via[0]
        hops.append(cur)
    tail = known.get(cur)
    suffix = f" (entry arg {tail.entry_arg_index})" if tail is not None else ""
    return " -> ".join(hops) + suffix

Activity · 9 steps
lines 409–409seeds = seed_map()lines 410–410hops = [name]lines 411–411cur = namelines 412–412◇ while cur in known and known[cur].via and cur not in seeds and len(hops) < 8lines 413–413cur = known[cur].via[0]lines 414–414hops.append(cur)lines 415–415tail = known.get(cur)lines 416–416suffix = f" (entry arg {tail.entry_arg_index})" if tail is not None else ""lines 417–417return " -> ".join(hops) + suffix

Requirements

REQ-DDB-CONFIG-001

classify_sites

Census clew.propose.threads_detect.classify_sites(Sequence[CallSite] sites, int entry_idx)

Classify a candidate's call sites the way the pipeline would read them.

clew/propose/threads_detect.py:311

Show on the map →

Called by _judge

Calls _site_kind

Source · 25 lines
def classify_sites(sites: Sequence[CallSite], entry_idx: int) -> Census:
    """CONCRETE means the entry argument names a function; FORWARDING means it
    names one of the ENCLOSING definition's parameters (so the enclosing
    definition is itself a wrapper, and declaring this one would mint a thread
    named after a parameter); OPAQUE is everything else.

    @brief Count concrete / forwarding / opaque spawn sites.
    @version 1
    """
    concrete: list[CallSite] = []
    forwarding = opaque = repo_wide = 0
    for site in sites:
        kind = _site_kind(site, entry_idx)
        repo_wide += 1 if kind == "concrete" else 0
        if not site.in_scope:
            continue
        if kind == "concrete":
            concrete.append(site)
        elif kind == "forwarding":
            forwarding += 1
        else:
            opaque += 1
    return Census(tuple(concrete), forwarding, opaque, repo_wide)

Activity · 14 steps
lines 320–320concrete: list[CallSite] = []lines 321–321forwarding = opaque = repo_wide = 0lines 322–322◇ for site in siteslines 323–323kind = _site_kind(site, entry_idx)lines 324–324repo_wide += 1 if kind == "concrete" else 0lines 325–325◇ if not site.in_scopelines 326–326continuelines 327–327◇ if kind == "concrete"lines 328–328concrete.append(site)lines 329–329◇ elif kind == "forwarding"lines 330–330forwarding += 1lines 331–331elselines 332–332opaque += 1lines 333–333return Census(tuple(concrete), forwarding, opaque, repo_wide)

Requirements

REQ-DDB-CONFIG-001

measure_candidate

dict[str, int] clew.propose.threads_detect.measure_candidate(Context ctx, str name, Derived derived)

Measure one candidate against the real index, if there is one.

clew/propose/threads_detect.py:427

Source · 12 lines
def measure_candidate(ctx: Context, name: str, derived: Derived) -> dict[str, int]:
    """@brief Run the candidate through a copy of the index."""
    if not ctx.can_measure():
        return {}
    spawn: dict[str, object] = {"name": name, "entry_arg_index": derived.entry_arg_index}
    if derived.name_arg_index is not None:
        spawn["name_arg_index"] = derived.name_arg_index
    spawn["kind"] = derived.kind
    params = frozenset(p for fdef in derived.defs for p in fdef.params if p)
    return measure_threads(Path(str(ctx.db_path)), ctx.repo_root, [spawn], params)

Activity · 8 steps
lines 429–429◇ if not ctx.can_measure()lines 430–430return {}lines 431–431spawn: dict[str, object] = {"name": name, "entry_arg_index": derived.entry_arg_index}lines 432–432◇ if derived.name_arg_index is not Nonelines 433–433spawn["name_arg_index"] = derived.name_arg_indexlines 434–434spawn["kind"] = derived.kindlines 435–435params = frozenset(p for fdef in derived.defs for p in fdef.params if p)lines 436–436return measure_threads(Path(str(ctx.db_path)), ctx.repo_root, [spawn], params)

Requirements

REQ-DDB-CONFIG-001

proposable_names

list[str] clew.propose.threads_detect.proposable_names(dict[str, Derived] known, dict[str, list[FuncDef]] corpus_defs)

The candidate names worth censusing, given the resolved fixpoint.

clew/propose/threads_detect.py:369

Show on the map →

Called by none

Calls seed_map

Source · 12 lines
def proposable_names(known: dict[str, Derived], corpus_defs: dict[str, list[FuncDef]]) -> list[str]:
    """@brief Candidates whose definition sits inside the derived index scope."""
    seeds = frozenset(seed_map())
    return sorted(
        name
        for name, derived in known.items()
        if name not in seeds
        and derived.defs
        and any(fdef.in_scope for fdef in corpus_defs.get(name, ()))
    )

Activity · 2 steps
lines 371–371seeds = frozenset(seed_map())lines 372–378return sorted( name for name, derived in known.items() if name not in seeds and derived.defs and any(fdef.in_scope for fdef in corpus_defs.get(name, ())) )

Requirements

REQ-DDB-CONFIG-001

propose_thread_patterns

SectionProposal clew.propose.threads_detect.propose_thread_patterns(Context ctx)

Detect thread_patterns.spawns entries for a repo.

clew/propose/threads_detect.py:386

Source · 15 lines
def propose_thread_patterns(ctx: Context) -> SectionProposal:
    """@brief Run the forwarding fixpoint and gate every candidate."""
    from .threads_report import build_section

    known, refused = resolve_fixpoint(ctx.corpus.defs)
    seeds = frozenset(seed_map())
    candidates = sorted(name for name in known if name not in seeds)
    watch = frozenset(candidates)
    sites = census_call_sites(ctx.repo_root, ctx.files, ctx.in_scope, watch)
    by_callee: dict[str, list[CallSite]] = {}
    for site in sites:
        by_callee.setdefault(site.callee, []).append(site)
    return build_section(ctx, known, refused, candidates, by_callee)

Activity · 10 steps
lines 388–388from .threads_report import build_sectionlines 390–390known, refused = resolve_fixpoint(ctx.corpus.defs)lines 391–391seeds = frozenset(seed_map())lines 392–392candidates = sorted(name for name in known if name not in seeds)lines 393–393watch = frozenset(candidates)lines 394–394sites = census_call_sites(ctx.repo_root, ctx.files, ctx.in_scope, watch)lines 395–395by_callee: dict[str, list[CallSite]] = {}lines 396–396◇ for site in siteslines 397–397by_callee.setdefault(site.callee, []).append(site)lines 398–398return build_section(ctx, known, refused, candidates, by_callee)

Requirements

REQ-DDB-CONFIG-001

resolve_fixpoint

tuple[dict[str, Derived], dict[str, tuple[int, ...]]] clew.propose.threads_detect.resolve_fixpoint(dict[str, list[FuncDef]] defs, int max_rounds=_MAX_ROUNDS)

Resolve every forwarding wrapper reachable from the spawn primitives.

clew/propose/threads_detect.py:132

Source · 29 lines
def resolve_fixpoint(
    defs: dict[str, list[FuncDef]], max_rounds: int = _MAX_ROUNDS
) -> tuple[dict[str, Derived], dict[str, tuple[int, ...]]]:
    """Two-phase per round: collect ALL evidence against the currently-resolved
    map, then resolve. Deriving a downstream index from a value that is itself
    still unresolved is how a chain ends up asserting an argument position no
    definition actually declares.

    A later round may REVISE an earlier answer, and must. A wrapper's evidence is
    only as complete as `known` was when it was collected, so a `#if` whose arms
    reach a spawn primitive at different depths is seen one arm at a time: the IoT
    lib's `SYSTEM_TASKCREATE` resolved from its ESP-IDF arm in round 1 and
    its POSIX arm only became visible in round 3. Freezing the first answer
    published `kind: "task"` for a repo that only ever compiles pthreads — this
    feature's headline failure, a plausible wrong declaration. The disagreement is
    a property of the DEFINITIONS, not of the order they resolve in.

    @brief Iterate forwarding evidence to a fixpoint, revising as it widens.
    @version 2
    """
    known = seed_map()
    seeds = frozenset(known)
    refused: dict[str, tuple[int, ...]] = {}
    for _round in range(max_rounds):
        if not _apply_round(known, refused, _collect_evidence(defs, known, seeds)):
            break
    return known, refused

Activity · 7 steps
lines 152–152known = seed_map()lines 153–153seeds = frozenset(known)lines 154–154refused: dict[str, tuple[int, ...]] = {}lines 155–155◇ for _round in range(max_rounds)lines 156–156◇ if not _apply_round(known, refused, _collect_evidence(defs, known, seeds))lines 157–157breaklines 158–158return known, refused

Requirements

REQ-DDB-CONFIG-001

seed_map

dict[str, Derived] clew.propose.threads_detect.seed_map()

The built-in spawn primitives, as the fixpoint's seed map.

clew/propose/threads_detect.py:102

Source · 24 lines
def seed_map() -> dict[str, Derived]:
    """A primitive that registers TWO entries in two contexts (`request_threaded_irq`, gh#47)
    seeds NOTHING: the fixpoint derives a wrapper's entry index from the primitive's, and there
    is no single index to derive from. Keeping either one silently would propose a wrapper
    convention for half the primitive — the same shape this module's `refused` path exists to
    report rather than guess at.

    @brief Seed the fixpoint with the language/OS spawn primitives.
    """
    grouped: dict[str, list] = {}
    for pattern in DEFAULT_SPAWN_PATTERNS:
        grouped.setdefault(pattern.name, []).append(pattern)
    return {
        name: Derived(
            entry_arg_index=patterns[0].entry_arg_index,
            name_arg_index=patterns[0].name_arg_index,
            kind=patterns[0].kind,
            via=(),
        )
        for name, patterns in grouped.items()
        if len({p.entry_arg_index for p in patterns}) == 1
    }

Activity · 4 steps
lines 111–111grouped: dict[str, list] = {}lines 112–112◇ for pattern in DEFAULT_SPAWN_PATTERNSlines 113–113grouped.setdefault(pattern.name, []).append(pattern)lines 114–123return { name: Derived( entry_arg_index=patterns[0].entry_arg_index, name_arg_index=patterns[0].name_arg_index, kind=patterns[0].kind, via=(), ) for name, patterns in grouped.items() if len({p.entry_arg_index for p in patterns}) == 1 }

Requirements

REQ-DDB-CONFIG-001