selector_waste.py

scripts/selector_waste.py

HOW OFTEN DOES `dossier` RETURN NOTHING, AND WHY — counted, with no judge and no grading.

classify_miss

list[str] selector_waste.classify_miss(object subject, bool passed_qualified)

Why a miss happened, one entry per subject in the call.

scripts/selector_waste.py:118

Show on the map →

Called by count_cell

Calls none

Source · 25 lines
def classify_miss(subject: object, passed_qualified: bool) -> list[str]:
    """Why a miss happened, one entry per subject in the call.

    ONE ENTRY PER SUBJECT, NOT PER CALL. A batched `dossier(subject=[a, b, c])` that misses is one
    wasted round trip but three unanswered names, and the two are different claims about the same
    data. Callers must say which denominator they are quoting.

    `qualified` is checked FIRST because it dominates: if the call passed a selector at all, the
    selector is why it failed, whatever the subject looked like.
    """
    subjects = subject if isinstance(subject, list) else [subject]
    out: list[str] = []
    for one in subjects:
        text = str(one)
        if passed_qualified:
            out.append("passed `qualified` that could not match")
        elif "/" in text or text.endswith(_PATHISH):
            out.append("a FILE PATH as subject")
        elif "::" in text or "." in text:
            out.append("a QUALIFIED name as subject")
        else:
            out.append("a bare name the index does not hold")
    return out

Activity · 13 steps
lines 128–128subjects = subject if isinstance(subject, list) else [subject]lines 129–129out: list[str] = []lines 130–130◇ for one in subjectslines 131–131text = str(one)lines 132–132◇ if passed_qualifiedlines 133–133out.append("passed `qualified` that could not match")lines 134–134◇ elif "/" in text or text.endswith(_PATHISH)lines 135–135out.append("a FILE PATH as subject")lines 136–136◇ elif "::" in text or "." in textlines 137–137out.append("a QUALIFIED name as subject")lines 138–138elselines 139–139out.append("a bare name the index does not hold")lines 140–140return out

Flows

count_cell

tuple[Counter, Counter] selector_waste.count_cell(Path path)

Count dossier behaviour in one session transcript.

scripts/selector_waste.py:186

Source · 51 lines
def count_cell(path: Path) -> tuple[Counter, Counter]:
    """Count dossier behaviour in one session transcript.

    Returns (totals, miss causes). Causes are keyed per SUBJECT and totals per CALL — see
    `classify_miss`.
    """
    uses, results = _blocks(path)
    totals: Counter = Counter()
    causes: Counter = Counter()
    seen: set[str] = set()
    for call_id, block in uses.items():
        if "dossier" not in str(block.get("name") or ""):
            continue
        totals["dossier_calls"] += 1
        args = block.get("input") or {}
        qualified = bool(args.get("qualified"))
        if qualified:
            totals["qualified_passed"] += 1
        raw_subject = args.get("subject")
        requested = [
            str(s) for s in (raw_subject if isinstance(raw_subject, list) else [raw_subject])
        ]
        totals["subjects_requested"] += len(requested)
        key = json.dumps(raw_subject)
        if key in seen:
            totals["repeat_subject"] += 1
        seen.add(key)
        reply = results.get(call_id, "")
        ## COUNTED EVEN WHEN NOTHING MATCHES. If `subjects_missed` is 0 while this is 0 too, the
        ## detector never saw a reply it could read and the run says nothing either way.
        if "found" in reply:
            totals["reply_mentions_found"] += 1

        missed = missed_subjects(reply, requested)
        totals["subjects_missed"] += len(missed)
        if missed:
            ## A CALL IS "PARTIAL" WHEN SOME SUBJECTS ANSWERED. Counting it as a full miss is the
            ## error the previous version made, so the two are now separate rows.
            if len(missed) == len(requested):
                totals["calls_fully_missed"] += 1
            else:
                totals["calls_partly_missed"] += 1
            if qualified:
                totals["qualified_missed"] += 1
            for name in missed:
                causes.update(classify_miss(name, qualified))
        elif qualified:
            totals["qualified_resolved"] += 1
    return totals, causes

