recovery.py

clew/query/recovery.py

What to try instead, when a lookup found nothing.

_documentation_mentions

bool clew.query.recovery._documentation_mentions(sqlite3.Connection conn, str name)

Whether any documentation text in this index mentions a name.

clew/query/recovery.py:190

Source · 41 lines
def _documentation_mentions(conn: sqlite3.Connection, name: str) -> bool:
    """MEASURED on the 1.1.0 entropic cells, replayed against a rebuilt index.
    `dossier("entropic_free_string")` correctly returns nothing — that checkout declares no such
    function — while the name appears four times in doc comments, always as "frees with
    `entropic_free_string`". The agent read the name out of a brief clew had served it, asked for
    it, and was told the index holds nothing of that name.

    Both facts were true and the reply carried only the discouraging one. "No symbol declares
    this" and "this repository has never heard of it" are different answers, and the first is
    itself a finding: the documentation describes an API this build does not contain.

    GUARDED ON COLUMNS, not only on the table, on the graceful-degradation contract the rest of
    the query layer obeys — this repository's own minimal fixtures omit the description columns.

    SHORT NAMES ARE REFUSED. A `LIKE '%x%'` over every description matches almost everything, and
    a hint that fires on any three-letter subject is noise. Six characters is the shortest name in
    the measured set minus a margin, and a bound that excludes a real case is better than a hint
    the reader learns to skip.

    @brief Does any documentation text mention this name.
    @param conn Open connection.
    @param name The name.
    @return True when it is mentioned.
    @version 1
    """
    if len(name) < 6 or not table_exists(conn, "memberdef"):
        return False
    columns = [
        c for c in ("briefdescription", "detaileddescription") if has_columns(conn, "memberdef", c)
    ]
    if not columns:
        return False
    clause = " OR ".join(f"{c} LIKE ?" for c in columns)
    params = [f"%{name}%"] * len(columns)
    row = conn.execute(
        f"SELECT 1 FROM memberdef WHERE {clause} LIMIT 1",
        params,  # noqa: S608
    ).fetchone()
    return row is not None

