test_thread_spawns.py

tests/test_thread_spawns.py

C/C++ spawn-primitive coverage: which platforms the DEFAULT pattern set can see.

test_a_declaration_still_overrides_a_windows_default

None test_thread_spawns.test_a_declaration_still_overrides_a_windows_default(Any tmp_path)

A declared pattern can still override a Windows default.

tests/test_thread_spawns.py:159

Checks

  • assert by_name["CreateThread"].entry_arg_index == 0, "the declaration must win"
  • assert by_name["CreateThread"].kind == "task"
  • assert by_name["_beginthread"].entry_arg_index == 0
  • assert by_name["pthread_create"].entry_arg_index == 2

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-SCHEMA-001measuredtest_a_declaration_still_overrides_a_windows_default → load_thread_patterns
REQ-DDB-SCHEMA-012measuredtest_a_declaration_still_overrides_a_windows_default → load_thread_patterns → declaration_origin
Source · 21 lines
def test_a_declaration_still_overrides_a_windows_default(tmp_path: Any) -> None:
    """Defaults must stay overridable. A project that wraps `CreateThread` behind its own
    signature has to be able to say so, and `load_thread_patterns` merges a declared entry OVER
    a default of the same name.

    @brief A declared entry replaces the built-in Windows pattern.
    @version 1
    """
    manifest = tmp_path / "spawns.yaml"
    manifest.write_text(
        "spawns:\n  - name: CreateThread\n    entry_arg_index: 0\n    kind: task\n",
        encoding="utf-8",
    )
    by_name = {p.name: p for p in load_thread_patterns(manifest)}
    assert by_name["CreateThread"].entry_arg_index == 0, "the declaration must win"
    assert by_name["CreateThread"].kind == "task"
    ## And the other defaults survive the merge.
    assert by_name["_beginthread"].entry_arg_index == 0
    assert by_name["pthread_create"].entry_arg_index == 2

Activity · 7 steps
lines 167–167manifest = tmp_path / "spawns.yaml"lines 168–171manifest.write_text( "spawns:\n - name: CreateThread\n entry_arg_index: 0\n kind: task\n", encoding="utf-8", )lines 172–172by_name = {p.name: p for p in load_thread_patterns(manifest)}lines 173–173assert by_name["CreateThread"].entry_arg_index == 0, "the declaration must win"lines 174–174assert by_name["CreateThread"].kind == "task"lines 176–176assert by_name["_beginthread"].entry_arg_index == 0lines 177–177assert by_name["pthread_create"].entry_arg_index == 2

test_a_wrapped_entry_argument_still_resolves

None test_thread_spawns.test_a_wrapped_entry_argument_still_resolves()

A cast or parenthesised entry argument still names its function.

tests/test_thread_spawns.py:566

Show on the map →

Called by none

Calls _parse_c, _walk_spawn_sites, load_thread_patterns, patterns_by_name

Checks

  • assert entries == ["ThreadMainHandler"] * 3, (f"a cast or parenthesised entry argument must resolve like a bare one, got {entries}" )

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-PIPE-003measuredtest_a_wrapped_entry_argument_still_resolves → _walk_spawn_sites → is_python_tree
REQ-DDB-SCHEMA-001measuredtest_a_wrapped_entry_argument_still_resolves → load_thread_patterns
REQ-DDB-SCHEMA-012inferredtest_a_wrapped_entry_argument_still_resolves → load_thread_patterns → declaration_origin
Source · 31 lines
def test_a_wrapped_entry_argument_still_resolves() -> None:
    """gh#45. `_named_entry` unwrapped exactly one node type — `pointer_expression` — so
    `(pthread_fn)ThreadMainHandler` reached `_tail_identifier` as a `cast_expression`, whose
    handler table has no entry for it, and the site was dropped fail-closed. The primitive was
    recognised the whole time; only the argument parse failed, so no `thread_patterns`
    declaration could recover it.

    MEASURED ON A REAL TREE: rtabmap indexed 1,439 files and 13,061 live symbols and yielded ONE
    thread — an Android JNI logger whose entry argument happens to be bare. Its five real spawn
    sites all sit in `UThreadC::Create` behind `(pthread_fn)`.

    THE SET WAS ALREADY WRITTEN, one module over: `propose/astdefs.py` unwraps
    `pointer_expression`, `parenthesized_expression` and `cast_expression` when asking the same
    question — "is this argument a bare name?" — so the propose path understood casts while the
    harvest path did not. Two answers to one question is the defect; sharing the constant is the
    fix.

    A LOOP RATHER THAN ONE UNWRAP, because the wrappers nest: `(pthread_fn)&Class::method` is a
    cast over a pointer expression, and unwrapping once leaves the other in place.

    @brief All three argument shapes name the same entry.
    @version 1
    """
    patterns = patterns_by_name(load_thread_patterns(None))
    tree, src = _parse_c(_BARE_AND_WRAPPED)
    sites = _walk_spawn_sites(tree, src, patterns)

    entries = sorted(site[1] for site in sites)
    assert entries == ["ThreadMainHandler"] * 3, (
        f"a cast or parenthesised entry argument must resolve like a bare one, got {entries}"
    )

1 more lines, not shown