Activity · 36 steps
lines 192–192uses, results = _blocks(path)lines 193–193totals: Counter = Counter()lines 194–194causes: Counter = Counter()lines 195–195seen: set[str] = set()lines 196–196◇ for call_id, block in uses.items()lines 197–197◇ if "dossier" not in str(block.get("name") or "")lines 198–198continuelines 199–199totals["dossier_calls"] += 1lines 200–200args = block.get("input") or {}lines 201–201qualified = bool(args.get("qualified"))lines 202–202◇ if qualifiedlines 203–203totals["qualified_passed"] += 1lines 204–204raw_subject = args.get("subject")lines 205–207requested = [ str(s) for s in (raw_subject if isinstance(raw_subject, list) else [raw_subject]) ]lines 208–208totals["subjects_requested"] += len(requested)lines 209–209key = json.dumps(raw_subject)lines 210–210◇ if key in seenlines 211–211totals["repeat_subject"] += 1lines 212–212seen.add(key)lines 213–213reply = results.get(call_id, "")lines 216–216◇ if "found" in replylines 217–217totals["reply_mentions_found"] += 1lines 219–219missed = missed_subjects(reply, requested)lines 220–220totals["subjects_missed"] += len(missed)lines 221–221◇ if missedlines 224–224◇ if len(missed) == len(requested)lines 225–225totals["calls_fully_missed"] += 1lines 226–226elselines 227–227totals["calls_partly_missed"] += 1lines 228–228◇ if qualifiedlines 229–229totals["qualified_missed"] += 1lines 230–230◇ for name in missedlines 231–231causes.update(classify_miss(name, qualified))lines 232–232◇ elif qualifiedlines 233–233totals["qualified_resolved"] += 1lines 234–234return totals, causes

Flows

main

int selector_waste.main(list[str] argv)

Report dossier waste per arm over a frozen run directory.

scripts/selector_waste.py:237

Source · 76 lines
def main(argv: list[str]) -> int:
    """Report dossier waste per arm over a frozen run directory."""
    if not argv:
        print("usage: selector_waste.py <run-dir>", file=sys.stderr)
        return 2
    run = Path(argv[0])
    per_arm: dict[str, Counter] = {}
    causes: Counter = Counter()
    cells: Counter = Counter()
    unreadable: list[str] = []

    for raw in sorted(run.glob("*/answers/*.raw.json")):
        arm = next((a for a in ("index_only", "baseline", "index") if f"_{a}_" in raw.name), "?")
        path = transcript_for(raw)
        if path is None:
            unreadable.append(raw.name)
            continue
        cells[arm] += 1
        totals, cell_causes = count_cell(path)
        per_arm.setdefault(arm, Counter()).update(totals)
        causes.update(cell_causes)

    print(f"run: {run}")
    print(
        f"{'arm':<12}{'cells':>6}{'calls':>7}{'subjects':>10}{'subj.miss':>11}"
        f"{'full':>6}{'part':>6}{'qual=':>7}{'q.miss':>8}{'repeat':>8}"
    )
    for arm in ARMS:
        got = per_arm.get(arm)
        if got is None:
            continue
        print(
            f"{arm:<12}{cells[arm]:>6}{got['dossier_calls']:>7}{got['subjects_requested']:>10}"
            f"{got['subjects_missed']:>11}{got['calls_fully_missed']:>6}"
            f"{got['calls_partly_missed']:>6}{got['qualified_passed']:>7}"
            f"{got['qualified_missed']:>8}{got['repeat_subject']:>8}"
        )

    for arm in ("index_only", "index"):
        got = per_arm.get(arm)
        if not got or not got["subjects_requested"]:
            continue
        calls = got["dossier_calls"]
        subjects = got["subjects_requested"]
        ## THE GUARD AGAINST A FLATTERING ZERO, printed rather than assumed.
        seen_field = got["reply_mentions_found"]
        ## TWO DENOMINATORS, BOTH STATED. A batched call that answered 7 of 8 is one partly-missed
        ## call and one unanswered subject; reporting it as a missed call is the error the second
        ## version of this script made.
        print(
            f"\n{arm}: {got['subjects_missed']}/{subjects} SUBJECTS unanswered "
            f"({got['subjects_missed'] / subjects:.1%} of subjects asked); of {calls} calls, "
            f"{got['calls_fully_missed']} answered nothing and {got['calls_partly_missed']} "
            f"answered some. {got['repeat_subject']} repeated a subject; "
            f"{got['qualified_passed']} passed `qualified`, of which {got['qualified_missed']} "
            f"missed. {seen_field} repl(ies) mentioned `found` at all."
        )
        if not seen_field:
            print(
                f"  WARNING: no reply in {arm} mentioned `found`. A 0% miss rate here means the "
                f"detector saw nothing it understands, NOT that nothing failed."
            )

    if causes:
        subjects = sum(causes.values())
        print(f"\nwhy each miss happened ({subjects} subjects across the missed calls):")
        for cause, count in causes.most_common():
            print(f"  {count:5d}  {cause}")

    ## REPORTED EVEN WHEN ZERO: "none unreadable" and "nobody checked" must not read alike.
    print(f"\nunreadable transcripts: {len(unreadable)}")
    for name in unreadable[:10]:
        print(f"  {name}")
    return 0