Activity · 9 steps
lines 215–215◇ if len(name) < 6 or not table_exists(conn, "memberdef")lines 216–216return Falselines 217–219columns = [ c for c in ("briefdescription", "detaileddescription") if has_columns(conn, "memberdef", c) ]lines 220–220◇ if not columnslines 221–221return Falselines 222–222clause = " OR ".join(f"{c} LIKE ?" for c in columns)lines 223–223params = [f"%{name}%"] * len(columns)lines 224–227row = conn.execute( f"SELECT 1 FROM memberdef WHERE {clause} LIMIT 1", params, # noqa: S608 ).fetchone()lines 228–228return row is not None

Flows

_hint_from

str clew.query.recovery._hint_from(sqlite3.Connection conn, str subject)

Build the hint from an open connection.

clew/query/recovery.py:285

Source · 59 lines
def _hint_from(conn: sqlite3.Connection, subject: str) -> str:
    """Split from `recovery_hint` so the failure handling and the logic are separately readable,
    and so the three checks sit together where their order can be seen.

    @brief The hint for an open connection.
    @param conn Open connection.
    @param subject The subject.
    @return The hint or "".
    @version 3
    """
    if looks_like_path(subject):
        found = _indexed_path(conn, subject)
        ## `found == subject` CANNOT REACH HERE on a current index — an exact path resolves as a
        ## file subject and never misses — but the guard stays, because this module is called from
        ## a reply that has already failed and must not advise re-making the call that just failed.
        if found and found != subject:
            return (
                f" THIS INDEX HOLDS THE FILE {found!r}, under that spelling and not the one you "
                f"passed. A FILE IS A SUBJECT: call "
                f'`dossier(subject="{found}")` for its file-level documentation, its symbol count '
                f"and the symbols it defines."
            )
        return ""

    tail = bare_tail(subject)
    if tail != subject and _name_exists(conn, tail):
        return (
            f" THE NAME IS INDEXED, THE SPELLING IS NOT. `subject` must be BARE: pass "
            f'`subject="{tail}", qualified="{subject}"` — `qualified` is what selects one '
            f"identity, and a qualified string in `subject` matches nothing."
        )

    ## ZERO OBSERVED HITS ON THE 1.1.0 GRID, STATED SO NOBODY CLAIMS OTHERWISE. Once the
    ## measurement was corrected for batch attribution, every bare-name miss fell into one of two
    ## buckets and neither is this one: 26 subjects had NO row at all (nothing to suggest), and 5
    ## had a row under that exact name and missed anyway — a retrieval defect, not a spelling one,
    ## and tracked separately. The branch is kept because the mechanism is sound and the cost is
    ## one indexed lookup on a path that has already failed; if the next grid also shows zero, it
    ## should be deleted rather than carried as decoration.
    ## DOCUMENTED BUT NOT DECLARED, which is a FINDING and not a dead end — see
    ## `_documentation_mentions` for the measurement. Placed after the qualified-form branch so a
    ## name that genuinely resolves under another spelling still gets the better advice first.
    if not _name_exists(conn, subject) and _documentation_mentions(conn, subject):
        return (
            f" NO SYMBOL DECLARES {subject!r} IN THIS INDEX, BUT ITS DOCUMENTATION MENTIONS IT — "
            f"so this build does not contain what the docs describe, which is itself the answer "
            f'to some questions. Read the mention with `search(text="{subject}", '
            f'corpus="prose")` or on the symbol whose brief names it.'
        )

    forms, total = _qualified_forms(conn, subject)
    if forms:
        named = ", ".join(repr(form) for form in forms)
        more = f" and {total - len(forms)} more" if total > len(forms) else ""
        return (
            f" NO BARE {subject!r}, but this index holds it qualified: {named}{more}. Re-ask as "
            f'`subject="{subject}", qualified="{forms[0]}"`.'
        )
    return ""

1 more lines, not shown

Activity · 16 steps
lines 295–295◇ if looks_like_path(subject)lines 296–296found = _indexed_path(conn, subject)lines 300–300◇ if found and found != subjectlines 301–306return ( f" THIS INDEX HOLDS THE FILE {found!r}, under that spelling and not the one you " f"passed. A FILE IS A SUBJECT: call " f'`dossier(subject="{found}")` for its file-level documentation, its symbol count ' f"and the symbols it defines." )lines 307–307return ""lines 309–309tail = bare_tail(subject)lines 310–310◇ if tail != subject and _name_exists(conn, tail)lines 311–315return ( f" THE NAME IS INDEXED, THE SPELLING IS NOT. `subject` must be BARE: pass " f'`subject="{tail}", qualified="{subject}"` — `qualified` is what selects one ' f"identity, and a qualified string in `subject` matches nothing." )lines 327–327◇ if not _name_exists(conn, subject) and _documentation_mentions(conn, subject)lines 328–333return ( f" NO SYMBOL DECLARES {subject!r} IN THIS INDEX, BUT ITS DOCUMENTATION MENTIONS IT — " f"so this build does not contain what the docs describe, which is itself the answer " f'to some questions. Read the mention with `search(text="{subject}", ' f'corpus="prose")` or on the symbol whose brief names it.' )lines 335–335forms, total = _qualified_forms(conn, subject)lines 336–336◇ if formslines 337–337named = ", ".join(repr(form) for form in forms)lines 338–338more = f" and {total - len(forms)} more" if total > len(forms) else ""lines 339–342return ( f" NO BARE {subject!r}, but this index holds it qualified: {named}{more}. Re-ask as " f'`subject="{subject}", qualified="{forms[0]}"`.' )lines 343–343return ""

Flows

_indexed_path

str clew.query.recovery._indexed_path(sqlite3.Connection conn, str subject)

Find a file in the index whose path matches a path-shaped subject.

clew/query/recovery.py:103

Source · 26 lines
def _indexed_path(conn: sqlite3.Connection, subject: str) -> str:
    """Exact, then suffix, then basename. A model that passed `src/inference/x.cpp` and one that
    passed `x.cpp` both want the same redirection, and the index stores repo-relative paths whose
    prefix the caller may not have.

    @brief Matching indexed path.
    @param conn Open connection.
    @param subject The subject.
    @return The path or "".
    @version 1
    """
    if not table_exists(conn, "path"):
        return ""
    needle = subject.lstrip("./")
    base = needle.rsplit("/", 1)[-1]
    for sql, arg in (
        ("SELECT name FROM path WHERE name = ? LIMIT 1", needle),
        ("SELECT name FROM path WHERE name LIKE ? LIMIT 1", f"%/{needle}"),
        ("SELECT name FROM path WHERE name LIKE ? LIMIT 1", f"%/{base}"),
    ):
        row = conn.execute(sql, (arg,)).fetchone()
        if row and row[0]:
            return str(row[0])
    return ""

Activity · 9 steps
lines 114–114◇ if not table_exists(conn, "path")lines 115–115return ""lines 116–116needle = subject.lstrip("./")lines 117–117base = needle.rsplit("/", 1)[-1]lines 118–118◇ for sql, arg in (lines 123–123row = conn.execute(sql, (arg,)).fetchone()lines 124–124◇ if row and row[0]lines 125–125return str(row[0])lines 126–126return ""

Flows

_name_exists

bool clew.query.recovery._name_exists(sqlite3.Connection conn, str name)

Whether a bare name resolves to any row.

clew/query/recovery.py:168

Source · 15 lines
def _name_exists(conn: sqlite3.Connection, name: str) -> bool:
    """@brief Does this bare name resolve.
    @param conn Open connection.
    @param name The bare name.
    @return True when it does.
    @version 1
    """
    if not name or not table_exists(conn, "memberdef"):
        return False
    return (
        conn.execute("SELECT 1 FROM memberdef WHERE name = ? LIMIT 1", (name,)).fetchone()
        is not None
    )

Activity · 3 steps
lines 175–175◇ if not name or not table_exists(conn, "memberdef")lines 176–176return Falselines 177–180return ( conn.execute("SELECT 1 FROM memberdef WHERE name = ? LIMIT 1", (name,)).fetchone() is not None )

Flows

_qualified_forms

tuple[list[str], int] clew.query.recovery._qualified_forms(sqlite3.Connection conn, str name)

Qualified names in the index whose bare tail equals a name.

clew/query/recovery.py:136

Source · 25 lines
def _qualified_forms(conn: sqlite3.Connection, name: str) -> tuple[list[str], int]:
    """SQL narrows by `name`, then `qualified_name_of` decides — the same function the `qualified`
    selector compares against, so a hint can never name a form the selector would then reject.
    Deriving the hint from one rule and the acceptance from another is exactly how the served text
    came to advertise `signature`.

    @brief Qualified forms for a bare name.
    @param conn Open connection.
    @param name The bare name.
    @return (named forms, total count).
    @version 1
    """
    if not table_exists(conn, "memberdef"):
        return [], 0
    rows = conn.execute(
        "SELECT DISTINCT name, COALESCE(definition, name) FROM memberdef WHERE name = ?", (name,)
    ).fetchall()
    forms: list[str] = []
    for row_name, definition in rows:
        qualified = qualified_name_of(str(row_name), str(definition))
        if qualified and qualified != name and qualified not in forms:
            forms.append(qualified)
    return sorted(forms)[:_MAX_NAMED], len(forms)

Activity · 9 steps
lines 148–148◇ if not table_exists(conn, "memberdef")lines 149–149return [], 0lines 150–152rows = conn.execute( "SELECT DISTINCT name, COALESCE(definition, name) FROM memberdef WHERE name = ?", (name,) ).fetchall()lines 153–153forms: list[str] = []lines 154–154◇ for row_name, definition in rowslines 155–155qualified = qualified_name_of(str(row_name), str(definition))lines 156–156◇ if qualified and qualified != name and qualified not in formslines 157–157forms.append(qualified)lines 158–158return sorted(forms)[:_MAX_NAMED], len(forms)

Flows

bare_tail

str clew.query.recovery.bare_tail(str subject)

The bare tail of a qualified name.

clew/query/recovery.py:84

Source · 12 lines
def bare_tail(subject: str) -> str:
    """Both separators, because the index holds C++ (`Owner::method`) and Python
    (`pkg.module.function`) in the same column.

    @brief Last segment of a qualified name.
    @param subject The subject.
    @return The tail.
    @version 1
    """
    return subject.rsplit("::", 1)[-1].rsplit(".", 1)[-1]

Activity · 1 steps
lines 93–93return subject.rsplit("::", 1)[-1].rsplit(".", 1)[-1]

Requirements

REQ-DDB-QUERY-013

Flows

looks_like_path

bool clew.query.recovery.looks_like_path(str subject)

Whether a subject string looks like a file rather than a symbol.

clew/query/recovery.py:66

Source · 12 lines
def looks_like_path(subject: str) -> bool:
    """A separator OR a known source suffix. `src/x.cpp` and `main.c` are both files; `C::f` has
    separators of a different kind and is excluded by checking `/` specifically.

    @brief Path-shaped subject test.
    @param subject The subject.
    @return True when path-shaped.
    @version 1
    """
    return "/" in subject or subject.lower().endswith(_PATHISH)

Activity · 1 steps
lines 75–75return "/" in subject or subject.lower().endswith(_PATHISH)

Requirements

REQ-DDB-QUERY-013

Flows

recovery_hint

str clew.query.recovery.recovery_hint(str|Path|None db, str|None subject)

What to try instead, for a subject this index could not answer.

clew/query/recovery.py:242

Source · 31 lines
def recovery_hint(db: str | Path | None, subject: str | None) -> str:
    """THREE CHECKS, IN THE ORDER THAT MATCHES THE MEASURED FREQUENCIES, and each one returns only
    what it actually found in the index:

      1. the subject is a FILE this index holds UNDER ANOTHER SPELLING -> name the path as stored,
         for `dossier` itself, which has answered about files since C1. 48 of 48 such subjects
         were indexed paths; the exact-spelling majority now resolves and never arrives here.
      2. the subject is QUALIFIED and its bare tail resolves -> the selector wants a bare `subject`
         plus `qualified=`, which the served parameter text says and the model did not do. 51 of 54.
      3. the subject is BARE and a qualified form exists -> name it. 92 of 121.

    EMPTY STRING WHEN NOTHING MATCHES, which is 29 of 121 bare names and 3 of 54 qualified ones.
    Those genuinely have no neighbour, and a fabricated suggestion there would make every real
    hint suspect.

    @brief A concrete next call, or "".
    @param db The index database or None.
    @param subject The subject.
    @return The hint, or "".
    @version 3
    """
    if db is None or not subject:
        return ""
    try:
        with connect(db) as conn:
            return _hint_from(conn, subject)
    except (sqlite3.Error, OSError, ValueError):
        ## A probe that cannot run contributes no clause, exactly as `_unresolved_for` does.
        return ""

Activity · 7 steps
lines 263–263◇ if db is None or not subjectlines 264–264return ""lines 265–265trylines 266–266with connect(db) as connlines 267–267return _hint_from(conn, subject)lines 268–268except (sqlite3.Error, OSError, ValueError)lines 270–270return ""

Requirements

REQ-DDB-QUERY-013

Flows