Activity · 5 steps
lines 589–589patterns = patterns_by_name(load_thread_patterns(None))lines 590–590tree, src = _parse_c(_BARE_AND_WRAPPED)lines 591–591sites = _walk_spawn_sites(tree, src, patterns)lines 593–593entries = sorted(site[1] for site in sites)lines 594–596assert entries == ["ThreadMainHandler"] * 3, ( f"a cast or parenthesised entry argument must resolve like a bare one, got {entries}" )

test_the_enclosing_name_strips_a_pointer_return_sigil

None test_thread_spawns.test_the_enclosing_name_strips_a_pointer_return_sigil()

A pointer-returning function's sigil does not leak into the recorded name.

tests/test_thread_spawns.py:459

Show on the map →

Called by none

Calls _parse_c, _walk_spawn_sites, load_thread_patterns, patterns_by_name

Checks

  • assert len(sites) == 1
  • assert sites[0][6] == "make_thread", f"the sigil leaked: {sites[0][6]!r}"

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-PIPE-003measuredtest_the_enclosing_name_strips_a_pointer_return_sigil → _walk_spawn_sites → is_python_tree
REQ-DDB-SCHEMA-001measuredtest_the_enclosing_name_strips_a_pointer_return_sigil → load_thread_patterns
REQ-DDB-SCHEMA-012inferredtest_the_enclosing_name_strips_a_pointer_return_sigil → load_thread_patterns → declaration_origin
Source · 21 lines
def test_the_enclosing_name_strips_a_pointer_return_sigil() -> None:
    """THE TRAP THAT SPLIT ONE MUTEX INTO TWO LOCK ROWS, one layer over. A pointer return type
    puts its `*` INSIDE the declarator, so `void *make_thread(void)` reads as `*make_thread` if
    the text is taken raw — and a name nobody can look up is worse than none, because it looks
    like an answer. `locks.py` learned this on the entropic grid; this is the same read.
    """
    patterns = patterns_by_name(load_thread_patterns(None))
    tree, raw = _parse_c(
        b"#include <pthread.h>\n"
        b"static void *WorkerProc(void *a) { return a; }\n"
        b"void *make_thread(void) {\n"
        b"    pthread_t t;\n"
        b"    pthread_create(&t, NULL, WorkerProc, NULL);\n"
        b"    return (void *) 0;\n"
        b"}\n"
    )
    sites = _walk_spawn_sites(tree, raw, patterns)
    assert len(sites) == 1
    assert sites[0][6] == "make_thread", f"the sigil leaked: {sites[0][6]!r}"

Activity · 5 steps
lines 465–465patterns = patterns_by_name(load_thread_patterns(None))lines 466–474tree, raw = _parse_c( b"#include <pthread.h>\n" b"static void *WorkerProc(void *a) { return a; }\n" b"void *make_thread(void) {\n" b" pthread_t t;\n" b" pthread_create(&t, NULL, WorkerProc, NULL);\n" b" return (void *) 0;\n" b"}\n" )lines 475–475sites = _walk_spawn_sites(tree, raw, patterns)lines 476–476assert len(sites) == 1lines 477–477assert sites[0][6] == "make_thread", f"the sigil leaked: {sites[0][6]!r}"

test_the_spawn_diagnostic_ignores_non_callable_symbols

None test_thread_spawns.test_the_spawn_diagnostic_ignores_non_callable_symbols()

A spawn primitive is callable; a variable that names one is not a candidate.

tests/test_thread_spawns.py:483

Checks

  • assert found == ["SYSTEM_TASKCREATE", "sys_thread_create"], (f"a spawn primitive is callable — a function or a wrapper macro. Got {found}; a variable, " f"typedef or enumeration that merely NAMES threading is a constant, not a primitive an " f"operator can declare" )

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-CONFIG-007measuredtest_the_spawn_diagnostic_ignores_non_callable_symbols → detect_undeclared_spawn_primitives
REQ-DDB-SCHEMA-001measuredtest_the_spawn_diagnostic_ignores_non_callable_symbols → load_thread_patterns
REQ-DDB-SCHEMA-012inferredtest_the_spawn_diagnostic_ignores_non_callable_symbols → load_thread_patterns → declaration_origin
Source · 54 lines
def test_the_spawn_diagnostic_ignores_non_callable_symbols() -> None:
    """MEASURED ON THREE BUILT INDEXES, not imagined. `detect_undeclared_spawn_primitives` read
    `SELECT DISTINCT name FROM memberdef` with NO kind filter, so every name in the database was a
    candidate and only `_spawn_shaped` adjacency stood between a constant and a hint:

      * clew's own index reported `_THREAD_SPAWNER_COLUMNS` — kind `variable`, a SQL
        column-list constant in `query/symbols.py`. `THREAD` and `SPAWNER` are adjacent, so shape
        cannot reject it. A spawn primitive is never a variable.
      * a firmware index reported outcome codes shaped like `CREATE_THREAD_ERROR` and
        `CREATE_THREAD_FAILED` beside the genuine wrappers they belong to. Those spellings and
        `SYSTEM_TASKCREATE` are ILLUSTRATIVE — the measurement was taken on a private target and
        its symbol names are not published here.

    THIS FIXES THE FIRST CLASS ONLY, and the boundary is worth stating: a primitive is a
    `function` or a `macro definition` — a wrapper macro like `xTaskCreate` is real and must stay
    — so the error-code macros share a kind with the real ones and NO kind filter can separate
    them. The rule that would is an outcome-suffix blocklist, which is what this detector's own
    docstring argues against, so it is filed rather than shipped.

    THE FIXTURE NOW CARRIES `kind`, which the old one did not. That omission is the same shape
    this module already records against itself: a fixture without the column the world has cannot
    exercise a filter on it, and would have reported this test green against no filter at all.

    @brief Non-callable symbols are not spawn-primitive candidates.
    @return None.
    @version 1
    """
    import sqlite3

    from clew.threads import detect_undeclared_spawn_primitives, load_thread_patterns

    conn = sqlite3.connect(":memory:")
    conn.execute("CREATE TABLE memberdef (rowid INTEGER PRIMARY KEY, name TEXT, kind TEXT)")
    conn.executemany(
        "INSERT INTO memberdef (name, kind) VALUES (?, ?)",
        [
            ("sys_thread_create", "function"),
            ("SYSTEM_TASKCREATE", "macro definition"),
            ## The real false positive, verbatim from this repository's own index.
            ("_THREAD_SPAWNER_COLUMNS", "variable"),
            ("thread_create_fn_t", "typedef"),
            ("THREAD_CREATE_RESULT", "enumeration"),
        ],
    )
    conn.commit()

    found = detect_undeclared_spawn_primitives(conn, load_thread_patterns(None))
    assert found == ["SYSTEM_TASKCREATE", "sys_thread_create"], (
        f"a spawn primitive is callable — a function or a wrapper macro. Got {found}; a variable, "
        f"typedef or enumeration that merely NAMES threading is a constant, not a primitive an "
        f"operator can declare"
    )