Activity · 44 steps
lines 239–239◇ if not argvlines 240–240print("usage: selector_waste.py <run-dir>", file=sys.stderr)lines 241–241return 2lines 242–242run = Path(argv[0])lines 243–243per_arm: dict[str, Counter] = {}lines 244–244causes: Counter = Counter()lines 245–245cells: Counter = Counter()lines 246–246unreadable: list[str] = []lines 248–248◇ for raw in sorted(run.glob("*/answers/*.raw.json"))lines 249–249arm = next((a for a in ("index_only", "baseline", "index") if f"_{a}_" in raw.name), "?")lines 250–250path = transcript_for(raw)lines 251–251◇ if path is Nonelines 252–252unreadable.append(raw.name)lines 253–253continuelines 254–254cells[arm] += 1lines 255–255totals, cell_causes = count_cell(path)lines 256–256per_arm.setdefault(arm, Counter()).update(totals)lines 257–257causes.update(cell_causes)lines 259–259print(f"run: {run}")lines 260–263print( f"{'arm':<12}{'cells':>6}{'calls':>7}{'subjects':>10}{'subj.miss':>11}" f"{'full':>6}{'part':>6}{'qual=':>7}{'q.miss':>8}{'repeat':>8}" )lines 264–264◇ for arm in ARMSlines 265–265got = per_arm.get(arm)lines 266–266◇ if got is Nonelines 267–267continuelines 268–273print( f"{arm:<12}{cells[arm]:>6}{got['dossier_calls']:>7}{got['subjects_requested']:>10}" f"{got['subjects_missed']:>11}{got['calls_fully_missed']:>6}" f"{got['calls_partly_missed']:>6}{got['qualified_passed']:>7}" f"{got['qualified_missed']:>8}{got['repeat_subject']:>8}" )lines 275–275◇ for arm in ("index_only", "index")lines 276–276got = per_arm.get(arm)lines 277–277◇ if not got or not got["subjects_requested"]lines 278–278continuelines 279–279calls = got["dossier_calls"]lines 280–280subjects = got["subjects_requested"]lines 282–282seen_field = got["reply_mentions_found"]lines 286–293print( f"\n{arm}: {got['subjects_missed']}/{subjects} SUBJECTS unanswered " f"({got['subjects_missed'] / subjects:.1%} of subjects asked); of {calls} calls, " f"{got['calls_fully_missed']} answered nothing and {got['calls_partly_missed']} " f"answered some. {got['repeat_subject']} repeated a subject; " f"{got['qualified_passed']} passed `qualified`, of which {got['qualified_missed']} " f"missed. {seen_field} repl(ies) mentioned `found` at all." )lines 294–294◇ if not seen_fieldlines 295–298print( f" WARNING: no reply in {arm} mentioned `found`. A 0% miss rate here means the " f"detector saw nothing it understands, NOT that nothing failed." )lines 300–300◇ if causeslines 301–301subjects = sum(causes.values())lines 302–302print(f"\nwhy each miss happened ({subjects} subjects across the missed calls):")lines 303–303◇ for cause, count in causes.most_common()lines 304–304print(f" {count:5d} {cause}")lines 307–307print(f"\nunreadable transcripts: {len(unreadable)}")lines 308–308◇ for name in unreadable[:10]lines 309–309print(f" {name}")lines 310–310return 0

Flows

missed_subjects

list[str] selector_waste.missed_subjects(str reply, list[str] requested)

