Retrieval Analysis Utilities
Original Python applied AI interviews on judgment gaps, evidence completion, retrieval-stage losses, bounded budgets, revision snapshots, score uncertainty, and exposure diagnostics.
These problems are original practice. They are not questions from a named employer or a live hiring loop.
1.Track unique judgment support at requested raw depths
Write
judgment_prefixes(ranking, judgments, depths). ranking lists document ids; judgments maps ids to numeric grades orNone. depths lists integers>=0. For each k return[k,distinct_ids_in_first_k,judged_count,sorted_unjudged_ids]. Absent/Nonegrades are unjudged; grade 0 is judged. Duplicates consume positions but count once. Preserve depths order, including repeats. No mutation.2.Bound unique hit credit while duplicates consume rank slots
Write
precision_bounds(ranking, judgments, k). k>=0; judgments maps ids to bool orNone. In the first k raw positions, a document earns at most one hit. Let s be position count, r distinct known relevant ids, u distinct absent/Noneids. Return{"lower":r/s,"upper":(r+u)/s,"unknown":sorted unknown ids}; both boundsNonewhen s=0. Repeated unknown ids share one possible judgment. No mutation.3.Retain assessor support and unresolved grade spread
Write
grade_spread(rows, gap). Rows[doc,assessor,finite_grade]have unique (doc,assessor) pairs; gap>0. Treat decimals exactly. Return[doc,assessor_count,min_grade,max_grade,median_grade,disputed]sorted by doc. disputed isTrueiff at least two assessors and max-min>=gap. Median averages the two middle grades for even counts. Never choose a consensus label or mutate.4.Locate first support for every required retrieval intent
Write
intent_depths(ranking, tags, required). ranking lists doc ids; tags maps docs to intent lists; absent docs have no tags. required lists unique intents in requested order. Return {"first":[intent,first_1_based_rank_or_None],"all_at":first depth covering every required intent orNoneif impossible}. Empty required givesall_at=0. Repeated docs/tags cannot move a first rank. No mutation.5.Discount repeated intent evidence without duplicate credit
Write
novelty_curve(ranking, tags, alpha). tags maps docs to intent lists; alpha in[0,1], exact decimal. At raw rank r>=1, first occurrence of doc earns sum((1-alpha)**h[intent])/r over its distinct tags, then increments those prior-hit counts. Repeated docs earn 0 and change no counts; absent tags are empty. Return{"gains":per-rank gains,"total":sum}. No mutation.6.Find depths of alternative sufficient evidence sets
Write
evidence_depths(ranking, alternatives). Each alternative lists document ids that together suffice; repeated ids count once. A set completes at the greatest first-occurrence rank of its members, orNoneif any is absent. Empty set completes at 0. Return {"alternatives":completion depths in input order,"rank":smallest defined depth orNoneif none}. Do not mutate.7.Separate candidate support from achieved cutoff evidence
Write
candidate_gap(candidates, ranking, relevant, k). Lists hold ids; ranking ids belong to candidates; k>=0. Let R=distinct relevant, C=distinct candidates. Ceiling=min(k,len(C&R))/len(R); achieved=len(set(ranking[:k])&R)/len(R). Return {"pool_hits":len(C&R),"ceiling":ceiling,"achieved":achieved,"gap":ceiling-achieved}; scoresNonewhen R is empty. Duplicates consume cutoff. No mutation.8.Assign relevant identities to their first absent stage
Write
stage_losses(relevant, stages). relevant lists ids; stages is ordered lists of retained ids and need not be nested. Assign each distinct relevant id to its first absent stage, even if it reappears later. Return {"lost":[stage_index,sorted_first_lost_ids]for every stage,"survived":sorted ids present in every stage}. With no stages all relevant ids survive. No mutation.9.Keep filter removals and unjudged opportunities separate
Write
filter_audit(rows, judgments). Rows[unique_doc,kept_bool,reason]record filter decisions; judgments maps docs to bool orNone. Return {"retained":kept count,"reasons":[reason,removed_count,known_relevant_count,unjudged_count]sorted by reason}. Group only removed rows. Absent/Nonejudgments are unjudged;Falseis known nonrelevant. Do not infer missing judgments or mutate.10.Attribute a cutoff gain change to individual documents
Write
rerank_attribution(before, after, gains, k). before lists unique ids; after is a permutation; gains maps every id to nonnegative finite gain; k>=0. At rank r, contribution=gain/r if r<=k else 0. Return {"items":[id,old_rank,new_rank,new_contribution-old_contribution]sorted by id,"change":sum of changes}. Use 1-based ranks and exact decimals. No mutation.11.Identify intents that lose their last source of evidence
Write
source_ablation(ranking, sources, tags, required, k). sources maps each ranked doc to a source; absent tags are empty; required lists intents; k>=0. Use distinct docs in the first k raw positions. Return {"baseline":sorted supported required intents,"lost":[source,sorted intents lost after removing all its docs]for each present source sorted by name}. Other sources still count. No mutation.12.Track evidence anchors lost during prefix context truncation
Write
context_audit(docs, budget). docs is ordered[unique_id,positive_token_length,anchors]; anchors are valid nonempty half-open token ranges. budget>=0. Consume docs in order, truncating the first partial doc; never skip ahead. Return {"kept":[id,positive_used],"lost":[id,anchor_index]for every anchor not wholly retained}. Keep doc/anchor order; even unread docs can lose anchors. No mutation.13.Charge results while accumulating first-document evidence
Write
evidence_cost_curve(rows, required). Rows[doc,nonnegative_cost,intent_list], exact decimals. At each prefix charge every row cost; only the first occurrence of a doc adds its distinct required intents. Return[cumulative_cost,covered_required_count,all_required_covered]per row. Repeated docs cannot add newly claimed tags. Empty required is always complete. No mutation.14.Choose an exact utility-maximizing rerank subset
Write
rerank_subset(rows, budget). Rows[unique_string_id,integer_cost>=0,integer_utility>=0]; budget>=0. Choose a subset with cost<=budget maximizing utility; ties prefer lower cost, then lexicographically smaller sorted id list. Return{"ids":sorted selected ids,"cost":total,"utility":total}. Each row may be selected once, including zero-cost rows. Empty subset is allowed. No mutation.15.Find a least-cost subset covering all required intents
Write
evidence_cover(required, docs). required lists unique intents; at most 16 docs are[unique_string_id,integer_cost>=0,intents]. Choose a subset covering every required intent. Minimize cost, then document count, then sorted ids lexicographically. Return{"ids":sorted ids,"cost":cost}, orNoneif impossible. Extra intents are irrelevant; empty required returns empty ids/cost 0. No mutation.16.Separate source validity from index availability
Write
index_eligibility(rows, time). Rows[unique_version,start,end_or_None,indexed_at]use integer times; valid intervals are [start,end), or unbounded above. Return {"eligible":sorted versions valid at time andindexed_at<=time,"waiting":sorted valid versions indexed later,"outside":sorted versions not valid at time}. Test validity before availability; boundaries are exact. No mutation.17.Audit reranking against the candidate revision snapshot
Write
revision_audit(candidates, responses). candidates maps doc ids to revision strings; responses are[unique_doc,revision,finite_score]. Return {"matched":[doc,score]for matching revisions in response order,"stale":sorted known docs with other revisions,"unexpected":sorted unknown docs,"missing":sorted candidates with no response}. Stale is present, not missing; 0 scores count. No mutation.18.Check cutoff support before computing distance regret
Write
distance_regret(distances, returned, k). distances maps ids to finite nonnegative exact distances; returned ids are known; k>=0. Optimal ismin(k,N)ids sorted by (distance,id). Actual is unique ids inreturned[:k], keeping order. Return {"optimal":optimal ids,"actual":actual ids,"gap":mean actual distance-mean optimal distance}, gapNoneunless both counts equal and nonzero. No mutation.19.Audit coordinate limits separately from score error
Write
quantization_audit(query, exact, approximate, limits). Equal-length finite decimal vectors; limits>=0. Setd[i]=approximate[i]-exact[i]. Return {"error":abs(sum(query[i]*d[i])),"bound":sum(abs(query[i])*limits[i]),"violations":indices withabs(d[i])>limits[i],"certified":no violations}. Exact decimals; cancellation cannot excuse violations. Empty vectors give zeros/True. No mutation.20.Apply strict score-interval separation to top-k membership
Write
topk_certificate(rows, k). Rows[unique_id,finite_score,error>=0], exact decimals; k>=0. Select first k by descending score then id. If selected and outside are nonempty, margin=min(selected score-error)-max(outside score+error), certified iff margin>0. Otherwise margin=None, certified=True. Return{"selected":ranked ids,"margin":margin,"certified":flag}. Bounds are assumed. No mutation.21.Bound each document rank over independent score intervals
Write
rank_bounds(rows). Rows[unique_string_id,low,high]are finite exact-decimal score intervals, low<=high, chosen independently. Rank scores descending, ties by id. For each doc return[id,best_possible_rank,worst_possible_rank]sorted by id. Bounds are per-document, not one jointly attainable rank assignment. Include interval endpoints and fixed identity ties. No mutation.22.Audit supplied fusion contributions with explicit support
Write
fusion_audit(sources). sources maps source names to doc->nonnegative finite contributions, exact decimals. Per doc in their union return [doc,total,dominant_source_or_None,[[source,share],...]] sorted by doc/source. Include only sources containing that doc, even with zero contribution. Dominant is max contribution, ties by name; zero total givesNonedominant andNoneshares. No mutation.23.Count exact multi-source result membership patterns
Write
source_patterns(runs). runs maps source names to doc-id lists, possibly repeated. Sort source names. For each doc in the union build a bit string in that order, 1 iff the source contains it. Return[pattern,sorted_docs]sorted by pattern. Each doc appears exactly once; empty sources remain zero columns. No all-zero pattern is generated. Do not mutate.24.Choose one retrieval-depth option per query under one budget
Write
query_allocation(options, budget). options maps query names to ordered[integer_cost>=0,integer_utility>=0]choices; budget>=0. Pick one option per query within budget. Maximize summed utility, then minimize cost, then lexicographic[query,option_index]list sorted by query. Return{"choices":list,"cost":total,"utility":total}, orNoneif infeasible. Empty options is feasible. No mutation.25.Build unjudged work with query and source provenance
Write
assessment_tasks(runs, judgments). runs are[query,source,ranked_doc_ids]; judgments maps queries to doc->grade_or_None. For each unjudged (query,doc), return[query,doc,minimum_1_based_rank,sorted_sources], sorted by (query,rank,doc). Absent/Nonegrades are unjudged; grade 0 is judged. Repeated occurrences merge provenance; same doc in different queries stays separate. No mutation.26.Audit capped click weights and unsupported examination
Write
click_diagnostic(rows, cap). Rows[doc,clicked_bool,examination_probability], p in[0,1], cap>0, exact decimals. p=0 is unsupported even for no click; otherwise score=clicked*min(cap,1/p). Return {"documents":[doc,supported_count,mean_score_or_None]sorted by doc,"unsupported":input indices with p=0}. Retain docs with no supported rows. No unbiased relevance claim. No mutation.27.Audit revision-keyed LRU reuse and recomputation cost
Write
rerank_cache(rows, capacity). Rows[query_revision_key,doc_revision_key,nonnegative_cost], exact decimals; capacity>=0. Cache key is both revision strings. A hit costs 0 and becomes most recent; a miss pays its row cost and, if capacity>0, inserts and evicts least recent as needed. Return {"hits":booleans,"cost":paid total,"cache":[query_key,doc_key]least to most recent}. No mutation.28.Find reciprocal best query-document similarities with ties
Write
mutual_neighbors(matrix). A rectangular finite similarity matrix has queries as rows and docs as columns. Each row picks its greatest score, ties lowest column; each column picks its greatest score, ties lowest row. Return {"pairs":[query,doc]for mutual picks sorted by query,"queries":unpaired query indices,"documents":unpaired doc indices}. Empty matrix has zero queries/docs. No mutation.29.Measure query exposure over a fixed document universe
Write
hubness(rankings, universe, k). universe has unique ids; all ranked ids are known; k>=0. Per doc count queries containing it in their first k raw slots, once per query. Return {"counts":[id,count]sorted by id,"gini":sum(abs(ci-cj))/(2*U*sum(counts)),"max_share":max(counts)/sum(counts)}. Include zero-count docs; both statisticsNonefor zero exposure or U=0. No mutation.30.Account for group exposure without hiding unmapped mass
Write
group_exposure(ranking, groups, targets, k), k>=0. groups maps docs to names; targets maps names to finite weights>=0. First-k rank r>=1 adds 1/r mass, repeats included. T=prefix mass; W=total target weight. Return {"groups":[name,mass/T,mass*W/(T*weight)]sorted over targets,"unmapped":unknown-group mass/T}. Empty prefix:Noneshares. Zero weight/W:Noneratios. Exact decimals; no mutation.