emptiness.py¶
clew/query/emptiness.py
What an EMPTY answer says, and how much confidence it is entitled to.
_conjunction_note
str clew.query.emptiness._conjunction_note(str text, dict[str, int] counts)
Note for a zero-result multi-token search, naming what emptied it.
Source · 33 lines
def _conjunction_note(text: str, counts: dict[str, int]) -> str:
"""gh#31's actual finding: ranking behaved exactly as documented and the NOTE
was wrong. A token with zero independent hits is the single cause of the
emptiness, and naming it converts a wasted call into an answer.
When every token matches something on its own the diagnosis is different in
kind — no ONE unit carries them all — and the advice is fewer tokens rather
than a named deletion.
@brief Word an over-specified-conjunction empty result.
@return Note text.
@version 3
"""
dead = [token for token, count in counts.items() if count == 0]
if dead:
blame = (
f"Token(s) {', '.join(repr(t) for t in dead)} match nothing alone, so they "
f"alone empty it. RETRY WITHOUT THEM — that is the correct next move, not "
f"guessing."
)
else:
blame = (
"Every token matches alone but no one symbol or file carries all of them. "
"RETRY WITH FEWER TOKENS — the two most distinctive — or use "
"search(corpus='prose'), which ranks rather than requiring all."
)
return (
f"No matching symbols for {text!r}. {_NOT_DEFINITIVE} Matching is a CONJUNCTION: "
f"every token must appear in one searchable unit. Per-token hits: "
f"{_render_counts(counts)}. {blame} {_SEARCHED}"
)
Activity · 6 steps
Flows
_render_counts
str clew.query.emptiness._render_counts(dict[str, int] counts)
Render per-token hit counts as token=count prose.
Source · 8 lines
def _render_counts(counts: dict[str, int]) -> str:
"""@brief Render the per-token diagnosis.
@return Comma-joined `token=count` text.
@version 1
"""
return ", ".join(f"{token}={count}" for token, count in counts.items())
Activity · 1 steps
Flows
_scope_payload
dict[str, Any] clew.query.emptiness._scope_payload(q.IndexScope scope)
The scope block for a per-query reply: the covered shape, minus the derivation.
Source · 28 lines
def _scope_payload(scope: q.IndexScope) -> dict[str, Any]:
"""`reason` is dropped HERE rather than in `wire` or in `IndexScope`, because it is not
absent — it is expensive, and only on this surface. `status` publishes the same
dataclass and MUST keep it: an operator asking why a file is missing is exactly who the
paragraph was written for. A field elided in the serializer would have taken it from
both.
Popped rather than rebuilt key by key so a field added to `IndexScope` later reaches
this reply by default. The costly key is the one named; the cheap ones are not a list
that can go stale.
@brief Serialize the scope without its derivation paragraph.
@return Scope wire dict.
@version 1
"""
block = wire.one(scope) or {}
block.pop("reason", None)
## THE FALSY-DROP RULE, APPLIED ON THE WAY OUT. An index built before the build stamped
## the not-indexed report has no row, and `not_indexed: []` beside the covered shape
## states that nothing was missed — a claim that build never made. This module's own
## standard is that "the limit was not reached" and "nobody looked" must not read the
## same, so an unrecorded report is absent rather than empty.
if not scope.not_indexed_count:
block.pop("not_indexed", None)
block.pop("not_indexed_count", None)
return block
Activity · 6 steps
Flows
_scope_sentence
str clew.query.emptiness._scope_sentence(q.IndexScope scope)
One short sentence naming the indexed scope, without its derivation.
Source · 27 lines
def _scope_sentence(scope: q.IndexScope) -> str:
"""THE DERIVATION IS GONE FROM HERE AND ONLY FROM HERE. This used to end with
"Scope was derived from {source}: {reason}." — and the whole-repo tier's `reason` is a
~840-byte paragraph that closes with advice to declare an `index_scope:`. Emitted on
every empty reply, that is two thirds of a zero-row `search` spent on operator
configuration a mid-session agent cannot act on. `status.scope.reason` still carries it
in full, which is the surface an operator actually reads.
The covered shape rides in the `scope` PAYLOAD rather than being spelled out twice, so
the extension and top-level lists are named once per reply instead of once in prose and
once in JSON. The source name stays, because "whole-repo" versus "declared" is one word
and it is the word that says whether a miss could be a scope miss at all.
Omitted, not faked, on an index built before the `scope.*` rows existed — an absent key
honestly reads as "not recorded".
@brief Render the scope summary as one short sentence.
@return Scope sentence.
@version 2
"""
tier = f", {scope.source}" if scope.source else ""
return (
f"Scope: {scope.file_count} indexed file(s){tier} — see the `scope` key for the "
f"covered shape, or status for how it was derived."
)
Activity · 2 steps
Flows
_unread_note
str clew.query.emptiness._unread_note(dict[str, int] unread)
The sentence naming rows an unread corpus holds, or '' when there are none.
Source · 11 lines
def _unread_note(unread: dict[str, int]) -> str:
"""@brief Word the unread-corpus finding.
@return Sentence, or ''.
@version 1
"""
if not unread:
return ""
hits = ", ".join(f"{count} {kind}" for kind, count in unread.items())
return _UNREAD_CORPUS.format(hits=hits)
Activity · 4 steps
Flows
_verdict
str clew.query.emptiness._verdict(Path db, dict[str, int] unread)
Grade a single-token empty search: definitive only when nothing unread matched.
Source · 37 lines
def _verdict(db: Path, unread: dict[str, int]) -> str:
"""THE STRONG WORDING IS NOW EARNED PER CALL rather than attached to a shape. A
single token that matched nothing used to be treated as proof of absence, which
confuses "nothing exists" with "I did not look there" — and this project keeps
finding that the second one was true. `q.unsearched_corpora` asks the database
which corpora `search` did not read and whether any of them holds this query, so
"definitive" is asserted only after that question comes back empty.
The ORDER of the downgrades matters, and it runs most-specific first. A matching row in
an unread corpus is a statement about THIS query and outranks everything below, which
are statements about the index as a whole: if a typedef matched, saying "rebuild to get
file docs" would send the caller to fix the wrong thing.
EXACTLY ONE ABSENT-CORPUS DOWNGRADE, and that is deliberate. gh#393 proposed a second
one for the preprocessor-gate layer and it was BUILT AND REVERTED, because
`test_an_absent_symbol_keeps_the_definitive_note` failed — the test that calls itself
"THE CONTROL ON THE WHOLE CHANGE" and says that if it ever needs weakening, the fix has
become a blanket hedge. It was right: most indexes that lack the gate layer lack it
because a hand-built fixture never made one, so downgrading on absence would hedge
almost every reply and spend the strong wording that gh#31 fought to earn.
THE REAL DEFECT WAS UPSTREAM ANYWAY. `search("MBEDTLS_THREADING_PTHREAD")` returned a
confident empty result nine times in one benchmark run because the HARVEST was
Kconfig-only; gh#390 fixed that and the query now returns rows, so it never reaches
here. A layer that is genuinely absent is reported by `graph_stats.layer_states` as
`absent` rather than `empty` — the distinction already exists, in the surface built to
carry it, and repeating it in every empty search reply buys nothing.
@brief Pick the earned verdict for a single-token empty result.
@return Verdict sentence.
@version 2
"""
if unread:
return _unread_note(unread)
return _DEFINITIVE if q.has_file_docs(db) else _NO_FILE_DOCS
Activity · 3 steps
Flows
prose_emptiness
tuple[str, dict[str, Any]] clew.query.emptiness.prose_emptiness(Path db, str text)
Note and payload for an empty search(corpus='prose )`.
Called by _prose_corpus
Tested by
Source · 41 lines
def prose_emptiness(db: Path, text: str) -> tuple[str, dict[str, Any]]:
"""gh#404 — THE PROSE CORPUS INHERITED A CERTAINTY IT NEVER EARNED. `_search_prose` passed no
`diagnose` callable, so `_many` applied its DEFAULT wording: "a definitive empty result… Do not
retry this query or fall back to guessing." Measured on mbedtls,
`search(corpus='prose', 'MBEDTLS_ALLOW_PRIVATE_ACCESS')` answered exactly that about a token
the same index holds in three `memberdef` rows — and the agent obeyed the instruction and ran
three greps.
GRADED BY THE SAME MACHINERY AS THE SYMBOL CORPUS, not a second one. `token_hit_counts` already
answers "does this index contain this token at all", and reusing it means the two corpora
cannot disagree about whether a name exists. The repo has been here twice (D1, D1b); what those
fixes established is that a note claiming certainty must have EARNED it, and the only way to
earn it here is to have looked elsewhere and found nothing.
THE ABSENT-CORPUS CASE IS DISTINCT and is checked first, because "we searched documentation and
it does not say this" and "this index has no documentation" are different facts and the second
must never be reported as the first.
@brief Word and instrument an empty prose result.
@return (note, extra payload).
@version 1
"""
tokens = [t.lower() for t in text.split() if t]
extra: dict[str, Any] = {}
if not q.has_prose_corpus(db):
return (f"No prose matches for {text!r}. {_NO_PROSE_CORPUS}", extra)
counts = q.token_hit_counts(db, tokens[: q.MAX_DIAGNOSED_TOKENS])
present = {token: n for token, n in counts.items() if n}
if present:
extra["token_hits"] = counts
return (
f"No prose matches for {text!r}. "
+ _PROSE_ELSEWHERE.format(hits=_render_counts(present)),
extra,
)
## Nothing anywhere: the corpus was read, the symbol corpora were read, and neither holds the
## token. THAT is a definitive negative, and it keeps the strong wording precisely because it
## is now the case that earns it.
if counts:
extra["token_hits"] = counts
return (f"No prose matches for {text!r}. {_DEFINITIVE}", extra)1 more lines, not shown
Activity · 12 steps
Requirements
Flows
search_emptiness
tuple[str, dict[str, Any]] clew.query.emptiness.search_emptiness(Path db, str text)
Note and payload for an empty search .
Called by _symbol_corpus
Tested by 6 tests
test_a_conjunction_miss_still_names_its_dead_token, test_a_genuinely_absent_token_still_gets_the_definitive_note, test_a_type_only_token_is_not_blamed_for_the_conjunction, test_an_undocumented_file_is_not_assumed_searchable, test_an_unread_corpus_downgrades_the_verdict, test_the_unread_set_is_derived_from_the_database
Calls _conjunction_note, _scope_payload, _scope_sentence, _unread_note, _verdict, index_scope, token_hit_counts, unsearched_corpora
Source · 41 lines
def search_emptiness(db: Path, text: str) -> tuple[str, dict[str, Any]]:
"""Grades the three cases in this module's docstring. The per-token diagnosis
is computed ONLY here — that is, only once the result is already zero — and only
for the first `MAX_DIAGNOSED_TOKENS` tokens.
THE COST DECISION, stated because it was a real choice: one `COUNT` per token,
paid exclusively on a call that has otherwise returned nothing at all. The
alternative — diagnosing every search — would tax the common path to serve the
rare one, and the alternative of never diagnosing is the defect. A cap keeps the
worst case bounded by the tool rather than by the length of whatever sentence a
caller pasted in.
gh#374 adds the second diagnosis, and it is the one that changes what the reply
CLAIMS: `q.unsearched_corpora` reports rows this query would have matched in a
corpus `search` does not read, derived by subtracting the searched kinds from the
kinds this database actually holds. Any hit downgrades the verdict and is published
as `unsearched_corpus_hits`, so the claim is checkable rather than merely worded.
Same cost argument, and it is two statements whatever the token count.
@brief Word and instrument an empty search result.
@return (note, extra payload).
@version 3
"""
tokens = [t.lower() for t in text.split() if t]
scope = q.index_scope(db)
extra: dict[str, Any] = {"scope": _scope_payload(scope)}
unread = q.unsearched_corpora(db, tokens[: q.MAX_DIAGNOSED_TOKENS])
if unread:
extra["unsearched_corpus_hits"] = unread
if len(tokens) > 1:
counts = q.token_hit_counts(db, tokens[: q.MAX_DIAGNOSED_TOKENS])
extra["token_hits"] = counts
note = f"{_conjunction_note(text, counts)} {_scope_sentence(scope)}"
return (f"{note} {_unread_note(unread)}".rstrip(), extra)
verdict = _verdict(db, unread)
return (
f"No matching symbols for {text!r}. {verdict} {_SEARCHED} {_scope_sentence(scope)}",
extra,
)