BACKSLASHES STRIPPED, because the spelling that lands here is the escaped one: json.dumps turns "found": false into \\"found\\\\": false , which is not valid JSON and so arrives in this branch.

scripts/selector_waste.py:72

Source · 46 lines
def missed_subjects(reply: str, requested: list[str]) -> list[str]:
    """Which of a call's subjects came back unanswered — PER ENTRY, never per call.

    **THE SECOND VERSION OF THIS SCRIPT OVERSTATED EVERY NUMBER IT PRODUCED, and the cause is one
    key.** A batch reply's top-level `found` is a COUNT OF HITS, not a boolean: measured on the
    real surface, `dossier(["execute", "absent"])` returns `found: 1` with `results[1].found ==
    False`. A substring search for `"found":false` therefore fired on any batch with a single bad
    name, so:

      - the call-level rate counted a partial miss as a total one, and
      - the per-subject breakdown then classified every subject in that call as missed, INCLUDING
        the ones that hit.

    That is how 121 subjects came to be labelled "a bare name the index does not hold" while
    `memberdef` held them as functions all along. The names were fine; the attribution was not.

    So the reply is PARSED, and each entry is attributed by its own `found`. A single reply has no
    `results` array: top-level `found is False` is the whole call missing, and a hit carries no
    `found` key at all.
    """
    try:
        payload = json.loads(reply)
    except ValueError:
        ## UNPARSEABLE IS UNKNOWN, NOT CLEAN. Returning [] here would credit a reply we cannot
        ## read as a full hit, which is the flattering reading on the axis under test.
        ##
        ## BACKSLASHES STRIPPED, because the spelling that lands here is the escaped one:
        ## `json.dumps` turns `"found": false` into `\\"found\\": false`, which is not valid JSON
        ## and so arrives in this branch. Matching without stripping is how the first version of
        ## this script reported a clean 0.0% miss rate.
        squashed = reply.replace(" ", "").replace("\\", "")
        return ["<unparseable>"] if '"found":false' in squashed else []
    if not isinstance(payload, dict):
        return []
    entries = payload.get("results")
    if isinstance(entries, list):
        return [
            str(entry.get("name") or "<unnamed>")
            for entry in entries
            if isinstance(entry, dict) and entry.get("found") is False
        ]
    if payload.get("found") is False:
        return [requested[0]] if requested else ["<unnamed>"]
    return []

Activity · 13 steps
lines 92–92trylines 93–93payload = json.loads(reply)lines 94–94except ValueErrorlines 102–102squashed = reply.replace(" ", "").replace("\\", "")lines 103–103return ["<unparseable>"] if '"found":false' in squashed else []lines 104–104◇ if not isinstance(payload, dict)lines 105–105return []lines 106–106entries = payload.get("results")lines 107–107◇ if isinstance(entries, list)lines 108–112return [ str(entry.get("name") or "<unnamed>") for entry in entries if isinstance(entry, dict) and entry.get("found") is False ]lines 113–113◇ if payload.get("found") is Falselines 114–114return [requested[0]] if requested else ["<unnamed>"]lines 115–115return []

Flows

transcript_for

Path | None selector_waste.transcript_for(Path raw)

Locate the session transcript for one frozen cell, or None.

scripts/selector_waste.py:143

Show on the map →

Called by main

Calls none

Source · 17 lines
def transcript_for(raw: Path) -> Path | None:
    """Locate the session transcript for one frozen cell, or None.

    The `.raw.json` envelope names the session; `.meta.json` does NOT carry it, which is why this
    reads the envelope. The glob across every project slug is deliberate — a run whose repo path
    moved still resolves, and `acceptance/execute.count_tools` falls back the same way.
    """
    try:
        session = json.loads(raw.read_text("utf-8")).get("session_id")
    except (OSError, ValueError):
        return None
    if not session:
        return None
    hits = sorted(PROJECTS.glob(f"*/{session}.jsonl"))
    return hits[0] if hits else None

Activity · 8 steps
lines 150–150trylines 151–151session = json.loads(raw.read_text("utf-8")).get("session_id")lines 152–152except (OSError, ValueError)lines 153–153return Nonelines 154–154◇ if not sessionlines 155–155return Nonelines 156–156hits = sorted(PROJECTS.glob(f"*/{session}.jsonl"))lines 157–157return hits[0] if hits else None

Flows