Activity · 8 steps
lines 510–510import sqlite3lines 512–512from clew.threads import detect_undeclared_spawn_primitives, load_thread_patternslines 514–514conn = sqlite3.connect(":memory:")lines 515–515conn.execute("CREATE TABLE memberdef (rowid INTEGER PRIMARY KEY, name TEXT, kind TEXT)")lines 516–526conn.executemany( "INSERT INTO memberdef (name, kind) VALUES (?, ?)", [ ("sys_thread_create", "function"), ("SYSTEM_TASKCREATE", "macro definition"), ## The real false positive, verbatim from this repository's own index. ("_THREAD_SPAWNER_COLUMNS", "variable"), ("thread_create_fn_t", "typedef"), ("THREAD_CREATE_RESULT", "enumeration"), ], )lines 527–527conn.commit()lines 529–529found = detect_undeclared_spawn_primitives(conn, load_thread_patterns(None))lines 530–534assert found == ["SYSTEM_TASKCREATE", "sys_thread_create"], ( f"a spawn primitive is callable — a function or a wrapper macro. Got {found}; a variable, " f"typedef or enumeration that merely NAMES threading is a constant, not a primitive an " f"operator can declare" )

test_the_spawn_hint_finds_a_declared_wrapper_and_not_an_external_api

None test_thread_spawns.test_the_spawn_hint_finds_a_declared_wrapper_and_not_an_external_api(Any tmp_path)

The spawn hint finds a repo's OWN wrapper and is honest about what it cannot see.

tests/test_thread_spawns.py:184

Checks

  • assert found == ["sys_thread_create"], (f"expected only the repo's own wrapper, got {found} — a subject word and a creation " f"verb are required TOGETHER precisely so this list stays short enough to act on" )
  • assert "_beginthread" not in found, ("if this ever starts passing, the detector has gained a call-site source and the " "payload's hedge about only-called APIs should be revisited" )
  • assert "xTaskCreate" not in covered, "a default-covered primitive must not be suggested"

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-CONFIG-007measuredtest_the_spawn_hint_finds_a_declared_wrapper_and_not_an_external_api → detect_undeclared_spawn_primitives
REQ-DDB-SCHEMA-001measuredtest_the_spawn_hint_finds_a_declared_wrapper_and_not_an_external_api → load_thread_patterns
REQ-DDB-SCHEMA-012inferredtest_the_spawn_hint_finds_a_declared_wrapper_and_not_an_external_api → load_thread_patterns → declaration_origin
Source · 82 lines
def test_the_spawn_hint_finds_a_declared_wrapper_and_not_an_external_api(tmp_path: Any) -> None:
    """THE NEGATIVE HALF IS THE POINT OF THIS TEST, and it was found by running the hint against
    its own motivating case rather than by believing it.

    `detect_undeclared_spawn_primitives` reads `memberdef` — the names this repository DECLARES.
    Asked what a build with no Windows coverage was missing on real mbedtls, it returns
    `thread_create` and NOT `_beginthread`, because `_beginthread` lives in `<process.h>` and
    mbedtls only CALLS it. So the hint could not have found the gap it exists for.

    The lock hint escapes the same limit only because mbedtls declares `mbedtls_mutex_lock`
    itself as an extern pointer in its own header. That asymmetry is a property of the two
    repositories, not of the two detectors — which is exactly why assuming the lock hint's
    success would transfer was worth checking.

    Pinned here so the limit cannot be quietly forgotten and the payload cannot drift back into
    promising a hint this class of primitive can never produce.

    @brief A declared wrapper is hinted; an only-called external API is not.
    @version 1
    """
    import sqlite3

    from clew.threads import detect_undeclared_spawn_primitives

    conn = sqlite3.connect(":memory:")
    ## `kind` IS PART OF THE WORLD AND WAS MISSING HERE. `detect_undeclared_spawn_primitives`
    ## now restricts to callable kinds, and a fixture without the column cannot exercise that —
    ## it would report green against no filter at all, which is this module's own recorded
    ## failure shape one turn later.
    conn.execute("CREATE TABLE memberdef (rowid INTEGER PRIMARY KEY, name TEXT, kind TEXT)")
    conn.executemany(
        "INSERT INTO memberdef (name, kind) VALUES (?, ?)",
        [
            ("sys_thread_create", "function"),  # the repo's OWN wrapper — declared, findable
            ("thread_local_slot", "function"),  # subject word, no creation verb -> noise
            ("CreateFileA", "function"),  # creation verb, no subject word -> noise
            ("pthread_mutex_lock", "function"),  # contains "thread", not a spawn at all
            ## THE FOUR NOISE NAMES BELOW ARE REAL, COPIED FROM THIS REPO'S OWN INDEX, and they
            ## are here because the first version of the heuristic named all of them. It asked
            ## for a subject word AND a verb ANYWHERE in the name, which prose satisfies
            ## trivially — clew's index produced SIX such candidates, every one a test
            ## function. The curated four above all passed while the detector was 100% noise on
            ## the first real corpus it saw: the fixture matched the detector, not the world.
            ("test_extract_threads_always_creates_empty_tables", "function"),
            ("test_a_null_entry_thread_is_attributed_by_its_spawn_site", "function"),
            ("test_default_spawn_patterns_cover_std_thread", "function"),
            ## `new_thread` IS adjacent, so adjacency alone does not reject this one — the
            ## `test_` prefix term is what does, and it earned its place on this single name.
            ("test_new_thread_kinds_are_registered_in_the_vocabulary", "function"),
            ## AND THE CONVERSE, which makes ADJACENCY load-bearing rather than decorative. All
            ## four real noise names above happen to be `test_`-prefixed, so a mutation that
            ## dropped adjacency entirely left the suite green — the prefix term was doing all
            ## the work and the more general rule was untested. This name is prose with a
            ## subject and a verb far apart and NO test prefix, so only adjacency rejects it.
            ("worker_pool_was_started_by_main", "function"),
        ],
    )
    conn.commit()

    found = detect_undeclared_spawn_primitives(conn, load_thread_patterns(None))
    assert found == ["sys_thread_create"], (
        f"expected only the repo's own wrapper, got {found} — a subject word and a creation "
        f"verb are required TOGETHER precisely so this list stays short enough to act on"
    )

    ## AND THE LIMIT: an external API present only as a CALL, never as a declared name, cannot
    ## be hinted at. `_beginthread` is absent from `memberdef` above exactly as it is absent
    ## from mbedtls's.
    assert "_beginthread" not in found, (
        "if this ever starts passing, the detector has gained a call-site source and the "
        "payload's hedge about only-called APIs should be revisited"
    )

    ## A COVERED primitive is never re-suggested, including one matched by its dotted tail —
    ## otherwise every Python default would leave its own primitive looking undeclared.
    conn.execute("INSERT INTO memberdef (name) VALUES ('xTaskCreate')")
    conn.execute("INSERT INTO memberdef (name) VALUES ('Thread')")
    conn.commit()
    covered = detect_undeclared_spawn_primitives(conn, load_thread_patterns(None))
    assert "xTaskCreate" not in covered, "a default-covered primitive must not be suggested"

Activity · 14 steps
lines 204–204import sqlite3lines 206–206from clew.threads import detect_undeclared_spawn_primitiveslines 208–208conn = sqlite3.connect(":memory:")lines 213–213conn.execute("CREATE TABLE memberdef (rowid INTEGER PRIMARY KEY, name TEXT, kind TEXT)")lines 214–240conn.executemany( "INSERT INTO memberdef (name, kind) VALUES (?, ?)", [ ("sys_thread_create", "function"), # the repo's OWN wrapper — declared, findable ("thread_local_slot", "function"), # subject word, no creation verb -> noise ("CreateFileA", "function"), # creation verb, no subject word -> noise ("pthread_mutex_lock", "function"), # contains "thread", not a spawn at all ## THE FOUR NOISE NAMES BELOW ARE REAL, COPIED FROM THIS REPO'S OWN INDEX, and they ## are here because the first version of the heuristic named all of them. It asked ## for a subject word AND a verb ANYWHERE in the name, which prose satisfies ## trivially — clew's index produced SIX such candidates, every one a test ## function. The curated four above all passed while the detector was 100% noise on ## the first real corpus it saw: the fixture matched the detector, not the world. ("test_extract_threads_always_creates_empty_tables", "function"), ("test_a_null_entry_thread_is_attributed_by_its_spawn_site", "function"), ("test_default_spawn_patterns_cover_std_thread", "function"), ## `new_thread` IS adjacent, so adjacency alone does not reject this one — the ## `test_` prefix term is what does, and it earned its place on this single name. ("test_new_thread_kinds_are_registered_in_the_vocabulary", "function"), ## AND THE CONVERSE, which makes ADJACENCY load-bearing rather than decorative. All ## four real noise names above happen to be `test_`-prefixed, so a mutation that ## dropped adjacency entirely left the suite green — the prefix term was doing all ## the work and the more general rule was untested. This name is prose with a ## subject and a verb far apart and NO test prefix, so only adjacency rejects it. ("worker_pool_was_started_by_main", "function"), ], )lines 241–241conn.commit()lines 243–243found = detect_undeclared_spawn_primitives(conn, load_thread_patterns(None))lines 244–247assert found == ["sys_thread_create"], ( f"expected only the repo's own wrapper, got {found} — a subject word and a creation " f"verb are required TOGETHER precisely so this list stays short enough to act on" )lines 252–255assert "_beginthread" not in found, ( "if this ever starts passing, the detector has gained a call-site source and the " "payload's hedge about only-called APIs should be revisited" )lines 259–259conn.execute("INSERT INTO memberdef (name) VALUES ('xTaskCreate')")lines 260–260conn.execute("INSERT INTO memberdef (name) VALUES ('Thread')")lines 261–261conn.commit()lines 262–262covered = detect_undeclared_spawn_primitives(conn, load_thread_patterns(None))lines 263–263assert "xTaskCreate" not in covered, "a default-covered primitive must not be suggested"

test_the_spawn_site_names_its_enclosing_function

None test_thread_spawns.test_the_spawn_site_names_its_enclosing_function()

A spawn site records WHO creates the thread, not only where.

tests/test_thread_spawns.py:408

Show on the map →

Called by none

Calls _parse_c, _walk_spawn_sites, load_thread_patterns, patterns_by_name

Checks

  • assert len(sites) == 1, f"expected the one pthread spawn, got {sites}"
  • assert len(sites[0]) == 10, f"the payload must have ten elements, got {len(sites[0])}"
  • assert sites[0][8:] == ["unknown", None], "a pthread_t nobody joins or detaches"
  • assert sites[0][6] == "thread_create"
  • assert _walk_spawn_sites(file_scope, raw2, patterns) == []

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-PIPE-003measuredtest_the_spawn_site_names_its_enclosing_function → _walk_spawn_sites → is_python_tree
REQ-DDB-SCHEMA-001measuredtest_the_spawn_site_names_its_enclosing_function → load_thread_patterns
REQ-DDB-SCHEMA-012inferredtest_the_spawn_site_names_its_enclosing_function → load_thread_patterns → declaration_origin
Source · 48 lines
def test_the_spawn_site_names_its_enclosing_function() -> None:
    """A COORDINATE WITH NO NAME IS WHY THE AGENT READ THE FILE. Build 35 gave the thread row its
    spawn file and line, so an agent could be told a thread is created at
    `programs/ssl/ssl_pthread_server.c:277` and still have nothing to ask a follow-up ABOUT.
    Measured on mbedtls 2026-08-14: the enclosing function is `thread_create`, whose body holds
    the one shared `mbedtls_ssl_config`, the `pthread_join` and the compile guard — four graded
    marks — and `dossier('thread_create')` already returned all of it. Only the route was absent.

    Verified against the real target after this change: `thread_create` for the pthread spawn at
    `:277`, and `mbedtls_set_alarm` for the `_beginthread` at `programs/test/benchmark.c:430`
    (confirmed by reading the source — the call really does sit in that function).

    FILE SCOPE IS EMPTY, not a placeholder, so a spawn in a static initialiser reads as "no
    enclosing function" rather than naming one that does not exist.
    """
    patterns = patterns_by_name(load_thread_patterns(None))
    src = (
        b"#include <pthread.h>\n"
        b"static void *WorkerProc(void *a) { return a; }\n"
        b"int thread_create(void) {\n"
        b"    pthread_t t;\n"
        b"    return pthread_create(&t, NULL, WorkerProc, NULL);\n"
        b"}\n"
        b"void *raced = (void *) 0;\n"
    )
    tree, raw = _parse_c(src)
    sites = _walk_spawn_sites(tree, raw, patterns)

    assert len(sites) == 1, f"expected the one pthread spawn, got {sites}"
    ## The ARITY MATTERS: the flattener folds positionally, so a walk that emitted one element
    ## fewer would silently drop the last field for every row. gh#47 made it an OCTET — the
    ## eighth is `threads.source`, which tells a registration call apart from a handler
    ## recognised at its definition. 2.1 adds the ninth and tenth, the thread's lifecycle and its
    ## line (`threadlife`).
    assert len(sites[0]) == 10, f"the payload must have ten elements, got {len(sites[0])}"
    assert sites[0][8:] == ["unknown", None], "a pthread_t nobody joins or detaches"
    assert sites[0][6] == "thread_create"

    ## FILE SCOPE: a spawn outside any function must report "" rather than borrow a name.
    file_scope, raw2 = _parse_c(
        b"#include <pthread.h>\n"
        b"static void *P(void *a) { return a; }\n"
        b"pthread_t g;\n"
        b"int ignored = 0;\n"
    )
    assert _walk_spawn_sites(file_scope, raw2, patterns) == []

Activity · 10 steps
lines 423–423patterns = patterns_by_name(load_thread_patterns(None))lines 424–432src = ( b"#include <pthread.h>\n" b"static void *WorkerProc(void *a) { return a; }\n" b"int thread_create(void) {\n" b" pthread_t t;\n" b" return pthread_create(&t, NULL, WorkerProc, NULL);\n" b"}\n" b"void *raced = (void *) 0;\n" )lines 433–433tree, raw = _parse_c(src)lines 434–434sites = _walk_spawn_sites(tree, raw, patterns)lines 436–436assert len(sites) == 1, f"expected the one pthread spawn, got {sites}"lines 442–442assert len(sites[0]) == 10, f"the payload must have ten elements, got {len(sites[0])}"lines 443–443assert sites[0][8:] == ["unknown", None], "a pthread_t nobody joins or detaches"lines 444–444assert sites[0][6] == "thread_create"lines 447–452file_scope, raw2 = _parse_c( b"#include <pthread.h>\n" b"static void *P(void *a) { return a; }\n" b"pthread_t g;\n" b"int ignored = 0;\n" )lines 453–453assert _walk_spawn_sites(file_scope, raw2, patterns) == []

test_the_targets_declared_doc_scope_is_recorded_not_ours

None test_thread_spawns.test_the_targets_declared_doc_scope_is_recorded_not_ours(Any tmp_path)

The target's OWN doc scope is recorded, and absence stays absent.

tests/test_thread_spawns.py:270

Show on the map →

Called by none

Calls _doxyfile_scope

Checks

  • assert got["doxyfile_path"] == "doxygen/project.doxyfile"
  • assert got["doxyfile_file_patterns"] == "*.h", ("the headers-only fact is the whole answer to 'does the doc build cover implementation'" )
  • assert "../include" in got["doxyfile_input"]
  • assert got["doxyfile_excludes"] == "*/extern/*"
  • assert _doxyfile_scope(tmp_path / "empty", rel, None) == {}

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-CONFIG-001measuredtest_the_targets_declared_doc_scope_is_recorded_not_ours → _doxyfile_scope → declared_file_patterns
REQ-DDB-INDEX-001measuredtest_the_targets_declared_doc_scope_is_recorded_not_ours → _doxyfile_scope → discover_doxyfile
Source · 54 lines
def test_the_targets_declared_doc_scope_is_recorded_not_ours(tmp_path: Any) -> None:
    """INDEX SCOPE IS NOT DOXYFILE SCOPE, and until now only the first was recorded. The
    pipeline reads a target's Doxyfile for ALIASES and PREDEFINED and deliberately REPLACES its
    INPUT, so nothing in the index could answer what the repository itself chooses to document
    — `FILE_PATTERNS = *.h` means an API reference over headers only, and that is a different
    claim from what we indexed.

    The cost was already recorded in `write_build_signature`'s own docstring: on the entropic
    grid the raw arm scored 3/3 on "checks the Doxyfile and reports that its INPUT does not
    list examples/" and the index arm 1/3, the only clearly actionable gap in 56 marks.
    Persisting our scope fixed the half about OUR boundary and left the half about THEIRS.

    THE STATED PATH IS WHAT MAKES IT REACHABLE. Discovery refuses to guess — root, then
    `docs/`/`doc/`, then nothing — so Mbed-TLS's `doxygen/mbedtls.doxyfile` is invisible to it
    and this section would stay empty on the one target the question is asked about.

    AND ABSENCE MUST STAY ABSENT: a repo that declares no doc scope records no keys, because
    "not recorded" and "recorded as doxygen's default" are different claims. `declared_file_patterns`
    was written for exactly this and returns empty rather than the defaults — it existed, was
    kept deliberately, and was read by nobody.

    @brief The declared doc scope is recorded from the target's own Doxyfile, or not at all.
    @version 1
    """
    from clew.cli import _doxyfile_scope

    root = tmp_path
    doxyfile = tmp_path / "doxygen" / "project.doxyfile"
    doxyfile.parent.mkdir()
    doxyfile.write_text(
        "PROJECT_NAME = probe\nINPUT = ../include input\nFILE_PATTERNS = *.h\n"
        "EXCLUDE_PATTERNS = */extern/*\n",
        encoding="utf-8",
    )

    def rel(path: Any) -> str:
        """@brief Repo-relative spelling. @return The relative path. @version 1"""
        return str(Path(path).resolve().relative_to(root))

    got = _doxyfile_scope(root, rel, str(doxyfile))
    assert got["doxyfile_path"] == "doxygen/project.doxyfile"
    assert got["doxyfile_file_patterns"] == "*.h", (
        "the headers-only fact is the whole answer to 'does the doc build cover implementation'"
    )
    assert "../include" in got["doxyfile_input"]
    ## THE THIRD KEY. A scope statement has three and reading one answers less than it looks:
    ## a surviving EXCLUDE_PATTERNS once dropped a submodule from a build that exited 0.
    assert got["doxyfile_excludes"] == "*/extern/*"

    ## NOT RECORDED, not recorded-as-empty, when the repo declares nothing. Discovery finds
    ## nothing at a bare root, and no key may be invented for it.
    assert _doxyfile_scope(tmp_path / "empty", rel, None) == {}

Activity · 12 steps
lines 294–294from clew.cli import _doxyfile_scopelines 296–296root = tmp_pathlines 297–297doxyfile = tmp_path / "doxygen" / "project.doxyfile"lines 298–298doxyfile.parent.mkdir()lines 299–303doxyfile.write_text( "PROJECT_NAME = probe\nINPUT = ../include input\nFILE_PATTERNS = *.h\n" "EXCLUDE_PATTERNS = */extern/*\n", encoding="utf-8", )lines 305–307def rel(path: Any) -> str: """@brief Repo-relative spelling. @return The relative path. @version 1""" return str(Path(path).resolve().relative_to(root))lines 309–309got = _doxyfile_scope(root, rel, str(doxyfile))lines 310–310assert got["doxyfile_path"] == "doxygen/project.doxyfile"lines 311–313assert got["doxyfile_file_patterns"] == "*.h", ( "the headers-only fact is the whole answer to 'does the doc build cover implementation'" )lines 314–314assert "../include" in got["doxyfile_input"]lines 317–317assert got["doxyfile_excludes"] == "*/extern/*"lines 321–321assert _doxyfile_scope(tmp_path / "empty", rel, None) == {}

test_the_win32_kind_is_admitted_by_the_vocabulary

None test_thread_spawns.test_the_win32_kind_is_admitted_by_the_vocabulary()

win32 is a real vocabulary member, so the CHECK constraint admits it.

tests/test_thread_spawns.py:136

Show on the map →

Called by none

Calls none

Checks

  • assert THREAD_KIND_WIN32 in THREAD_KIND.values
  • assert THREAD_KIND_WIN32 in THREAD_KIND.rank, ("`values` and `rank` were two hand-maintained copies; a member in one and not the " "other is a KeyError waiting on a payload path" )
  • assert (THREAD_KIND.validated(THREAD_KIND_WIN32, owner="probe", field="kind") == THREAD_KIND_WIN32 )

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-SCHEMA-012measured
Source · 20 lines
def test_the_win32_kind_is_admitted_by_the_vocabulary() -> None:
    """A pattern whose `kind` the CHECK rejects fails at INSERT — after a full parse — so the
    cost of getting this wrong is a build that dies late rather than a pattern that is ignored.
    `THREAD_KIND.validated` is what `load_thread_patterns` routes a declared kind through, and
    a value in `values` but missing from `rank` raises on a payload path rather than at import,
    which is why both now derive from one tuple.

    @brief The win32 kind validates and ranks.
    @version 1
    """
    assert THREAD_KIND_WIN32 in THREAD_KIND.values
    assert THREAD_KIND_WIN32 in THREAD_KIND.rank, (
        "`values` and `rank` were two hand-maintained copies; a member in one and not the "
        "other is a KeyError waiting on a payload path"
    )
    assert (
        THREAD_KIND.validated(THREAD_KIND_WIN32, owner="probe", field="kind") == THREAD_KIND_WIN32
    )

Activity · 3 steps
lines 146–146assert THREAD_KIND_WIN32 in THREAD_KIND.valueslines 147–150assert THREAD_KIND_WIN32 in THREAD_KIND.rank, ( "`values` and `rank` were two hand-maintained copies; a member in one and not the " "other is a KeyError waiting on a payload path" )lines 151–153assert ( THREAD_KIND.validated(THREAD_KIND_WIN32, owner="probe", field="kind") == THREAD_KIND_WIN32 )

test_vendored_paths_name_only_what_exists_and_report_what_does_not

None test_thread_spawns.test_vendored_paths_name_only_what_exists_and_report_what_does_not(Any tmp_path)

The vendored signal names only what exists, and counts the rest.

tests/test_thread_spawns.py:328

Show on the map →

Called by none

Calls _vendored_scope

Checks

  • assert got["vendored_roots"] == "3rdparty", "only the path that EXISTS may be named"
  • assert got["vendored_declared_missing"] == "thirdparty_typo", ("a declared path that matches nothing is a FINDING, not a no-op — it is the " "difference between no vendored code and an unchecked declaration" )
  • assert got["vendored_declared"] == "3rdparty, thirdparty_typo"
  • assert (_vendored_scope(tmp_path, rel, argparse.Namespace(guard_config=None, vendored=None)) == {} )

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-CONFIG-001measuredtest_vendored_paths_name_only_what_exists_and_report_what_does_not → _vendored_scope → load_declaration
REQ-DDB-GUARD-012inferredtest_vendored_paths_name_only_what_exists_and_report_what_does_not → _vendored_scope → load_declaration → load_declaration_located → _checked_sections → _checked_section → _checked_requirements → _validate_node
REQ-DDB-WIKI-054inferredtest_vendored_paths_name_only_what_exists_and_report_what_does_not → _vendored_scope → load_declaration → load_declaration_located → _checked_sections → _checked_section → _checked_list_section → all
Source · 52 lines
def test_vendored_paths_name_only_what_exists_and_report_what_does_not(tmp_path: Any) -> None:
    """D4: `external` STAYS A GIT TREE and this is a separate declared signal. The distinction is
    not pedantry — on Mbed-TLS `3rdparty/` (holding `everest` and `p256-m`) is COMMITTED, not a
    submodule, so `dg_external_root` is correctly NULL across all 570 rows and no git-tree test
    can ever find it. Widening `external` to mean "looks vendored" would move `coverage`,
    `graph_stats` and every orphan count for a naming fashion.

    DECLARED, NOT INFERRED, per the no-hardcoding mandate: one repo keeps it at `3rdparty/`,
    another at `external/` or `deps/`, and a directory named `3rdparty` full of first-party glue
    is a real thing.

    ONLY PATHS THAT EXIST ARE NAMED. gh#335 nearly published a machine path exactly this way —
    the nested-tree walk saw every directory on disk including ones another rule excluded, and
    the first version stamped an excluded target's name into `scope.external_roots`. The rule
    that came out of it is "report only roots that own at least one indexed row; count the
    rest", and a declared path that is simply a TYPO is the same failure: echoing it back as
    though it were found is how a declaration gets believed.

    So the missing half is the actionable half — it distinguishes a repository with no vendored
    code from one whose declaration nobody checked.

    @brief Declared vendored paths are split into present and missing.
    @version 1
    """
    import argparse

    from clew.cli import _vendored_scope

    real = tmp_path / "3rdparty"
    (real / "everest").mkdir(parents=True)

    def rel(path: Any) -> str:
        """@brief Repo-relative spelling. @return The relative path. @version 1"""
        return str(Path(path).resolve().relative_to(tmp_path))

    args = argparse.Namespace(guard_config=None, vendored=["3rdparty", "thirdparty_typo"])
    got = _vendored_scope(tmp_path, rel, args)

    assert got["vendored_roots"] == "3rdparty", "only the path that EXISTS may be named"
    assert got["vendored_declared_missing"] == "thirdparty_typo", (
        "a declared path that matches nothing is a FINDING, not a no-op — it is the "
        "difference between no vendored code and an unchecked declaration"
    )
    ## What was asked for is kept beside what was found, so the two cannot be confused.
    assert got["vendored_declared"] == "3rdparty, thirdparty_typo"

    ## NOT RECORDED when nothing is declared. Absence must not read as "no vendored code".
    assert (
        _vendored_scope(tmp_path, rel, argparse.Namespace(guard_config=None, vendored=None)) == {}
    )

Activity · 11 steps
lines 352–352import argparselines 354–354from clew.cli import _vendored_scopelines 356–356real = tmp_path / "3rdparty"lines 357–357(real / "everest").mkdir(parents=True)lines 359–361def rel(path: Any) -> str: """@brief Repo-relative spelling. @return The relative path. @version 1""" return str(Path(path).resolve().relative_to(tmp_path))lines 363–363args = argparse.Namespace(guard_config=None, vendored=["3rdparty", "thirdparty_typo"])lines 364–364got = _vendored_scope(tmp_path, rel, args)lines 366–366assert got["vendored_roots"] == "3rdparty", "only the path that EXISTS may be named"lines 367–370assert got["vendored_declared_missing"] == "thirdparty_typo", ( "a declared path that matches nothing is a FINDING, not a no-op — it is the " "difference between no vendored code and an unchecked declaration" )lines 372–372assert got["vendored_declared"] == "3rdparty, thirdparty_typo"lines 375–377assert ( _vendored_scope(tmp_path, rel, argparse.Namespace(guard_config=None, vendored=None)) == {} )

test_windows_spawns_are_harvested_and_posix_still_is

None test_thread_spawns.test_windows_spawns_are_harvested_and_posix_still_is()

Every Windows spawn primitive is covered, and POSIX still is.

tests/test_thread_spawns.py:77

Show on the map →

Called by none

Calls _parse_c, _walk_spawn_sites, load_thread_patterns, patterns_by_name

Checks

  • assert entries == ["PosixProc", "TimerProc", "WorkerProc", "WorkerProc"], (f"expected all four spawn sites, got {entries}" )

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-PIPE-003measuredtest_windows_spawns_are_harvested_and_posix_still_is → _walk_spawn_sites → is_python_tree
REQ-DDB-SCHEMA-001measuredtest_windows_spawns_are_harvested_and_posix_still_is → load_thread_patterns
REQ-DDB-SCHEMA-012inferredtest_windows_spawns_are_harvested_and_posix_still_is → load_thread_patterns → declaration_origin
Source · 17 lines
def test_windows_spawns_are_harvested_and_posix_still_is() -> None:
    """The two-sided assertion. Adding a platform must not cost the one already working, and a
    test that only checked the new rows would not notice if it had.

    @brief All four spawn sites resolve to their own entry function.
    @version 1
    """
    patterns = patterns_by_name(load_thread_patterns(None))
    tree, src = _parse_c(_WIN_AND_POSIX)
    sites = _walk_spawn_sites(tree, src, patterns)

    entries = sorted(site[1] for site in sites)
    assert entries == ["PosixProc", "TimerProc", "WorkerProc", "WorkerProc"], (
        f"expected all four spawn sites, got {entries}"
    )

Activity · 5 steps
lines 84–84patterns = patterns_by_name(load_thread_patterns(None))lines 85–85tree, src = _parse_c(_WIN_AND_POSIX)lines 86–86sites = _walk_spawn_sites(tree, src, patterns)lines 88–88entries = sorted(site[1] for site in sites)lines 89–91assert entries == ["PosixProc", "TimerProc", "WorkerProc", "WorkerProc"], ( f"expected all four spawn sites, got {entries}" )